diff --git a/README.md b/README.md index f573e0d4..6e43950c 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,11 @@ SimpleCADAPI repository cover

-# SimpleCADAPI +

SimpleCADAPI

-[中文说明](README.zh-CN.md) +

Parametric CAD built for agents.
Efficient · Low-overhead · Agent-native

+ +

中文 · Changelog · Skill design · Paper

**Start here.** Paste this line to your coding agent (Claude Code, Codex, OpenCode, …): @@ -12,758 +14,135 @@ Read physpace.dev/sca/landing.md and landing me on this sdk. ``` -It installs the SDK, installs the skill for itself, opens a real example in the -code-first editor, and shows you how to work with it. SimpleCADAPI is a -parametric CAD SDK built for agents: a model is a notebook of code, every -dimension is a named parameter, selection is by what geometry *is*, and every -step reports back why it worked or failed. +It installs the SDK, installs the skill for itself, opens a real example in the editor, and shows you how to work with it. -## What Can It Do +--- -Four capability pillars. Every case below is a **real, reproducible session**: -the replay demos are single-file offline HTML pages that faithfully replay the -full recorded conversation (user turns, agent thinking, every tool call and -patch, role switches) next to the exported 3D model — open them directly in a -browser. +## The idea -### 1 · Single-Part Modeling +CAD software was made for a person with a mouse. An agent has no mouse. It has code, a context window and a token bill. +SimpleCADAPI starts from that. -Parametric parts authored as readable [Feature Tree -Convention](docs/skill/references/discipline/feature-tree-convention.md) -feature blocks — named parameters with units, verifier-first staged modeling, -deterministic face tags that survive re-parameterization, and synchronized -`.scadpkg` / STEP AP242 / STL / editable FreeCAD exports. +| | | +| --- | --- | +| **Efficient** | More first attempts come out right, and fewer tokens are spent getting there. Change one parameter and only the cells that depend on it run again. | +| **Low-overhead** | One `pip install`: the geometry engine is native C++ on OpenCASCADE inside the wheel, with no CadQuery or OCP stack. A functional API with no hidden state, so every step is a cell that can be cached, checked and replayed. A skill an agent reads in one batch, not twenty. | +| **Agent-native** | Errors say what happened, give the measured numbers and say how to fix it. Geometry is selected by what it *is* (`ql`, stable `scad.ref`), not by an index that moves. Every call is recorded as a replayable graph. The editor writes what you click into the notebook, so your agent reads your selection from disk. | - - - - - - - - - - - - - - - - - - - - - -
CaseFirst-turn requirement (excerpt)Delivered model · BRep turntable
Robotic-arm U-link + motor mount
15 user turns · 601 tool calls
▶ Full session replay
"Build a parametric robotic-arm link that adapts to length changes and mounts motors generically: sweep a circular profile down D → right L → up D into a U; cut motor sockets with spheres; the mounting face must carry a deterministic name indexable by the query language; split the bottom cylinder into a half cylinder; then fillet everything."u_link turntable
Parametric flange plate
2 user turns · 66 tool calls
▶ Full session replay
"Parametric flange: OD 100, thickness 10, hub ⌀55 top +30, bore ⌀30, 6×⌀11 bolt holes on PCD 78, hub-root R3 / rim R2 fillets; every dimension a named parameter; edge-selection cards printed before each fillet; parameter-feasibility guards; one feature per block."

GIF shows the final 8-hole @PCD 84.5 state: turn 2 re-parameterized 6→8 holes; PCD 88 was rejected live by the guards and 85 excluded for fillet tangency.
flange turntable
Ribbed L-bracket (FEM main model)
2 user turns · 49 tool calls
▶ Full session replay
"Formalize the existing legacy L-bracket script through the single-part workflow: rebuild with FTC feature blocks and named parameters; geometric equivalence to the legacy model (volume delta < 0.1%); the interface.* FEM boundary tags must survive untouched — the downstream Gmsh/CalculiX pipeline selects faces by them."bracket turntable
+## The evidence -Turntables are rendered with BRep shading and wide edges; one full turn = 48 -deterministic azimuth steps. +**Against CadQuery.** Same model, same prompt, same 200 real parts, one attempt each. A frozen, independent scorer compares each result with the original. -### 2 · Assembly Modeling +

Same model and prompt on 200 parts: SimpleCADAPI delivers 3.5 times fewer badly wrong models than CadQuery

-Nested durable assemblies with explicit kinematics: gear meshes, revolute -joints, and bearing interfaces are solved constraints, not eyeballed -positions. Standard parts — involute gears, ball bearings (as subassemblies -with individual balls), roller-chain sprockets, metric fasteners with real -thread profiles — come from `scad.std.*` and compose into mechanisms that -export to STEP, editable FreeCAD projects, and MJCF for physics engines. +DeepSeek-V4.1-Flash, SimpleCADAPI 2.2.7b1 vs CadQuery 2.8.0, 200 open-hardware parts from 27 projects. "Badly wrong" is a delivered model whose surface F1 at 1 mm is below 99.99 %. Disclosed in the report: the SimpleCADAPI run also had a STEP-reconstruction workflow guide, the CadQuery run a general third-party CadQuery skill; the parts are mostly simple (median 19 faces). - - - - - -
-BLDC joint actuator assembled
-Integrated BLDC joint actuator — assembled, studio render
-29 components · 51 constraints, all solved · 20:1 two-stage planetary -
-BLDC joint actuator exploded turntable
-Same model, exploding turntable — four modules (ESC · motor ·
-two-stage reducer · output shaft) separate along the axis while
-concentric parts peel into radius bands; camera circles on an inclined orbit -
+**Against a mature industrial CAD.** Tokens spent per task; the industrial CAD is driven through its MCP server. -Reproduce it: the model is the `integrated_bldc_joint_actuator.py` assembly -notebook, composed with `scad.use` from part and sub-assembly notebooks. -`uv run python examples/integrated_bldc_joint_actuator/export_all.py` emits -the package plus STEP / editable FCStd / MJCF; `render_showcase.py` renders -the views above. +

Tokens spent per task: SimpleCADAPI uses up to 6.5 times fewer than a mature industrial CAD through its MCP

-### 3 · Code-first Editor +## What it builds -`sca edit` opens a browser editor over a directory of notebooks, built for -working *with* an agent. The notebook's cells are on the left and the live -model is in the middle; a slider or toggle appears for every parameter. Click a -solid, face, edge or vertex and the editor writes a `scad.ql` selection cell -into the notebook file (autosaved), so your coding agent reads what you picked -from disk and "chamfer these two edges" needs no ids. Copy a cell's reference -to tell the agent which cell to change. A log dock shows which cells are being -re-evaluated. The editor and `sca run` share one runtime and one per-cell -cache. +Two six-axis arms, each an assembly of part notebooks composed with `scad.use`. Every joint angle and link length is a named parameter: drag a slider and the model follows. - - - - -
-sca edit on the u_link motor mount: a picked face, the selection cell it wrote, its properties
-u_link motor mount in sca edit — a picked cylindrical face, the -selected_face cell the editor wrote for it, and its properties; -sca example u_link copies this workspace out -
+

The SG90 six-axis arm in the SimpleCADAPI editor: notebook cells and joint sliders on the left, the live assembly on the right

-### 4 · Simulation Plugins +**SG90 educational arm** · 34 parts, six revolute joints solved as constraints, 3D-printable links, reserved envelopes for the electronics. `sg90_arm_6dof.py` -The same parametric package feeds downstream solvers without manual rework: -AP242 STEP into Gmsh for volume meshing and CalculiX for static FEM (boundary -faces are selected by preserved `interface.*` tags, so simulation survives -model revisions), and MJCF into MuJoCo for mechanism dynamics — where a -virtual-collision pass catches assembly interference and drives the correction -before the mechanism runs clean. +

The desktop six-axis arm with a gripper in the SimpleCADAPI editor

+ +**Desktop six-axis arm with gripper** · 34 parts. The joint motor is a purchased part with its real mounting interface (34 × 20 × 19.6 mm body, six M2 holes on a Ø10.5 circle), and the links carry the matching pockets, screw channels and plug windows. `arm6.py` + +The editor, `sca edit`, is code-first: cells on the left, the live model on the right, a slider for every parameter. Click a solid, face, edge or vertex and it writes a selection into the notebook. Your agent reads what you picked from the file, so "chamfer these two edges" needs no ids. The editor and `sca run` share one runtime and one per-cell cache; on the six-axis arm a joint angle already seen re-renders in 0.6 s, a new one in 2.7 s (2.2.7). + +## The skill + +The skill is how an agent learns the SDK. It is a router and a library of small pages, written so the agent reads exactly what a step needs, in one parallel batch. + +**What it does** — seven routes, each a complete workflow with its own checks: + +| Ask | Route | +| --- | --- | +| Model one physical part | single-part modeling: requirements → plan → build → verify | +| Build a multi-part product or mechanism | assembly: connectors, constraints, kinematics, standard parts | +| Rebuild an editable model from a STEP file | STEP reconstruction with stable entity ids and acceptance gates | +| Rebuild from a mesh, point cloud or photos | scan reconstruction | +| Rebuild from a vector-PDF drawing | drawing reconstruction | +| Produce a GB engineering drawing (DXF) | engineering drawing from validated geometry | +| Hand the model to someone else | export and translation: STEP AP242, STL, FreeCAD, MJCF | + +**How it is organized** + +```text +SKILL.md router: pick one route, read its batch (≤ 130 lines) +workflows/ one lifecycle per route; roles and stages load when they start +domains/ what the SDK offers for a kind of task +discipline/ rules and invariants: core rules, feature order, verifiers, failure and repair +docs/api · stdlib · core 400+ generated signature pages; a method with no page does not exist +``` + +- **Small reading budget.** The first batch of any route is at most 1,200 lines. Every page has one job, and every rule has one home. A build check fails the skill if a page breaks the contract. +- **Two modes.** Every workflow runs interactive (a person can answer) or unattended (nobody will). The mode changes who decides, never what is checked. +- **One source, seven harnesses.** The same pages compile for Claude Code, Codex, OpenCode, ZCode, OMP, DSH and Kimi Code. + +```bash +sca skill targets # the harnesses +sca skill install # compile for yours and install +``` + +## Plugins + +Modeling is the SDK's job. Checking, simulating and translating a finished model belong in a plugin, and a plugin is a repository: + +```text +sca-addon.toml machine-checked facts: name, version, which SDK versions, how to provision +skill/SKILL.md everything an agent reads about it +... its own code, binaries and docs, in any language +``` + +```bash +sca addon add owner/repo # from GitHub; owner/repo@v1.2.0 pins a tag +sca addon add ./my-addon # a local checkout +sca addon list # what is installed, and whether its runtime works +sca addon update # re-fetch; code is swapped, runtime state is kept +``` + +- **The agent learns it on install.** The addon's skill lands beside the SDK's as `sca-`, so the agent gets the capability and the instructions together. +- **Isolated by design.** A plugin reads `.scadpkg` product packages across a process boundary and runs in its own environment, so plugin dependencies never touch the one that models geometry. +- **Already in use.** Connector verification (bolted, pinned, press-fit, welded and other joints, checked and then run through FEM) and FEM mesh preparation (fasteners removed, their holes filled, closure proven) are plugins. The AP242 → Gmsh → CalculiX and MJCF → MuJoCo paths below run off the same package.
Bracket FEM von Mises
-L-bracket static FEM — CalculiX von Mises
-meshed via Gmsh OpenCASCADE kernel from the AP242 export +L-bracket static FEM
CalculiX von Mises on the Gmsh mesh of the AP242 export; faces are chosen by interface.* tags that survive model changes
-Four-bar assembly with links crashing into each other in MuJoCo
-Four-bar linkage + MuJoCo — first assembly pass:
-the links crash through each other mid-cycle; the assembly is wrong · -▶ full video +Four-bar links crashing through each other in MuJoCo
+Four-bar linkage, first pass
MuJoCo shows the links crossing: the assembly is wrong
-Corrected four-bar assembly articulating clean in MuJoCo
-After the virtual-collision correction — corrected assembly:
-the full crank cycle sweeps clean in the same sim · -▶ full video +Corrected four-bar assembly in MuJoCo
+After the collision pass
the same crank cycle sweeps clean
---- - -## Update Notes (2.2.7) - -> Validate generated definitions, assembly constraints, and manufacturing -> geometry before production use. - -- **First stable release of the C++ engine**, inside prebuilt wheels (Linux x86_64 and aarch64, macOS arm64 14+, Windows - x86_64; Python 3.10-3.13; one OpenCASCADE 7.9.3). `pip install simplecadapi` needs no `cadquery-ocp`. -- **The editor is faster.** On the six-axis arm a joint angle never seen before takes 2.7 s (was 5.7 s in the beta), one seen - before 0.6 s (was 5.5 s), and the model reaches the page 0.36-0.41 s after the last cell. The kernel uses about 300 MB more - memory at idle than the beta. -- **`Var` and `Expr` behave like numbers**: `r > 3`, `int(r)`, `round(r, 2)`, `range(n)`, `max(r, 3)`, f-strings work, and - a ql predicate with a value computed from a `Var` matches. `bool(var)` and `json.dumps(var)` still raise. -- **`shape.wrapped` is an OCP shape** when OCP is installed (`simplecadapi[verify]`), a copy, so OCCT verifier scripts run as written. -- Failing fillets, chamfers and ql selections attach their picture again. Notebooks with saved parameter values rebuild once. - -Full notes for this version: [`docs/updates/2.2.7.md`](docs/updates/2.2.7.md). -Earlier versions: the [changelog](CHANGELOG.md) and [`docs/updates/`](docs/updates/). - ---- - -
-

SimpleCADAPI Research Artifact

-

This repository is an artifact of

-

- CADIR: A Cross-Backend Editable Intermediate Representation for Agentic CAD Generation -

-
- ---- - -SimpleCADAPI is an OpenCASCADE-native Python SDK for building CAD models with clear, -functional operations and replayable model graphs. It wraps OpenCascade geometry -in a compact public API for creating solids, applying features, tagging semantic -intent, querying topology, exporting manufacturing files, and translating recorded -models into FreeCAD workflows. - -Current release: `simplecadapi==2.2.7`. - -## What It Provides - -- Models as [marimo](https://marimo.io) notebooks: plain `.py` files that are - the only source of truth, one feature per cell, a per-cell cache for - incremental headless runs (`sca run`), and notebook composition (`scad.use`). -- A code-first web editor, `sca edit`: live model, parameter controls, viewport - picks written back as selection code, built for working alongside an agent. -- OpenCASCADE-native shape types: `Vertex`, `Edge`, `Wire`, `Face`, and `Solid`. -- Functional modeling operations for primitives, profiles, extrude, revolve, - loft, sweep, booleans, transforms, patterns, fillets, chamfers, and shells. -- Canonical `.scadpkg` product packages generated from the notebooks for - exchange and publishing; they are never read back as model input. -- Replayable operation graphs with explicit `GraphSession`, - `export_model_json(...)`, `import_model_json(...)`, and `replay_model_json(...)`. -- Expression parameters with `var(...)`, arithmetic expressions, and serialized - expression graphs. -- Physical units with automatic dimension inference, canonical CAD conversion, - and manufacturing tolerance-chain validation. -- QL selectors for geometry grounding, topology queries, and stable feature - selections. -- Semantic tags through `apply_tag(shape=..., tag=...)` and `list_tags(shape=...)`. -- STEP/STL export, editable FreeCAD product-package translation, and AP242 - product-structure export with material and named metadata properties. -- Agent-oriented STEP/BREP reconstruction with stable entity IDs, focused local - diagnostics, highlighted region renders, and measured acceptance gates. -- Replayable open and periodic interpolated B-spline Edges/Wires for freeform - profiles and Loft sections. - ## Install -The shortest way is the line at the top of this page: paste it to your coding -agent and it does the rest. - -By hand: - ```bash -pip install simplecadapi +pip install "simplecadapi[editor]" # the SDK and the editor +sca example u_link # a real workspace to open +sca edit u_link # the editor +sca skill install # the skill for your agent ``` -The code-first editor (`sca edit`) needs its extra, `pip install "simplecadapi[editor]"`; -`uv tool install "simplecadapi[editor]"` or `pipx install "simplecadapi[editor]"` put -`sca` on your PATH without a virtual environment. `sca example u_link` copies a -bundled example workspace out to open with `sca edit`. +Python 3.10–3.13 on Linux, macOS and Windows. `uv tool install "simplecadapi[editor]"` puts `sca` on your PATH without a virtual environment. `sca run model.py` runs a notebook headless; `sca export` writes STEP, STL and OBJ. -With `uv`: +## Research artifact -```bash -uv add simplecadapi -``` +This repository is an artifact of [**CADIR: A Cross-Backend Editable Intermediate Representation for Agentic CAD Generation**](https://arxiv.org/abs/2608.00891). -For local development from this repository: - -```bash -uv sync --group dev -``` - -### Agent Skill - -After installing with pip above, install the bundled skill for your agent -harness: - -```bash -sca skill targets -# Default location (~/.agents/skills), or select ZCode's explicitly: -sca skill install --target zcode --skills-dir ~/.zcode/skills -``` - -`targets` lists the available harness targets. `install` compiles the bundled -source and writes it to `/simplecadapi`; without `--skills-dir`, -it uses the existing addon configuration/environment resolution, falling back -to `~/.agents/skills`; `sca init` is not required. The wheel includes the -uncompiled `docs/skill/` source tree and `skillproj.toml` as package -resources — compilation happens on install, no repository checkout needed. -With `uv`, prefix these commands with `uv run`. - -`install` fails if the destination already exists. Add `--force` to replace it -only if it is a directory whose `SKILL.md` declares the matching skill name -(`simplecadapi`); unrelated directories cannot be overwritten. - -## Quick Start - -A model is a [marimo](https://marimo.io) notebook: a plain `.py` file in your -repository, which stays the only source of truth. A `[tool.simplecadapi]` -table in its PEP 723 header names the product; each cell holds one -[feature block](docs/skill/references/discipline/feature-tree-convention.md) -and records its geometry automatically — no session or decorator boilerplate. - -```python -# bracket.py -# /// script -# requires-python = ">=3.10" -# dependencies = ["simplecadapi"] -# -# [tool.simplecadapi] -# id = "bracket" -# revision = "1.0.0" -# /// -import marimo - -app = marimo.App() - -with app.setup: - import simplecadapi as scad - - -@app.cell -def _(): - # ---- params: plate ---- - width = scad.var("width", 60.0, unit="mm") - return (width,) - - -@app.cell -def _(): - # ---- params: bore ---- - hole_radius = scad.var("hole_radius", 5.0, unit="mm") - return (hole_radius,) - - -@app.cell -def _(width): - # ---- feature: base-plate (build) ---- - base = scad.make_box_rsolid( - width=width, height=36.0, depth=8.0, bottom_face_center=(0.0, 0.0, 0.0) - ) - return (base,) - - -@app.cell -def _(base, hole_radius): - # ---- feature: bore-and-slot (subtract) ---- - _bore = scad.make_cylinder_rsolid( - radius=hole_radius, height=14.0, bottom_face_center=(0.0, 0.0, -3.0) - ) - _slot = scad.make_box_rsolid( - width=18.0, height=8.0, depth=14.0, bottom_face_center=(14.0, 0.0, -3.0) - ) - drilled = scad.cut_rsolid(base, _bore, _slot) - return (drilled,) - - -@app.cell -def _(drilled): - # ---- feature: boss (add) ---- - _boss = scad.make_cylinder_rsolid( - radius=8.0, height=7.0, bottom_face_center=(-18.0, 0.0, 8.0) - ) - bossed = scad.union_rsolid(drilled, _boss) - return (bossed,) - - -@app.cell -def _(bossed): - # ---- feature: role-tag (annotate) ---- - tagged = scad.apply_tag(shape=bossed, tag="role.demo.bracket") - return (tagged,) - - -@app.cell -def _(tagged): - bracket = scad.Part(part_id="bracket", body=tagged) - return (bracket,) - - -if __name__ == "__main__": - app.run() -``` - -The product is the top-level value whose id equals the notebook id. Edit the -notebook interactively, or run it headlessly with only `simplecadapi` -installed: - -```bash -marimo edit bracket.py # reactive editor -sca run bracket.py # run, print a JSON report -sca run bracket.py --set width=80 --out out/bracket.scadpkg -sca export out/bracket.scadpkg --output-dir out/exports # AP242 STEP, STL, OBJ -sca edit . # web editor over this directory of notebooks -``` - -`sca edit` (`pip install "simplecadapi[editor]"`) is the code-first editor -described above: the notebook's cells on the left, the live model in the -middle, a slider or toggle for every parameter (`# ---- params ----` cells; a -`# ui:` comment on the line picks the control), and your viewport picks written -back as `selected_*` selection cells. See -`docs/skill/references/docs/guides/notebook-runtime.md` and -`docs/skill/references/domains/editor-collaboration.md` (how an agent works with -what you picked and which cell you mean). - -## Notebook Runtime - -The same runtime runs a notebook in the marimo editor, under `sca run`, and -from Python with `simplecadapi.runtime.run_notebook()`. Headless runs cache -every cell, so a rerun only executes the cells whose code, inputs, local -modules, or child notebooks changed. `--set` overrides a top-level variable -(the cell that defines it is skipped, so group parameters into cells by what -changes together); the report lists each cell as `ran`, `cached`, or -`skipped`. - -Export and verification scripts are plain Python that load the product with -`run_notebook` and write packages from it: - -```python -from pathlib import Path - -import simplecadapi as scad -from simplecadapi.runtime import run_notebook - -out = Path("out") -run = run_notebook("bracket.py", overrides={"width": 80.0}) -print("volume", round(run.product.body.get_volume(), 3)) -print("tags", scad.list_tags(shape=run.product.body)) - -package = out / "bracket.scadpkg" -scad.capture(run.definition, package) -scad.exporter.export_product_package_to_step(package, out / "bracket.step") -scad.exporter.export_product_package_to_stl(package, out / "bracket.stl") -scad.exporter.export_product_package_to_obj(package, out / "bracket.obj") -``` - -The `.scadpkg` embeds the definition closure, evaluated scene, feature -graphs, source snapshots, topology, and render/selection assets. It is -generated for exchange and publishing, never read back as model input. - -### Composing notebooks - -An assembly notebook brings in other notebooks with `scad.use`. A relative -path is relative to the calling notebook, and keyword arguments override the -child's top-level variables: - -```python -@app.cell -def _(): - bracket = scad.use("bracket.py", width=80.0) - return (bracket,) - - -@app.cell -def _(bracket): - rig = scad.make_assembly_rassembly(assembly_id="rig", name="Rig") - rig = scad.add_component_rassembly( - assembly=rig, item=bracket, component_id="bracket", - placement=scad.identity_placement_rplacement(), - ) - return (rig,) -``` - -One notebook can describe a part family — parts that differ only in their -parameters, such as the links of a linkage. Its product takes -`part_id=scad.notebook_id()`, and each use names its member: -`scad.use("link_bar.py", id="crank", center_distance=40.0)` (or -`sca run link_bar.py --id crank`). Each member is one definition with its own -content hash and cell cache. - -`@scad.part` / `@scad.assemble` remain for reusable library builders in plain -modules next to the notebooks; cells call them and take `.value`. See the -[notebook runtime and product build workflow](docs/skill/references/docs/guides/notebook-runtime.md) -for the project layout, the cell cache, and downstream targets. - -### Migrating from `@scad.part` scripts - -The script-anchored part cache of 2.1.2 (the `cache=` builder option, the -`.simplecad` cache directories, and the incremental assembly report) is -removed; the cell is now the unit of caching. - -- Move each part into a notebook: its parameters into params cells, each FTC - block into a cell of its own (each cell binds a new name), and the final - `scad.Part(...)` / assembly into the last cell. -- Replace `main.py` entry points that build and export as a side effect with - export scripts that call `run_notebook` and `scad.capture`. -- Replace direct builder calls between products with `scad.use(...)`; keep - `@scad.part` builders only for library parts called from cells. -- Add `__marimo__/` (generated runtime state) to `.gitignore`. - -### Command-line product export - -Export the standard delivery set (AP242 STEP, binary STL, and OBJ) from a -validated product package with no wrapper script: - -```bash -uv run sca export out/bracket.scadpkg --output-dir out/exports -``` - -Request additional targets explicitly. FCStd requires `FreeCADCmd` (or an -explicit `--freecad-cmd` path); `--check` validates the package, output paths, -and selected target prerequisites without writing files. - -```bash -uv run sca export out/bracket.scadpkg \ - --format fcstd --format mjcf --output-dir out/exports --check -uv run sca export out/bracket.scadpkg \ - --format fcstd --freecad-cmd /path/to/FreeCADCmd --output-dir out/exports -``` - -STL and OBJ share one direct OpenCASCADE tessellation of the evaluated BREP. -Both outputs contain the same oriented triangles and require no optional -remeshing dependency. Control curved-surface accuracy with `linear_deflection` -and `angular_deflection_degrees`. - -## Replayable Operation Graphs - -Use an explicit `GraphSession` when a geometry flow outside a notebook should -be inspectable, serializable, or replayable. - -```python -import simplecadapi as scad -from simplecadapi import GraphSession, export_model_json, replay_model_json -from simplecadapi import ql as Q - -with GraphSession(graph_id="chamfered_block") as session: - body = scad.make_box_rsolid( - width=40.0, height=24.0, depth=10.0, - bottom_face_center=(0.0, 0.0, 0.0), - ) - cutter = scad.make_cylinder_rsolid( - radius=4.0, height=16.0, bottom_face_center=(0.0, 0.0, -3.0) - ) - drilled = scad.cut_rsolid(body, cutter) - - bottom_circle = ( - Q.edges() - .where(Q.curve_type(kind="circle")) - .order_by(Q.center_axis(axis="z")) - .take(1) - .exactly(1) - ) - final = scad.chamfer_rsolid(solid=drilled, edges=bottom_circle, distance=0.6) - session.capture_result(value=final) - model_json = export_model_json(session=session) - recorded_nodes = session.graph.node_count - -rebuilt = replay_model_json(json_str=model_json) -print("recorded_nodes", recorded_nodes) -print("replayed_outputs", len(rebuilt)) -``` - -An explicit `GraphSession` is for inspection, serialization, and replay -outside a notebook; notebook cells already record into sessions of their own, -so do not open one there. It stays in memory until an export API is called. -A durable CAD/viewer deliverable is a notebook product captured to -`.scadpkg` (see [Notebook Runtime](#notebook-runtime)). - -## STEP/BREP Inspection - -Synchronized STEP views, highlighted regions and slice overlays need nothing -beyond `pip install simplecadapi`: they are drawn by the built-in software -renderer (no GPU, no display server, no VTK). Only the engineering-drawing -family (`simplecadapi.inspect.drawing`) needs the `drawing` extra. - -Inspection lives under `simplecadapi.inspect.brep`. These APIs are diagnostic -tools, not modeling operations: they do not enter the graph and are rejected -inside `GraphSession`. Export or obtain the geometry first, then -inspect it outside the modeling script. - -Choose calls from the evidence required by the case instead of following a -fixed reverse-engineering pipeline. Start with bounded global and local facts; -add sections, component renders, boundary distance, material difference, or -strict topology comparison only when those facts answer the current question. - -```python -from simplecadapi.inspect import brep - -summary = brep.inspect_step_rsummary( - path="target.step", - include_parameter_groups=True, -) -face = brep.inspect_step_entity_rdescriptor( - path="target.step", - entity_id="face:0", -) - -print("faces", summary["face_count"]) -print("carrier", face["geometry"]["type"]) -``` - -Use the [Reconstruction Agent test specification](docs/skill/references/docs/guides/reconstruction-agent-test-prompt.md) -for controlled runs and the [STEP reconstruction workflow](docs/skill/references/workflows/step-reconstruction.md) -for the inspection primitives, modeling loop, replay checks, and acceptance gates. - -## Physical Units And Tolerances - -Declare nominal and manufacturing-tolerance units at the variable boundary. -SimpleCAD evaluates lengths in millimeters and angles in degrees while preserving -the declaration units in model JSON: - -```python -import simplecadapi as scad - -width = scad.var( - "width", - 1.0, - unit="in", - tolerance=0.1, - tolerance_unit="mm", -) -height = scad.var("height", 40.0, unit="mm", tolerance=0.2) -diagonal = scad.sqrt(width**2 + height**2) - -analysis = scad.analyze_tolerance(diagonal) -check = scad.check_tolerance(diagonal, 0.3, tolerance_unit="mm") - -print(analysis.dimension.name, analysis.unit.symbol) -print(analysis.nominal, analysis.lower_bound, analysis.upper_bound) -print("passes", check.passed) -``` - -Addition and subtraction require matching dimensions. Multiplication, division, -integer powers, and square root derive dimensions. Trigonometric functions require -angle or dimensionless inputs as appropriate. Legacy variables without `unit` -remain supported, but cannot be mixed with unit-declared variables in one -expression. - -## Modeling Mental Model - -- Start from design intent: reference axes, critical profiles, and the features - that produce the final solid. -- Build from lower-dimensional geometry to higher-dimensional geometry: profile - wires/faces first, then solid features such as extrude, revolve, loft, and - sweep. -- Keep operations functional. Create new values with public functions such as - `make_rectangle_rface(...)`, `extrude_rsolid(...)`, `cut_rsolid(...)`, and - `fillet_rsolid(...)`. -- Use tags for semantic intent and selection anchors, for example - `role.mounting.surface`, `anchor.datum.primary`, or `group.fasteners`. -- Store numeric and geometric facts in metadata or graph payloads, not in tags. -- Use QL to ground selections by geometry facts rather than relying on topology - iteration order. -- When an indexed topology pick is intentional, pass the index to the plural - child-geometry getter, such as `get_edges(index)`, `get_faces(index)`, - `get_wires(index)`, or `get_vertices(index)`, so replayable graph workflows - preserve the pick as a geo select node. - -Use model JSON only for graph replay and inspection. External CAD translation and -file export consume the validated `.scadpkg` closure: - -```python -script = scad.translator.freecad_translator.translate_product_package_to_freecad_script( - package_path -) -scad.translator.freecad_translator.translate_product_package_to_fcstd( - package_path, "bracket.FCStd" -) -``` - -Part/Assembly models are written as editable FreeCAD assembly structure: parts are -`App::Part`, assemblies are `Assembly::AssemblyObject`, and components are links. -The exporter namespace owns neutral STEP and STL file output. - -## Examples - -Every example is a self-contained folder: part and assembly notebooks, the -plain modules they import, export and verification scripts, and fresh -artifacts under `examples//out/`. The set covers part modeling, -assemblies, reverse engineering, and FEM — see the category index in -[`examples/README.md`](examples/README.md). - -```bash -# part (quickstart FTC notebook, external verification script included) -marimo edit examples/flange_plate/flange_plate.py -uv run python examples/flange_plate/verify.py - -# assembly (two-stage planetary reducer: part-family notebooks, MJCF export) -sca run examples/compact_two_stage_planetary_reducer/compact_two_stage_planetary_reducer.py -uv run python examples/compact_two_stage_planetary_reducer/export_mjcf.py - -# Gmsh volume mesh (AP242 STEP -> volume mesh) -uv run python examples/ap242_gmsh_volume_mesh/export_step.py -uv run --extra gmsh python examples/ap242_gmsh_volume_mesh/export_fem_mesh.py -``` - -To try the editor on a real model, `sca example u_link` copies a motor mount -(two part notebooks and the assembly that fixes them) out of the package, and -`sca edit u_link_motor_mount` opens it; from a checkout, -`sca edit examples/u_link_motor_mount`. Reconstructing a STEP file (see -`examples/bowl_connector/`) is driven by the agent through the inspection API -and the [STEP reconstruction workflow](docs/skill/references/workflows/step-reconstruction.md). - -## Documentation - -- 2.2.7 update notes: [`docs/updates/2.2.7.md`](docs/updates/2.2.7.md) -- 2.2.7b1 update notes: [`docs/updates/2.2.7b1.md`](docs/updates/2.2.7b1.md) -- 2.2.6.post2 update notes: [`docs/updates/2.2.6.post2.md`](docs/updates/2.2.6.post2.md) -- 2.2.6.post1 update notes: [`docs/updates/2.2.6.post1.md`](docs/updates/2.2.6.post1.md) -- 2.2.6 update notes: [`docs/updates/2.2.6.md`](docs/updates/2.2.6.md) -- 2.2.5 update notes: [`docs/updates/2.2.5.md`](docs/updates/2.2.5.md) -- 2.2.4 update notes: [`docs/updates/2.2.4.md`](docs/updates/2.2.4.md) -- 2.2.3 update notes: [`docs/updates/2.2.3.md`](docs/updates/2.2.3.md) -- 2.2.2 update notes: [`docs/updates/2.2.2.md`](docs/updates/2.2.2.md) -- 2.2.1 update notes: [`docs/updates/2.2.1.md`](docs/updates/2.2.1.md) -- 2.1.3b1 update notes: [`docs/updates/2.1.3b1.md`](docs/updates/2.1.3b1.md) -- 2.1.2 update notes: [`docs/updates/2.1.2.md`](docs/updates/2.1.2.md) -- 2.1.1 update notes: [`docs/updates/2.1.1.md`](docs/updates/2.1.1.md) -- 2.1.0 update notes: [`docs/updates/2.1.0.md`](docs/updates/2.1.0.md) -- Reconstruction Agent test specification: - [`docs/skill/references/docs/guides/reconstruction-agent-test-prompt.md`](docs/skill/references/docs/guides/reconstruction-agent-test-prompt.md) -- Landing script for agents: [`docs/landing.md`](docs/landing.md) -- Editor collaboration (selection, cell references, parameters): - [`docs/skill/references/domains/editor-collaboration.md`](docs/skill/references/domains/editor-collaboration.md) -- STEP reconstruction workflow: - [`docs/skill/references/workflows/step-reconstruction.md`](docs/skill/references/workflows/step-reconstruction.md) -- Notebook runtime and product build workflow: - [`docs/skill/references/docs/guides/notebook-runtime.md`](docs/skill/references/docs/guides/notebook-runtime.md) -- Public API reference: [`docs/skill/references/docs/api/`](docs/skill/references/docs/api/) -- Core type and modeling notes: [`docs/skill/references/docs/core/`](docs/skill/references/docs/core/) -- Serialization and replay details: - [`docs/skill/references/docs/core/serialization/README.md`](docs/skill/references/docs/core/serialization/README.md) -- Dimension tolerance chains: - [`docs/core/dimension-tolerance-chains.md`](docs/skill/references/docs/core/dimension-tolerance-chains.md) -- Physical units and dimension inference: - [`docs/core/physical-units.md`](docs/skill/references/docs/core/physical-units.md) -- Operation graph JSON spec: - [`docs/core/operation_graph_json_spec.md`](docs/skill/references/docs/core/operation_graph_json_spec.md) -- `.scadpkg` package format: - [`docs/skill/references/scadpkg-format.md`](docs/skill/references/scadpkg-format.md) - -## Releasing the Agent Skill - -The skill source tree lives under `docs/skill/` and stays harness-neutral. -`tools/skillbuild.py` wraps the same compiler the `sca skill` CLI uses, for -maintainer builds in this repository: it compiles per harness target (targets -and default output directories are configured in `skillproj.toml`; the outputs -under `skills/simplecadapi-*/` are regenerable build artifacts and are not -committed). Harness-specific text, when it is ever needed, is marked with -`` conditional blocks that compile per target. The wheel -itself never contains precompiled targets — end users install from the -bundled source with `sca skill install`. - -From a clean checkout, update the project version and documentation, then -build and validate the release artifacts: - -```bash -uv sync --group dev -uv run python tools/auto_docs_gen.py --quiet -uv run python tools/skillbuild.py --target omp -uv run pytest test/test_skill_build.py -tar -C skills -czf skills/simplecadapi.tar.gz simplecadapi-omp -``` - -The commands regenerate the API references inside the skill tree, recompile -the omp target, and create `skills/simplecadapi.tar.gz`. Review the source -tree and the compiled output before release: - -```bash -git diff -- docs/skill -tar -tzf skills/simplecadapi.tar.gz | head -``` - -Commit only the `docs/skill/` source tree; the release workflow builds the -harness outputs and uploads the archive to the GitHub release. Prefer -`sca skill` for installation from a pip-installed package. - -## Development - -```bash -uv sync --group dev -uv run python -m pytest test tests -python3 -m compileall src/simplecadapi -``` - -## License - -Apache-2.0, see [`LICENSE`](LICENSE). - -## Community - -The group chat currently has too many members for direct QR-code joining. Scan the QR code below to add Teacher Du Peng on WeChat, then ask him for an invitation to the CADDesigner technical community: - -

- Teacher Du Peng's personal WeChat QR code -

- -## Star History - - - - - - Star History Chart - - +Apache-2.0. Validate generated models before production use. diff --git a/README.zh-CN.md b/README.zh-CN.md index 651de4dc..80608637 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -2,9 +2,11 @@ SimpleCADAPI 仓库封面

-# SimpleCADAPI +

SimpleCADAPI

-[English](README.md) +

为 Agent 而生的参数化 CAD。
高效率 · 低开销 · Agent Native

+ +

English · 更新日志 · Skill 设计 · 论文

**从这里开始。** 把下面这句话发给你的 coding agent(Claude Code、Codex、OpenCode 等): @@ -12,639 +14,135 @@ Read physpace.dev/sca/landing.md and landing me on this sdk. ``` -它会帮你安装 SDK、为自己安装 skill、在 code-first 编辑器里打开一个真实示例,并 -教你怎么和它一起工作。SimpleCADAPI 是为 agent 设计的参数化 CAD SDK:模型就是一个 -代码 notebook,每个尺寸都是命名参数,按“几何是什么”来选择对象,每一步都会反馈 -成功或失败的原因。 +它会帮你安装 SDK、为自己安装 skill、在编辑器里打开一个真实示例,并教你怎么和它一起工作。 + +--- + +## 理念 + +CAD 软件是为握着鼠标的人做的。Agent 没有鼠标,它只有代码、上下文窗口和 Token 账单。 +SimpleCADAPI 从这一点出发。 + +| | | +| --- | --- | +| **高效率** | 一次尝试就做对的更多,花的 Token 更少。改一个参数,只有依赖它的单元会重新运行。 | +| **低开销** | 一条 `pip install`:几何引擎是 wheel 里的原生 C++(基于 OpenCASCADE),没有 CadQuery 或 OCP 那一整套依赖。函数式 API、没有隐藏状态,每一步都是可以缓存、检查、重放的单元。Skill 让 agent 一批读完所需内容,而不是读二十次。 | +| **Agent Native** | 报错会说清发生了什么、给出带单位的实测数值、告诉你怎么修。按“几何是什么”选择对象(`ql`、稳定的 `scad.ref`),而不是靠会漂移的序号。每次调用都被记录成可重放的图。编辑器把你点选的内容写进 notebook,agent 直接从文件里读到你的选择。 | + +## 数据 + +**对 CadQuery。** 同一个模型、同一套提示词、同样 200 个真实零件,各只试一次。由独立且已冻结的评分器,把每个结果与原件比对。 + +

同一模型、同一提示词、200 个零件:SimpleCADAPI 交付的严重失真模型比 CadQuery 少 3.5 倍

+ +DeepSeek-V4.1-Flash,SimpleCADAPI 2.2.7b1 对 CadQuery 2.8.0,来自 27 个项目的 200 个开源硬件零件。“严重失真”指已交付、但 1 mm 阈值下表面 F1 低于 99.99 % 的模型。报告中已披露:SimpleCADAPI 一组另有 STEP 逆向重建的工作流文档,CadQuery 一组用的是通用的第三方 CadQuery skill;零件以简单件为主(面数中位数 19)。 + +**对某成熟工业软件。** 每个任务消耗的 Token;该工业软件通过其 MCP 服务驱动。 + +

每个任务消耗的 Token:SimpleCADAPI 比某成熟工业软件(经其 MCP)最多少 6.5 倍

## 它能做什么 -四块能力支柱。下面每个 case 都是**真实、可复现的会话**:回放 demo 是单文件离线 -HTML,忠实回放完整录制的对话(用户输入、Agent 思考、每一次工具调用与补丁、角色 -切换),旁边就是导出的 3D 模型 —— 浏览器直接打开即可。 +两台六轴机械臂,都是由零件 notebook 通过 `scad.use` 组合出来的装配体。每个关节角和连杆长度都是命名参数:拖动滑块,模型跟着动。 -### 1 · 单零件建模 +

SimpleCADAPI 编辑器里的 SG90 六轴机械臂:左侧是 notebook 单元和关节滑块,右侧是实时装配体

-以可读的[特征树规约](docs/skill/references/discipline/feature-tree-convention.md) -特征块编写参数化零件 —— 带单位的命名参数、验证先行的分阶段建模、改参后仍然命中的 -确定性面标签,以及同步产出的 `.scadpkg` / STEP AP242 / STL / 可编辑 FreeCAD 工程。 +**SG90 教学机械臂** · 34 个零件,六个转动关节作为约束被求解,连杆可 3D 打印,为电子元件预留了空间。`sg90_arm_6dof.py` - - - - - - - - - - - - - - - - - - - - - -
案例首轮需求(prompt 节选)交付模型 · BRep 旋转展示
机械臂 U 形连杆 + 电机安装槽
15 轮用户输入 · 601 次工具调用
▶ 完整会话回放
“构建参数化的机械臂连杆,能适应长度变化、通用安装电机:圆形 profile 沿『下 D → 右 L → 上 D』扫掠成 U 形;两侧圆珠 boolean cut 切出电机安装槽,安装面必须有确定命名、可被查询语言索引;底部圆柱切成半圆柱;然后全局倒角平滑。”u_link 旋转展示
参数化法兰盘
2 轮用户输入 · 66 次工具调用
▶ 完整会话回放
“参数化法兰盘:外径 100、厚 10、凸台 ⌀55 顶高 30、中心孔 ⌀30、6×⌀11 螺栓孔 @PCD 78、根部 R3 / 外缘 R2 圆角;所有尺寸走命名参数;每次圆角前打印选边卡;参数可行性守卫;一个 feature 一个块。”

GIF 为终态 8 孔 @PCD 84.5:第 2 轮改参 6→8 孔,PCD 88 被守卫当场拒绝、85 因圆角相切排除。
法兰旋转展示
筋板 L 形支架(FEM 主模型)
2 轮用户输入 · 49 次工具调用
▶ 完整会话回放
“把已有的 L 形直角连接件 legacy 脚本按 single-part-modeling 工作流正式化:FTC 特征块 + 命名参数重建;与旧版几何等价(体积偏差 < 0.1%);interface.* FEM 边界标签必须原样保留——下游 Gmsh/CalculiX 按标签选面。”支架旋转展示
+

SimpleCADAPI 编辑器里带夹爪的桌面六轴机械臂

-旋转展示使用 BRep 着色加宽边线渲染;转一整圈 = 48 个确定性方位角步进。 +**带夹爪的桌面六轴机械臂** · 34 个零件。关节电机是带真实安装接口的采购件(机体 34 × 20 × 19.6 mm,Ø10.5 圆周上六个 M2 孔),连杆上开有对应的腔体、螺钉通道和插接窗口。`arm6.py` -### 2 · 装配体建模 +编辑器 `sca edit` 是代码优先的:左边是单元,右边是实时模型,每个参数都有滑块。点选实体、面、边或顶点,它就把一条选择写进 notebook。Agent 从文件里读到你选了什么,所以“把这两条边倒角”不需要任何 id。编辑器和 `sca run` 共用同一个运行时和同一份逐单元缓存;在六轴臂上,见过的关节角 0.6 秒重新渲染,新角度 2.7 秒(2.2.7)。 -嵌套持久装配体 + 显式运动学:齿轮啮合、转动副、轴承接口都是被求解的约束,不是目测 -摆放。标准件 —— 渐开线齿轮、带滚珠的轴承子装配、滚子链轮、真实牙型公制紧固件 —— -全部来自 `scad.std.*`,组合成机构后可导出 STEP、可编辑 FreeCAD 工程和面向物理引擎 -的 MJCF。 +## Skill - - - - - -
-BLDC 关节执行器装配态
-一体化 BLDC 关节执行器 —— 装配态(影棚渲染)
-29 个组件 · 51 条约束全部解算 · 两级行星减速 20:1 -
-BLDC 关节执行器爆炸旋转
-同一模型 —— 爆炸旋转展示:四个模块(电调 · 电机 ·
-双级减速器 · 输出轴)沿轴向分离,模块内同心零件按半径
-分层剥离;相机沿倾斜圆轨道环绕 -
+Skill 是 agent 学会使用 SDK 的方式。它是一个路由页加一批小页面,写成让 agent 恰好读到一步所需的内容,并且一批并行读完。 -复现方式:模型是装配 notebook `integrated_bldc_joint_actuator.py`,用 -`scad.use` 组合各零件与子装配 notebook。 -`uv run python examples/integrated_bldc_joint_actuator/export_all.py` 导出装配包和 -STEP / 可编辑 FCStd / MJCF;`render_showcase.py` 渲染上述视图。 +**能做什么** —— 七条路线,每条都是带自检的完整工作流: -### 3 · Code-first 编辑器 +| 你要 | 路线 | +| --- | --- | +| 建一个实体零件 | 单零件建模:需求 → 规划 → 构建 → 验证 | +| 建多零件产品或机构 | 装配:连接器、约束、运动学、标准件 | +| 从 STEP 文件重建可编辑模型 | STEP 逆向重建,稳定实体 id 与验收门 | +| 从网格、点云或照片重建 | 扫描重建 | +| 从矢量 PDF 图纸重建 | 图纸重建 | +| 出国标工程图(DXF) | 由已验证的几何生成工程图 | +| 把模型交给别人 | 导出与转译:STEP AP242、STL、FreeCAD、MJCF | -`sca edit` 在浏览器里打开一个面向“与 agent 协作”的编辑器,作用于一个 notebook -目录。左边是 notebook 的 cell,中间是实时模型,每个参数都有滑块或开关。点选实体、 -面、边或顶点后,编辑器会把一个 `scad.ql` 选择 cell 写进 notebook 文件(自动保存), -你的 coding agent 直接从磁盘读到你选了什么,“给这两条边倒角”不需要任何 id。复制 -cell 引用就能告诉 agent 要改哪个 cell。底部日志面板显示哪些 cell 正在重算。编辑器 -与 `sca run` 共用同一个运行时和同一份逐 cell 缓存。 +**怎么组织** - - - - -
-sca edit 打开 u_link 电机座:选中的面、编辑器写出的选择 cell 及其属性
-sca edit 中的 u_link 电机座 —— 选中的圆柱面、编辑器为它写出的 -selected_face cell,以及它的属性; -sca example u_link 可把这个工作区复制出来 -
+```text +SKILL.md 路由:选一条路线,读它的那一批页面(≤ 130 行) +workflows/ 每条路线一个生命周期;角色与阶段在开始时才加载 +domains/ 某类任务上 SDK 提供什么 +discipline/ 规则与不变量:核心规则、特征顺序、验证脚本、失败与修复 +docs/api · stdlib · core 400+ 页自动生成的签名;没有页面的方法就不存在 +``` -### 4 · 仿真插件 +- **阅读预算很小。** 任何路线的第一批最多 1,200 行;每页只做一件事,每条规则只有一个家。构建检查会在页面违反约定时让 skill 构建失败。 +- **两种模式。** 每个工作流都分交互式(有人可以回答)和无人值守(没人回答)。模式改变的是谁来决定,而不是检查什么。 +- **一份源码,七个 harness。** 同一批页面可编译给 Claude Code、Codex、OpenCode、ZCode、OMP、DSH 和 Kimi Code。 -同一份参数化包直接喂给下游求解器,无需人工返工:AP242 STEP 进 Gmsh 体网格 + -CalculiX 静力 FEM(边界面按保真的 `interface.*` 标签选取,仿真链在模型改版后依然 -成立),MJCF 进 MuJoCo 做机构动力学——仿真环境里的虚拟碰撞检查会暴露装配干涉, -驱动修正,直到机构全程干净运动。 +```bash +sca skill targets # 支持的 harness +sca skill install # 为你的 harness 编译并安装 +``` + +## 插件 + +建模是 SDK 的事。对建好的模型做检查、仿真、转译,属于插件;一个插件就是一个仓库: + +```text +sca-addon.toml 可机器检查的事实:名称、版本、兼容的 SDK 版本、如何准备运行环境 +skill/SKILL.md agent 读到的关于它的一切 +... 它自己的代码、二进制和文档,任何语言都行 +``` + +```bash +sca addon add owner/repo # 从 GitHub 安装;owner/repo@v1.2.0 锁定标签 +sca addon add ./my-addon # 本地目录 +sca addon list # 已装了什么,运行环境是否可用 +sca addon update # 重新拉取;代码被替换,运行时状态保留 +``` + +- **装上即会用。** 插件的 skill 会以 `sca-<名字>` 装在 SDK 的 skill 旁边,agent 同时得到能力和使用说明。 +- **天然隔离。** 插件通过进程边界读取 `.scadpkg` 产品包,在自己的环境里运行,因此插件的依赖不会碰到做几何建模的那套环境。 +- **已经在用。** 连接器验证(螺栓、销、过盈、焊接等连接,先检查再送入有限元)和有限元网格预处理(移除紧固件、补上它们的孔、证明闭合)都是插件。下面的 AP242 → Gmsh → CalculiX 与 MJCF → MuJoCo 两条链路,用的是同一个产品包。
-支架 FEM von Mises 云图
-L 形支架静力 FEM —— CalculiX von Mises 云图
-经 Gmsh OpenCASCADE 内核从 AP242 导出体网格 +支架有限元 von Mises
+L 形支架静力有限元
AP242 导出经 Gmsh 划分网格,CalculiX 算出 von Mises;边界面由模型改动后仍保留的 interface.* 标签选取
-MuJoCo 中四连杆相互碰撞贯穿
-四连杆 + MuJoCo —— 首次装配:连杆在运动中撞在一起,装配不对 · -▶ 完整视频 +MuJoCo 里四连杆互相穿过
+四连杆,第一版
MuJoCo 里连杆互相穿过:装配是错的
-修正后的四连杆在 MuJoCo 中全程干净运动
-虚拟碰撞修正后 —— 同一仿真环境,修正后的装配全程干净运动 · -▶ 完整视频 +修正后的四连杆装配在 MuJoCo 里运行
+碰撞修正之后
同一个曲柄周期,干净地转完
---- - -## 更新日志(2.2.7) - -> 投入生产前请验证生成的定义、装配约束和制造几何。 - -- **C++ 引擎的第一个正式版**,随预编译 wheel 发布(Linux x86_64 与 aarch64、macOS arm64 14+、Windows x86_64; - Python 3.10-3.13;统一使用 OpenCASCADE 7.9.3)。`pip install simplecadapi` 不再需要 `cadquery-ocp`。 -- **编辑器更快。** 六轴机械臂上一个没见过的关节角 2.7 s(beta 是 5.7 s),见过的 0.6 s(beta 是 5.5 s), - 模型在最后一个 cell 之后 0.36-0.41 s 到达页面。内核空闲时比 beta 多用约 300 MB 内存。 -- **`Var` 和 `Expr` 像数字一样工作**:`r > 3`、`int(r)`、`round(r, 2)`、`range(n)`、`max(r, 3)`、f-string 可用, - 用 `Var` 算出的值写 ql 谓词也能匹配。`bool(var)` 和 `json.dumps(var)` 仍然报错。 -- **装了 OCP 时 `shape.wrapped` 是 OCP 形状**(`simplecadapi[verify]`),是拷贝,OCCT 验证脚本可以原样运行。 -- fillet、chamfer 和 ql 选择失败重新附带图片。保存了参数值的笔记本会重建一次。 - -本版本的完整说明:[`docs/updates/2.2.7.zh-CN.md`](docs/updates/2.2.7.zh-CN.md)。 -更早的版本:见[更新日志](CHANGELOG.md)和 [`docs/updates/`](docs/updates/)。 - ---- - -
-

SimpleCADAPI 论文成果

-

本仓库是以下论文工作的项目产物:

-

- CADIR: A Cross-Backend Editable Intermediate Representation for Agentic CAD Generation -

-

Computer-Aided Design 2026 接收

-
- ---- - -SimpleCADAPI 是一个基于 OCP 的 Python CAD SDK,提供清晰的函数式建模操作和可重放的模型图。它在 OpenCascade 几何内核之上提供精简的公共 API,可用于创建实体、应用特征、添加语义标签、查询拓扑、导出制造文件,以及将记录的模型转换为 FreeCAD 工作流。 - -当前版本:`simplecadapi==2.2.7`。 - -## 核心能力 - -- 模型即 [marimo](https://marimo.io) notebook:普通 `.py` 文件就是唯一的真相 - 来源,一个 cell 一个特征,按 cell 缓存实现增量无头运行(`sca run`),并可用 - `scad.use` 组合 notebook。 -- Code-first 网页编辑器 `sca edit`:实时模型、参数控件,视口点选写回为选择代码, - 为与 agent 协作而设计。 -- 由 notebook 生成的规范 `.scadpkg` 产品包,用于交换和发布,不会反过来作为模型 - 输入。 -- 基于 OCP 的 `Vertex`、`Edge`、`Wire`、`Face` 和 `Solid` 类型。 -- 支持基本体、轮廓、拉伸、旋转、放样、扫掠、布尔运算、变换、阵列、圆角、倒角和抽壳等函数式建模操作。 -- 通过显式 `GraphSession`、`export_model_json(...)`、`import_model_json(...)` 和 `replay_model_json(...)` 记录并重放操作图。 -- 通过 `var(...)`、算术表达式和可序列化表达式图定义参数。 -- 使用 QL 选择器定位几何、查询拓扑并稳定选择特征。 -- 通过 `apply_tag(shape=..., tag=...)` 和 `list_tags(shape=...)` 管理语义标签。 -- 支持 STEP/STL/OBJ 导出、可编辑 FreeCAD 产品包转换,以及带材料和命名元数据 - 属性的 AP242 产品结构导出。 -- 面向 Agent 的 STEP/BREP 逆向能力,提供稳定实体 ID、局部诊断、区域高亮截图和 - 可测量的验收门槛。 -- 可回放的开放/周期插值 B 样条 Edge 和 Wire,可用于自由轮廓与 Loft 截面。 - ## 安装 -最快的方式是页面顶部那句话:发给你的 coding agent,剩下的它来做。 - -手动安装,使用 pip: - ```bash -pip install simplecadapi +pip install "simplecadapi[editor]" # SDK 和编辑器 +sca example u_link # 一个可以直接打开的真实工作区 +sca edit u_link # 编辑器 +sca skill install # 给你的 agent 装 skill ``` -代码优先编辑器(`sca edit`)需要 `editor` extra:`pip install "simplecadapi[editor]"`; -`uv tool install "simplecadapi[editor]"` 或 `pipx install "simplecadapi[editor]"` -不用虚拟环境就能把 `sca` 放进 PATH。`sca example u_link` 把内置示例工作区复制出来, -再用 `sca edit` 打开。 +Python 3.10–3.13,Linux、macOS 和 Windows。`uv tool install "simplecadapi[editor]"` 不需要虚拟环境就能把 `sca` 放进 PATH。`sca run model.py` 无界面运行 notebook;`sca export` 导出 STEP、STL 和 OBJ。 -使用 uv: +## 研究 artifact -```bash -uv add simplecadapi -``` +本仓库是 [**CADIR: A Cross-Backend Editable Intermediate Representation for Agentic CAD Generation**](https://arxiv.org/abs/2608.00891) 的 artifact。 -从本仓库进行本地开发: - -```bash -uv sync --group dev -``` - -### Agent Skill - -pip 安装完成后,为你的 agent harness 安装内置 skill: - -```bash -sca skill targets -# 默认位置(~/.agents/skills),或显式指定 ZCode 的 skills 目录: -sca skill install --target zcode --skills-dir ~/.zcode/skills -``` - -`targets` 列出可用的 harness 目标。`install` 编译内置源码并写入 -`/simplecadapi`;不传 `--skills-dir` 时,沿用既有 addon 配置/ -环境解析,默认回退到 `~/.agents/skills`,不要求先执行 `sca init`。wheel -内置的是未编译的 `docs/skill/` 源树和 `skillproj.toml` 资源,编译发生在 -安装时机;无需 checkout 本仓库。使用 `uv` 时,上述命令前缀 `uv run`。 - -`install` 在目标位置已存在时报错。加 `--force` 允许替换,但仅限 -`SKILL.md` 声明了同名 skill(`simplecadapi`)的目录;无关目录不会被覆盖。 - -## 快速开始 - -模型是一个 [marimo](https://marimo.io) notebook:仓库里的一个普通 `.py` 文件, -它始终是唯一的真相来源。PEP 723 头部的 `[tool.simplecadapi]` 表声明产品;每个 -cell 放一个[特征块](docs/skill/references/discipline/feature-tree-convention.md), -几何会被自动记录——不需要 session 或装饰器样板代码。 - -```python -# bracket.py -# /// script -# requires-python = ">=3.10" -# dependencies = ["simplecadapi"] -# -# [tool.simplecadapi] -# id = "bracket" -# revision = "1.0.0" -# /// -import marimo - -app = marimo.App() - -with app.setup: - import simplecadapi as scad - - -@app.cell -def _(): - # ---- params: plate ---- - width = scad.var("width", 60.0, unit="mm") - return (width,) - - -@app.cell -def _(): - # ---- params: bore ---- - hole_radius = scad.var("hole_radius", 5.0, unit="mm") - return (hole_radius,) - - -@app.cell -def _(width): - # ---- feature: base-plate (build) ---- - base = scad.make_box_rsolid( - width=width, height=36.0, depth=8.0, bottom_face_center=(0.0, 0.0, 0.0) - ) - return (base,) - - -@app.cell -def _(base, hole_radius): - # ---- feature: bore-and-slot (subtract) ---- - _bore = scad.make_cylinder_rsolid( - radius=hole_radius, height=14.0, bottom_face_center=(0.0, 0.0, -3.0) - ) - _slot = scad.make_box_rsolid( - width=18.0, height=8.0, depth=14.0, bottom_face_center=(14.0, 0.0, -3.0) - ) - drilled = scad.cut_rsolid(base, _bore, _slot) - return (drilled,) - - -@app.cell -def _(drilled): - # ---- feature: boss (add) ---- - _boss = scad.make_cylinder_rsolid( - radius=8.0, height=7.0, bottom_face_center=(-18.0, 0.0, 8.0) - ) - bossed = scad.union_rsolid(drilled, _boss) - return (bossed,) - - -@app.cell -def _(bossed): - # ---- feature: role-tag (annotate) ---- - tagged = scad.apply_tag(shape=bossed, tag="role.demo.bracket") - return (tagged,) - - -@app.cell -def _(tagged): - bracket = scad.Part(part_id="bracket", body=tagged) - return (bracket,) - - -if __name__ == "__main__": - app.run() -``` - -产品是 id 等于 notebook id 的那个顶层变量。可以在编辑器里交互修改,也可以只装 -`simplecadapi` 无头运行: - -```bash -marimo edit bracket.py # 响应式编辑器 -sca run bracket.py # 运行并输出 JSON 报告 -sca run bracket.py --set width=80 --out out/bracket.scadpkg -sca export out/bracket.scadpkg --output-dir out/exports # AP242 STEP、STL、OBJ -sca edit . # 这个目录 notebook 的网页编辑器 -``` - -`sca edit`(`pip install "simplecadapi[editor]"`)就是上面介绍的 code-first -编辑器:左边是 notebook 的 cell,中间是实时模型,每个参数一个滑块或开关 -(`# ---- params ----` cell;一行末尾的 `# ui:` 注释选择控件),视口点选写回为 -`selected_*` 选择 cell。详见 -`docs/skill/references/docs/guides/notebook-runtime.md` 和 -`docs/skill/references/domains/editor-collaboration.md`(agent 如何使用你的选择和 -指定的 cell)。 - -## Notebook 运行时 - -marimo 编辑器、`sca run` 和 Python 里的 `simplecadapi.runtime.run_notebook()` -用的是同一个运行时。无头运行会缓存每个 cell,重跑时只执行代码、输入文件、本地 -模块或子 notebook 发生变化的 cell。`--set` 覆盖一个顶层变量(定义它的 cell -不再运行,所以要按“一起变化”的原则把参数分进不同 cell);报告里每个 cell 的 -状态是 `ran`、`cached` 或 `skipped`。 - -导出和验证脚本是普通 Python 脚本,用 `run_notebook` 载入产品再写出产品包: - -```python -from pathlib import Path - -import simplecadapi as scad -from simplecadapi.runtime import run_notebook - -out = Path("out") -run = run_notebook("bracket.py", overrides={"width": 80.0}) -print("volume", round(run.product.body.get_volume(), 3)) -print("tags", scad.list_tags(shape=run.product.body)) - -package = out / "bracket.scadpkg" -scad.capture(run.definition, package) -scad.exporter.export_product_package_to_step(package, out / "bracket.step") -scad.exporter.export_product_package_to_stl(package, out / "bracket.stl") -scad.exporter.export_product_package_to_obj(package, out / "bracket.obj") -``` - -`.scadpkg` 包含完整定义闭包、求值场景、特征图、源码快照、拓扑以及渲染/选择 -资源。它由代码生成,只用于交换和发布,不会反过来作为模型输入。 - -### 组合 notebook - -装配 notebook 用 `scad.use` 引入其他 notebook。相对路径相对于调用方 notebook, -关键字参数覆盖子 notebook 的顶层变量: - -```python -@app.cell -def _(): - bracket = scad.use("bracket.py", width=80.0) - return (bracket,) - - -@app.cell -def _(bracket): - rig = scad.make_assembly_rassembly(assembly_id="rig", name="Rig") - rig = scad.add_component_rassembly( - assembly=rig, item=bracket, component_id="bracket", - placement=scad.identity_placement_rplacement(), - ) - return (rig,) -``` - -一个 notebook 可以描述一个零件族——只有参数不同的一组零件,比如连杆机构里的 -各根连杆。产品写成 `part_id=scad.notebook_id()`,每处使用时给成员起名: -`scad.use("link_bar.py", id="crank", center_distance=40.0)`(或 -`sca run link_bar.py --id crank`)。每个成员是一个独立定义,有自己的内容哈希和 -cell 缓存。 - -`@scad.part` / `@scad.assemble` 保留给放在 notebook 旁边普通模块里的可复用库 -构建函数;cell 调用它们并取 `.value`。工程目录结构、cell 缓存和下游格式见 -[Notebook 运行时与产品构建工作流](docs/skill/references/docs/guides/notebook-runtime.md)。 - -### 从 `@scad.part` 脚本迁移 - -2.1.2 的脚本锚定 part cache(构建函数的 `cache=` 选项、`.simplecad` 缓存目录和 -增量装配报告)已删除;现在缓存的单位是 cell。 - -- 每个零件搬进一个 notebook:参数放进 params cell,每个 FTC 块单独一个 cell - (每个 cell 绑定一个新名字),最后一个 cell 构建 `scad.Part(...)` 或装配体。 -- 用调用 `run_notebook` 和 `scad.capture` 的导出脚本,替换那些顺带构建并导出的 - `main.py` 入口。 -- 产品之间直接调用构建函数的地方改成 `scad.use(...)`;`@scad.part` 构建函数只 - 保留给在 cell 中调用的库零件。 -- 把 `__marimo__/`(生成的运行时状态)加入 `.gitignore`。 - -### 命令行产品导出 - -不写包装脚本,直接从经过验证的产品包导出标准交付集(AP242 STEP、二进制 STL -和 OBJ): - -```bash -uv run sca export out/bracket.scadpkg --output-dir out/exports -``` - -其他格式需显式指定。FCStd 需要 `FreeCADCmd`(或显式的 `--freecad-cmd` 路径); -`--check` 只校验产品包、输出路径和所选格式的前置条件,不写文件。 - -```bash -uv run sca export out/bracket.scadpkg \ - --format fcstd --format mjcf --output-dir out/exports --check -uv run sca export out/bracket.scadpkg \ - --format fcstd --freecad-cmd /path/to/FreeCADCmd --output-dir out/exports -``` - -STL 与 OBJ 共用 OpenCASCADE 对求值后 BREP 的直接三角化。两种格式包含相同的 -定向三角面,不再需要可选 remeshing 依赖。曲面精度由 `linear_deflection` 和 -`angular_deflection_degrees` 控制。 - -## 可重放操作图 - -notebook 之外的几何流程需要检查、序列化或重放时,使用显式 `GraphSession`: - -```python -import simplecadapi as scad -from simplecadapi import GraphSession, export_model_json, replay_model_json -from simplecadapi import ql as Q - -with GraphSession(graph_id="chamfered_block") as session: - body = scad.make_box_rsolid( - width=40.0, height=24.0, depth=10.0, - bottom_face_center=(0.0, 0.0, 0.0), - ) - cutter = scad.make_cylinder_rsolid( - radius=4.0, height=16.0, bottom_face_center=(0.0, 0.0, -3.0) - ) - drilled = scad.cut_rsolid(body, cutter) - - bottom_circle = ( - Q.edges() - .where(Q.curve_type(kind="circle")) - .order_by(Q.center_axis(axis="z")) - .take(1) - .exactly(1) - ) - final = scad.chamfer_rsolid(solid=drilled, edges=bottom_circle, distance=0.6) - session.capture_result(value=final) - model_json = export_model_json(session=session) - recorded_nodes = session.graph.node_count - -rebuilt = replay_model_json(json_str=model_json) -print("recorded_nodes", recorded_nodes) -print("replayed_outputs", len(rebuilt)) -``` - -显式 `GraphSession` 用于 notebook 之外的检查、序列化和重放;notebook 的每个 -cell 已经记录进各自的 session,不要在 cell 里再开一个。它在调用导出 API 前只 -存在于内存。持久的 CAD/Viewer 交付物是 notebook 产品捕获出的 `.scadpkg`(见 -[Notebook 运行时](#notebook-运行时))。 - -## STEP/BREP 检查 - -同步 STEP 视图、区域高亮和截面叠加不需要额外安装:`pip install simplecadapi` 即可,由内置软渲染绘制 -(不依赖 GPU、显示服务和 VTK)。只有工程图系列(`simplecadapi.inspect.drawing`)需要 `drawing` 额外依赖。 - -检查 API 位于 `simplecadapi.inspect.brep`。它们是诊断工具,不是建模操作:不进入 -操作图,在 `GraphSession` 内调用会被拒绝。先导出或拿到几何,再在建模脚本之外 -检查。 - -按当前问题需要的证据选择调用,而不是走固定的逆向流程。先取有界的全局和局部 -事实;只有这些事实回答得了当前问题时,才再加截面、组件渲染、边界距离、材料差集 -或严格拓扑比较。 - -```python -from simplecadapi.inspect import brep - -summary = brep.inspect_step_rsummary( - path="target.step", - include_parameter_groups=True, -) -face = brep.inspect_step_entity_rdescriptor( - path="target.step", - entity_id="face:0", -) - -print("faces", summary["face_count"]) -print("carrier", face["geometry"]["type"]) -``` - -受控测试请使用 [Reconstruction Agent 测试规范](docs/skill/references/docs/guides/reconstruction-agent-test-prompt.md), -检查原语、建模循环、回放检查和验收门槛请阅读 -[STEP 重建工作流](docs/skill/references/workflows/step-reconstruction.md)。 - -## FreeCAD 转换 - -外部 CAD 转换只接受经过验证的 `.scadpkg` 产品包: - -```python -package_path = "out/bracket.scadpkg" -script = scad.translator.freecad_translator.translate_product_package_to_freecad_script( - package_path -) -scad.translator.freecad_translator.translate_product_package_to_fcstd( - package_path, "out/bracket.FCStd" -) -``` - -Part/Assembly 模型写成可编辑的 FreeCAD 装配结构:零件是 `App::Part`,装配是 -`Assembly::AssemblyObject`,组件是链接。中性 STEP 与 STL 文件由 exporter 命名 -空间输出。 - -## 示例 - -每个示例都是一个自包含目录:零件和装配 notebook、它们导入的普通模块、导出与 -验证脚本,以及 `examples//out/` 下的新鲜产物。覆盖零件建模、装配、逆向 -工程和 FEM——分类索引见 [`examples/README.md`](examples/README.md)。 - -```bash -# 零件(快速入门 FTC notebook,附外部验证脚本) -marimo edit examples/flange_plate/flange_plate.py -uv run python examples/flange_plate/verify.py - -# 装配(两级行星减速器:零件族 notebook、MJCF 导出) -sca run examples/compact_two_stage_planetary_reducer/compact_two_stage_planetary_reducer.py -uv run python examples/compact_two_stage_planetary_reducer/export_mjcf.py - -# Gmsh 体网格(AP242 STEP -> 体网格) -uv run python examples/ap242_gmsh_volume_mesh/export_step.py -uv run --extra gmsh python examples/ap242_gmsh_volume_mesh/export_fem_mesh.py -``` - -想在真实模型上试用编辑器:`sca example u_link` 把一个电机座(两个零件 notebook 加 -把它们固定在一起的装配)从包里复制出来,`sca edit u_link_motor_mount` 打开它; -在源码仓库里则是 `sca edit examples/u_link_motor_mount`。重建 STEP 文件(见 -`examples/bowl_connector/`)由 agent 通过检查 API 和 -[STEP 重建工作流](docs/skill/references/workflows/step-reconstruction.md)驱动。 - -## 文档 - -- 2.2.7 更新说明:[`docs/updates/2.2.7.zh-CN.md`](docs/updates/2.2.7.zh-CN.md) -- 2.2.7b1 更新说明:[`docs/updates/2.2.7b1.zh-CN.md`](docs/updates/2.2.7b1.zh-CN.md) -- 2.2.6.post2 更新说明:[`docs/updates/2.2.6.post2.zh-CN.md`](docs/updates/2.2.6.post2.zh-CN.md) -- 2.2.6.post1 更新说明:[`docs/updates/2.2.6.post1.zh-CN.md`](docs/updates/2.2.6.post1.zh-CN.md) -- 2.2.6 更新说明:[`docs/updates/2.2.6.zh-CN.md`](docs/updates/2.2.6.zh-CN.md) -- 2.2.5 更新说明:[`docs/updates/2.2.5.zh-CN.md`](docs/updates/2.2.5.zh-CN.md) -- 2.2.4 更新说明:[`docs/updates/2.2.4.zh-CN.md`](docs/updates/2.2.4.zh-CN.md) -- 2.2.3 更新说明:[`docs/updates/2.2.3.zh-CN.md`](docs/updates/2.2.3.zh-CN.md) -- 2.2.2 更新说明:[`docs/updates/2.2.2.zh-CN.md`](docs/updates/2.2.2.zh-CN.md) -- 2.2.1 更新说明:[`docs/updates/2.2.1.zh-CN.md`](docs/updates/2.2.1.zh-CN.md) -- 2.1.3b1 更新说明:[`docs/updates/2.1.3b1.zh-CN.md`](docs/updates/2.1.3b1.zh-CN.md) -- 2.1.2 更新说明:[`docs/updates/2.1.2.zh-CN.md`](docs/updates/2.1.2.zh-CN.md) -- 2.1.1 更新说明:[`docs/updates/2.1.1.zh-CN.md`](docs/updates/2.1.1.zh-CN.md) -- 2.1.0 更新说明:[`docs/updates/2.1.0.zh-CN.md`](docs/updates/2.1.0.zh-CN.md) -- Reconstruction Agent 测试规范: - [`docs/guides/reconstruction-agent-test-prompt.md`](docs/skill/references/docs/guides/reconstruction-agent-test-prompt.md) -- Agent 落地脚本:[`docs/landing.md`](docs/landing.md) -- 编辑器协作(选择、cell 引用、参数): - [`docs/skill/references/domains/editor-collaboration.md`](docs/skill/references/domains/editor-collaboration.md) -- STEP 重建工作流: - [`docs/skill/references/workflows/step-reconstruction.md`](docs/skill/references/workflows/step-reconstruction.md) -- Notebook 运行时与产品构建工作流: - [`docs/guides/notebook-runtime.md`](docs/skill/references/docs/guides/notebook-runtime.md) -- 公共 API 参考:[`docs/api/`](docs/skill/references/docs/api/) -- 核心类型与建模说明:[`docs/core/`](docs/skill/references/docs/core/) -- 序列化与重放:[`docs/core/serialization/README.md`](docs/skill/references/docs/core/serialization/README.md) -- 操作图 JSON 规范:[`docs/core/operation_graph_json_spec.md`](docs/skill/references/docs/core/operation_graph_json_spec.md) -- 示例索引:[`examples/README.md`](examples/README.md) -- `.scadpkg` 产品包格式:[`docs/skill/references/scadpkg-format.md`](docs/skill/references/scadpkg-format.md) - -## 发布 Agent Skill - -skill 源树位于 `docs/skill/`,保持 harness 中立。`tools/skillbuild.py` 是 -`sca skill` CLI 所用同一编译器的封装,供本仓库维护者构建:按 harness 目标 -编译(目标与默认输出目录配置在 `skillproj.toml`;`skills/simplecadapi-*/` -下的输出是可再生的构建产物,不提交入库)。如需 harness 特定文本,用 -`` 条件块标记,按目标编译。wheel 本身不包含任何预编译 -目标——终端用户用 `sca skill install` 从内置源码自行安装。 - -在干净的工作区中更新项目版本和文档,然后生成并验证发布产物: - -```bash -uv sync --group dev -uv run python tools/auto_docs_gen.py --quiet -uv run python tools/skillbuild.py --target omp -uv run pytest test/test_skill_build.py -tar -C skills -czf skills/simplecadapi.tar.gz simplecadapi-omp -``` - -这组命令会重新生成 skill 源树内的 API 参考、重新编译 omp 目标,并生成 -`skills/simplecadapi.tar.gz`。发布前检查源树和编译产物: - -```bash -git diff -- docs/skill -tar -tzf skills/simplecadapi.tar.gz | head -``` - -发布时只提交 `docs/skill/` 源树;harness 编译产物由发布工作流生成,归档 -文件上传到 GitHub Release。通过 pip 安装后,优先使用 `sca skill` 构建和安装。 - -## 开发 - -```bash -uv sync --group dev -uv run python -m pytest test tests -python3 -m compileall src/simplecadapi -``` - -## 许可证 - -本项目采用 Apache 许可证 2.0 版(Apache-2.0),详见 [`LICENSE`](LICENSE)。 - -## 社区交流 - -由于群聊人数过多,无法直接扫码入群。请扫描下方二维码添加杜鹏老师微信,由杜鹏老师邀请加入 CADDesigner 技术交流群: - -

- 杜鹏老师个人微信二维码 -

- -## Star History - - - - - - Star History Chart - - +Apache-2.0。生产使用前请验证生成的模型。 diff --git a/img/benchmark/vs_cadquery.svg b/img/benchmark/vs_cadquery.svg new file mode 100644 index 00000000..3757cbc8 --- /dev/null +++ b/img/benchmark/vs_cadquery.svg @@ -0,0 +1,35 @@ + +SimpleCADAPI against CadQuery, same model and prompt on 200 parts: 3.5 times fewer badly wrong results + +Same model. Same prompt. Same 200 real parts. One attempt each. +Task: rebuild a part as parametric code from its STEP file. An independent, frozen scorer measures the result against the original. + +SimpleCADAPI + +CadQuery +Delivered, but badly wrong +lower is better + + +4.4% + +15.6% +3.5× fewer +Distance from the original +mean surface error, mm · lower is better + + +0.006 mm + +2.885 mm +472× smaller +Valid models delivered +out of 200 · higher is better + + +181 + +173 ++8 models +SimpleCADAPI 2.2.7b1 vs CadQuery 2.8.0 · DeepSeek-V4.1-Flash · 200 open-hardware parts (2–1,384 mm) · no retries · paired test on the distorted rate: p = 0.002 + diff --git a/img/benchmark/vs_cadquery.zh.svg b/img/benchmark/vs_cadquery.zh.svg new file mode 100644 index 00000000..a42f49c3 --- /dev/null +++ b/img/benchmark/vs_cadquery.zh.svg @@ -0,0 +1,35 @@ + +SimpleCADAPI 对 CadQuery:同一模型、同一提示词、200 个零件,严重失真的模型少 3.5 倍 + +同一个模型,同一套提示词,同样 200 个真实零件,各只试一次。 +任务:根据 STEP 文件,用参数化代码重建零件。由独立且已冻结的评分器,把结果与原件逐一比对。 + +SimpleCADAPI + +CadQuery +交付了,但严重失真 +越低越好 + + +4.4% + +15.6% +少 3.5 倍 +与原件的距离 +平均表面误差,mm · 越低越好 + + +0.006 mm + +2.885 mm +小 472 倍 +交付的有效模型 +共 200 个 · 越高越好 + + +181 + +173 +多 8 个 +SimpleCADAPI 2.2.7b1 对 CadQuery 2.8.0 · DeepSeek-V4.1-Flash · 200 个开源硬件零件(2–1,384 mm)· 不重试 · 严重失真率的配对检验 p = 0.002 + diff --git a/img/benchmark/vs_industrial_mcp.svg b/img/benchmark/vs_industrial_mcp.svg new file mode 100644 index 00000000..b02c254e --- /dev/null +++ b/img/benchmark/vs_industrial_mcp.svg @@ -0,0 +1,44 @@ + +Tokens spent per task, SimpleCADAPI against a mature commercial CAD through its MCP: up to 6.5 times fewer + +Up to 6.5× fewer tokens for the same task +Tokens an agent spends on each task (millions) · SimpleCADAPI against a mature commercial CAD driven through its MCP · lower is better + +SimpleCADAPI + +Mature industrial CAD, through its MCP + +0 M + +10 M + +20 M + +30 M +S01 + +3.56 + +14.17 +4.0× fewer +S05 + + +≥11.07 + +22.39 +≤2.0× fewer +S06 + +4.14 + +26.96 +6.5× fewer +S07 + +12.07 + +14.88 +1.2× fewer +≥ marks a lower bound: the figure is at least that much. + diff --git a/img/benchmark/vs_industrial_mcp.zh.svg b/img/benchmark/vs_industrial_mcp.zh.svg new file mode 100644 index 00000000..b3832d22 --- /dev/null +++ b/img/benchmark/vs_industrial_mcp.zh.svg @@ -0,0 +1,44 @@ + +每个任务消耗的 Token:SimpleCADAPI 对某成熟工业软件(经其 MCP),最多少 6.5 倍 + +同样的任务,最多少用 6.5 倍 Token +智能体在每个任务上消耗的 Token(百万)· SimpleCADAPI 对某成熟工业软件(经其 MCP 驱动)· 越低越好 + +SimpleCADAPI + +某成熟工业软件(经其 MCP) + +0 M + +10 M + +20 M + +30 M +S01 + +3.56 + +14.17 +少 4.0 倍 +S05 + + +≥11.07 + +22.39 +至多少 2.0 倍 +S06 + +4.14 + +26.96 +少 6.5 倍 +S07 + +12.07 + +14.88 +少 1.2 倍 +≥ 表示下界:实际数值不低于该值。 + diff --git a/img/editor/desktop_arm_en.jpg b/img/editor/desktop_arm_en.jpg new file mode 100644 index 00000000..200f647b Binary files /dev/null and b/img/editor/desktop_arm_en.jpg differ diff --git a/img/editor/desktop_arm_zh.jpg b/img/editor/desktop_arm_zh.jpg new file mode 100644 index 00000000..15f934bc Binary files /dev/null and b/img/editor/desktop_arm_zh.jpg differ diff --git a/img/editor/sg90_arm_en.jpg b/img/editor/sg90_arm_en.jpg new file mode 100644 index 00000000..c31f32d5 Binary files /dev/null and b/img/editor/sg90_arm_en.jpg differ diff --git a/img/editor/sg90_arm_zh.jpg b/img/editor/sg90_arm_zh.jpg new file mode 100644 index 00000000..51e763a7 Binary files /dev/null and b/img/editor/sg90_arm_zh.jpg differ diff --git a/tools/make_readme_charts.py b/tools/make_readme_charts.py new file mode 100644 index 00000000..83f20471 --- /dev/null +++ b/tools/make_readme_charts.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +"""Draw the two comparison charts of the README (img/benchmark/*.svg) from the numbers below. + + python tools/make_readme_charts.py + +The numbers are copied from the evaluation reports; to relabel a case or add one, change DATA and run it again. +The SVGs carry their own light card, so they read the same on GitHub's light and dark themes. +""" + +from __future__ import annotations + +from html import escape +from pathlib import Path + +OUT = Path(__file__).resolve().parent.parent / "img" / "benchmark" + +INK, MUTED, GRID, CARD, SCA, OTHER = "#16181d", "#5b6270", "#e4e7ec", "#ffffff", "#e8590c", "#a3aab8" +FONT = "-apple-system, 'Segoe UI', 'Helvetica Neue', Arial, 'PingFang SC', 'Noto Sans CJK SC', sans-serif" + +# ---- the data ------------------------------------------------------------------------------------------------------ +# Same model (DeepSeek-V4.1-Flash), same prompt, same 200 parts, one attempt, one frozen scorer. +# SimpleCADAPI 2.2.7b1 against CadQuery 2.8.0. (report: SimpleCADAPI vs CadQuery, testset200, sections 5 and 6) +CQ = { + "distorted": (4.4, 15.6), # % of delivered models with F1@1mm < 99.99 % (8/181 against 27/173) + "error_mm": (0.00612, 2.885), # mean Chamfer distance to the original, mm + "delivered": (181, 173), # valid models out of 200 +} +# Tokens (millions) to finish each task, SimpleCADAPI against a mature commercial CAD driven through its MCP. +# `lower_bound`: the figure is "at least this much". The case names are the evaluation's own ids. +MCP = [ + {"case": "S01", "sca": 3.555, "other": 14.166}, + {"case": "S05", "sca": 11.070, "other": 22.393, "lower_bound": True}, + {"case": "S06", "sca": 4.136, "other": 26.964}, + {"case": "S07", "sca": 12.072, "other": 14.880}, +] +# -------------------------------------------------------------------------------------------------------------------- + +STR = { + "en": { + "cq_title": "Same model. Same prompt. Same 200 real parts. One attempt each.", + "cq_sub": "Task: rebuild a part as parametric code from its STEP file. An independent, frozen scorer measures the result against the original.", + "cq_other": "CadQuery", + "p1": ("Delivered, but badly wrong", "lower is better", "3.5× fewer"), + "p2": ("Distance from the original", "mean surface error, mm · lower is better", "472× smaller"), + "p3": ("Valid models delivered", "out of 200 · higher is better", "+8 models"), + "cq_foot": "SimpleCADAPI 2.2.7b1 vs CadQuery 2.8.0 · DeepSeek-V4.1-Flash · 200 open-hardware parts (2–1,384 mm) · no retries · paired test on the distorted rate: p = 0.002", + "cq_alt": "SimpleCADAPI against CadQuery, same model and prompt on 200 parts: 3.5 times fewer badly wrong results", + "mcp_title": "Up to 6.5× fewer tokens for the same task", + "mcp_sub": "Tokens an agent spends on each task (millions) · SimpleCADAPI against a mature commercial CAD driven through its MCP · lower is better", + "mcp_other": "Mature industrial CAD, through its MCP", + "fewer": "{}× fewer", + "fewer_bound": "≤{}× fewer", + "mcp_foot": "≥ marks a lower bound: the figure is at least that much.", + "mcp_alt": "Tokens spent per task, SimpleCADAPI against a mature commercial CAD through its MCP: up to 6.5 times fewer", + "suffix": "", + }, + "zh": { + "cq_title": "同一个模型,同一套提示词,同样 200 个真实零件,各只试一次。", + "cq_sub": "任务:根据 STEP 文件,用参数化代码重建零件。由独立且已冻结的评分器,把结果与原件逐一比对。", + "cq_other": "CadQuery", + "p1": ("交付了,但严重失真", "越低越好", "少 3.5 倍"), + "p2": ("与原件的距离", "平均表面误差,mm · 越低越好", "小 472 倍"), + "p3": ("交付的有效模型", "共 200 个 · 越高越好", "多 8 个"), + "cq_foot": "SimpleCADAPI 2.2.7b1 对 CadQuery 2.8.0 · DeepSeek-V4.1-Flash · 200 个开源硬件零件(2–1,384 mm)· 不重试 · 严重失真率的配对检验 p = 0.002", + "cq_alt": "SimpleCADAPI 对 CadQuery:同一模型、同一提示词、200 个零件,严重失真的模型少 3.5 倍", + "mcp_title": "同样的任务,最多少用 6.5 倍 Token", + "mcp_sub": "智能体在每个任务上消耗的 Token(百万)· SimpleCADAPI 对某成熟工业软件(经其 MCP 驱动)· 越低越好", + "mcp_other": "某成熟工业软件(经其 MCP)", + "fewer": "少 {} 倍", + "fewer_bound": "至多少 {} 倍", + "mcp_foot": "≥ 表示下界:实际数值不低于该值。", + "mcp_alt": "每个任务消耗的 Token:SimpleCADAPI 对某成熟工业软件(经其 MCP),最多少 6.5 倍", + "suffix": ".zh", + }, +} + + +def text(x, y, s, size=14, fill=INK, weight=400, anchor="start", italic=False): + style = ' font-style="italic"' if italic else "" + return ( + f'{escape(s)}' + ) + + +def rect(x, y, w, h, fill, rx=3): + return f'' + + +def svg(width, height, body, title): + return ( + f'\n{escape(title)}\n' + f'\n' + "\n".join(body) + "\n\n" + ) + + +def legend(x, y, other): + return [ + rect(x, y - 11, 14, 14, SCA, 3), + text(x + 22, y, "SimpleCADAPI", 14, INK, 600), + rect(x + 150, y - 11, 14, 14, OTHER, 3), + text(x + 172, y, other, 14, INK, 600), + ] + + +def cq_chart(lang): + t = STR[lang] + w, h = 1040, 430 + body = [ + text(36, 50, t["cq_title"], 24, INK, 700), + text(36, 78, t["cq_sub"], 14, MUTED), + *legend(36, 112, t["cq_other"]), + ] + panels = [ + (*t["p1"][:2], CQ["distorted"], lambda v: f"{v:.1f}%", 18.0, t["p1"][2]), + (*t["p2"][:2], CQ["error_mm"], lambda v: f"{v:.3f} mm", 3.2, t["p2"][2]), + (*t["p3"][:2], CQ["delivered"], lambda v: f"{v:.0f}", 200.0, t["p3"][2]), + ] + px, pw, gap, top = 36, 308, 30, 150 + for i, (title, sub, (a, b), fmt, top_value, callout) in enumerate(panels): + x0 = px + i * (pw + gap) + body += [ + text(x0, top, title, 16, INK, 700), + text(x0, top + 20, sub, 12.5, MUTED), + f'', + ] + barmax = pw - 96 + for j, (value, colour) in enumerate(((a, SCA), (b, OTHER))): + y = top + 62 + j * 62 + body += [rect(x0, y, barmax * value / top_value, 34, colour, 4), text(x0 + 6 + barmax * value / top_value, y + 23, fmt(value), 17, INK, 700)] + body.append(text(x0, top + 218, callout, 30, SCA, 800)) + body.append(text(36, 400, t["cq_foot"], 12.5, MUTED)) + return svg(w, h, body, t["cq_alt"]) + + +def mcp_chart(lang): + t = STR[lang] + w, h = 1040, 520 + top_value = 30.0 + body = [ + text(36, 50, t["mcp_title"], 24, INK, 700), + text(36, 78, t["mcp_sub"], 14, MUTED), + *legend(36, 112, t["mcp_other"]), + ] + left, right, y0 = 120, w - 150, 140 + scale = (right - left) / top_value + for tick in range(0, int(top_value) + 1, 10): + x = left + tick * scale + body += [f'', text(x, y0 + 4 * 74 + 26, f"{tick} M", 12.5, MUTED, 400, "middle")] + for i, row in enumerate(MCP): + y = y0 + i * 74 + ratio = row["other"] / row["sca"] + body.append(text(36, y + 36, row["case"], 20, INK, 700)) + sw, ow = row["sca"] * scale, row["other"] * scale + label = f'{"≥" if row.get("lower_bound") else ""}{row["sca"]:.2f}' + body.append(rect(left, y + 4, sw, 28, SCA, 4)) + if row.get("lower_bound"): # an open end: at least this much + body.append(f'') + body.append(text(left + sw + (20 if row.get("lower_bound") else 8), y + 24, label, 15, INK, 700)) + body.append(rect(left, y + 38, ow, 28, OTHER, 4)) + body.append(text(left + ow + 8, y + 58, f'{row["other"]:.2f}', 15, INK, 700)) + note = t["fewer_bound" if row.get("lower_bound") else "fewer"].format(f"{ratio:.1f}") # a lower bound on our side caps the ratio + body.append(text(w - 36, y + 36, note, 20, SCA, 800, "end")) + body.append(text(36, 496, t["mcp_foot"], 12.5, MUTED)) + return svg(w, h, body, t["mcp_alt"]) + + +def main(): + OUT.mkdir(parents=True, exist_ok=True) + for lang, t in STR.items(): + (OUT / f"vs_cadquery{t['suffix']}.svg").write_text(cq_chart(lang), encoding="utf-8") + (OUT / f"vs_industrial_mcp{t['suffix']}.svg").write_text(mcp_chart(lang), encoding="utf-8") + print("wrote", *sorted(p.name for p in OUT.glob("*.svg"))) + + +if __name__ == "__main__": + main()