Phase 10A/10B Inc 0: build system, handle model, first module surface

Builds n3xd-ocp end to end and publishes 7.9.3.1.dev1 to the Gitea registry,
where it installs anonymously and passes its suite.

- occt/Dockerfile: OCCT 7.9.3 compiled once into a manylinux_2_28 builder
  image (base digest + tarball sha256 pinned), Draw/VTK/Tk/Xlib/OpenGL off,
  FreeType on, -O2 without fast-math or march=native. A final layer asserts
  TKService/TKV3d exist with no libGL/libX11 DT_NEEDED, which is what lets the
  app image drop libgl1/libx11-6. Mounted into, never built FROM.
- scikit-build-core + nanobind STABLE_ABI -> one cp312-abi3 extension that
  registers every OCP.* submodule via PyImport_AddModule, so `import
  OCP.TopoDS` needs no shim and cls.__module__ is right. Version <occt>.N is
  asserted against the OCCT found, keeping occt_version() truthful.
- occt_handle.h: type caster for opencascade::handle<T> over OCCT's intrusive
  refcount. Wrappers are non-owning instances holding exactly one handle in
  their keep-alive list, reusing an existing wrapper so identity survives a
  round trip. Transient constructors go through ocp_new (never nb::init<>,
  which would let OCCT delete nanobind's storage); the caster refuses a
  refcount-0 object rather than corrupt the heap. Verified under ASAN with no
  memory-safety errors, plus an RSS bound over 50k create/destroy cycles.
- Sub-shapes are returned by value everywhere, making the TShape lifetime class
  that segfaulted a process-global face memo unrepresentable.
- Standard_Failure derives RuntimeError, with ~20 concrete types dispatched on
  the dynamic OCCT type (cad_pool marshals failures home by type name).
- Inc 0 surface: gp subset, TopAbs, TopoDS (+ downcasts), TopExp, TopLoc,
  TopTools, BRep, BinTools, Poly, Standard. 34 of the app's 139 symbols.
- n3xd_ocp: additive APIs kept out of the OCP namespace so parity testing stays
  meaningful. bintools (shape <-> bytes, GIL-free, byte-identical) and _debug.

Two findings worth the record, both verified against the stock wheel rather
than assumed: upstream binds __hash__ but leaves __eq__ at identity, which is
exactly what geom_memo.py's hash-bucket + IsSame scan is built around, so we
match it instead of "fixing" it; and BinTools can release the GIL after all, by
slurping the file-like object instead of bridging a streambuf that would call
back into Python.

Gate: BREP round-trips are byte-identical to cadquery-ocp-novtk across six
fixtures (the generator asserts stock idempotency first). That matters beyond
IPC — derive.py content-addresses BREP payloads by sha256 and stores the ref.
This commit is contained in:
2026-08-10 16:10:28 +02:00
parent b757d6e8d6
commit 6139852768
58 changed files with 3446 additions and 13 deletions

172
tools/gen_fixtures.py Normal file
View File

@@ -0,0 +1,172 @@
"""Generate the .brep byte-identity fixtures.
Runs under the STOCK cadquery-ocp-novtk wheel, not this binding — the fixtures
are the reference the Inc 0 gate compares against. From the app checkout:
app/.venv/bin/python ../ocp/tools/gen_fixtures.py
Two properties are recorded, and the first is checked here rather than assumed:
* stock is idempotent — reading a shape and writing it back reproduces the
same bytes. Without that the gate would be comparing against a moving
target, and a mismatch would say nothing.
* the digest of those bytes, which is what the gate reproduces. This matters
beyond IPC: cad/derive.py content-addresses BREP payloads as
payloads/derived/brep/<sha256>.brep and stores the ref in the document, so
a binding that serialises differently rewrites every derived payload.
Face counts are recorded alongside, pinning the map ordering that face and edge
identity depend on throughout the topology code.
"""
from __future__ import annotations
import hashlib
import io
import json
import pathlib
import sys
from OCP.BinTools import BinTools
from OCP.BRep import BRep_Builder
from OCP.BRepAlgoAPI import BRepAlgoAPI_Cut, BRepAlgoAPI_Fuse
from OCP.BRepMesh import BRepMesh_IncrementalMesh
from OCP.BRepPrimAPI import BRepPrimAPI_MakeBox, BRepPrimAPI_MakeCylinder
from OCP.gp import gp_Ax2, gp_Dir, gp_Pnt, gp_Trsf, gp_Vec
from OCP.TopAbs import TopAbs_FACE
from OCP.TopExp import TopExp
from OCP.TopLoc import TopLoc_Location
from OCP.TopoDS import TopoDS_Compound, TopoDS_Shape
from OCP.TopTools import TopTools_IndexedMapOfShape
OUT = pathlib.Path(__file__).resolve().parent.parent / "tests" / "data"
def _box(dx=10.0, dy=20.0, dz=30.0) -> TopoDS_Shape:
return BRepPrimAPI_MakeBox(dx, dy, dz).Shape()
def _meshed_box() -> TopoDS_Shape:
shape = _box()
BRepMesh_IncrementalMesh(shape, 0.1, False, 0.5, True)
return shape
def _fused() -> TopoDS_Shape:
op = BRepAlgoAPI_Fuse()
from OCP.TopTools import TopTools_ListOfShape
args, tools = TopTools_ListOfShape(), TopTools_ListOfShape()
args.Append(_box())
tools.Append(
BRepPrimAPI_MakeBox(gp_Pnt(5, 5, 5), 20.0, 20.0, 20.0).Shape()
)
op.SetArguments(args)
op.SetTools(tools)
op.Build()
return op.Shape()
def _cut_cylinder() -> TopoDS_Shape:
op = BRepAlgoAPI_Cut()
from OCP.TopTools import TopTools_ListOfShape
args, tools = TopTools_ListOfShape(), TopTools_ListOfShape()
args.Append(_box())
tools.Append(
BRepPrimAPI_MakeCylinder(
gp_Ax2(gp_Pnt(5, 10, 0), gp_Dir(0, 0, 1)), 3.0, 30.0
).Shape()
)
op.SetArguments(args)
op.SetTools(tools)
op.Build()
return op.Shape()
def _located_compound() -> TopoDS_Shape:
"""Exercises the location/TShape sharing part of the format."""
builder = BRep_Builder()
comp = TopoDS_Compound()
builder.MakeCompound(comp)
base = _box()
builder.Add(comp, base)
trsf = gp_Trsf()
trsf.SetTranslation(gp_Vec(50.0, 0.0, 0.0))
builder.Add(comp, base.Moved(TopLoc_Location(trsf)))
return comp
def _empty_compound() -> TopoDS_Shape:
builder = BRep_Builder()
comp = TopoDS_Compound()
builder.MakeCompound(comp)
return comp
SHAPES = {
"box": _box,
"box_meshed": _meshed_box,
"fused": _fused,
"cut_cylinder": _cut_cylinder,
"located_compound": _located_compound,
"empty_compound": _empty_compound,
}
def write_bytes(shape: TopoDS_Shape) -> bytes:
buf = io.BytesIO()
BinTools.Write_s(shape, buf)
return buf.getvalue()
def read_shape(data: bytes) -> TopoDS_Shape:
shape = TopoDS_Shape()
BinTools.Read_s(shape, io.BytesIO(data))
return shape
def face_count(shape: TopoDS_Shape) -> int:
faces = TopTools_IndexedMapOfShape()
TopExp.MapShapes_s(shape, TopAbs_FACE, faces)
return faces.Extent()
def main() -> int:
import OCP
OUT.mkdir(parents=True, exist_ok=True)
manifest: dict = {
"generated_by": "cadquery-ocp-novtk",
"occt_version": getattr(OCP, "__version__", "unknown"),
"shapes": {},
}
for name, build in SHAPES.items():
shape = build()
data = write_bytes(shape)
# The gate is "our rewrite == stock rewrite". If stock itself is not
# idempotent for a fixture, that fixture cannot serve as a reference.
rewritten = write_bytes(read_shape(data))
if rewritten != data:
print(f"FAIL {name}: stock is not idempotent", file=sys.stderr)
return 1
(OUT / f"{name}.brep").write_bytes(data)
manifest["shapes"][name] = {
"sha256": hashlib.sha256(data).hexdigest(),
"size": len(data),
"faces": face_count(shape),
}
print(f"{name}: {len(data)} bytes, {manifest['shapes'][name]['faces']} faces")
(OUT / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
print(f"\nwrote {len(SHAPES)} fixtures + manifest to {OUT}")
return 0
if __name__ == "__main__":
raise SystemExit(main())