A cross-paradigm automatic conversion method, system and medium for a parameterized geometry modeling script
By using a two-layer abstract syntax tree approach, the cross-paradigm conversion problem from OpenSCAD to CadQuery was solved, achieving efficient and semantically complete model conversion, supporting complex operations and accurate representation, expanding the application scope of design assets, and reducing migration costs.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- SHANGHAI INST OF OPTICS & FINE MECHANICS CHINESE ACAD OF SCI
- Filing Date
- 2026-04-14
- Publication Date
- 2026-07-21
AI Technical Summary
Existing technologies cannot achieve fully automated, semantically complete, and performance-optimized cross-paradigm transformations from OpenSCAD to CadQuery, especially when dealing with multi-file dependencies, hierarchical nested scopes, implicit geometry explicitation, and general matrix transformations.
A method based on two-layer abstract syntax tree (AST) mapping and state stack management is adopted. By constructing an abstract syntax tree parsing module, a transformation engine, an intermediate representation factory module and a code generator transformation pipeline, the transformation from implicit CSG paradigm to explicit B-rep paradigm is realized. This includes multi-file recursive parsing, state initialization, scope isolation, explicit geometric flow tracing and code generation.
It achieves seamless conversion from OpenSCAD to CadQuery, supports advanced topological feature operations, improves computational efficiency and rendering accuracy, expands the application boundaries of design assets, reduces the migration and maintenance costs of open-source model libraries, and connects the data chain between maker design and industrial manufacturing.
Smart Images

Figure CN122020760B_ABST
Abstract
Description
Technical Field
[0001] This invention belongs to the fields of computer-aided design (CAD), computer graphics and compilation technology, and specifically relates to a method, system and computer-readable storage medium for converting modeling scripts based on implicit constructive solid geometry (CSG) descriptions (such as OpenSCAD) into programming modeling scripts based on explicit boundary representation (B-rep) kernels (such as CadQuery / Python). Background Technology
[0002] In the field of procedural CAD modeling, OpenSCAD boasts a large user base and open-source model library due to its concise scripting syntax and modeling concept based on Constructed Solid Geometry (CSG). However, OpenSCAD's geometry kernel is inefficient when handling complex Boolean operations, and its implicit geometry definition makes it difficult to perform advanced topology-based operations such as filleting and shelling on the model. Typically, it can only export discretized STL meshes, losing the parametric design intent.
[0003] In contrast, the Python-based CadQuery framework employs an explicit boundary representation (B-rep) kernel (OpenCASCADE), supporting powerful feature modeling and parametric queries, and can be directly integrated into Python's rich scientific computing ecosystem. However, a fundamental semantic gap exists between OpenSCAD and CadQuery: the former uses an implicit, functional, CSG tree-based modeling paradigm, while the latter uses an explicit, imperative, B-rep-based feature modeling paradigm. This difference means that migrating existing OpenSCAD models to CadQuery almost entirely relies on manual rewriting, resulting in low efficiency, high error rates, and poor maintainability.
[0004] Currently, there are a few automatic conversion tools available, but they suffer from the following technical shortcomings:
[0005] 1. Inability to handle project-level multi-file dependencies: Existing tools typically do not support differentiated imports between include and use, and cannot handle complex library references.
[0006] 2. Incomplete semantic mapping: It cannot correctly transform complex general matrix transformations (multmatrix).
[0007] 3. Performance bottleneck: Blindly converting Boolean operations causes B-rep kernel calculations to crash.
[0008] In summary, current technologies have not yet achieved a fully automated, semantically complete, and performance-optimized cross-paradigm conversion from OpenSCAD to CadQuery. Therefore, there is an urgent need for a cross-paradigm conversion method that can deeply understand geometric semantics, automatically handle hierarchical scope and file dependencies, and perform algorithmic optimization for the B-rep kernel. Summary of the Invention
[0009] This invention aims to address the semantic gap problem encountered in the conversion of OpenSCAD scripts to CadQuery scripts in the prior art, particularly solving the performance optimization problems of differential parsing of multi-file dependencies, mapping of hierarchical nested scopes, expliciting of implicit geometric flows, general matrix transformations, and specific operations (such as Minkowski).
[0010] To address the aforementioned technical problems, this invention provides a method for automatic cross-paradigm conversion of parametric geometric modeling scripts based on two-layer Abstract Syntax Tree (AST) mapping and state stack management. This method achieves semantic-level conversion from the implicit CSG paradigm (OpenSCAD) to the explicit B-rep paradigm (CadQuery / Python) by constructing a complete conversion pipeline comprising an AST parsing module, a conversion engine, an intermediate representation factory module, and a code generator.
[0011] The technical solution of the present invention is as follows:
[0012] On the one hand, this invention provides a method for automatic cross-paradigm conversion of parametric geometric modeling scripts, characterized by the following steps:
[0013] S1. Multi-file recursive parsing steps:
[0014] In response to a request to resolve the source script based on the implicitly constructed entity geometry paradigm and its referenced external dependency files, identify the type of the current reference instruction;
[0015] If the reference instruction is a full inclusion instruction, then all abstract syntax tree nodes of the target file are merged into the current abstract syntax tree;
[0016] If the reference instruction is a definition import instruction, then only the module definition nodes and function definition nodes in the target file are filtered and merged, and the top-level geometry instantiation statements in the target file are filtered.
[0017] Based on the merge results, a unified source abstract syntax tree containing multi-file dependencies is constructed;
[0018] S2. State initialization steps: Initialize the module object of the target language, and establish a statement container stack and a global result lookup table; the statement container stack is used to store the target abstract syntax tree node sequence corresponding to different nesting levels, and the global result lookup table is used to store the mapping relationship between the source abstract syntax tree node identifier and the generated target language variable name;
[0019] S3. Scope isolation and intermediate representation generation steps:
[0020] Traverse the nodes of the unified source abstract syntax tree and perform the following operations:
[0021] In response to traversing to a nested scope node, a new sequence of target abstract syntax tree nodes is pushed onto the top of the statement container stack, creating an independent code generation scope for the current nesting level;
[0022] The corresponding processing function is called according to the type of the current node. The processing function instantiates an intermediate representation node object of the target language. The intermediate representation node object is an encapsulation of the target language syntax element.
[0023] The instantiated intermediate representation node objects are written into the target abstract syntax tree node sequence at the top of the current stack to achieve code isolation between different levels of scope.
[0024] In response to the completion of the traversal of the current nested scope node, a pop operation is performed to pop the target abstract syntax tree node sequence corresponding to the nested scope node from the statement container stack, and encapsulate it as a code block node of the target language and attach it to the parent abstract syntax tree node.
[0025] S4. Geometric flow explicit tracing steps:
[0026] In response to traversing to the source abstract syntax tree node that generates the geometric entity, a globally unique target language variable name is generated for that node, and the mapping relationship between the unique identifier of the node and the target language variable name is stored in the global result lookup table;
[0027] In response to traversing to a Boolean operation node, traverse all its child nodes, query the global result lookup table based on the unique identifier of each child node, and obtain the corresponding list of target language variable names;
[0028] Generate an explicit Boolean function call expression or a binary operation expression that takes the list of variable names as parameters, and assign the evaluation result of the expression to a newly generated globally unique variable name;
[0029] The mapping relationship between the unique identifier of the Boolean operation node and the newly generated variable name is stored in the global result lookup table;
[0030] S5. Code generation steps:
[0031] In response to the completion of the traversal of the unified source abstract syntax tree, the serialization method of each intermediate representation node object is recursively called to generate executable script code in the target language.
[0032] Furthermore, the multi-file recursive parsing step also includes:
[0033] Maintain the set of accessed file paths;
[0034] Before performing recursive parsing of the target file, check whether the path of the current target file already exists in the set of visited file paths;
[0035] If it exists, terminate the current recursive branch to avoid infinite recursion caused by circular references;
[0036] If it does not exist, the path of the current target file is added to the set of visited file paths, and recursive parsing continues.
[0037] Furthermore, the statement container stack is a last-in-first-out (LIFO) stack data structure, where each element is a sequential container for storing intermediate representation node objects; the push operation is triggered when traversing to at least one of the following types of nested scope nodes: module definition nodes, Boolean operation nodes, geometric transformation and modification nodes, and control flow structure nodes; the pop operation is triggered when exiting the aforementioned types of nested scope nodes; in the encapsulation operation, the popped target abstract syntax tree node sequence is encapsulated into a target language code block structure that matches the nested scope node type, and the code block structure includes at least one of the following: module definition body, function definition body, loop body, conditional judgment body, and general statement block.
[0038] Furthermore, the Boolean operation node includes at least one of the following types: union operation node, difference operation node, and intersection operation node.
[0039] Furthermore, it also includes Minkowski and computational semantic optimization steps:
[0040] In response to traversing to the Minkowski and operation nodes, traverse all child nodes within their scope and extract the geometric type and size parameters of each child node;
[0041] Determine whether the number and geometric type combination of child nodes belong to a preset specific geometric pair pattern library;
[0042] If the determination result is yes, then the corresponding auxiliary function requirement flag is set, and an intermediate representation node object for calling the preset optimized auxiliary function is injected into the header of the target script in the code generation step;
[0043] The pre-configured optimization auxiliary function is configured to use the chamfering or offset operation of the boundary representation (B-rep) kernel to equivalently replace the general Minkowski Boolean convolution operation, so as to generate geometric entities with the same geometric shape but lower computational complexity.
[0044] If the result is negative, an intermediate representation node object is generated that calls the generic Minkowski function.
[0045] Furthermore, the preset specific geometry pair pattern library includes at least one or more of the following geometry type combinations: cube and sphere; cube and cylinder; cylinder and sphere.
[0046] Furthermore, it also includes the imperative expansion steps of functional list comprehensions:
[0047] In response to traversing to a functional list comprehension node, generate an intermediate representation node object of the list initialization statement at the beginning of the current scope;
[0048] The nested substructure of nodes is derived by traversing the functional list using a recursive descent method, and a structured mapping is performed based on the type of the current child node:
[0049] If the current child node is an iterative node, then generate the intermediate representation node object of the loop structure in the target language and push it into the new statement container;
[0050] If the current child node is a conditional filter node, then generate the intermediate representation node object of the conditional judgment structure in the target language and push it into a new statement container.
[0051] If the current child node is a local variable bound node, then the node object is represented in the middle of the assignment statement in the target language.
[0052] In response to traversing to the innermost pure expression node, an intermediate representation node object is generated to call the list append method, and the result of the current expression is added as a parameter to the list object initialized by the list initialization statement;
[0053] During the return process of the recursive descent traversal, the stack pop operation is performed in sequence, and each inner statement container is encapsulated into a loop body or conditional judgment body and attached to the corresponding parent control flow node.
[0054] Furthermore, it also includes a dynamic child node scope mapping step:
[0055] Define the injection sub-step: In response to traversing to the module definition node, when generating the intermediate representation node object of the function definition in the target language, force the injection of a list-type parameter at the end of the parameter list of the function definition, and set the default value of the parameter to an empty list;
[0056] The calling side encapsulates the following sub-steps: In response to traversing to a module call node that contains a sub-scope, recursively process all geometric entity generation nodes within the sub-scope to obtain the target language variable names generated for each geometric entity by the explicit geometry flow tracing step; generate a list to construct an intermediate representation node object, and encapsulate the obtained list of target language variable names into a list object; when generating the intermediate representation node object in the function call, pass the list object as a keyword argument to the formal parameter of the list type.
[0057] Furthermore, the node mapping step includes the following sub-steps for processing the general matrix transformation node: extracting 4×4 transformation matrix parameters from the general matrix transformation node; generating an intermediate representation node object for constructing a target language matrix object, wherein the matrix object encapsulates the 4×4 transformation matrix; recursively processing the sub-geometry nodes of the general matrix transformation node, and generating an intermediate representation node object for each sub-geometry node that calls a geometric transformation method, wherein the geometric transformation method takes the target language matrix object as a parameter; the method supports precise semantic mapping for arbitrary affine transformations, wherein the arbitrary affine transformations include translation, rotation, reflection, uniform scaling, non-uniform scaling, shearing, and combinations thereof.
[0058] Secondly, this invention provides an automatic cross-paradigm conversion system for parametric geometric modeling scripts, used to convert source scripts based on the Constructed Solid Geometry (CSG) paradigm into executable target scripts based on the Boundary Representation (B-rep) paradigm, characterized in that it includes:
[0059] The Abstract Syntax Tree (AST) parsing module is configured to receive a source script file written in a first programming language, perform lexical and syntactic analysis on the source script, and generate a Source Abstract Syntax Tree (SourceAST) representing its program structure.
[0060] A transformation engine, communicatively connected to the Abstract Syntax Tree (AST) parsing module, is configured to traverse the source AST and, based on predefined node mapping rules, convert the geometric operation semantics in the source language into equivalent imperative statements in the target language, thereby constructing a Target AST; wherein, the transformation engine includes:
[0061] - A statement container stack used to dynamically maintain the scope hierarchy of the currently generated code during traversal;
[0062] - A global result lookup table, used to store the mapping relationship between each geometry generation node in the source abstract syntax tree and its corresponding variable identifier in the target code;
[0063] The intermediate representation factory module is configured to generate intermediate representation node objects that conform to the syntax of the second programming language according to the instructions of the conversion engine. The intermediate representation node objects include script module definitions, library import instructions, function definitions, assignment statements, function calls, control flow structures, and basic expression objects.
[0064] A code serializer is configured to serialize the target abstract syntax tree into an executable target script file according to the format specification of a second programming language.
[0065] Furthermore, the Abstract Syntax Tree (AST) parsing module includes:
[0066] The full merge unit is configured to perform lexical tokenization and syntactic analysis on the source script code and construct source abstract syntax tree node objects with a hierarchical structure.
[0067] An import unit is defined and configured to recognize a full include instruction. In response to the instruction, the target file is recursively parsed and the generated abstract syntax tree node is directly embedded at the current syntax tree position.
[0068] A loop protection unit is configured to maintain a set of accessed file paths, check for duplicate target file paths before performing recursive parsing, and terminate the current recursive branch when a duplicate path is encountered.
[0069] Thirdly, the present invention also provides a computer-readable storage medium having a computer program stored thereon, characterized in that the computer program implements the above-described method when executed by a processor.
[0070] Compared with the prior art, the present invention has the following significant advantages:
[0071] 1. It has established a data chain connecting "maker manufacturing" to "industrial manufacturing".
[0072] This invention achieves an industrial-grade leap in manufacturing processes: Existing OpenSCAD can only export discretized mesh data (STL / OBJ), suitable only for additive manufacturing such as 3D printing, and cannot be directly recognized by CNC machine tools or CAM software. This invention reconstructs implicit geometry into a precise B-rep topology, enabling the converted model to be directly exported to standard industrial exchange formats such as STEP / IGES. This allows open-source designs, originally limited to the maker community, to seamlessly integrate into precision industrial production processes such as subtractive manufacturing (CNC) and injection mold design, greatly expanding the application boundaries of design assets.
[0073] 2. Unlocked advanced post-processing capabilities based on topological features.
[0074] This invention empowers legacy models with topological editing and feature enhancement capabilities: OpenSCAD's CSG expression, based on purely mathematical formulas, makes it difficult to select specific "edges" or "faces" for operations. This invention restores the topological relationships of faces, edges, and points in the model through cross-paradigm semantic transformation. This allows users to directly apply advanced operations unique to the B-rep kernel, such as filleting, shelling, and lofting, on the converted CadQuery script. This enables refined beautification and engineering transformation of old, rough OpenSCAD models at extremely low cost, solving the pain points of "difficult modification and beautification" in the original design.
[0075] 3. Achieved a dual improvement in computational efficiency and rendering accuracy.
[0076] This invention overcomes the performance bottleneck of CSG trees as complexity increases exponentially: OpenSCAD experiences an exponential increase in mesh subdivision computation when processing highly complex models (especially those involving numerous Minkowski or hull operations). This invention addresses this by using semantic recognition and algorithm reconstruction (e.g., optimizing Minkowski operations to Offset / Fillet operations) to replace mesh Boolean operations with analytical geometry algorithms from the B-rep kernel. Experiments demonstrate that when processing chamfered structures of equivalent complexity, the converted script execution efficiency is improved by several orders of magnitude, and the generated model surface is absolutely smooth, eliminating accuracy errors caused by polyhedral mesh approximation.
[0077] 4. It has built a bridge from "closed scripts" to "general-purpose ecosystem".
[0078] This invention represents a leap from a domain-specific language (DSL) to a general-purpose programming language ecosystem: it releases the logic confined within the OpenSCAD interpreter into standard Python code. This not only preserves the original parametric features but also allows geometric modeling to be directly extended through Python's rich scientific computing libraries (such as NumPy for data-driven modeling, SciPy for optimization design, and PyTorch for AI-assisted generation). The converted code is no longer merely a "drawing script" but a programmable software component that can be integrated into large software systems, web services, or automated pipelines.
[0079] 5. Enabled low-cost revival and migration of open-source design assets.
[0080] This invention significantly reduces the migration and maintenance costs of massive open-source model libraries: Millions of OpenSCAD open-source models (such as the Thingiverse library) exist on the internet. The multi-file parsing and automated conversion mechanism provided by this invention allows these dormant "digital assets" to be migrated to the modern CadQuery / OpenCASCADE technology stack without manual rewriting. This saves enterprises and developers a huge amount of manpower from repetitive modeling, enabling historically accumulated parametric design knowledge (such as gear generation algorithms and thread libraries) to be directly reused by modern CAD systems. Attached Figure Description
[0081] Figure 1 This is a schematic diagram illustrating the abstract syntax tree transformation from OpenSCAD difference operations to CadQuery Boolean subtraction operations in this embodiment of the invention.
[0082] Figure 2 The following is a schematic diagram of the overall system architecture and data flow provided in this embodiment of the invention.
[0083] Figure 3 : Flowchart of scope management based on stack structure in this embodiment of the invention.
[0084] Figure 4 : Flowchart of the semantic optimization decision logic for the Minkowski sum operation in this embodiment of the invention.
[0085] Figure 5 : A schematic diagram of the recursive expansion process of the functional list comprehension structure in this embodiment of the invention.
[0086] Figure 6 : A schematic diagram of the dynamic child node (Children) parameter injection mechanism in this embodiment of the invention.
[0087] Figure 7 : A schematic diagram of the hardware structure of an electronic device (computer system) suitable for implementing embodiments of the present invention. Detailed Implementation
[0088] To make the objectives, technical solutions, and advantages of this invention clearer, the invention will be further described in detail below with reference to the accompanying drawings and specific embodiments. It should be understood that the specific embodiments described herein are merely illustrative of the invention and are not intended to limit the invention.
[0089] The target language of this invention is not limited to Python or the CadQuery framework, but is also applicable to generating code based on other B-rep programming paradigms such as C++ and JavaScript (such as derivative ecosystems like Build123d).
[0090] 1. Overall Architecture and Initialization The system first reads the OpenSCAD source script through the Abstract Syntax Tree (AST) parsing module, performs lexical and syntactic analysis, and constructs the Source Abstract Syntax Tree (Source AST). Then, it initializes the transformation engine (referred to as CQASTGenerator in this embodiment). This engine establishes two core data structures in memory: a statement stack for managing code-level scope, and a global results lookup table (Node Results Map) for tracking the propagation of geometric variables. During initialization, a global module container is pushed onto the statement stack as the root node for target code generation.
[0091] 2. Differentiated multi-file recursive parsing mechanism
[0092] For OpenSCAD's external file reference directives, construct a recursive parser:
[0093] Full inclusion: When an include directive is detected, the target file is treated as part of the current context, and the geometry generation statements and module definitions within it are recursively parsed and preserved, achieving logical merging at the text level.
[0094] Definition Import (Use): When the use instruction is detected, only the module and function definitions in the target file are extracted, while the geometry instantiation statements at the top level of the target file are filtered out to prevent side effect pollution.
[0095] Circular reference protection: Maintain a file path stack (Visited Paths) to prevent recursive parsing from resulting in an infinite loop.
[0096] 3. Stack-based hierarchical scope isolation and refactoring mechanism: For hierarchical nested structures in the source script (such as module definitions, union / difference boolean operation blocks), the transformation engine adopts a dynamic management mechanism of "push-write-pop":
[0097] Context Push: When traversing to a new nested scope node, the engine immediately creates a new empty Sequence of Target Abstract Syntax Tree Nodes and pushes it onto the top of the stack. At this point, the container at the top of the stack becomes the current independent code generation scope, isolated from interference from parent variables.
[0098] Context Write: During the recursive processing of child nodes, all generated intermediate representation (IR) objects (such as assignment statements and function calls) are only added to the container at the top of the current stack.
[0099] Context Pop & Encapsulate: When the nested scope nodes have been processed, the engine pops the top list of the stack and encapsulates them into structured nodes of the target language according to the node type (such as encapsulating the target abstract syntax tree node sequence into Python's Block or FunctionDef). Finally, it is mounted back into the parent abstract syntax tree, thereby accurately restoring the topological hierarchy of the original script.
[0100] 4. Explicit Variable Tracking for Implicit Geometry Flow: To address the characteristics of OpenSCAD's "implicitly transferred geometry," this invention implements explicit reference conversion:
[0101] Unique identifier generation: The transformation engine assigns a unique Python variable name (e.g., sld1) to each source abstract syntax tree (AST) node that generates the geometric entity (e.g., cube, sphere).
[0102] Result mapping record: Store the key-value pairs {Abstract Syntax Tree Node ID : Target Variable Name} in the global result lookup table.
[0103] Explicit aggregation: When processing Boolean operations (such as difference), the engine does not rely on implicit context, but actively queries the result lookup table to obtain the list of variable names of child nodes and generates explicit Boolean operation expressions (such as target = sld1 - sld2), thereby realizing the traceability of data flow and the explicit topological relationship.
[0104] 5. Semantic mapping of spatial transformations
[0105] Semantic reconstruction for spatial operations in OpenSCAD:
[0106] General matrix transformation: For a multimatrix (4x4 matrix), instead of attempting to decompose it into Euler angles, a CadQuery Matrix object is directly generated and transform(matrix) is called to ensure the geometric accuracy of non-orthogonal transformations (such as shearing).
[0107] 6. Imperative expansion of complex functional structures: For functional list comprehensions in the source script, the engine employs a recursive descent expansion strategy:
[0108] After identifying the list comprehension node, generate the list initialization statement (res = []) on the target side.
[0109] The recursive traversal comprehension internal structure maps iterators (LcFor) to Python's for loops, conditional filters (LcIf) to if statements, and local variables (LcLet) to assignment statements.
[0110] In the innermost recursive case (Base Case), an append method call is generated to explicitly append the calculated result to a list, thus flattening the complex single-line expression into an easy-to-debug imperative control flow.
[0111] 7. Dynamic Child Node Injection and Parameterized Passing: To address the dynamic scope issue of OpenSCAD's `children()` function, this invention implements a "formal parameter injection - actual parameter encapsulation" strategy:
[0112] Definition side: When converting a module to a Python function, force the injection of a keyword argument named children_list.
[0113] On the calling side: When processing module calls, the sub-geometry is first recursively calculated, encapsulated as a list object, and explicitly passed as an argument to children_list, thus achieving the correct passing of dynamic child nodes in a statically typed language.
[0114] 8. Geometric Semantics-Based Algorithm Optimization (Minkowski Special Case Handling) To address the inefficiency of the B-rep kernel in handling general Minkowski operations, the conversion engine incorporates heuristic semantic analysis:
[0115] When processing minkowski() nodes, the combination of geometry types of child nodes is scanned in advance.
[0116] If a specific combination is identified (such as "cube + sphere" or "cube + cylinder"), the general conversion path is blocked, and a specific helper function call (such as minkowski_cube_sphere) is generated instead.
[0117] This helper function utilizes the efficient fillet or offset operations of the B-rep kernel to replace expensive Boolean convolution operations, significantly reducing computational overhead.
[0118] 9. Code Generation Finally, the code generator traverses the completed Target Abstract Syntax Tree (AST), serializes it according to Python specifications, and outputs a formatted, executable CadQuery / Python script.
[0119] Example 1: System Architecture and Core Components
[0120] like Figure 2As shown in this embodiment, a cross-paradigm automatic conversion system for parametric geometric modeling scripts is provided, constructing a complete conversion pipeline from the source language (OpenSCAD) to the target language (CadQuery / Python). The system mainly consists of four modules:
[0121] 1. Abstract Syntax Tree (AST) parsing module: responsible for reading .scad source files, performing lexical and syntactic analysis, and constructing the source abstract syntax tree (Source AST).
[0122] 2. Transformation Engine (CQASTGenerator): The core controller of the system, responsible for traversing the source abstract syntax tree and maintaining the transformation state. It includes:
[0123] - Statement Container Stack: Used to temporarily store code nodes generated in the current scope.
[0124] - Global Result Lookup Table: This table records the mapping between the abstract syntax tree node IDs and the generated target variable names (e.g., cube_result_1). The transformation engine traverses the source abstract syntax tree nodes, calls the corresponding processing functions based on the node type, and utilizes the two data structures mentioned above to work together to complete the semantic transformation from implicit CSG to explicit B-rep.
[0125] - Helper function injector: Used to inject Python helper functions such as resize and minkowski_helper into the header of the target script as needed for conversion.
[0126] 3. Intermediate Presentation Layer (IR Factory): Provides the PythonASTNode class and its factory methods to construct the target language's Abstract Syntax Tree (AST), ensuring the generated code is syntactically correct. The transformation engine does not directly concatenate strings to generate code; instead, it requests the IR factory to construct the target AST.
[0127] 4. Code Generator: Traverses the final Target Abstract Syntax Tree (AST) and serializes it into correctly indented Python source code.
[0128] Example 2: Stack-based scope management mechanism
[0129] OpenSCAD's module definitions, Boolean operations (union / difference), and other structures naturally have nested hierarchies. To accurately reproduce this hierarchy in the target language, a dynamic scope management mechanism of "push-write-pop" is adopted.
[0130] like Figure 3 As shown, in order to correctly map the hierarchical nesting structure of OpenSCAD, the conversion engine performs the following steps:
[0131] S301. Stack Push Operation: When the transformation engine traverses to a new nested scope node (such as processUnion), it calls pushStatementContainer to push a new empty sequence of target abstract syntax tree nodes onto the global statement_stack. At this time, the container at the top of the stack represents the active scope of the current code block.
[0132] S302. Recursive processing of child nodes: The transformation engine recursively processes all child nodes of the nested scope node.
[0133] S303. The generated IR is written to the current top stack container: All intermediate representation objects (such as Assign and Call) generated by child nodes are written to the active scope of the current top stack container through the addStatement method, ensuring that the child node code will not leak into the parent scope.
[0134] S304. Pop operation: After all child nodes have been processed, the engine executes popStatementContainer to pop the target abstract syntax tree node sequence from the top of the stack.
[0135] S305. Encapsulate the pop-up sequence into code block nodes: The engine encapsulates this target abstract syntax tree node sequence into a Block node or function body of the target language, depending on the type of the nested scope node.
[0136] S306. Mounting operation: This encapsulated code block is mounted as a whole to its parent abstract syntax tree node, completing the reconstruction of the hierarchical structure.
[0137] As can be seen from the code of processUnion, stack-based scope management perfectly solves the following problems:
[0138] 1. Isolation: When processing child nodes, there is no need to worry about code being accidentally written to other places.
[0139] 2. Sequentiality: The order of code generated by child nodes (block_statements) is fully preserved.
[0140] Reorganization capability: Through the process of "push on stack -> generate -> pop on stack -> add again", the system can analyze, filter (such as filtering out echo) or reorganize child code blocks before writing the code to the parent.
[0141] Example 3: Explicit Transformation of Geometric Flow
[0142] One of OpenSCAD's core features is its implicit geometry transfer: within an operation block (such as difference), the geometry generated by preceding statements automatically becomes the object of subsequent operations, without the need for explicit variable references. This is not directly achievable in the B-rep paradigm.
[0143] This invention solves this problem by using a global result lookup table. For example... Figure 1 As shown, when the engine processes a basic geometry node (such as a cube), it will:
[0144] 1. Call the IR factory to generate the corresponding CadQuery code (e.g., sld1 = box(10, 10, 10)).
[0145] 2. Assign a unique variable name to this geometry (e.g., sld1).
[0146] 3. Store the mapping relationship {cube_node_id: "sld1"} into the node_results lookup table.
[0147] When the engine traces back to its parent node `difference`, it knows that a Boolean subtraction operation needs to be performed on two child geometries. However, it doesn't know the variable names of these two geometries in the target code. At this point, the engine queries the `node_results` table and retrieves "sld1" and "sld2" based on the child node IDs. Finally, the engine generates the explicit Boolean operation code `target_solid = sld1 - sld2`. This process automatically converts the "invisible" data flow in OpenSCAD into "visible and traceable" explicit variable references in CadQuery, which is the key to achieving cross-paradigm transformation in this invention.
[0148] Example 4: Intelligent Optimization of Minkowski Operations
[0149] The general Minkowski sum operation is computationally very expensive in the B-rep kernel, often leading to poor performance or even crashes in the converted script. This invention designs a heuristic optimization strategy based on geometric semantics, such as... Figure 4As shown, when the engine processes an OpenSCAD minkowski() node, it does not immediately generate a generic minkowski() call. Instead, it performs the following specific judgment and processing steps:
[0150] 1. Start and Collection: The process begins with the `processMinkowski` function. The system first traverses the current scope, collecting all valid geometric sub-objects and their parameters (such as dimensions and radii), and storing them in a temporary list.
[0151] 2. Quantity determination: The system determines whether the number of collected geometric objects is strictly equal to 2.
[0152] If not (e.g., the number of objects is 1 or greater than 2), the system directly proceeds to path D (general processing).
[0153] If so, the system will proceed with the matching process for specific combinations.
[0154] 3. Type Combination Determination and Optimization Path: The system checks the type combination of two objects sequentially:
[0155] Decision 1 (Cube + Cylinder): If it is identified as a cube and a cylinder:
[0156] The system sets the flag Need_CubeCylinder_Helper to notify the helper function injector to import the corresponding Python implementation.
[0157] The generation step proceeds to generate the code that calls the optimization function `minkowski_cube_cylinder`. This function uses chamfering operations to simulate computation, avoiding complex Boolean calculations.
[0158] Decision 2 (Cube + Sphere): If Decision 1 is false, continue checking if it is a cube and a sphere:
[0159] If so, set the Need_CubeSphere_Helper flag.
[0160] Generate the calling code for the optimization function minkowski_cube_sphere.
[0161] Decision 3 (Cylinder + Sphere): If decision 2 is false, continue checking if it is a cylinder and a sphere.
[0162] If so, set the Need_CylinderSphere_Helper flag.
[0163] Generate the calling code for the optimization function minkowski_cylinder_sphere.
[0164] 4. General Processing Path (Path D): If all the above specific combinations are judged as "no", or the number of objects is not 2, the system executes general logic and generates a standard minkowski([List]) call to ensure the universality of the transformation result.
[0165] 5. End: Regardless of the path taken, the process eventually converges, assigning the generated function call result to a new result variable and returning the variable name for use by the upper-level nodes.
[0166] Example 5: Recursive Expansion of List Comprehensions
[0167] OpenSCAD supports powerful functional list comprehensions, allowing nested loops, conditions, and local variable bindings within a single line of code. While Python also supports list comprehensions, its expressive power is limited, and it struggles to seamlessly integrate with complex CadQuery geometry operations. This embodiment employs a recursive descent expansion strategy to completely flatten complex functional expressions into a clear imperative control flow. For example... Figure 5 As shown, for the source statement [ for (i=[0:3])if (i>0) i*10 ], the conversion engine will:
[0168] 1. Initialization phase: When processListComprehension captures a list comprehension node, it first creates a unique list variable (such as res_list) in the target code and generates the initialization statement res_list = [].
[0169] 2. Recursive Descent and Structure Mapping: The system calls the core recursive function `generateExplicitLoopForLCRecursive`, which performs the corresponding abstract syntax tree construction operation based on the type of the current node.
[0170] Handling Iteration Nodes (LcFor): As shown in level 1 of the diagram, when an LcFor node is encountered, the system maps it to a Python ForLoop node (e.g., for i in range(4):). At this point, the system pushes a new container onto the statement stack, so that the subsequently generated code is automatically placed within the loop body.
[0171] Handling conditional nodes (LcIf): As shown in level 2 of the diagram, when an LcIf node is encountered within the loop body, the system maps it to a Python IfStmt node (e.g., if i > 0:). Similarly, it pushes onto the stack again, creating an inner scope for the If statement.
[0172] Handling assignment nodes (LcLet): If an LcLet node is encountered (not shown in the diagram, but included in the logic), the system will generate a Python assignment statement (such as val = ...) in the current scope and update the variable context.
[0173] 3. Base Case and Append Operation: As shown in level 3 of the diagram, when the recursion reaches the innermost expression node (i.e., a pure expression that no longer contains control flow, such as i * 10), the system determines that the recursion has ended. At this time, the system generates a method call node (Call) with the corresponding code res_list.append(i * 10), adding it to the current innermost statement container.
[0174] 4. Backtracking and Encapsulation: As the recursive function returns, the system sequentially performs "pop" operations, encapsulating the inner container into a Block node, which is then attached to the child node list of the outer parent node (such as IfStmt or ForLoop), ultimately forming a complete imperative code block.
[0175] In this way, any complex list comprehension logic can be losslessly converted into standard Python loop and conditional structures that are easy to understand and debug, enhancing the maintainability of the converted code.
[0176] Example 6: Parameterized Passing of Dynamic Child Nodes (Children)
[0177] OpenSCAD's `children()` mechanism allows modules to manipulate child geometries included at the time of their invocation; this is dynamic scoping. To achieve the same functionality in statically scoped Python, this invention designs a parameter injection-argument encapsulation mechanism.
[0178] like Figure 6 As shown in the upper part, when converting an OpenSCAD module definition into a Python function, the conversion engine will forcibly inject a keyword parameter named children_list, which defaults to an empty list, regardless of whether the source module declares parameters.
[0179] like Figure 6 As shown in the lower half, when processing module calls, the engine will:
[0180] 1. First, recursively process the child nodes (cube, sphere) within the curly braces to obtain their variable names (such as child_1, child_2).
[0181] 2. Encapsulate these variable names into a Python list (e.g., [child_1, child_2]).
[0182] 3. When generating the function call, explicitly pass this list as the keyword argument children_list=[child_1,child_2] to the target function.
[0183] This mechanism successfully transforms the implicit, scope-based access to children() in OpenSCAD into explicit, parameter-pass-based list operations in Python, perfectly solving the dynamic scope mapping problem between the two programming paradigms.
[0184] Example 7. Differential Analysis of Multiple File Dependencies
[0185] To address the common multi-file dependency problem in engineering-level OpenSCAD projects, the Abstract Syntax Tree (AST) parsing module of this invention implements differentiated processing for the include and use directives:
[0186] 1. Path tracking: The parser maintains a `visited_paths` set. Before processing each file, it checks if the path exists in the set; if it does, it skips the path to prevent circular references.
[0187] 2. Include handling: When encountering an include...<lib.scad> The parser recursively calls processFile and appends the generated abstract syntax tree nodes directly to the current abstract syntax tree node list. This means that cube(10) in lib.scad will directly generate geometry in the main file.
[0188] 3. Use handling: When encountering a use...<utils.scad> The parser also parses recursively, but when merging abstract syntax trees, it only selects nodes of type ModuleDef and FunctionDef to add to the current abstract syntax tree, discarding the top-level ModuleInstantiation (geometry calls). This ensures that no extra models are accidentally generated when importing libraries.
[0189] Figure 7 A schematic diagram of the hardware structure of an electronic device (computer system) suitable for implementing embodiments of the present invention is shown, such as... Figure 7As shown, the electronic device includes:
[0190] External storage / hard disk: used for non-volatile storage of data and program files. In this embodiment, the storage medium explicitly stores computer program instructions that implement the conversion logic of the present invention, specifically including:
[0191] Abstract Syntax Tree (AST) parsing module: used to parse OpenSCAD source code;
[0192] CQASTGenerator Transformation Engine: The core logic unit responsible for state management and algorithm execution;
[0193] IR Factory Module: Used to build intermediate presentation layer objects.
[0194] Internal memory / RAM: When the system is running, the above program instructions are loaded into RAM for the processor to call.
[0195] Processor / CPU: Reads instructions from RAM and executes the parsing, traversal, optimization (such as Minkowski processing), and code generation steps in the foregoing embodiments of this specification.
[0196] System bus and interfaces: responsible for data transmission between various hardware components and interaction with external devices.
[0197] The specific embodiments of the present invention have been described above. It should be understood that the present invention is not limited to the specific embodiments described above, and those skilled in the art can make various modifications or variations within the scope of the claims, which do not affect the essence of the present invention.
Claims
1. A method for automatic cross-paradigm conversion of parametric geometric modeling scripts, characterized in that, Includes the following steps: S1. Multi-file recursive parsing steps: In response to a request to resolve the source script based on the implicitly constructed entity geometry paradigm and its referenced external dependency files, identify the type of the current reference instruction; If the reference instruction is a full inclusion instruction, then all abstract syntax tree nodes of the target file are merged into the current abstract syntax tree; If the reference instruction is a definition import instruction, then only the module definition nodes and function definition nodes in the target file are filtered and merged, and the top-level geometry instantiation statements in the target file are filtered. Based on the merge results, a unified source abstract syntax tree containing multi-file dependencies is constructed; S2. State initialization steps: Initialize the module object of the target language and establish a statement container stack and a global result lookup table; the statement container stack is used to store the target abstract syntax tree node sequence corresponding to different nesting levels, and the global result lookup table is used to store the mapping relationship between the source abstract syntax tree node identifier and the generated target language variable name; S3. Scope isolation and intermediate representation generation steps: Traverse the nodes of the unified source abstract syntax tree and perform the following operations: In response to traversing to a nested scope node, a new sequence of target abstract syntax tree nodes is pushed onto the top of the statement container stack, creating an independent code generation scope for the current nesting level; The corresponding processing function is called according to the type of the current node. The processing function instantiates an intermediate representation node object of the target language. The intermediate representation node object is an encapsulation of the target language syntax element. The instantiated intermediate representation node objects are written into the target abstract syntax tree node sequence at the top of the current stack to achieve code isolation between different levels of scope. In response to the completion of the traversal of the current nested scope node, a pop operation is performed to pop the target abstract syntax tree node sequence corresponding to the nested scope node from the statement container stack, and encapsulate it as a code block node of the target language and attach it to the parent abstract syntax tree node. S4. Geometric flow explicit tracing steps: In response to traversing to the source abstract syntax tree node that generates the geometric entity, a globally unique target language variable name is generated for that node, and the mapping relationship between the unique identifier of the node and the target language variable name is stored in the global result lookup table; In response to traversing to a Boolean operation node, traverse all its child nodes, query the global result lookup table based on the unique identifier of each child node, and obtain the corresponding list of target language variable names; Generate an explicit Boolean function call expression or a binary operation expression that takes the list of variable names as parameters, and assign the evaluation result of the expression to a newly generated globally unique variable name; The mapping relationship between the unique identifier of the Boolean operation node and the newly generated variable name is stored in the global result lookup table; S5. Code generation steps: In response to the completion of the traversal of the unified source abstract syntax tree, the serialization method of each intermediate representation node object is recursively called to generate executable script code in the target language.
2. The method for automatic cross-paradigm conversion of parametric geometric modeling scripts according to claim 1, characterized in that, The multi-file recursive parsing step also includes: Maintain the set of accessed file paths; Before performing recursive parsing of the target file, check whether the path of the current target file already exists in the set of visited file paths; If it exists, terminate the current recursive branch to avoid infinite recursion caused by circular references; If it does not exist, the path of the current target file is added to the set of visited file paths, and recursive parsing continues.
3. The method for automatic cross-paradigm conversion of parametric geometric modeling scripts according to claim 1, characterized in that, The statement container stack is a last-in-first-out stack data structure, and each element in the stack is a sequential container used to store intermediate representation node objects; the push operation is triggered when traversing to at least one of the following types of nested scope nodes: module definition node, Boolean operation node, geometric transformation and modification node, and control flow structure node; The pop operation is triggered when exiting the nested scope node of the aforementioned type; In the encapsulation operation, the popped-up target abstract syntax tree node sequence is encapsulated into a target language code block structure that matches the nested scope node type. The code block structure includes at least one of module definition body, function definition body, loop body, conditional judgment body, and general statement block.
4. The method for automatic cross-paradigm conversion of parametric geometric modeling scripts according to claim 1, characterized in that, The Boolean operation nodes include at least one of the following types: union operation node, difference operation node, and intersection operation node.
5. The method for automatic cross-paradigm conversion of parametric geometric modeling scripts according to claim 1, characterized in that, It also includes Minkowski and computational semantic optimization steps: In response to traversing to the Minkowski and operation nodes, traverse all child nodes within their scope and extract the geometric type and size parameters of each child node; Determine whether the number and geometric type combination of child nodes belong to a preset specific geometric pair pattern library; If the determination result is yes, then the corresponding auxiliary function requirement flag is set, and an intermediate representation node object for calling the preset optimized auxiliary function is injected into the header of the target script in the code generation step; The pre-configured optimization auxiliary function is configured to use the boundary representation of the chamfer or offset operation of the B-rep kernel, which is equivalent to replacing the general Minkowski Boolean convolution operation. If the result is negative, an intermediate representation node object is generated that calls the generic Minkowski function.
6. The method for automatic cross-paradigm conversion of parametric geometric modeling scripts according to claim 5, characterized in that, The preset specific geometry pair pattern library includes at least one or more of the following geometry type combinations: cube and sphere; cube and cylinder; cylinder and sphere.
7. The method for automatic cross-paradigm conversion of parametric geometric modeling scripts according to claim 1, characterized in that, It also includes the imperative expansion step of the functional list comprehension structure: In response to traversing to a functional list comprehension node, generate an intermediate representation node object of the list initialization statement at the beginning of the current scope; The nested substructure of nodes is derived by traversing the functional list using a recursive descent method, and a structured mapping is performed based on the type of the current child node: If the current child node is an iterative node, then generate the intermediate representation node object of the loop structure in the target language and push it into the new statement container; If the current child node is a conditional filter node, then generate the intermediate representation node object of the conditional judgment structure in the target language and push it into a new statement container. If the current child node is a local variable bound node, then the node object is represented in the middle of the assignment statement in the target language. In response to traversing to the innermost pure expression node, an intermediate representation node object is generated to call the list append method, and the result of the current expression is added as a parameter to the list object initialized by the list initialization statement; During the return process of the recursive descent traversal, the stack pop operation is performed in sequence, and each inner statement container is encapsulated into a loop body or conditional judgment body and attached to the corresponding parent control flow node.
8. The method for automatic cross-paradigm conversion of parametric geometric modeling scripts according to claim 1, characterized in that, It also includes the dynamic child node scope mapping step: Define the injection sub-step: In response to traversing to the module definition node, when generating the intermediate representation node object of the function definition in the target language, force the injection of a list-type parameter at the end of the parameter list of the function definition, and set the default value of the parameter to an empty list; The calling side encapsulates the following sub-steps: In response to traversing to a module call node that contains a sub-scope, recursively process all geometric entity generation nodes within the sub-scope to obtain the target language variable names generated for each geometric entity through the geometric flow explicit tracing step described in claim 1; generate a list to construct an intermediate representation node object, and encapsulate the obtained list of target language variable names into a list object; when generating the intermediate representation node object in the function call, pass the list object as a keyword argument to the formal parameter of the list type.
9. A cross-paradigm automatic conversion system for parametric geometric modeling scripts, used to implement the method described in any one of claims 1-8 to convert a source script based on the constructive solid geometry (CSG) paradigm into an executable target script based on the boundary representation (B-rep) paradigm, characterized in that, include: The Abstract Syntax Tree (AST) parsing module is configured to receive source script files written in a first programming language, perform lexical and syntactic analysis on the source scripts, and generate a Source Abstract Syntax Tree (Source AST) representing its program structure. A conversion engine, communicatively connected to the Abstract Syntax Tree (AST) parsing module, is configured to traverse the source AST and, based on predefined node mapping rules, convert the geometric operation semantics in the source language into equivalent imperative statements in the target language, thereby constructing a Target Abstract Syntax Tree (AST); wherein, the conversion engine includes: - A statement container stack used to dynamically maintain the scope hierarchy of the currently generated code during traversal; - A global result lookup table, used to store the mapping relationship between each geometry generation node in the source abstract syntax tree and its corresponding variable identifier in the target code; The intermediate representation factory module is configured to generate intermediate representation node objects that conform to the syntax of the second programming language according to the instructions of the conversion engine. The intermediate representation node objects include script module definitions, library import instructions, function definitions, assignment statements, function calls, control flow structures, and basic expression objects. A code serializer is configured to serialize the target abstract syntax tree into an executable target script file according to the format specification of a second programming language.
10. The cross-paradigm automatic conversion system for parametric geometric modeling scripts according to claim 9, characterized in that, The Abstract Syntax Tree (AST) parsing module includes: The full merge unit is configured to perform lexical tokenization and syntactic analysis on the source script code and construct source abstract syntax tree node objects with a hierarchical structure. An import unit is defined and configured to recognize a full include instruction. In response to the instruction, the target file is recursively parsed and the generated abstract syntax tree node is directly embedded at the current syntax tree position. A loop protection unit is configured to maintain a set of accessed file paths, check for duplicate target file paths before performing recursive parsing, and terminate the current recursive branch when a duplicate path is encountered.
11. A computer-readable storage medium having a computer program stored thereon, characterized in that, When executed by a processor, the computer program implements the method described in any one of claims 1 to 8.