-- cad/step tests: OCCT-written and public STEP files against a Python Part 21 census, OCCT and brep-luau. -- Fixtures: tools/fixtures/step.py. local T = require("@tests/T") local F = require("@rosetta") local Step = require("@rosetta/cad/step") local Bytes = require("@rosetta/core/Bytes") local Err = require("@rosetta/core/Err") local Cases = require("@tests/gen/step_cases") local t = T.suite("step") local function decode(s: string, opts: any?): (any, any) return Step.decode(Bytes.reader(buffer.fromstring(s)), opts) end local function encode(cad: any, opts: any?): string local b, err = Step.encode(cad, opts) t:check(b, "encode: " .. tostring(err)) return if b then buffer.tostring(b) else "" end local function near(a: number, b: number, rel: number): boolean return math.abs(a - b) <= rel * math.max(1, math.abs(a), math.abs(b)) end t:eq(Step.name, "step", "name") t:eq(Step.category, "cad", "category") t:check(Step.caps.decode and Step.caps.encode and table.find(Step.extensions, "stp"), "contract") local function same(a: any, b: any, path: string, depth: number?): (boolean, string) local d = depth or 0 if type(a) ~= "table" or type(b) ~= "table" then return a == b, path end if a == b then return true, path end if d > 60 then return false, path .. " (too deep)" end for k, v in a do local ok, where = same(v, b[k], path .. "." .. tostring(k), d + 1) if not ok then return false, where end end for k in b do if a[k] == nil then return false, path .. "." .. tostring(k) .. " (extra)" end end local ma, mb = getmetatable(a), getmetatable(b) local ra = ma and ma.__reals or {} local rb = mb and mb.__reals or {} for k in ra do if not rb[k] then return false, path .. "[" .. tostring(k) .. "] real mark" end end for k in rb do if not ra[k] then return false, path .. "[" .. tostring(k) .. "] real mark (extra)" end end return true, path end local decoded = {} local samples = {} local t0 = T.clock() local bytes = 0 for i, c in Cases do local cad, err = decode(c.data) t:check(cad, c.name .. ": decode: " .. tostring(err)) decoded[i] = cad bytes += #c.data t:eq(cad.meta.count, c.census.count, c.name .. ": instances (census)") local types = {} for _, e in cad.entities do types[e.type] = (types[e.type] or 0) + 1 end for ty, n in c.census.types do t:eq(types[ty], n, c.name .. ": " .. ty .. " count") end for ty in types do t:check(c.census.types[ty], c.name .. ": no extra type " .. ty) end local text = encode(cad) local again = decode(text) t:check(again, c.name .. ": our output decodes") local ok, where = same(cad.entities, again.entities, "entities") t:check(ok, c.name .. ": round trip differs at " .. where) t:eq(encode(again), text, c.name .. ": write is stable") t:check(same(cad.header, again.header, "header"), c.name .. ": header round trip") if c.occt and not c.occt.failed then t:check(c.ours and not c.ours.failed, c.name .. ": OCCT reads our output") t:eq(c.ours.solids, c.occt.solids, c.name .. ": OCCT solids of our output") t:eq(c.ours.faces, c.occt.faces, c.name .. ": OCCT faces of our output") t:check(near(c.ours.volume, c.occt.volume, 1e-9), c.name .. ": OCCT volume of our output") t:check(near(c.ours.area, c.occt.area, 1e-9), c.name .. ": OCCT area of our output") end if #samples < 4 and #c.data < 40000 then table.insert(samples, buffer.fromstring(c.data)) end end local dt = T.clock() - t0 t:note("%d files (%.1f MB): census, OCCT read-back, round trips (%.2f s)", #Cases, bytes / 1e6, dt) local CRAFT = [[ ISO-10303-21; /* a comment */ HEADER; FILE_DESCRIPTION(('test'),'2;1'); FILE_NAME('craft.stp','2024-01-01T00:00:00',('A \X2\00C9\X0\crivain'),(''),'','',''); FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }')); ENDSEC; DATA; #1=CARTESIAN_POINT('',(0.,1.5,-2.E-3)); #2 = DIRECTION ( 'd' , ( 1. , 0. , 0. ) ) ; #3=FOO('It''s','back\\slash','\S\i','\X\E9t\X\E9','\X2\03B103B2\X0\ ok','\X4\0001F600\X0\',.T.,.UNSPECIFIED.,$,*,#1, "0FF",LENGTH_MEASURE(2.),POSITIVE_LENGTH_MEASURE(3.5),(1,2,(3,4.)),(),-7,+8,1.E2); #10=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNIT_ASSIGNED_CONTEXT((#11))REPRESENTATION_CONTEXT('c','3D')); #11=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.)); /* comment between instances */ #12=!USER_DEFINED(1); ENDSEC; END-ISO-10303-21; ]] local cad, err = decode(CRAFT) t:check(cad, "craft: " .. tostring(err)) t:eq(cad.schema, "AP214", "craft: schema") t:eq(cad.meta.count, 6, "craft: count") t:eq(cad.header.FILE_NAME[3][1], "A Écrivain", "craft: header \\X2\\") local p = cad.entities[1] t:eq(p.type, "CARTESIAN_POINT", "craft: type") t:eq(p.args[2][3], -2e-3, "craft: real") t:check(getmetatable(p.args[2]).__reals[1] and getmetatable(p.args[2]).__reals[2] == nil, "craft: integral real marked") t:eq(cad.entities[2].args[1], "d", "craft: spaced instance") local a = cad.entities[3].args t:eq(a[1], "It's", "craft: ''") t:eq(a[2], "back\\slash", "craft: \\\\") t:eq(a[3], "é", "craft: \\S\\") t:eq(a[4], "été", "craft: \\X\\") t:eq(a[5], "αβ ok", "craft: \\X2\\") t:eq(a[6], "😀", "craft: \\X4\\") t:eq(a[7].enum, "T", "craft: boolean") t:eq(a[8].enum, "UNSPECIFIED", "craft: enum") t:eq(a[9], Step.NULL, "craft: $") t:eq(a[10], Step.DERIVED, "craft: *") t:eq(a[11].ref, 1, "craft: ref") t:eq(Step.get(cad, a[11]), p, "craft: get(ref)") t:eq(a[12].binary, "0FF", "craft: binary") t:eq(a[13].typed, "LENGTH_MEASURE", "craft: typed") t:eq(a[13].value, 2, "craft: typed value") t:eq(a[14].value, 3.5, "craft: typed real") t:eq(a[15][3][2], 4, "craft: nested list") t:eq(#a[16], 0, "craft: empty list") t:eq(a[17], -7, "craft: negative integer") t:eq(a[18], 8, "craft: +integer") t:eq(a[19], 100, "craft: 1.E2") local cx = cad.entities[10] t:eq(cx.type, "COMPLEX", "craft: complex") t:eq(#cx.parts, 3, "craft: complex parts") t:eq(Step.part(cx, "GEOMETRIC_REPRESENTATION_CONTEXT")[1], 3, "craft: part()") t:eq(Step.part(cad.entities[11], "SI_UNIT")[2].enum, "METRE", "craft: SI_UNIT part") t:eq(cad.entities[12].type, "!USER_DEFINED", "craft: user-defined entity") t:eq(#Step.byType(cad, "SI_UNIT"), 1, "craft: byType through complex parts") local text = encode(cad) t:check(string.find(text, "#3=FOO('It''s','back\\\\slash','\\X2\\00E9\\X0\\'", 1, true), "craft: strings re-escaped") t:check(string.find(text, "'\\X4\\0001F600\\X0\\'", 1, true), "craft: \\X4\\ written") t:check(string.find(text, "CARTESIAN_POINT('',(0.,1.5,-0.002))", 1, true), "craft: reals written") t:check(string.find(text, "LENGTH_MEASURE(2.)", 1, true), "craft: typed integral real") t:check(string.find(text, "(1,2,(3,4.)),(),-7,8,100.);", 1, true), "craft: integers and lists") t:check(string.find(text, "#10=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNIT_ASSIGNED_CONTEXT((#11))", 1, true), "craft: complex written") local back = decode(text) t:check(back and same(cad.entities, back.entities, "entities"), "craft: round trip") t:eq(back.header.FILE_NAME[3][1], "A Écrivain", "craft: header round trip") -- edition 3: named DATA sections, ANCHOR section kept raw local ED3 = [[ISO-10303-21; HEADER; FILE_DESCRIPTION((''),'3;1'); FILE_NAME('','',(''),(''),'','',''); FILE_SCHEMA(('CONFIG_CONTROL_DESIGN','OTHER_SCHEMA')); ENDSEC; ANCHOR; = #1; ENDSEC; DATA('first',('CONFIG_CONTROL_DESIGN')); #1=A(1); ENDSEC; DATA('second',('OTHER_SCHEMA')); #2=B('x;y',#1); ENDSEC; END-ISO-10303-21; ]] local e3, e3err = decode(ED3) t:check(e3, "ed3: " .. tostring(e3err)) t:eq(e3.schema, "AP203", "ed3: schema") t:eq(#e3.meta.source.sections, 2, "ed3: sections") t:eq(e3.entities[2].section, 2, "ed3: entity section") t:eq(e3.entities[2].args[1], "x;y", "ed3: ; inside a string") t:eq(e3.meta.source.extra[1].name, "ANCHOR", "ed3: anchor kept") local e3text = encode(e3) t:check(string.find(e3text, "DATA('second',('OTHER_SCHEMA'));\n#2=B('x;y',#1);", 1, true), "ed3: sections written") t:check(string.find(e3text, "ANCHOR;\n = #1;\nENDSEC;", 1, true), "ed3: anchor written") local e3b = decode(e3text) t:check(e3b and same(e3.entities, e3b.entities, "e"), "ed3: round trip") local new = Step.new("AP242") local pt = Step.add(new, "cartesian_point", { "origin", Step.real({ 0, 0, 1.25 }, 1) }) Step.add(new, "VERTEX_POINT", { "", { ref = pt } }) local ntext = encode(new, { name = "built.stp" }) t:check(string.find(ntext, "FILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }'));", 1, true), "new: schema") t:check(string.find(ntext, "#1=CARTESIAN_POINT('origin',(0.,0,1.25));\n#2=VERTEX_POINT('',#1);", 1, true), "new: instances") t:eq(decode(ntext).schema, "AP242", "new: decodes") local _, bad = Step.encode({ kind = "cad", entities = { [1] = { id = 1, type = "X", args = { 0 / 0 } } }, header = {}, meta = {} }) t:eq(bad and bad.code, Err.ARG, "encode: nan -> ARG") local _, bad2 = Step.encode({ kind = "cad", entities = { [1] = { id = 1, type = "bad type", args = {} } }, header = {}, meta = {} }) t:eq(bad2 and bad2.code, Err.ARG, "encode: bad type -> ARG") local cyc = {} cyc[1] = cyc local _, bad3 = Step.encode({ kind = "cad", entities = { [1] = { id = 1, type = "X", args = cyc } }, header = {}, meta = {} }) t:eq(bad3 and bad3.code, Err.ARG, "encode: cycle -> ARG") local _, bad4 = Step.encode({ kind = "image" } :: any) t:eq(bad4 and bad4.code, Err.ARG, "encode: not a Cad") local function code(s: string, opts: any?): string? local v, e = decode(s, opts) return if v then nil else e.code end t:eq(code("hello"), Err.CORRUPT, "no magic") t:eq(code(string.sub(CRAFT, 1, 400)), Err.TRUNCATED, "truncated") t:eq(code("ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=A(1,;\nENDSEC;\nEND-ISO-10303-21;"), Err.CORRUPT, "bad list") t:eq(code("ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=A('x);\nENDSEC;\n"), Err.TRUNCATED, "open string") t:eq(code(CRAFT, { maxEntities = 3 }), Err.LIMIT, "maxEntities") t:eq(code(CRAFT, { maxBytes = 100 }), Err.LIMIT, "maxBytes") t:eq(code("ISO-10303-21;\nHEADER;\nENDSEC;\n"), Err.TRUNCATED, "no DATA") local deep = "ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=A(" .. string.rep("(", 500) .. string.rep(")", 500) .. ");\nENDSEC;\n" t:eq(code(deep), Err.CORRUPT, "nesting limit") t:eq(Step.sniff(Bytes.reader(buffer.fromstring(CRAFT))), 1, "sniff") t:eq(Step.sniff(Bytes.reader(buffer.fromstring("\239\187\191/* x */ ISO-10303-21;"))), 1, "sniff: BOM + comment") t:eq(Step.sniff(Bytes.reader(buffer.fromstring("ISO-10303-28"))), 0, "sniff: other") local loaded, lerr = F.load(CRAFT) t:check(loaded and loaded.kind == "cad", "F.load: " .. tostring(lerr)) t:eq(F.detect(CRAFT), "step", "F.detect") local saved = F.save(loaded) t:check(type(saved) == "buffer" and decode(buffer.tostring(saved)).meta.count == 6, "F.save (source format)") local _, nop = Step.toBodies(loaded) t:eq(nop and nop.code, Err.UNSUPPORTED, "toBodies without a plug-in") local _, nop2 = F.cad.tessellate(loaded) t:eq(nop2 and nop2.code, Err.UNSUPPORTED, "F.cad.tessellate without a plug-in") local calls = {} local fake = { read = function(text: string, _opts: any): any calls.read = #text return { bodies = { { name = "tri", color = { 1, 0, 0 } } }, stats = { solids = 1 } } end, write = function(bodies: { any }, _opts: any): string calls.write = #bodies return CRAFT end, tessellate = function(_body: any, _opts: any): any return { positions = { { 0, 0, 0 }, { x = 1, y = 0, z = 0 }, { 0, 1, 0 }, { 0, 0, 1 } }, indices = { 1, 3, 2, 1, 2, 4, 1, 4, 3, 2, 3, 4 } } end, } local fb, finfo = Step.toBodies(loaded, { brep = fake }) t:check(fb and #fb == 1 and finfo.stats.solids == 1 and calls.read > 0, "custom plug-in: toBodies") local fc = Step.fromBodies({ {} }, { plugins = { brep = fake } }) t:check(fc and fc.kind == "cad" and calls.write == 1, "custom plug-in: fromBodies") local fs, fserr = Step.tessellate(loaded, { brep = fake }) t:check(fs and fs.kind == "scene", "custom plug-in: tessellate: " .. tostring(fserr)) t:eq(fs.meta.up, "z", "scene: z up") t:eq(fs.meta.unit, 0.001, "scene: millimetres") t:eq(fs.meshes[1].name, "tri", "scene: body name") t:eq(fs.materials[fs.meshes[1].primitives[1].material].extras.color[1], 1, "scene: body colour") t:eq(fs.meshes[1].primitives[1].indices.count, 12, "scene: indices") local throwing = { read = function(): any error("kernel failure") end } local _, terr = Step.toBodies(loaded, { brep = throwing }) t:eq(terr and terr.code, Err.CORRUPT, "plug-in that throws -> Err") F.plugins.brep = fake local fapi = F.cad.tessellate(loaded) t:check(fapi and fapi.kind == "scene", "F.cad.tessellate through F.plugins") F.plugins.brep = nil -- brep-luau: luau CLI only (tests/gen/.luaurc aliases it); LuaJIT has no `vector` type local function volume(scene: any): (number, { number }) local v = 0 local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } for _, m in scene.meshes do for _, pr in m.primitives do local pos, ind = pr.attributes.POSITION.data, pr.indices.data local function P(i: number, k: number): number return buffer.readf32(pos, (i * 3 + k) * 4) end for tri = 0, pr.indices.count // 3 - 1 do local ia, ib, ic = buffer.readu32(ind, tri * 12), buffer.readu32(ind, tri * 12 + 4), buffer.readu32(ind, tri * 12 + 8) local ax, ay, az = P(ia, 0), P(ia, 1), P(ia, 2) local bx, by, bz = P(ib, 0), P(ib, 1), P(ib, 2) local cx2, cy, cz = P(ic, 0), P(ic, 1), P(ic, 2) v += (ax * (by * cz - bz * cy) - ay * (bx * cz - bz * cx2) + az * (bx * cy - by * cx2)) / 6 for _, q in { { ax, ay, az }, { bx, by, bz }, { cx2, cy, cz } } do for k = 1, 3 do lo[k] = math.min(lo[k], q[k]) hi[k] = math.max(hi[k], q[k]) end end end end end return v, { lo[1], lo[2], lo[3], hi[1], hi[2], hi[3] } end local brepOk, brep = false, nil if T.runtime == "luau" then local ok, mods = pcall(require, "@tests/gen/step_brep") brepOk, brep = ok and type(mods) == "table", mods end if brepOk then local plug = { Step = brep.Step, StepBrep = brep.StepBrep, StepWrite = brep.StepWrite, Tess = brep.Tess } local n = 0 for i, c in Cases do -- the gmsh solids and the small public part (the 2 MB sample takes too long to tessellate here) if decoded[i] and c.occt and not c.occt.failed and #c.data < 400000 then local scene, serr = Step.tessellate(decoded[i], { brep = plug, tess = { chord = 0.01, angle = 0.05 } }) t:check(scene, c.name .. ": tessellate: " .. tostring(serr)) if scene then local bodies = Step.toBodies(decoded[i], { brep = plug }) t:eq(#bodies, c.occt.solids, c.name .. ": solids (OCCT)") local v, bb = volume(scene) -- brep-luau reading the original text directly: our parse + write must not change what the kernel sees local direct = brep.StepBrep.read(brep.Step.parse(c.data)).bodies local dv, leaks = 0, 0 for _, b in direct do local m = brep.Tess.body(b, { chord = 0.01, angle = 0.05 }) dv += brep.Tess.volume(m) leaks += brep.Tess.leaks(m) end t:check(near(v, dv, 1e-6), string.format("%s: volume %.4f, brep-luau on the original %.4f", c.name, v, dv)) if leaks == 0 then t:check(near(v, c.occt.volume, 2e-3), string.format("%s: volume %.3f, OCCT %.3f", c.name, v, c.occt.volume)) else t:note("%s: brep-luau's tessellation leaks (%d open edges): volume %.1f vs OCCT %.1f not compared", c.name, leaks, v, c.occt.volume) end for k = 1, 6 do -- (OCCT's box is not tight around curved faces: ours must lie inside it) local inside = if k <= 3 then bb[k] >= c.occt.bbox[k] - 0.05 else bb[k] <= c.occt.bbox[k] + 0.05 t:check(inside, string.format("%s: bounds[%d] %.4f, OCCT %.4f", c.name, k, bb[k], c.occt.bbox[k])) end n += 1 end end end local M = brep.M local part = brep.Boolean.subtract(brep.Build.box(M.v(0, 0, 0), M.v(40, 30, 5)), brep.Build.cylinder(M.v(20, 15, -1), 6, 7))[1] part.color = { r = 0.2, g = 0.5, b = 0.9 } local built, berr = F.cad.fromBodies({ part }, { brep = plug }) t:check(built and built.kind == "cad" and #Step.byType(built, "ADVANCED_FACE") >= 7, "fromBodies: " .. tostring(berr)) local again2 = decode(encode(built)) local scene2 = Step.tessellate(again2, { brep = plug, chord = 0.01 }) local v2 = volume(scene2) local want = brep.Tess.volume(brep.Tess.body(part, { chord = 0.01 })) t:check(near(v2, want, 1e-3), string.format("fromBodies round trip: volume %.3f, kernel %.3f", v2, want)) t:check(near(v2, 40 * 30 * 5 - math.pi * 36 * 5, 2e-3), "fromBodies round trip: analytic volume") local col = scene2.materials[scene2.meshes[1].primitives[1].material].extras.color t:check(col and near(col[1], 0.2, 1e-6) and near(col[3], 0.9, 1e-6), "fromBodies round trip: colour") t:note("brep-luau plug-in: %d files tessellated against OCCT, bodies -> STEP -> bodies", n) else t:note("brep-luau plug-in part skipped (%s)", if T.runtime ~= "luau" then "LuaJIT: no vector type" else "no ~/dev/luau/brep-luau") end table.insert(samples, buffer.fromstring(CRAFT)) table.insert(samples, buffer.fromstring(ED3)) t:fuzz("decode", function(b: buffer): any return Step.decode(Bytes.reader(b)) end, samples, { keepHeader = 13 }) t:done()