Commit Graph

174 Commits

Author SHA1 Message Date
NiJingzhe b496530363 feat(helix): handedness parameter for right/left helices
make_helix_redge/make_helix_rwire/helical_sweep_rsolid accept
handedness='Right'|'Left'. The kernel negates the u component of the
cylinder 2-D line, mirroring the winding while keeping the ascent
direction: sampled chirality asserts +5 turns CCW (right) vs -5 turns
CW (left) with identical rise, length, and sweep volume.

FreeCAD: Part::Helix stays the right-handed path; left-handed helices
materialize through Part.makeHelix(..., lefthand=True) since Part::Helix
cannot express mirrored winding via placement (rotations preserve
chirality).
2026-09-04 05:36:27 +08:00
NiJingzhe e05231312f feat(chamfer): asymmetric angled chamfers via angle + reference_direction
chamfer_rsolid(distance, angle=, reference_direction=) drives an
asymmetric chamfer: the second leg is distance * tan(angle) and the
distance itself lands on the adjacent face whose outward normal best
matches reference_direction (resolved per edge through incident-face
tracking). Without angle the symmetric behavior is unchanged.

Kernel: tracked_chamfer gains distance2/edge_face_pairs and uses OCC's
SetDists(d1, d2, contour, face), whose first distance lands on the
passed face — verified by chamfer-face bbox placement tests.
FreeCAD: Part::Chamfer Edges tuples use distance2 when recorded.
Graph params record angle, reference_direction, and distance2.
2026-09-04 05:34:26 +08:00
NiJingzhe 23fcc6a4e1 feat(ellipse): full ellipse support at geometry tier, sketch tier, and FreeCAD translation
- Geometry tier: make_ellipse_redge/rwire/rface with major_direction
  orientation; exact OCC Geom_Ellipse geometry (area pi*a*b).
- Sketch tier: add_ellipse_rsketch derives the shape from three solving
  points (center, major-axis end, minor-axis end) so radius constraints
  solve natively; constrain_major_radius_rsketch and
  constrain_minor_radius_rsketch drive point distances; fix pins all
  three points; promotion builds an ellipse profile branch.
- Solved entities report center/axis points, radii, and major-axis angle.
- FreeCAD: Part.Ellipse(S1, S2, Center) three-point construction in both
  Sketcher materialization and wire fallback; major radius maps to the
  native Radius constraint, minor radius to a reference distance on the
  solved minor-axis point (FreeCAD has no native minor-radius
  constraint; noted in mapping status); geometry-tier emitter uses
  _kernel_ellipse_from_params.
- QL curve_type('ELLIPSE') verified against promoted faces.
- 14 new tests; API doc pages regenerated.
2026-09-04 05:29:19 +08:00
NiJingzhe d57835232a feat(sketch): HistCAD constraint coverage — driving angle, line distance, point alignment, normal, mirror, midpoint
- Driving angle lowering: addAngle folds directed 0-360 values to the
  undirected magnitude; the solve keeps the branch nearest the initial
  geometry. Angle measurement normalizes to [0, 360).
- constrain_line_distance_rsketch: minimum offset between lines via a
  signed point-line distance (initial side preserved).
- constrain_points_horizontal/vertical_rsketch for two-point alignment.
- constrain_normal_rsketch (line through curve center),
  constrain_mirror_rsketch (entity mirror decomposed to point symmetric
  pairs with nearest-initial endpoint pairing), and
  constrain_midpoint_points_rsketch (two-point midpoint via helper
  segments: equal length + parallel through the shared point).
- Repair: symmetric lowering no longer uses py-slvs addSymmetricLine,
  which mirrors about the workplane u-axis regardless of the axis entity;
  it now decomposes to midpoint-on-line + perpendicular. Regression
  tests cover vertical and diagonal axes.
- FreeCAD translator: new kinds map to Sketcher Angle/Distance (point to
  line)/point-form Horizontal/Vertical/PointOnObject (center on line)/
  Symmetric (line mirror and three-point midpoint); priority map,
  emitter registry, capabilities, and canonical op set updated.
- 24 new tests (solve semantics, side/basin behavior, serialization
  round-trip, FCStd script mapping) + regenerated API doc pages.
2026-09-04 05:14:09 +08:00
NiJingzhe ece13ffb6d feat(render): axis triads as corner overlays instead of in-model actors
The show_axes triad no longer places a world-space vtkAxesActor inside
the model bounds (where it intersected geometry and fought the camera
fit). Each panel now gets a small orientation triad overlaid in its
bottom-right corner: a dedicated transparent layered renderer sized to
20% of the panel edge, with the camera direction copied from the panel
camera so the triad reads correctly for that specific view. The
single-view sdk path switches to the same corner overlay.

Verified visually on the 4-panel grid: triads present in every panel,
no overlap with model, titles, callouts or legend. ty: no new
diagnostics. Full suite: 1432 passed, 5 skipped.
2026-09-04 04:03:13 +08:00
NiJingzhe 8261a28545 feat(render): multi-view screenshots with tags, callouts, legend and axes
render_screenshot_rpath now defaults to a multi-view grid instead of a
single view: one PNG with a panel per SCREENSHOT_VIEWS entry (isometric,
top, front, side), carrying the same highlight-tag color groups, callout
labels (2-D leader-line style, projected per panel), legend and — new
for the grid engine — per-panel axis triads.

- The multi-view grid engine (_render_polydata_views[_in_process])
  gains show_axes: a vtkAxesActor per panel, sized from the visible
  bounds, forwarded through the macOS render worker protocol.
- _render_sdk_screenshot_rpath keeps all of its view-independent
  tag-to-group / callout-anchor / legend computation and routes through
  the grid engine when views is provided; image_size (pixels) maps to
  inches*dpi=100 so pixel dimensions are preserved.
- Public API: new views parameter; default (view='auto') resolves to
  SCREENSHOT_VIEWS; an explicit view keeps the legacy single-view path
  unchanged. zoom only applies to the single-view camera.
- render_shape_views_rpath is unchanged: it remains the raw-TopoDS_Shape
  entry for the STEP inspection family; both entries now share one grid
  engine with identical annotation capabilities.

BEHAVIOR CHANGE: the default output of render_screenshot_rpath switches
from a single-view image to the 4-panel grid. Callers passing an
explicit view are unaffected.

ty: no new diagnostics (1043 before and after). Auto-doc pages
regenerated. Full suite: 1432 passed, 5 skipped (7 new tests: wiring,
custom views, legacy single-view routing, two real renders, constant
shape, empty-views rejection).
2026-09-04 03:52:21 +08:00
NiJingzhe 85ce7ae424 refactor(types): ty-driven fixes — NoReturn wrapper, redundant casts, narrowing guards
Four groups from a full 'ty check' pass (1718 -> 1043 diagnostics,
non-noise 560 -> 394; remaining are OCP stub-less imports and a
long-tail annotation backlog):

1. NoReturn propagation: _wrap_public_api_error was annotated -> None,
   hiding that the except branch of every public API wrapper always
   raises. Annotating it NoReturn (raise_harness_error already is)
   lets ty prove 104 'function can implicitly return None' diagnostics
   away instead of annotating every call site.

2. Removed all 54 redundant casts (cast(List[X], _iter_x()),
   cast(TrackedResult, tracked_x(...)), cast(Any, outputs[0]), ...)
   and the now-unused cast imports.

3. Narrowing guards for Optional/duck-typed values:
   - dxf_engine/agent.py: anchor may stay None when the candidate loop
     never runs; guard before the reject path uses anchor[0].
   - operators/_support.py: hasattr(...).to_tuple()/get_center()
     patterns rewritten as getattr + callable() so the None case is
     explicit.
   - build/incremental_solver.py: _interface_changes values are
     tuple | bool; isinstance-narrow before iterating bindings and
     connectors.

4. Annotation corrections:
   - @part now declares proper @overload signatures (bare decorator vs
     keyword factory); the previous union return type made decorated
     builders infer as PartBuildResult and flagged calling them.
   - dxf_engine/model.py: 11 dataclass fields defaulted to None are
     now Optional.
   - solidworks_translator: possible_causes passed a bare string
     where Sequence[str] is required (a string would render
     per-character bullets); now a 1-tuple.

Full suite: 1425 passed, 5 skipped.
2026-09-04 03:11:02 +08:00
NiJingzhe 102fc3adb6 fix(types): resolve names used in annotations
params/units.py referenced ScalarExpr/ScalarLike in quoted annotations
without importing them (they live in params/expr.py; added under
TYPE_CHECKING). inspect/brep/render.py used ColorSpec in four
annotations without defining it anywhere — now defined as
Union[int, str, tuple[float, float, float]] (palette index, hex/named
string, or rgb tuple) next to _resolve_color, which already implements
exactly that contract.
2026-09-04 03:10:50 +08:00
NiJingzhe 77ad2c9440 chore(verifier): drop collision verifier module superseded by external implementation
Removes src/simplecadapi/verifier (current-pose mesh penetration checks
via python-fcl), its test, and the planetary-reducer collision probe
example. Collision verification now lives in an external implementation
outside this SDK.

The python-fcl>=0.7.0.11 dependency is dropped with it: the verifier
module was its only consumer.

BREAKING CHANGE: scad.verifier and check_collision_rcollisionreport are
no longer exported. Workflow docs mentioning 'verifier' refer to the
Verifier Planner role, not this module, and are unchanged.

Full suite: 1425 passed, 5 skipped.
2026-09-04 02:19:29 +08:00
NiJingzhe 67f78f893d fix(geometry): align planar profile axes with the box convention
_orthonormal_plane_axes built the in-plane basis with x = cross(z, ref),
which for a +z normal yields x=(0,1,0), y=(-1,0,0): every non-square
rectangle made on the z=0 plane was silently rotated 90 degrees relative
to make_box_rsolid (width along global y instead of x).

Build the basis by projecting the reference vector onto the plane
(Gram-Schmidt) instead: for a +z normal the frame is exactly the global
(x, y, z), matching the box convention and the OCC gp_Ax2 default. The
reference-axis branch keeps ref away from z, so the projection never
degenerates. Only make_rectangle_rwire uses the helper (session and
legacy paths); other planar makers are unaffected.

BREAKING CHANGE: non-square rectangles now orient width along global x
for +z normals; both session and legacy paths rotate together. Recorded
replay graphs built with non-square rectangles reproduce rotated
geometry.

test_surface_api's partial-overlap trim test encoded the transposed
convention; its loop dims (4, 2) -> (2, 4) reproduce the exact footprint
(x in [0.5, 2.5], y in [-2, 2]) the test has always exercised.
2026-09-03 17:57:47 +08:00
NiJingzhe 6c0f9ee3a6 feat(dxf): 1-DOF annotation model, rad inner-arc variant, auto-diag loop
- Direction-first placement: once at/side is fixed the text has exactly
  one DOF (slide along the line); rad candidates run outer (s=3..27)
  then inner-arc (s<0, line through center, arrow flips to point at the
  arc from the center side, deepening ladder for tight centers)
- Linear dims gain slide; dimension line auto-extends (derived, never
  hand-placed) to cover text that leaves the measured span; narrow
  spans place outside with elongation directly; _lin_geometry is the
  single derivation shared by solver and apply
- rad action surface reduced to at(+s); rot is line direction only (R2),
  out removed; dia/rad split insert (baseline-left anchor, matches
  set_placement rendering) from anchor (OBB center, collision/eval) —
  fixes text rendered half-width off its registered OBB
- Leader fixes: multiline elbow moved above the text box (old elbow
  crossed line 2), no-space fallback no longer crashes unpacking None,
  seg-over-text check references the right loop variable
- SheetDecl.diag_png: solve()/apply() auto-refresh the annotated
  conflict image and return a must-read instruction — visual feedback
  is the first-class agent-in-the-loop channel
- test/test_dxf_engine.py: 18 tests covering the above contracts plus
  render determinism; API pages regenerated
2026-09-01 19:10:33 +08:00
NiJingzhe 37c46ccad5 Merge branch 'dev' into feat/dxf-engine 2026-09-01 13:39:14 +08:00
NiJingzhe a5e6bf8eb6 feat(core)!: QL-only topology enumeration — remove bare getter list form
Plural topology getters (get_edges/get_faces/get_wires/get_vertices/
get_solids/get_inner_wires/get_edge_occurrences and the Compound
variants) now accept ONLY an index. The no-argument list form raises a
SimpleCADError with migration guidance (enumerate via
ql.<kind>().resolve(shape), pick via get_X(index)). This closes the
selection channel that escapes the graph: Python loops over bare lists
lose the predicate, capture kernel artifacts (the periodic-face seam
edges that broke FCStd translation), and leave no cardinality contract.

- each shape class keeps its enumeration logic as private _iter_<kind>();
  indexed picks record geo-select nodes as before (contract test added);
  Compound getters gain the same indexed recording they lacked
- _TopologySelectionList (the __getitem__ recording vehicle, which also
  made get_X()[i] a silent escape hatch) is retired
- all 109 internal call sites, 165 test call sites, and 31 example call
  sites migrated: SDK/tests use the private channel, user-facing
  examples use ql.<kind>().resolve(...)
- QL _resolve_scope_items switches to the private channel; scene
  contract profile descriptions synced; error strings recommending
  bracket indexing rewritten
- skill docs: strict prohibition added to SKILL.md global rules (new
  rule 6), core README contract statement rewritten, solid/wire/face/
  shell/tagged_mixin pages re-exemplified with QL, geometric-validation
  anti-pattern section updated; mirrors rebuilt via tools/skillbuild.py

Gates: full suite 1418 passed / 5 skipped; translator suites 133 passed;
u_link stage verifiers + render check ALL PASS; scadpkg->FCStd
retranslation verified (5 visible deliverables, 167-object editable
tree).
2026-09-01 02:09:29 +08:00
NiJingzhe 14f3fe952e fix(translator): sweep all document objects in result visibility
The final _apply_result_visibility pass only iterated GRAPH_OUTPUTS, so
objects created outside the graph-output registry kept their default
Visibility=True while being marked ShowInTree=False: boolean tool/step
wrappers, geo-selection features (make_select_redge), transform
App::Links, and construction wires/faces rendered in the viewport but
were absent from the tree until their owning container was double-
clicked — ghost bodies with no selectable tree entry (observed 62/167
objects visible in the u_link package).

Sweep every doc.Objects entry instead: results stay visible, everything
else is hidden from both viewport and tree, then the product pass re-
shows deliverables as before. The u_link assembly FCStd now shows
exactly 5 visible objects (two final part bodies, the assembly object,
two component links); translator suites pass unchanged (123 tests).
2026-08-31 23:48:40 +08:00
NiJingzhe 5d5e69343b fix(translator): accept clearly separated geo-selector matches
The FreeCAD runtime rejected any geo match scoring above an absolute
1e-2, but the score is a sum of 10x-scaled relative-error terms and a
rebuild in FreeCAD's OCC differs from the recorded OCP geometry in the
4th-6th significant digit — the CORRECT candidate lands at ~0.01-0.5
while wrong candidates score >= ~1. The absolute threshold was
calibrated for same-kernel replay and rejected correct cross-kernel
matches (observed: best 0.0516 vs runner-up 2.12, a 40x separation,
rejected).

Accept the best candidate when best <= 0.5 AND second >= 10*best + 0.5
in addition to the unchanged near-exact path. Rejection semantics are
preserved: absent targets (best >= 1) and ambiguous twins (second close
to best) still raise.

Unit tests cover all five cases: near-exact accept, kernel-drift
accept (both orderings), similar-runner-up reject, absent-target
reject, single-candidate accept.
2026-08-31 23:18:29 +08:00
NiJingzhe e9dcba0f96 feat(sketch): unified loop/chain extraction for wire promotion
Replace _ordered_edge_loop with _ordered_edge_path: a connected edge
component with all vertex degrees <= 2 is either a closed loop (no
degree-1 vertices) or a simple open chain (exactly two), so one walker
classifies both and reports closedness as a payload property.

- make_wire_from_sketch_rwire now promotes open chains (e.g. sweep
  paths); branching remains unusable and is named per component
  ('branch point X carrying N edges') in selection errors instead of
  being silently dropped behind a misleading 'no closed profile' message
- make_face_from_sketch_rface keeps requiring closed loops; its error
  lists each component's classification (closed loop / open chain /
  branched)
- closedness stays a consumer contract: extrude/revolve/face builders
  already reject open wires at the point of use; sweep accepts open
  paths unchanged

Tests cover chain promotion, consumer rejection, branch-point
diagnostics, mixed loop+chain selection, and a fully constrained
tangent-continuous U sweep path promoted from a sketch and swept to a
solid.
2026-08-31 20:45:55 +08:00
NiJingzhe 40dc5354a5 docs(skill): engineering drawing workflow, domain, and generated API pages
Add references/workflows/engineering-drawing.md (preliminary staged
workflow: preconditions -> declare views -> declare datums/dims -> solve
and audit -> render and visual review) and references/domains/
engineering-drawing.md (capability boundary, R1-R7 solver contract, API
groups, known engine limits, failure modes). Route the new goal in
SKILL.md.

Backfill docstrings for the dxf_engine public surface (declaration
dataclasses, SheetPlan, render_plan) so auto_docs_gen can produce their
API pages under references/docs/api/ with an Engineering Drawings index
section, following the inspect/brep sub-namespace pattern.
2026-08-31 12:59:41 +08:00
NiJingzhe 600b03a157 feat(dxf): add DXF drafting engine with PDF sheet output
Add simplecadapi.dxf_engine: a declarative 2D drawing pipeline (SheetDecl/
ViewDecl/DimDecl/DatumDecl/CenterDecl/LeaderDecl) that plans views, runs
hidden-line removal, and renders annotated sheets to DXF/PDF via ezdxf +
pymupdf. Include the u_link_motor_mount drawing scripts as the worked
example.
2026-08-31 12:48:12 +08:00
NiJingzhe 152bbf3432 refactor!: reorganize package root into themed subpackages
- operators/: _support + geometry/features/boolean/transform/selection/sketch/product
- product/: semantic value model, solver, occurrence, packages, capture
- topology/: model, tagging, tracking, autotag (package re-exports model symbols)
- params/: units, expr, tolerance, frame
- recording/: graph, serializer, source_mapping
- _internal/: canonical_json, vendor_warning_filters, semantic, mesh, brep_region

Root shrinks from 46 to 7 modules. Drop the legacy geometry/boolean/transform/
selection monolith copies and the operations.py facade; unified operator
exports now live in operators/__init__ with monkeypatch mirroring preserved.
Remove the legacy evolve generators and their example/tests/docs. Import paths
for simplecadapi.topology keep working via package re-export; update all
in-repo consumers, tests, tools/auto_docs_gen source tables, and regenerate
the skill API reference docs.
2026-08-31 12:46:57 +08:00
Jiahang Shen 26bd7e922a feat(inspect): add manufacturing feature highlights (#23)
* feat(inspect): add manufacturing feature highlights

* docs(inspect): normalize manufacturing API references
2026-08-30 12:14:58 +08:00
Ni Jingzhe c454a3af10 feat(skill): per-harness skillbuild toolchain replaces skill-pack (#18)
* feat(skill): replace skill-pack with per-harness conditional compiler

skillbuild compiles the skill tree into per-target harness builds:
- <!-- skill:if omp,!claude --> blocks include text only for matching
  targets; name-list conditions only, no else/nesting, fail-loud on
  unknown targets and unpaired/nested directives
- fence-aware: directive-looking lines inside code fences are literal
- layout is the filesystem; tree root configured in skillproj.toml
- post-build assertion: zero directive residue, SKILL.md frontmatter
  name check

Migration to the new model:
- docs/skill/ becomes the self-contained source root (SKILL.md,
  references/, generated api/stdlib/core/guides now under
  references/docs/; SDK_OVERVIEW/LICENSE/inspect are ordinary tree
  files)
- auto_docs_gen output redirected into the tree (docs/api ->
  docs/skill/references/docs/api, likewise stdlib)
- skills/simplecadapi/ is now the compiled omp target output;
  dist/generic/simplecadapi the generic target
- dropped skill-pack entry point (plus dangling evolve/make-export
  entries and their orphaned test), release workflow builds via
  skillbuild + tar; README updated

First real conditional block: harness reading paths in SKILL.md
(skill:// mount on omp vs disk-relative on generic).

Verified: 59 tests pass (skillbuild 31, auto_docs_gen 19, persistence
regression 9); both targets build; outputs residue-clean; full suite
collects (1376 tests).

* refactor(tools): auto_docs_gen moves out of the installed package

tools/ scripts are repo-checkout dev scripts, not packaged CLIs:
- auto_docs_gen.py now lives in tools/ beside the other generators;
  auto_tools/ package removed entirely
- path resolution simplifies: repo root = parent of tools/, fail-loud
  if pyproject.toml missing; site-packages/cwd fallback branches were
  dead code once the script stopped shipping in the wheel
- auto-docs-gen console script dropped from [project.scripts];
  release.yml and README invoke python tools/auto_docs_gen.py
- MANIFEST.in stale src/auto_tools include removed; CadQuery-free
  runtime scan no longer needs the auto_tools filter
- run_examples.py retired (user removal): README example-runner text
  updated to direct examples/ scripts; dangling runner-contract test
  (runpy.run_path into the deleted script) removed

Verified: 53 tests pass (auto_docs_gen + skill_build + ocp runtime
scan) and test_example_model_contract passes; regeneration from
tools/ is byte-identical (zero docs drift).

* refactor(skill): strip harness and build-tool content from the skill tree

The skill is plain harness-neutral content again:
- SKILL.md 'Reading skill files' section removed (the omp skill://
  mount block and its !omp complement were the only conditional
  blocks; the tree compiles identically for every target now)
- references/README.md: build-tool meta removed ('per-harness
  conditional compilation', skillbuild packaging/validation claims —
  link validation was never implemented, so the claim was false)
- live test now asserts the tree stays harness-neutral (zero blocks)
- skillproj.toml targets aligned with the user's output table
  (omp -> skills/simplecadapi-omp, opencode -> skills/simplecadapi-opencode;
  leftover 'generic' entry had no output and failed the build)
- compiled outputs are regenerable artifacts: skills/simplecadapi/
  untracked from git, skills/simplecadapi-*/ gitignored, release.yml
  and README build via skillbuild and tar the omp output directly
  (bsdtar has no --transform; inner dir keeps its suffixed name)

Verified: 49 tests pass; both targets build 372 files with zero
conditional blocks; no omp/conditional/directive residue in the tree
or outputs.

* chore(docs): drop stale architecture review and design notes
2026-08-22 20:20:49 +08:00
NiJingzhe dbcb145125 chore(auto_tools): drop evolution and make_export tools, default skill license to MIT
Removes the evolve/make-export CLI modules; skill-pack default license
switched from AGPL-3.0 to MIT.

Note: pyproject [project.scripts] still declares evolve/make-export and
test/test_make_export.py loads the removed module (collection error) —
cleanup tracked separately.
2026-08-22 16:57:36 +08:00
NiJingzhe dc143f3f9c fix(persistence): evaluate Var/Expr primitive geometry before serialization
Expression objects leaked into primitive geo metadata (make_cylinder/cone/
sphere) and were rejected by .scadpkg serialization. Write evaluated values
at the source (_operators_geometry) and project Var/Expr to float in
topology snapshots; add parametrized regression for var-driven primitive
positions.

Found during session 01a02469 (arc handle build) as two independent
serialization failures.
2026-08-22 16:57:20 +08:00
NiJingzhe f5727fe642 refacot(skill&docs): reorgnize skill for better function routing and adding diciplins from text to cad 2026-08-21 20:35:34 +08:00
NiJingzhe 0f351a56c1 perf(occurrence): linearize graph validation
Reuse node definition identities during occurrence compilation and replace repeated parent/source walks with iterative stateful traversal. Preserve full canonical occurrence closure comparison and add deep graph, cycle, and resigned-tamper contracts.
2026-08-21 18:36:19 +08:00
NiJingzhe 7a34108dfa refactor(exporter): validate per-solid tessellation through one API
Expose tessellate_solid as the validated per-solid OpenCASCADE mesh
entry point and make product-surface and MJCF exporters use it. MJCF no
longer imports a private implementation or bypasses angular parameter
validation; it accepts angular_deflection_degrees explicitly while its
default remains exactly equivalent to the previous 0.35-radian value.

Exporter contracts cover the public surface and invalid MJCF linear and
angular deflections.
2026-08-21 17:53:02 +08:00
NiJingzhe b0b1ae1ff2 fix(cache): make lock ownership explicit and tolerate lock timeouts
Store a unique lock token with the owning PID, refuse to reclaim locks
held by live processes, and only unlink a lock when its on-disk token
still belongs to the current context. This prevents stale recovery from
removing a replacement owner's lock.

When get_or_compute cannot acquire the key lock within policy timeout,
compute independently and publish via the existing atomic object/record
writes. Cache contention can duplicate work but no longer fails an
otherwise valid build.
2026-08-21 17:42:08 +08:00
NiJingzhe 0f6027eba5 refactor(package): drive definition blob refs from one spec
Replace the runtime-side and manifest-side hand-maintained blob-ref
lists with one declarative role table per definition kind. Each role
carries the runtime attribute, manifest path, optionality, and semantic
path domain, so adding a blob-bearing field has one source of truth.

Enforce the role path domain on both package construction and decode.
Contract tests prove runtime/manifest reference symmetry and reject a
hash-consistent package whose feature graph ref escapes features/.
2026-08-21 17:34:49 +08:00
NiJingzhe 06bb58b2bb fix(translator): stop reading the FreeCAD package twice
translate_product_package called read_product_package_translation_units
and then passed the package into _translate_product_package_to_script,
which called the same reader again - for bytes/path inputs the ZIP
parse, full validation, occurrence verification, and feature-graph
deserialization all ran twice on the slowest export path. Pass the
already-read units into the script builder instead. Contract test
wraps the reader with a spy: one translation call, exactly one read,
and byte-identical script output.
2026-08-21 16:24:28 +08:00
NiJingzhe a6f6646172 fix(translator): dedupe package units by definition identity
Consumers index translation units by (definition_kind, definition_id) -
the STEP label index looks up materialized definitions by identity, the
product graph resolves reference_definition nodes by definition_id, and
the FreeCAD compiler names definition tokens by id - but the unit walk
deduplicated by content hash, so two same-content definitions with
distinct ids collapsed into one unit and broke every id-keyed lookup
with a missing-unit error. Deduplicate by definition identity instead;
same-content same-id definitions (the normal instancing case) still
collapse. Contract test: a package with two identical-geometry bars
under distinct ids keeps both units and exports STEP with both
definition ids and both occurrences.
2026-08-21 16:21:03 +08:00
NiJingzhe cb720dd1f3 docs(stdlib): regenerate pages for ring-gear sweep migration and bearing builder
Picks up the twisted-sweep docstrings from the ring-gear migration and
the new build_ball_bearing durable builder in the stdlib index.
2026-08-21 15:41:27 +08:00
NiJingzhe 00cef32b94 feat(mjcf): emit equality/connect constraints for loop-closing joints
A movable joint whose two groups are already connected through the
spanning tree (a kinematic loop such as a four-bar linkage) previously
landed in redundant_movable_joints and was silently dropped, exporting
an open-chain model whose末端 swung freely. Loop closure is a nonlinear
pose constraint that neither a tree hinge (MJCF bodies form a strict
hierarchy) nor the linear fixed-tendon equalities can express, but
MuJoCo solves it natively as an equality/connect.

Emit one closure site per endpoint group at the connector frame and one
equality/connect joining them; record closures in the mapping, add
closure_count to the report, and empty redundant_movable_joints (every
non-tree movable edge is now either a coupling equality or a closure).
Add example 21 (planar Grashof four-bar with a closed-form assembled
pose, all drives None so the authored closure is the solve reference)
with build/export scripts, update the shared-connector test to the new
closure contract, and lock the loop topology with a dedicated test.
MuJoCo verification: the exported model loads, holds the closure gap at
1e-16 over 500 steps, and behaves as a 1-DOF mechanism.
2026-08-21 13:57:06 +08:00
NiJingzhe 02b6f0601e feat(example): split BLDC exports into parallel scripts and fix FCStd multi-wire sweep
- capture() accepts include_scene=False; the BLDC build skips the
  tessellated Scene projection (STEP/MJCF/FCStd read meshes and feature
  graphs from the definition closure), shrinking the package from 230MB
  to 75MB and capture from ~460s to ~39s.
- main.py is now build + capture only with per-stage timing; the replay
  verification and preview compound stages are dropped.
- export_mjcf.py / export_step.py / export_fcstd.py each translate the
  captured .scadpkg independently; export_all.py runs them concurrently
  (MJCF 84s, STEP 51s, FCStd 569s wall on BLDC).
- FreeCAD twisted-sweep emulation rejected multi-loop profile faces
  ('requires a face with one outer wire'), so the new ring-gear sweep
  path failed FCStd export. Loft each wire of the face separately and
  cut the inner plugs from the outer loft, matching the kernel's
  sewn-shell semantics for annular and multi-hole profiles.
2026-08-21 13:05:24 +08:00
NiJingzhe 70251a980d perf(stdlib): build helical/herringbone ring gears by direct multi-loop sweep
Ring gears still used small-step ruled lofts through rotated copies of
the internal tooth wire plus a boolean cut, while external gears had
already moved to continuous twisted sweeps. Sweep the multi-loop ring
face directly (outer rim + internal tooth profile): helical uses one
twisted sweep, herringbone fuses two opposite-handed halves, both
mirroring the external gear construction. On BLDC-scale rings this is
~40x faster than the ruled-loft+cut path and produces ~6x fewer faces
(45t m0.8: 0.38s/183 faces vs 15.2s/1083 faces), with volume matching
the swept reference; the ruled loft was the approximation (chordal
sections undersize the void by ~1e-4). Invert the two loft-era contract
tests to require zero loft/cut nodes and the twisted-sweep op counts.
2026-08-21 11:14:18 +08:00
NiJingzhe 50f27b893f feat(kernel): support inner-wire profiles in twisted sweep
tracked_twisted_sweep previously rejected any profile face with inner
wires because MakePipeShell only receives one profile wire per shell.
Sweep every wire of the face into its own shell under the shared
rotation law, sew the shells with the profile face and its rotated
translate as end caps, and orient the sewed shell into a solid. Roles
are identified on the sewed result (caps by axial station, remaining
faces as sides) because sewing copies faces and kernel history cannot
be mapped through it. Split the old rejection test: invalid-axis
assertions stay, the inner-wire case flips to a volume/faces contract
on an exact annulus (rotationally symmetric, so volume is analytic).
2026-08-21 11:14:16 +08:00
NiJingzhe 3935173e55 feat(stdlib): add build_ball_bearing durable sub-assembly builder
Standard parts until now could only be consumed as runtime assemblies;
durable parents had to extract ring parts and re-declare bindings by hand
(the pattern examples 16 and 20 both copy). Add build_ball_bearing, which
returns an AssemblyBuildResult whose definition re-declares the stdlib
contract: public outer_axis/inner_axis over one internal
inner_outer_revolute, grounded on the outer ring by default (ground
selectable), returned unsolved so parent-level fixed constraints can drive
both rings. Part/assembly source capture is anchored to the stdlib package
directory so the builder works from any project root. Update the naming
contract to allow build_* durable builders beside make_*_r* runtime
factories and lock the nested dual-fixed behavior with a contract test.
2026-08-21 10:28:34 +08:00
NiJingzhe 474d5b21aa fix(solver): restore nested public-connector solve for external dual-fixed constraints
Commit 2fc3029 dropped _try_close_forwarded_constraint and the forwarded
solve-target machinery without a replacement, making any nested sub-assembly
exposing public connectors over an internal revolute (the standard bearing
topology) over-constrained when a parent fixes both public frames. Both
example 16 and example 20 failed to solve on current HEAD; the committed
example-16 MJCF mapping predates the regression.

Restore the mechanism adapted to the PublicConnectorRef model: descend
public connectors to their nested source component, move it via
_with_component_path_placement when an external constraint's residual
exceeds tolerance, and keep sibling constraints and nested reports valid.
Invert the regression-era test that asserted this topology must fail.
2026-08-21 10:28:33 +08:00
NiJingzhe d4761de159 feat(mjcf): drive kinematics from the canonical occurrence graph
- Nodes, transforms, connectors, joints, and grounding now come solely
  from package.occurrence_graph; the scene projection is an optional
  sidecar consulted only for entity_asset_id (interface.* sites).
- Drop the scene re-encoding path and scene/occurrence cross-checks;
  tamper protection is already enforced by package content hashes.
- Package without a scene projection exports full kinematics; add a
  contract test locking that behavior.
2026-08-21 02:01:41 +08:00
NiJingzhe 8dc285b7c0 feat(capture): enforce runtime/definition consistency and scene asset closure
- capture() verifies the runtime Part/Assembly matches its durable
  definition content hash and kind before writing the .scadpkg.
- validate_product_scene_package rejects duplicate asset definition IDs
  and dangling product/feature-graph asset references on definitions.
2026-08-21 02:01:41 +08:00
NiJingzhe 6b03fd1531 feat(package): extract canonical occurrence graph and enforce v3 package invariants
- Add ProductOccurrenceGraph compiled from the definition closure with a
  fully closed manifest validator: unique definitions/nodes/connectors/
  joints/ground edges, parent and connector-forwarding cycle detection,
  joint endpoint resolution, and ground-edge parentage checks.
- Bump product package schema to 3.0: definitions path-sorted and unique,
  blobs hash-sorted and deduplicated, root resolution, occurrence graph
  member, optional scene projection, and recomputed content_hash.
- validate_product_package now checks the member set against manifest
  declarations, resource limits over all objects, root_definition
  identity, occurrence closure equality, and scene projection foreign
  keys.
2026-08-21 02:01:34 +08:00
NiJingzhe ebff7e53d7 fix: avoid VTK worker shutdown crashes 2026-08-20 14:54:27 +08:00
NiJingzhe bc0a967c85 feat: propagate public connectors to exporters 2026-08-20 14:52:47 +08:00
NiJingzhe 2fc3029a86 refactor: split operator facade and public connectors 2026-08-20 14:52:07 +08:00
NiJingzhe e1df185f5b Merge cadir/dev into feat/prt-and-assemble 2026-08-19 14:42:27 +08:00
NiJingzhe e6896d7baf fix: preserve nested assembly state 2026-08-19 14:02:58 +08:00
NiJingzhe ba1e06a489 feat: expand product exporters and FEM workflow 2026-08-18 01:36:44 +08:00
Jiahang Shen b4c1053a74 fix(reconstruction): keep similarity metrics diagnostic 2026-08-17 00:59:56 +08:00
NiJingzhe 2427048ea8 feat(brep): add region snapshots 2026-08-17 00:46:20 +08:00
Jiahang Shen 7ffd57dbc5 fix(reconstruction): harden trusted evaluator evidence 2026-08-15 21:01:41 +08:00
Jiahang Shen 1145bacfcf fix(reconstruction): define evaluator contracts 2026-08-15 21:01:41 +08:00