ws-3d2/step: cad/step (ISO 10303-21 read/write + injected B-rep plug-in)

- src/Formats/cad/step: Part 21 editions 1-3 parsed into Types.Cad fully in-library (header, named DATA sections,
  complex instances, every parameter kind, string escapes to UTF-8, comments, ANCHOR/REFERENCE/SIGNATURE kept raw);
  writer round-trips at the entity level (integral reals keep their real-ness via a list metatable mark).
- B-rep plug-in: a small injected table { read, write, tessellate } (or brep-luau's { Step, StepBrep, StepWrite, Tess }
  as is), taken from opts.brep / opts.plugins.brep; Step.toBodies / fromBodies / tessellate (-> Scene, z up, mm).
- Types.luau: StepEntity gains optional parts (complex instances) and section (edition 3); backward compatible.
- init.luau (api): withHooks also passes opts.plugins = F.plugins to decoders/encoders unless given; new facades
  F.cad.toBodies / fromBodies / tessellate (pass F.plugins, pcall, Err-wrapped). Backward compatible.
- tests/cad/step.luau + tools/fixtures/step.py: OCCT (gmsh) generated and public STEP files, Python census, OCCT reads
  our output back, brep-luau through a generated tests/gen/.luaurc alias (luau only), fuzz.
- tools/bench.luau: step parse / write lines.
This commit is contained in:
4DBug committed 2026-10-31 09:33:58 -05:00
1 parent 646d18f056
commit 443a7e45cb
12 files changed
+2154 -2

No files matched your search

+19
View File
@@ -535,3 +535,22 @@ do
Webp.encode(img, { effort = 1 })
end)
end
do
-- STEP (tools/fixtures/step.py): the largest case, parse and write
local Step = require("@formats/cad/step")
local SC = require("@tests/gen/step_cases")
local big = SC[1]
for _, c in SC do
if #c.data > #big.data then
big = c
end
end
local data = buffer.fromstring(big.data)
local cad = assert(Step.decode(Bytes.reader(data)))
bench(string.format("step parse (%.1f MB)", #big.data / 1e6), 3, #big.data, function()
Step.decode(Bytes.reader(data))
end)
bench("step write", 3, #big.data, function()
Step.encode(cad)
end)
end
+27
View File
@@ -0,0 +1,27 @@
-- tools/fixtures/_step_encode: run by tools/fixtures/step.py (luau CLI, repo root): decodes every STEP case with our
-- reader and writes it back with our writer, printing "case_<i>.step\t<hex>" lines for OCCT (through gmsh) to read.
local Step = require("@formats/cad/step")
local Bytes = require("@formats/core/Bytes")
local Cases = require("@tests/gen/step_cases")
local HEX = {}
for i = 0, 255 do
HEX[i] = string.format("%02x", i)
end
local function hex(s: string): string
local out = table.create(#s)
for i = 1, #s do
out[i] = HEX[string.byte(s, i)]
end
return table.concat(out)
end
for i, c in Cases do
local cad, err = Step.decode(Bytes.reader(buffer.fromstring(c.data)))
if cad then
local out = assert(Step.encode(cad))
print(string.format("case_%d.step\t%s", i, hex(buffer.tostring(out))))
else
print("skipped " .. c.name .. ": " .. tostring(err))
end
end
+185
View File
@@ -0,0 +1,185 @@
# STEP fixtures (tools/fixtures.py): solids modelled in gmsh's OpenCASCADE kernel and written as STEP by OCCT
# (gmsh -0 x.geo -o x.step), plus public STEP files fetched at fixture time into a fresh temporary directory
# (untrusted input, only read; skipped when offline). Reference values:
# - a Part 21 instance census by an independent Python tokenizer (instance count, count per entity type),
# - OCCT through gmsh's Python API: number of solids, total volume, number of faces, total area, bounding box.
# Our writer's output (tools/fixtures/_step_encode.luau re-encodes every case) is read back by OCCT through gmsh too.
# tests/gen/step_cases.luau { name, data, census = { count, types = { TYPE = n } }, occt = { solids, volume,
# faces, area, bbox }, ours = occt values of our re-encoded file }
# tests/gen/step_brep.luau brep-luau's modules ({ Step, StepBrep, StepWrite, Tess, Build, Boolean, M }) through the
# tests/gen/.luaurc alias "brep" (only when ~/dev/luau/brep-luau, or $BREP_LUAU, exists; luau CLI only)
import json, os, re, shutil, subprocess, tempfile, urllib.request
INPUTS = ["src/Formats/cad/step", "tools/fixtures/_step_encode.luau"]
GEO = {
"plate": """Box(1) = {0,0,0, 40,30,5};
Cylinder(2) = {20,15,-1, 0,0,7, 6};
BooleanDifference{ Volume{1}; Delete; }{ Volume{2}; Delete; }""",
"sphere": "Sphere(1) = {0,0,0, 10};",
"torus": "Torus(1) = {0,0,0, 20, 5};",
"cone": "Cone(1) = {0,0,0, 0,0,12, 6, 2};",
"two_boxes": """Box(1) = {0,0,0, 10,10,10};
Box(2) = {20,0,0, 5,5,30};""",
"bracket": """Box(1) = {0,0,0, 60,40,8};
Box(2) = {0,0,0, 8,40,50};
BooleanUnion{ Volume{1}; Delete; }{ Volume{2}; Delete; }
Cylinder(3) = {30,20,-1, 0,0,10, 7};
Sphere(4) = {4,20,35, 9};
BooleanDifference{ Volume{1}; Delete; }{ Volume{3,4}; Delete; }""",
}
URLS = {
# build123d documentation example (Apache-2.0)
"nema17_bracket": "https://raw.githubusercontent.com/gumyr/build123d/dev/docs/topology_selection/examples/nema-17-bracket.step",
# pythonocc-demos sample model (parse + OCCT reference only; not committed)
"ventilator": "https://raw.githubusercontent.com/tpaviot/pythonocc-demos/master/assets/models/Ventilator.stp",
}
MAX_FETCH = 4 << 20
OCCT = r"""
import json, sys, gmsh
gmsh.initialize()
gmsh.option.setNumber("General.Terminal", 0)
res = []
for p in json.loads(sys.stdin.read()):
try:
gmsh.clear()
gmsh.model.occ.importShapes(p)
gmsh.model.occ.synchronize()
vols = gmsh.model.getEntities(3)
faces = gmsh.model.getEntities(2)
bb = gmsh.model.getBoundingBox(-1, -1)
res.append({"solids": len(vols), "volume": sum(gmsh.model.occ.getMass(3, t) for _, t in vols),
"faces": len(faces), "area": sum(gmsh.model.occ.getMass(2, t) for _, t in faces), "bbox": list(bb)})
except Exception as e:
res.append({"failed": True})
print(json.dumps(res))
"""
def census(text):
# an independent Part 21 tokenizer: comments and strings removed, statements split at ';'
out = []
i, n = 0, len(text)
while i < n:
c = text[i]
if c == "'":
j = i + 1
while True:
j = text.index("'", j)
if j + 1 < n and text[j + 1] == "'":
j += 2
else:
break
out.append("''")
i = j + 1
elif c == "/" and text.startswith("/*", i):
i = text.index("*/", i + 2) + 2
else:
out.append(c)
i += 1
clean = "".join(out)
data = clean[clean.index("DATA"):]
types = {}
count = 0
for st in data.split(";"):
m = re.match(r"\s*#(\d+)\s*=\s*(\(|[A-Za-z_][A-Za-z0-9_]*)", st)
if m:
count += 1
t = "COMPLEX" if m.group(2) == "(" else m.group(2).upper()
types[t] = types.get(t, 0) + 1
return {"count": count, "types": types}
def occt(ctx, paths):
expr = "with import <nixpkgs> {}; python3.withPackages (p: [p.gmsh])"
cmd = ["nix", "shell", "--impure", "--expr", expr, "-c", "python3", "-I", "-c", OCCT]
res = subprocess.run(cmd, input=json.dumps(paths).encode(), capture_output=True, check=True)
return json.loads(res.stdout)
def luau(ctx, script):
exe = shutil.which("luau")
cmd = [exe, script] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script]
res = subprocess.run(cmd, cwd=ctx.root, capture_output=True, check=True)
files = {}
for line in res.stdout.decode().split("\n"):
if "\t" in line:
name, hexdata = line.split("\t", 1)
files[name] = bytes.fromhex(hexdata.strip())
return files
def brep(ctx):
root = os.environ.get("BREP_LUAU") or os.path.expanduser("~/dev/luau/brep-luau")
rc = os.path.join(ctx.gen, ".luaurc")
mod = os.path.join(ctx.gen, "step_brep.luau")
if not os.path.exists(os.path.join(root, "src", "step", "StepBrep.luau")):
for p in (rc, mod):
if os.path.exists(p):
os.remove(p)
ctx.emit("step_brep", False)
return
with open(rc, "w") as f:
json.dump({"aliases": {"brep": os.path.join(os.path.abspath(root), "src")}}, f)
path = os.path.join(ctx.gen, "step_brep.luau")
with open(path, "w") as f:
f.write("-- generated by tools/fixtures.py (tools/fixtures/step.py) - do not edit\n"
"-- brep-luau through the tests/gen/.luaurc alias \"brep\" (luau CLI only)\n"
"return {\n"
"\tStep = require(\"@brep/step/Step\"),\n"
"\tStepBrep = require(\"@brep/step/StepBrep\"),\n"
"\tStepWrite = require(\"@brep/kernel/StepWrite\"),\n"
"\tTess = require(\"@brep/kernel/Tess\"),\n"
"\tBuild = require(\"@brep/kernel/Build\"),\n"
"\tBoolean = require(\"@brep/kernel/Boolean\"),\n"
"\tM = require(\"@brep/kernel/Math\"),\n"
"}\n")
ctx.outputs.append(path)
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="formats-step-")
cases = []
for name, geo in GEO.items():
g = os.path.join(tmp, name + ".geo")
with open(g, "w") as f:
f.write('SetFactory("OpenCASCADE");\n' + geo + "\n")
out = os.path.join(tmp, name + ".step")
ctx.nix("gmsh", ["gmsh", "-0", g, "-o", out])
cases.append({"name": "gmsh/" + name, "path": out})
fetched = tempfile.mkdtemp(prefix="formats-step-fetch-")
for name, url in URLS.items():
dst = os.path.join(fetched, name + ".step")
try:
with urllib.request.urlopen(url, timeout=30) as r:
data = r.read(MAX_FETCH + 1)
if len(data) > MAX_FETCH:
continue
with open(dst, "wb") as f:
f.write(data)
cases.append({"name": "public/" + name, "path": dst, "public": True})
except Exception:
pass
refs = occt(ctx, [c["path"] for c in cases])
for c, r in zip(cases, refs):
c["data"] = open(c["path"], "rb").read()
c["census"] = census(c["data"].decode("latin-1"))
c["occt"] = r
# our writer's output of every case, read back by OCCT
ctx.emit("step_cases", [{k: v for k, v in c.items() if k != "path"} for c in cases])
ours = luau(ctx, "tools/fixtures/_step_encode.luau")
xtmp = tempfile.mkdtemp(prefix="formats-step-ours-")
paths = []
for i in range(len(cases)):
data = ours.get("case_%d.step" % (i + 1))
p = os.path.join(xtmp, "case_%d.step" % (i + 1))
with open(p, "wb") as f:
f.write(data or b"")
paths.append(p)
back = occt(ctx, paths)
for c, r in zip(cases, back):
c["ours"] = r
ctx.emit("step_cases", [{k: v for k, v in c.items() if k != "path"} for c in cases])
brep(ctx)