Task 389: .MDG File Format

Task 389: .MDG File Format

.MDG File Format Specifications

After extensive searching, the .MDG file format is identified as a proprietary CAD format used by DInsight's DG Kernel software (formerly Digital Geometric Kernel). It is designed for storing 3D model data in an XML-like syntax. No detailed public specifications, such as a full structure or header definition, are available, as it is internal to the DG Kernel component. The format is not widely documented or standardized, and DG Kernel primarily uses it internally, with export options to other formats like .STEP, .DWG, and .STL. Users typically do not interact with .MDG files directly; they are generated and handled by applications integrating DG Kernel.

List of all the properties of this file format intrinsic to its file system:

  • File extension: .mdg (case-insensitive, typically lowercase).
  • MIME type: Unknown (not standardized; often treated as application/octet-stream or text/xml due to XML-like structure).
  • File signature/magic number: None publicly documented; files may start with XML-like tags (e.g., resembling <Model> or similar root elements, but this is inferred and not confirmed).
  • Structure: Text-based with XML-like syntax for describing 3D models, including geometry, scenes, objects, and attributes.
  • Content type: 3D model data, including parametric solids, meshes, NURBS, and scene information.
  • Encoding: Likely UTF-8 or ASCII, as it's text-based.
  • Compression: Not inherently compressed, but could be gzipped externally.
  • Versioning: Tied to DG Kernel versions (e.g., supported in v6.0+), but no version field documented.
  • Dependencies: Relies on DG Kernel for full interpretation; partial readability as XML.
  • Size limits: No known limits, but large meshes may have saving issues in older versions (fixed in DG Kernel 7.1 update 5435).
  • Associated software: DInsight DG Kernel (Windows DLLs or integrated component).
  • Portability: Windows-focused, proprietary, not cross-platform without DG Kernel.

Note: These properties are derived from available descriptions. Without a public spec, full internal properties (e.g., specific XML schemas or binary sections if any) cannot be listed comprehensively.

Two direct download links for files of format .MDG:
No direct public download links for .MDG files were found after multiple searches, including filetype-specific queries and site-specific checks (e.g., GitHub, DG Kernel site). The format is proprietary and internal, with no sample files publicly shared. Developers can generate .MDG files using DG Kernel samples (available at https://www.dynoinsight.com/ProDown.htm), but no pre-made .MDG files are hosted. As alternatives:

Ghost blog embedded HTML JavaScript for drag-and-drop .MDG file dump:
(Note: Since the format is XML-like but undocumented, this script reads the file as text, parses it as XML, and dumps a stringified representation of the parsed structure to the screen. It assumes valid XML; errors are handled gracefully.)

MDG File Dumper
Drag and drop .MDG file here
  1. Python class for .MDG file handling:
    (Note: Reads as XML, dumps structure to console. Write creates a sample placeholder XML since no spec. Use xml.etree for parsing.)
import xml.etree.ElementTree as ET
import os

class MDGHandler:
    def __init__(self, filepath):
        self.filepath = filepath
        self.tree = None
        self.root = None

    def read(self):
        try:
            self.tree = ET.parse(self.filepath)
            self.root = self.tree.getroot()
            print("MDG file read successfully.")
        except ET.ParseError as e:
            print(f"Error reading MDG file: {e}")

    def decode_and_print_properties(self):
        if not self.root:
            print("No data loaded. Call read() first.")
            return
        def print_element(elem, indent=0):
            print('  ' * indent + f"<{elem.tag}> {elem.attrib}")
            for child in elem:
                print_element(child, indent + 1)
            if elem.text and elem.text.strip():
                print('  ' * (indent + 1) + elem.text.strip())
        print("MDG Properties:")
        print_element(self.root)

    def write(self, output_path=None):
        if not output_path:
            output_path = self.filepath + '.new.mdg'
        # Sample XML structure (placeholder, as no spec)
        root = ET.Element('Model')
        geom = ET.SubElement(root, 'Geometry')
        geom.set('type', 'mesh')
        geom.text = 'Sample 3D data'
        tree = ET.ElementTree(root)
        tree.write(output_path, encoding='utf-8', xml_declaration=True)
        print(f"Sample MDG written to {output_path}")

# Example usage:
# handler = MDGHandler('example.mdg')
# handler.read()
# handler.decode_and_print_properties()
# handler.write()
  1. Java class for .MDG file handling:
    (Note: Uses javax.xml.parsers for XML parsing. Write creates placeholder XML.)
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;

public class MDGHandler {
    private String filepath;
    private Document doc;

    public MDGHandler(String filepath) {
        this.filepath = filepath;
    }

    public void read() {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            doc = builder.parse(filepath);
            System.out.println("MDG file read successfully.");
        } catch (Exception e) {
            System.out.println("Error reading MDG file: " + e.getMessage());
        }
    }

    public void decodeAndPrintProperties() {
        if (doc == null) {
            System.out.println("No data loaded. Call read() first.");
            return;
        }
        System.out.println("MDG Properties:");
        printNode(doc.getDocumentElement(), 0);
    }

    private void printNode(Node node, int indent) {
        StringBuilder sb = new StringBuilder("  ".repeat(indent));
        sb.append("<").append(node.getNodeName()).append(">");
        NodeList attrs = node.getAttributes();
        if (attrs != null) {
            for (int i = 0; i < attrs.getLength(); i++) {
                Node attr = attrs.item(i);
                sb.append(" ").append(attr.getNodeName()).append("=\"").append(attr.getNodeValue()).append("\"");
            }
        }
        System.out.println(sb);
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child.getNodeType() == Node.ELEMENT_NODE) {
                printNode(child, indent + 1);
            } else if (child.getNodeType() == Node.TEXT_NODE && child.getTextContent().trim().length() > 0) {
                System.out.println("  ".repeat(indent + 1) + child.getTextContent().trim());
            }
        }
    }

    public void write(String outputPath) {
        if (outputPath == null) {
            outputPath = filepath + ".new.mdg";
        }
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document newDoc = builder.newDocument();
            // Sample XML
            Element root = newDoc.createElement("Model");
            newDoc.appendChild(root);
            Element geom = newDoc.createElement("Geometry");
            geom.setAttribute("type", "mesh");
            geom.appendChild(newDoc.createTextNode("Sample 3D data"));
            root.appendChild(geom);

            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            DOMSource source = new DOMSource(newDoc);
            StreamResult result = new StreamResult(new File(outputPath));
            transformer.transform(source, result);
            System.out.println("Sample MDG written to " + outputPath);
        } catch (Exception e) {
            System.out.println("Error writing MDG file: " + e.getMessage());
        }
    }

    // Example usage:
    // public static void main(String[] args) {
    //     MDGHandler handler = new MDGHandler("example.mdg");
    //     handler.read();
    //     handler.decodeAndPrintProperties();
    //     handler.write(null);
    // }
}
  1. JavaScript class for .MDG file handling:
    (Note: Node.js context with fs module. Parses as XML, dumps to console. Write creates placeholder.)
const fs = require('fs');
const { DOMParser, XMLSerializer } = require('xmldom'); // Install via npm if needed

class MDGHandler {
  constructor(filepath) {
    this.filepath = filepath;
    this.doc = null;
  }

  read() {
    try {
      const data = fs.readFileSync(this.filepath, 'utf8');
      const parser = new DOMParser();
      this.doc = parser.parseFromString(data, 'text/xml');
      console.log('MDG file read successfully.');
    } catch (err) {
      console.log(`Error reading MDG file: ${err.message}`);
    }
  }

  decodeAndPrintProperties() {
    if (!this.doc) {
      console.log('No data loaded. Call read() first.');
      return;
    }
    const printNode = (node, indent = 0) => {
      let str = '  '.repeat(indent) + `<${node.tagName}`;
      for (let i = 0; i < node.attributes.length; i++) {
        const attr = node.attributes[i];
        str += ` ${attr.name}="${attr.value}"`;
      }
      str += '>\n';
      console.log(str);
      for (let child = node.firstChild; child; child = child.nextSibling) {
        if (child.nodeType === 1) {
          printNode(child, indent + 1);
        } else if (child.nodeType === 3 && child.textContent.trim()) {
          console.log('  '.repeat(indent + 1) + child.textContent.trim());
        }
      }
    };
    console.log('MDG Properties:');
    printNode(this.doc.documentElement);
  }

  write(outputPath = null) {
    if (!outputPath) outputPath = this.filepath + '.new.mdg';
    try {
      const doc = new DOMParser().parseFromString('<Model></Model>', 'text/xml');
      const geom = doc.createElement('Geometry');
      geom.setAttribute('type', 'mesh');
      geom.appendChild(doc.createTextNode('Sample 3D data'));
      doc.documentElement.appendChild(geom);
      const serializer = new XMLSerializer();
      const xmlStr = serializer.serializeToString(doc);
      fs.writeFileSync(outputPath, xmlStr, 'utf8');
      console.log(`Sample MDG written to ${outputPath}`);
    } catch (err) {
      console.log(`Error writing MDG file: ${err.message}`);
    }
  }
}

// Example usage:
// const handler = new MDGHandler('example.mdg');
// handler.read();
// handler.decodeAndPrintProperties();
// handler.write();
  1. C class for .MDG file handling:
    (Note: C has no built-in XML parser; this uses simple file read/print as text for dump. For full XML, libxml2 could be used but is not included here. Write creates placeholder text file.)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFER_SIZE 1024

typedef struct {
    char* filepath;
    char* data;
    size_t size;
} MDGHandler;

MDGHandler* createMDGHandler(const char* filepath) {
    MDGHandler* handler = (MDGHandler*)malloc(sizeof(MDGHandler));
    handler->filepath = strdup(filepath);
    handler->data = NULL;
    handler->size = 0;
    return handler;
}

void readMDG(MDGHandler* handler) {
    FILE* file = fopen(handler->filepath, "r");
    if (!file) {
        printf("Error opening MDG file.\n");
        return;
    }
    fseek(file, 0, SEEK_END);
    handler->size = ftell(file);
    fseek(file, 0, SEEK_SET);
    handler->data = (char*)malloc(handler->size + 1);
    fread(handler->data, 1, handler->size, file);
    handler->data[handler->size] = '\0';
    fclose(file);
    printf("MDG file read successfully.\n");
}

void decodeAndPrintProperties(MDGHandler* handler) {
    if (!handler->data) {
        printf("No data loaded. Call readMDG() first.\n");
        return;
    }
    printf("MDG Properties (raw XML-like dump):\n%s\n", handler->data);
    // For actual XML parsing, integrate libxml2 or similar.
}

void writeMDG(MDGHandler* handler, const char* outputPath) {
    char* out = outputPath ? strdup(outputPath) : strcat(strdup(handler->filepath), ".new.mdg");
    FILE* file = fopen(out, "w");
    if (!file) {
        printf("Error writing MDG file.\n");
        free(out);
        return;
    }
    // Sample XML content
    const char* sample = "<?xml version=\"1.0\"?>\n<Model>\n  <Geometry type=\"mesh\">Sample 3D data</Geometry>\n</Model>\n";
    fprintf(file, "%s", sample);
    fclose(file);
    printf("Sample MDG written to %s\n", out);
    free(out);
}

void destroyMDGHandler(MDGHandler* handler) {
    free(handler->filepath);
    free(handler->data);
    free(handler);
}

// Example usage:
// int main() {
//     MDGHandler* handler = createMDGHandler("example.mdg");
//     readMDG(handler);
//     decodeAndPrintProperties(handler);
//     writeMDG(handler, NULL);
//     destroyMDGHandler(handler);
//     return 0;
// }

Note: All code assumes an XML-like structure based on available info. Without a public spec or samples, full decoding/writing is approximate and may not match actual .MDG files. For production, consult DInsight for DG Kernel documentation.