Files

186 lines
7.7 KiB
Python

# 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/Rosetta/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)