From 2D Diagrams to Drawing Code: Structural Reconstruction with Multimodal Models
Converting a 2D diagram into editable drawing code is a representative multimodal challenge: the input is a pixel matrix, while the output is a set of parameterized geometric instructions. This article breaks the task into visual element recognition, 3D structure inference, occlusion and layer handling, and coordinate mapping. It then presents a depth-sorted drawing description format, an engineering workflow for generation, compilation, rendering, and comparison, and an evaluation framework covering structure, geometry, occlusion, compilability, and maintainability. It also discusses common failure modes and practical mitigations.
1. Task Background: Why Diagram-to-Drawing-Code Conversion Is Hard
Restoring a diagram as editable drawing code is a typical challenge for multimodal models. An image is essentially a pixel matrix, while drawing code is a set of geometric instructions with parameters. Several semantic transformations are required between the two: first identify which elements are present in the image, then determine their spatial relationships, and finally encode those relationships with precise numerical values.
This task places high demands on three capabilities. The first is spatial reasoning: the model must infer front/back, up/down, and orientation from a planar projection. The second is occlusion judgment: line segments that are hidden should not appear in the final drawing. The third is structured output: coordinates, proportions, and drawing order must conform to the target syntax, and any single error can invalidate the entire drawing.
Therefore, when evaluating this type of model, it is not enough to ask whether the output “looks similar.” It is also necessary to check whether the structure is correct, whether the code compiles, and whether changing a parameter produces the expected change in the drawing.
2. Task Decomposition: From Pixels to Drawing Semantics
A reliable approach is to decompose the overall task into four subproblems and solve them step by step.
2.1 Visual Element Recognition
First, list all basic elements in the image, including planar polygons, curved-surface contours, straight lines, arrows, text labels, and shaded regions. For each element, record its category, approximate position, and visual attributes such as solid or dashed line style, fill shade, and line width.
The output of this step is best represented as a structured list rather than free text. A list makes it easier to verify items one by one and to identify missing elements.
2.2 3D Structure Inference
The sense of depth in a diagram usually comes from perspective or isometric projection. The model needs to determine which vertices belong to the same face, which edges are visible, and which edges are hidden on the back side. Common cues include:
- The convergence direction of parallel lines in the image, which can be used to estimate vanishing points;
- The number of vertices on the same face and their connectivity, which can be used to determine face boundaries;
- Shadows or shading differences, which can be used to infer face orientation.
The inference results should be recorded as explicit geometric relationships, such as “face A is in front of face B,” rather than leaving only a vague impression.
2.3 Occlusion and Layer Relationships
Occlusion determines drawing order. A general rule is to draw distant objects first and nearby objects afterward. If a dashed line passes through a solid face that is in front of the line, the dashed line should not be displayed in that region.
When handling occlusion, assign a depth value to each element. A larger depth value means farther back. When outputting code, sorting by depth from largest to smallest produces the correct covering effect. This approach is consistent with the layering strategy used in many vector graphics systems; it is simple to implement and easy to debug.
2.4 Coordinate Mapping
Coordinate mapping requires first defining a unified coordinate system. A common approach is to use the lower-left corner of the image as the origin and convert pixel lengths into target units such as centimeters. The scale can be derived from a known length in the diagram or specified by the user.
Coordinate precision directly affects visual quality. When vertex error exceeds one line width, the misalignment at connections becomes visible to the human eye. Coordinates should therefore retain two to three decimal places, followed by a uniform rounding check after generation.
3. Output Representation: Writing the Drawing as an Executable Description
A drawing description should satisfy three goals at the same time: readability, editability, and reproducibility. The following is an abstract illustrative syntax used only to show the structure; it is not a specific interface.
# Example: cube outline with occlusion relationshipscanvas(width=10, height=8, unit="cm")# Draw from larger depth to smaller; larger depth means farther backface(id="back", pts=[(2,6),(5,7.5),(8,6),(5,4.5)], fill="gray!10", z=4)face(id="front", pts=[(2,6),(5,4.5),(5,1.5),(2,3)], fill="gray!35", z=1)face(id="side", pts=[(5,4.5),(8,6),(8,3),(5,1.5)], fill="gray!20", z=2)# Edges hidden by front faces use dashed lines and are limited to visible segmentsedge(from=(5,4.5), to=(5,1.5), style="dashed", z=0, visible=False)
When writing this type of description, several points require attention:
- Use consistent coordinate units and state them at the beginning of the file.
- Give every element a unique identifier to support localized edits.
- Record depth values separately from drawing order to avoid interference between the two.
- Use semantic names for colors and line styles, such as “light fill,” rather than only numeric values.
4. Engineering Workflow
In real projects, the process can be designed as follows:
- Input preprocessing: normalize image size, remove noise, and crop the target region if necessary.
- Structure extraction: generate an element list and a geometric relationship table.
- Code generation: output description text using a consistent template.
- Compilation and rendering: convert the description into an image.
- Comparison and validation: overlay the rendered result on the original image and check position deviations and occlusion errors.
- Manual correction: make targeted edits to elements with large deviations rather than rewriting the entire output.
Steps 4 and 5 are critical for quality assurance. When compilation fails, the error message should be returned directly rather than silently skipped. Comparison and validation can use metrics such as mask overlap ratio or edge distance, with thresholds set according to business tolerance.
5. Evaluation Methods
Evaluation should cover multiple dimensions rather than relying only on overall visual impression.
- Structural correctness: whether the number and categories of elements match the original image;
- Geometric error: the average offset of key vertices, measured in unit length;
- Occlusion correctness: whether occluded regions are correctly hidden;
- Compilation rate: whether generated code passes syntax checks on the first attempt;
- Maintainability: whether other elements remain stable when a parameter is modified.
It is advisable to prepare a fixed set of test images for each task type, covering simple planar diagrams, single solid blocks, multi-layer nested structures, and complex diagrams with text labels. A fixed test set makes results from different versions comparable.
6. Common Issues and Mitigations
Issue 1: Perspective inference errors cause proportion distortion.
A mitigation is to provide reference lines of known length so the model can calibrate the scale. The output can also be required to include vanishing point coordinates for manual verification.
Issue 2: Occlusion relationships are reversed.
A mitigation is to require a depth value for every element and to check in post-processing whether depth sorting is consistent with the geometric relationships.
Issue 3: The code compiles, but graphical details are missing.
This is usually caused by an incomplete element list. An additional “element completion check” can be added, asking the model to compare each item against the original image and verify whether anything has been omitted.
Issue 4: Coordinate precision is insufficient.
Precision requirements should be stated explicitly in the prompt, and pixel-level comparison should be used after rendering to locate deviations.
7. Conclusion
Diagram-to-drawing-code conversion is a task that combines visual understanding, spatial reasoning, and structured generation. After decomposition into four subproblems—element recognition, structure inference, occlusion handling, and coordinate mapping—each step can be evaluated and improved independently. A description format with depth sorting makes occlusion relationships more controllable. Combined with compilation, rendering, and comparison validation, teams can detect deviations early and correct them at low cost. For technical drawings that require ongoing maintenance, this workflow offers more practical value than one-off generation.
