diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 40e275f..0d46299 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -26,6 +26,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | +| cad | step | .step .stp .p21 | yes | yes | complexEntities: true, sections: true, brep: "plugin", tessellate: "plugin" | `tests/cad/step.luau` | | font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary" | `tests/font/bmfont.luau` | | font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` | | font | woff | .woff | yes | - | outlines: "truetype", "cff" | `tests/font/woff.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d514aa9..1cbc445 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -266,6 +266,18 @@ local list: { Entry } = { return require("@formats/model/vox") end, }, + { + name = "step", + category = "cad", + path = "cad/step", + extensions = { "step", "stp", "p21" }, + mime = { "model/step", "application/step", "application/p21" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" }, + load = function() + return require("@formats/cad/step") + end, + }, { name = "bmfont", category = "font", diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index 6464e98..66eeba6 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -561,7 +561,9 @@ end -- ------------------------------------------------------------------------------------------------ Cad -- the STEP entity graph; B-rep bodies and tessellation come from the injected brep plug-in (Formats.plugins.brep) -export type StepEntity = { id: number, type: string, args: { any } } +-- complex (external mapping) instances: type = "COMPLEX", args = {}, parts = { { type, args } } in file order; +-- section = the DATA section index when a file has more than one (edition 3) +export type StepEntity = { id: number, type: string, args: { any }, parts: { { type: string, args: { any } } }?, section: number? } export type Cad = { kind: "cad", schema: string, -- "AP203", "AP214", "AP242", ... diff --git a/src/Formats/cad/step/Brep.luau b/src/Formats/cad/step/Brep.luau new file mode 100644 index 0000000..2d44ef7 --- /dev/null +++ b/src/Formats/cad/step/Brep.luau @@ -0,0 +1,248 @@ +--!strict +-- cad/step/Brep: the injected B-rep plug-in (Formats.plugins.brep; formats-luau never requires a kernel). Normalises +-- the plug-in table, calls it under pcall (kernels throw on bad geometry) and turns its tessellated meshes into a +-- Scene. Interpreted on purpose: the plug-in's errors unwind through here. +-- +-- The interface (every function may throw; results are checked): +-- read(text: string, opts) -> { bodies = { Body }, stats = { ... }? } STEP text -> B-rep bodies (body.name?, +-- body.color? = Color3 | { r, g, b } | { 1, 2, 3 }) +-- write(bodies: { Body }, opts) -> string bodies -> STEP text +-- tessellate(body: Body, opts) -> { positions = { vector | {x, y, z} }, normals = { ... }?, indices = { 1-based +-- triples }, faceOf = { [triangle] = Face (face.color?) }? } +-- or brep-luau's modules as they are: { Step = , StepBrep = , StepWrite = , Tess = } (adapted here: read = +-- StepBrep.read(Step.parse(text)), write = StepWrite.write with options.colors from body.color, tessellate = Tess.body). +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") + +local Brep = {} + +export type Plugin = { + read: (text: string, opts: any) -> any, + write: ((bodies: { any }, opts: any) -> string)?, + tessellate: ((body: any, opts: any) -> any)?, +} + +local function rgbOf(c: any): (number?, number?, number?) + if c == nil then + return nil, nil, nil + end + local ok, r, g, b = pcall(function(): (any, any, any) + if type(c) == "table" then + return c.r or c.R or c[1], c.g or c.G or c[2], c.b or c.B or c[3] + end + return (c :: any).R, (c :: any).G, (c :: any).B -- Color3 + end) + if ok and type(r) == "number" and type(g) == "number" and type(b) == "number" then + return r, g, b + end + return nil, nil, nil +end + +-- plugin(p) -> the normalised interface, or nil + the reason +function Brep.plugin(p: any): (Plugin?, string?) + if type(p) ~= "table" then + return nil, "needs the B-rep plug-in (Formats.plugins.brep = { read, write, tessellate }, e.g. brep-luau's { Step, StepBrep, StepWrite, Tess })" + end + if type(p.read) == "function" then + return { + read = p.read, + write = if type(p.write) == "function" then p.write else nil, + tessellate = if type(p.tessellate) == "function" then p.tessellate else nil, + }, nil + end + local S, SB, SW, Tess = p.Step, p.StepBrep, p.StepWrite, p.Tess + if type(S) == "table" and type(SB) == "table" and type(S.parse) == "function" and type(SB.read) == "function" then + return { + read = function(text: string, opts: any): any + return SB.read(S.parse(text), opts) + end, + write = if type(SW) == "table" and type(SW.write) == "function" + then function(bodies: { any }, opts: any): string + local o = if type(opts) == "table" then table.clone(opts) else {} + if o.colors == nil then + local colors = {} + for i, b in bodies do + local r, g, bl = rgbOf(type(b) == "table" and b.color or nil) + if r then + colors[i] = { r, g, bl } + end + end + o.colors = colors + end + return SW.write(bodies, o) + end + else nil, + tessellate = if type(Tess) == "table" and type(Tess.body) == "function" + then function(body: any, opts: any): any + return Tess.body(body, opts) + end + else nil, + }, nil + end + return nil, "the B-rep plug-in has neither read() nor brep-luau's Step + StepBrep modules" +end + +-- find(opts) -> the plug-in from opts.brep or opts.plugins.brep +function Brep.find(opts: any): (Plugin?, Err.Err?) + local p = nil + if type(opts) == "table" then + p = opts.brep + if p == nil and type(opts.plugins) == "table" then + p = opts.plugins.brep + end + end + local plug, why = Brep.plugin(p) + if not plug then + return nil, Err.new(Err.UNSUPPORTED, why :: string) + end + return plug, nil +end + +-- read(plug, text, opts) -> bodies, result | nil, Err +function Brep.read(plug: Plugin, text: string, opts: any): (({ any })?, any, Err.Err?) + local ok, res = pcall(plug.read, text, opts) + if not ok then + return nil, nil, Err.new(Err.CORRUPT, "the B-rep plug-in failed to read: " .. tostring(res)) + end + if type(res) ~= "table" or type(res.bodies) ~= "table" then + return nil, nil, Err.new(Err.CORRUPT, "the B-rep plug-in's read returned no bodies") + end + return res.bodies, res, nil +end + +-- write(plug, bodies, opts) -> text | nil, Err +function Brep.write(plug: Plugin, bodies: { any }, opts: any): (string?, Err.Err?) + local w = plug.write + if not w then + return nil, Err.new(Err.UNSUPPORTED, "the B-rep plug-in has no write()") + end + local ok, res = pcall(w, bodies, opts) + if not ok then + return nil, Err.new(Err.ARG, "the B-rep plug-in failed to write: " .. tostring(res)) + end + if type(res) ~= "string" then + return nil, Err.new(Err.ARG, "the B-rep plug-in's write returned no text") + end + return res, nil +end + +local function xyz(p: any): (number, number, number) + if type(p) == "table" then + return tonumber(p.x or p.X or p[1]) or 0, tonumber(p.y or p.Y or p[2]) or 0, tonumber(p.z or p.Z or p[3]) or 0 + end + return (p :: any).X, (p :: any).Y, (p :: any).Z -- vector / Vector3 +end + +local function linear(c: number): number + c = math.clamp(c, 0, 1) + return if c <= 0.04045 then c / 12.92 else ((c + 0.055) / 1.055) ^ 2.4 +end + +-- scene(plug, bodies, opts) -> Scene: one node + mesh per body, one primitive per face colour (materials shared by +-- colour; baseColor = the STEP colour converted from sRGB to linear, extras.color = the colour as written) +function Brep.scene(plug: Plugin, bodies: { any }, opts: any): (Types.Scene?, Err.Err?) + local tess = plug.tessellate + if not tess then + return nil, Err.new(Err.UNSUPPORTED, "the B-rep plug-in has no tessellate()") + end + local scene = Types.Scene.new() + scene.meta.up = "z" + scene.meta.unit = 0.001 + local tessOpts = if type(opts) == "table" and type(opts.tess) == "table" + then opts.tess + else { chord = if type(opts) == "table" and type(opts.chord) == "number" then opts.chord else 0.05 } + local matByKey: { [string]: number } = {} + local function material(r: number?, g: number?, b: number?): number + local key = if r then string.format("%.6f,%.6f,%.6f", r, g :: number, b :: number) else "default" + local m = matByKey[key] + if m then + return m + end + local mat = Types.Scene.material(if r then "step_" .. #scene.materials + 1 else "default") + if r then + mat.baseColor = { linear(r), linear(g :: number), linear(b :: number), 1 } + mat.extras = { color = { r, g, b } } + else + mat.baseColor = { 0.6, 0.6, 0.6, 1 } + end + mat.metallic, mat.roughness = 0, 0.5 + table.insert(scene.materials, mat) + matByKey[key] = #scene.materials + return #scene.materials + end + for bi, body in bodies do + local ok, mesh = pcall(tess, body, tessOpts) + if not ok then + return nil, Err.new(Err.CORRUPT, "the B-rep plug-in failed to tessellate body " .. bi .. ": " .. tostring(mesh)) + end + if type(mesh) ~= "table" or type(mesh.positions) ~= "table" or type(mesh.indices) ~= "table" then + return nil, Err.new(Err.CORRUPT, "the B-rep plug-in's tessellate returned no mesh") + end + local cok, prims = pcall(function(): { Types.Primitive } + local P, N, I = mesh.positions, mesh.normals, mesh.indices + local nv = #P + local pos = Types.Scene.accessor(nil, "f32", 3, nv) + local nrm = if type(N) == "table" and #N == nv then Types.Scene.accessor(nil, "f32", 3, nv) else nil + for i = 1, nv do + local x, y, z = xyz(P[i]) + buffer.writef32(pos.data, (i - 1) * 12, x) + buffer.writef32(pos.data, (i - 1) * 12 + 4, y) + buffer.writef32(pos.data, (i - 1) * 12 + 8, z) + if nrm then + local a, b, c = xyz(N[i]) + buffer.writef32(nrm.data, (i - 1) * 12, a) + buffer.writef32(nrm.data, (i - 1) * 12 + 4, b) + buffer.writef32(nrm.data, (i - 1) * 12 + 8, c) + end + end + local br, bg, bb = rgbOf(type(body) == "table" and body.color or nil) + -- triangles grouped by colour, in first-seen order + local groups: { { mat: number, tris: { number } } } = {} + local byMat: { [number]: { mat: number, tris: { number } } } = {} + local faceOf = if type(mesh.faceOf) == "table" then mesh.faceOf else {} + local nt = #I // 3 + for t = 1, nt do + local f = faceOf[t] + local r, g, b = rgbOf(type(f) == "table" and f.color or nil) + if not r then + r, g, b = br, bg, bb + end + local m = material(r, g, b) + local grp = byMat[m] + if not grp then + grp = { mat = m, tris = {} } + byMat[m] = grp + table.insert(groups, grp) + end + table.insert(grp.tris, t) + end + local out: { Types.Primitive } = {} + for _, grp in groups do + local idx = Types.Scene.accessor(nil, "u32", 1, #grp.tris * 3) + for k, t in grp.tris do + for c = 0, 2 do + local v = (tonumber(I[(t - 1) * 3 + c + 1]) or 1) - 1 + buffer.writeu32(idx.data, ((k - 1) * 3 + c) * 4, math.clamp(v, 0, math.max(nv - 1, 0))) + end + end + local attrs: { [string]: Types.Accessor } = { POSITION = pos } + if nrm then + attrs.NORMAL = nrm + end + table.insert(out, { attributes = attrs, indices = idx, mode = "triangles" :: any, material = grp.mat }) + end + return out + end) + if not cok then + return nil, Err.new(Err.CORRUPT, "bad tessellation of body " .. bi .. ": " .. tostring(prims)) + end + local name = if type(body) == "table" and type(body.name) == "string" then body.name else "body_" .. bi + table.insert(scene.meshes, { name = name, primitives = prims }) + table.insert(scene.nodes, { name = name, children = {}, mesh = #scene.meshes }) + table.insert(scene.roots, #scene.nodes) + end + scene.meta.source = { format = "step", tessellated = true, bodies = #bodies } + return scene, nil +end + +return Brep diff --git a/src/Formats/cad/step/Parse.luau b/src/Formats/cad/step/Parse.luau new file mode 100644 index 0000000..1a86bf3 --- /dev/null +++ b/src/Formats/cad/step/Parse.luau @@ -0,0 +1,573 @@ +--!strict +--!native +-- cad/step/Parse: ISO 10303-21 (STEP physical file, editions 1-3) text -> header + entity instances. A single pass +-- over the text: comments, the HEADER section, any number of DATA sections (edition 3 `DATA('name', ('schema'));`), +-- ANCHOR / REFERENCE / SIGNATURE sections kept as raw text, simple and complex (external mapping) instances, every +-- parameter kind (integer, real, string with its \S\ \X\ \X2\ \X4\ escapes decoded to UTF-8, enumeration, binary, +-- entity reference, $, *, list, typed parameter). Never throws: failures return nil, message, offset. +-- +-- Values: numbers; strings; { enum = "T" }; { ref = 12 }; { binary = "0FF" }; { typed = "LENGTH_MEASURE", value = v }; +-- lists as arrays; NULL / DERIVED sentinels (from the caller). A real literal with an integral value (`0.`, `1.E2`) +-- is recorded in the metatable of the list (or typed table) holding it (`__reals = { [index | "value"] = true }`), so +-- the writer prints it back as a real; integral numbers without that mark are written as integers. +local Parse = {} + +local sbyte, ssub, sfind, schar, floor = string.byte, string.sub, string.find, string.char, math.floor + +local MAX_DEPTH = 100 + +export type Ctx = { + s: string, + n: number, + err: string?, + errAt: number?, + null: any, + derived: any, +} + +local function fail(ctx: Ctx, msg: string, at: number): nil + if not ctx.err then + ctx.err, ctx.errAt = msg, at + end + return nil +end + +-- the next position that is not white space or inside a /* comment */ (n + 1 at the end; an open comment -> error) +local function skip(ctx: Ctx, i: number): number + local s, n = ctx.s, ctx.n + while i <= n do + local c = sbyte(s, i) + if c == 32 or c == 10 or c == 13 or c == 9 or c == 12 then + i += 1 + elseif c == 47 and sbyte(s, i + 1) == 42 then + local _, e = sfind(s, "*/", i + 2, true) + if not e then + fail(ctx, "unterminated comment", i) + return n + 1 + end + i = e + 1 + else + return i + end + end + return i +end + +local function isAlpha(c: number): boolean + return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 +end +local function isWord(c: number): boolean + return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or (c >= 48 and c <= 57) +end + +-- keyword at i ([!]A-Z_ A-Z0-9_*) -> word, next; nil when there is none +local function keyword(ctx: Ctx, i: number): (string?, number) + local s, n = ctx.s, ctx.n + local j = i + if j <= n and sbyte(s, j) == 33 then -- '!' user-defined + j += 1 + end + if j > n or not isAlpha(sbyte(s, j) :: number) then + return nil, i + end + j += 1 + while j <= n and isWord(sbyte(s, j) :: number) do + j += 1 + end + return string.upper(ssub(s, i, j - 1)), j +end + +-- UTF-8 of a code point +local function utf8char(cp: number): string + if cp < 0x80 then + return schar(cp) + elseif cp < 0x800 then + return schar(0xC0 + floor(cp / 64), 0x80 + cp % 64) + elseif cp < 0x10000 then + return schar(0xE0 + floor(cp / 4096), 0x80 + floor(cp / 64) % 64, 0x80 + cp % 64) + elseif cp < 0x110000 then + return schar(0xF0 + floor(cp / 262144), 0x80 + floor(cp / 4096) % 64, 0x80 + floor(cp / 64) % 64, 0x80 + cp % 64) + end + return "\239\191\189" +end +Parse.utf8char = utf8char + +local function hexAt(s: string, i: number, k: number): number? + local h = ssub(s, i, i + k - 1) + if #h ~= k or sfind(h, "[^%x]") then + return nil + end + return tonumber(h, 16) +end + +-- the text between the quotes of a string literal -> its value ('' -> ', \\ -> \, \S\c, \X\hh, \X2\..\X0\, \X4\..\X0\, +-- \P?\ page switches ignored: every page reads as ISO 8859-1). Bytes >= 0x80 written raw (common, though not allowed) +-- pass through. +function Parse.unescape(raw: string): string + if not sfind(raw, "[\\']") then + return raw + end + local out = {} + local i, n = 1, #raw + local plain = 1 + while i <= n do + local c = sbyte(raw, i) + if c == 39 then -- '' -> ' + table.insert(out, ssub(raw, plain, i)) + i += 2 + plain = i + elseif c == 92 then + table.insert(out, ssub(raw, plain, i - 1)) + local d = sbyte(raw, i + 1) + if d == 92 then + table.insert(out, "\\") + i += 2 + elseif d == 83 and sbyte(raw, i + 2) == 92 and i + 3 <= n then -- \S\c + table.insert(out, utf8char(((sbyte(raw, i + 3) :: number) + 128) % 256)) + i += 4 + elseif d == 80 and sbyte(raw, i + 3) == 92 then -- \P?\ code page + i += 4 + elseif d == 88 and sbyte(raw, i + 2) == 92 then -- \X\hh + local h = hexAt(raw, i + 3, 2) + if h then + table.insert(out, utf8char(h)) + i += 5 + else + table.insert(out, "\\") + i += 1 + end + elseif d == 88 and (sbyte(raw, i + 2) == 50 or sbyte(raw, i + 2) == 52) and sbyte(raw, i + 3) == 92 then + local k = if sbyte(raw, i + 2) == 50 then 4 else 8 + local j = i + 4 + local hi: number? = nil + while j <= n do + if sbyte(raw, j) == 92 then + break + end + local cp = hexAt(raw, j, k) + if not cp then + break + end + if k == 4 and cp >= 0xD800 and cp < 0xDC00 then + hi = cp + elseif k == 4 and hi and cp >= 0xDC00 and cp < 0xE000 then + table.insert(out, utf8char(0x10000 + (hi - 0xD800) * 1024 + (cp - 0xDC00))) + hi = nil + else + table.insert(out, utf8char(cp)) + hi = nil + end + j += k + end + if ssub(raw, j, j + 3) == "\\X0\\" then + j += 4 + end + i = j + else + table.insert(out, "\\") + i += 1 + end + plain = i + else + i += 1 + end + end + table.insert(out, ssub(raw, plain, n)) + return table.concat(out) +end + +local function markReal(t: { [any]: any }, key: any) + local mt: any = getmetatable(t) + if not mt then + mt = { __reals = {} } + setmetatable(t, mt) + end + mt.__reals[key] = true +end + +-- one parameter at i -> value, next, integralReal (nil value + ctx.err on failure) +local value: (ctx: Ctx, i: number, depth: number) -> (any, number, boolean) + +local function list(ctx: Ctx, i: number, depth: number): ({ any }?, number) + -- i is just past "(" + local s = ctx.s + local out = {} + i = skip(ctx, i) + if sbyte(s, i) == 41 then + return out, i + 1 + end + local k = 0 + while true do + local v, j, intReal = value(ctx, i, depth + 1) + if v == nil then + return nil, j + end + k += 1 + out[k] = v + if intReal then + markReal(out, k) + end + j = skip(ctx, j) + local c = sbyte(s, j) + if c == 44 then + i = skip(ctx, j + 1) + elseif c == 41 then + return out, j + 1 + elseif c == nil then + return fail(ctx, "truncated list", j), j + else + return fail(ctx, "expected , or ) in a list", j), j + end + end +end +Parse.list = list + +value = function(ctx: Ctx, i: number, depth: number): (any, number, boolean) + if depth > MAX_DEPTH then + return fail(ctx, "lists nested too deeply", i), i, false + end + local s = ctx.s + i = skip(ctx, i) + local c = sbyte(s, i) + if c == nil then + return fail(ctx, "truncated parameter", i), i, false + elseif c == 35 then -- #ref + local _, e = sfind(s, "^%d+", i + 1) + if not e then + return fail(ctx, "bad entity reference", i), i, false + end + return { ref = tonumber(ssub(s, i + 1, e)) }, e + 1, false + elseif c == 39 then -- 'string' + local j = i + 1 + while true do + local q = sfind(s, "'", j, true) + if not q then + return fail(ctx, "unterminated string", i), i, false + end + if sbyte(s, q + 1) == 39 then + j = q + 2 + else + return Parse.unescape(ssub(s, i + 1, q - 1)), q + 1, false + end + end + elseif c == 36 then + return ctx.null, i + 1, false + elseif c == 42 then + return ctx.derived, i + 1, false + elseif c == 40 then + local l, j = list(ctx, i + 1, depth) + return l, j, false + elseif c == 46 then -- .ENUM. + local _, e = sfind(s, "^[%a_][%w_]*%.", i + 1) + if not e then + return fail(ctx, "bad enumeration", i), i, false + end + return { enum = string.upper(ssub(s, i + 1, e - 1)) }, e + 1, false + elseif c == 34 then -- "binary" + local _, e = sfind(s, "^[0-3]%x*\"", i + 1) + if not e then + return fail(ctx, "bad binary literal", i), i, false + end + return { binary = string.upper(ssub(s, i + 1, e - 1)) }, e + 1, false + elseif (c >= 48 and c <= 57) or c == 45 or c == 43 then + local _, e = sfind(s, "^[+-]?%d*%.?%d*[eE]?[+-]?%d*", i) + local tok = ssub(s, i, e :: number) + local num = tonumber(if c == 43 then ssub(tok, 2) else tok) + if num == nil then + -- "1.E" without digits and the like + local core = string.match(tok, "^[+-]?%d*%.?%d*") + num = core and tonumber(if c == 43 then ssub(core, 2) else core) + if num == nil then + return fail(ctx, "bad number", i), i, false + end + e = i + #(core :: string) - 1 + end + local real = sfind(tok, "[.eE]") ~= nil + local nv = num :: number + return nv, (e :: number) + 1, real and nv == floor(nv) and nv == nv + elseif isAlpha(c) or c == 33 then -- typed parameter NAME(value) + local word, j = keyword(ctx, i) + j = skip(ctx, j) + if word == nil or sbyte(s, j) ~= 40 then + return fail(ctx, "expected a parameter", i), i, false + end + local v, k, intReal = value(ctx, j + 1, depth + 1) + if v == nil then + return nil, k, false + end + k = skip(ctx, k) + if sbyte(s, k) ~= 41 then + return fail(ctx, "expected ) after a typed parameter", k), k, false + end + local t = { typed = word, value = v } + if intReal then + markReal(t, "value") + end + return t, k + 1, false + end + return fail(ctx, "unexpected character " .. string.format("%q", schar(c)), i), i, false +end +Parse.value = value + +-- the simple record at i: NAME(params) -> type, args, next +local function record(ctx: Ctx, i: number): (string?, { any }?, number) + local word, j = keyword(ctx, i) + if not word then + return fail(ctx, "expected an entity name", i), nil, i + end + j = skip(ctx, j) + if sbyte(ctx.s, j) ~= 40 then + return fail(ctx, "expected ( after " .. word, j), nil, j + end + local args, k = list(ctx, j + 1, 0) + if not args then + return nil, nil, k + end + return word, args, k +end + +-- expect(ctx, i, ch) -> next position after ch (skipping blanks), or nil +local function expect(ctx: Ctx, i: number, ch: number, what: string): number? + i = skip(ctx, i) + if sbyte(ctx.s, i) ~= ch then + if i > ctx.n then + return fail(ctx, "truncated: expected " .. what, i) + end + return fail(ctx, "expected " .. what, i) + end + return i + 1 +end + +local function at(s: string, i: number, word: string): boolean + return ssub(s, i, i + #word - 1) == word +end + +export type Result = { + header: { [string]: { any } }, + headerOrder: { string }, + entities: { [number]: any }, + count: number, + sections: { { name: any?, schema: any? } }, + extra: { { name: string, text: string } }, + duplicates: number, + terminated: boolean, +} + +-- parse(s, opts) -> Result | nil, message, offset (1-based position in s) +function Parse.parse(s: string, null: any, derived: any, maxEntities: number): (Result?, string?, number?) + local ctx: Ctx = { s = s, n = #s, err = nil, errAt = nil, null = null, derived = derived } + local res: Result = { + header = {}, + headerOrder = {}, + entities = {}, + count = 0, + sections = {}, + extra = {}, + duplicates = 0, + terminated = false, + } + local i = skip(ctx, 1) + if not at(s, i, "ISO-10303-21") then + return nil, "no ISO-10303-21 magic", i + end + local ni = expect(ctx, i + 12, 59, ";") + if not ni then + return nil, ctx.err, ctx.errAt + end + i = ni + local sawData = false + while true do + i = skip(ctx, i) + if ctx.err then + return nil, ctx.err, ctx.errAt + end + if i > ctx.n then + if not sawData then + return nil, "truncated: no DATA section", i + end + break + end + if at(s, i, "END-ISO-10303-21") then + res.terminated = true + local e = expect(ctx, i + 16, 59, ";") + if not e then + return nil, ctx.err, ctx.errAt + end + break + end + local word, j = keyword(ctx, i) + if word == "HEADER" then + local e = expect(ctx, j, 59, ";") + if not e then + return nil, ctx.err, ctx.errAt + end + i = e + while true do + i = skip(ctx, i) + if at(s, i, "ENDSEC") then + local e2 = expect(ctx, i + 6, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + i = e2 + break + end + if i > ctx.n then + return nil, "truncated header", i + end + local t, args, k = record(ctx, i) + if not t then + return nil, ctx.err, ctx.errAt + end + local e2 = expect(ctx, k, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + if res.header[t] == nil then + table.insert(res.headerOrder, t) + end + res.header[t] = args :: { any } + i = e2 + end + elseif word == "DATA" then + sawData = true + local sec: { name: any?, schema: any? } = {} + j = skip(ctx, j) + if sbyte(s, j) == 40 then + local params, k = list(ctx, j + 1, 0) + if not params then + return nil, ctx.err, ctx.errAt + end + sec.name, sec.schema = params[1], params[2] + j = k + end + table.insert(res.sections, sec) + local secIndex = #res.sections + local e = expect(ctx, j, 59, ";") + if not e then + return nil, ctx.err, ctx.errAt + end + i = e + while true do + i = skip(ctx, i) + if ctx.err then + return nil, ctx.err, ctx.errAt + end + local c = sbyte(s, i) + if c == nil then + return nil, "truncated: the DATA section has no ENDSEC", i + end + if c ~= 35 then + if at(s, i, "ENDSEC") then + local e2 = expect(ctx, i + 6, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + i = e2 + break + end + return nil, "expected an entity instance (#id = ...)", i + end + local _, idEnd = sfind(s, "^%d+", i + 1) + if not idEnd then + return nil, "bad entity instance name", i + end + local id = tonumber(ssub(s, i + 1, idEnd)) :: number + local k = expect(ctx, idEnd + 1, 61, "=") + if not k then + return nil, ctx.err, ctx.errAt + end + k = skip(ctx, k) + local ent: any + if sbyte(s, k) == 40 then -- complex instance (A(..) B(..)) + local parts = {} + k = skip(ctx, k + 1) + while sbyte(s, k) ~= 41 do + if k > ctx.n then + return nil, "truncated complex instance", k + end + local t, args, k2 = record(ctx, k) + if not t then + return nil, ctx.err, ctx.errAt + end + table.insert(parts, { type = t, args = args }) + k = skip(ctx, k2) + end + if #parts == 0 then + return nil, "empty complex instance", k + end + ent = { id = id, type = "COMPLEX", args = {}, parts = parts } + k += 1 + else + local t, args, k2 = record(ctx, k) + if not t then + return nil, ctx.err, ctx.errAt + end + ent = { id = id, type = t, args = args } + k = k2 + end + local e2 = expect(ctx, k, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + if secIndex > 1 then + ent.section = secIndex + end + if res.entities[id] then + res.duplicates += 1 + else + res.count += 1 + if res.count > maxEntities then + return nil, "LIMIT", i + end + end + res.entities[id] = ent + i = e2 + end + elseif word == "ANCHOR" or word == "REFERENCE" or word == "SIGNATURE" then + -- kept as raw text (to the ENDSEC outside strings) + local k = j + local stop: number? = nil + while k <= ctx.n do + local c = sbyte(s, k) + if c == 39 then + local q = k + 1 + while true do + local p = sfind(s, "'", q, true) + if not p then + return nil, "unterminated string", k + end + if sbyte(s, p + 1) == 39 then + q = p + 2 + else + k = p + 1 + break + end + end + elseif c == 69 and at(s, k, "ENDSEC") then + stop = k + break + else + k += 1 + end + end + if not stop then + return nil, "truncated " .. word .. " section", i + end + table.insert(res.extra, { name = word, text = ssub(s, j, stop - 1) }) + local e2 = expect(ctx, stop + 6, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + i = e2 + else + return nil, "unknown section " .. tostring(word), i + end + end + if not sawData then + return nil, "no DATA section", i + end + return res, nil, nil +end + +return Parse diff --git a/src/Formats/cad/step/Write.luau b/src/Formats/cad/step/Write.luau new file mode 100644 index 0000000..0045126 --- /dev/null +++ b/src/Formats/cad/step/Write.luau @@ -0,0 +1,252 @@ +--!strict +--!native +-- cad/step/Write: header + entity instances -> ISO 10303-21 text. Values as cad/step/Parse produces them; strings +-- re-escaped (' -> '', \ -> \\, UTF-8 outside printable ASCII -> \X2\..\X0\ / \X4\..\X0\, control bytes and invalid +-- UTF-8 -> \X\hh), reals printed with the fewest digits (15..17) that read back to the same double. Never throws: +-- failures return nil, message. +local Write = {} + +local sformat, sbyte, ssub, sfind, floor, huge = string.format, string.byte, string.sub, string.find, math.floor, math.huge + +local MAX_DEPTH = 100 + +-- the shortest %g form that reads back exactly, in Part 21 syntax (a '.' always, upper-case E) +function Write.real(v: number): string? + if v ~= v or v == huge or v == -huge then + return nil + end + local s = sformat("%.15g", v) + if tonumber(s) ~= v then + s = sformat("%.16g", v) + if tonumber(s) ~= v then + s = sformat("%.17g", v) + end + end + s = string.upper(s) + local e = sfind(s, "E", 1, true) + if not sfind(s, ".", 1, true) then + if e then + s = ssub(s, 1, e - 1) .. "." .. ssub(s, e) + else + s ..= "." + end + end + return s +end + +local HEX = "0123456789ABCDEF" +local function hex(v: number, k: number): string + local out = table.create(k) + for i = k, 1, -1 do + local d = v % 16 + out[i] = ssub(HEX, d + 1, d + 1) + v = floor(v / 16) + end + return table.concat(out) +end + +-- a string's Part 21 literal (with the quotes) +function Write.str(s: string): string + if not sfind(s, "[^ -&(-[%]^-~]") then -- printable ASCII without ' and \ + return "'" .. s .. "'" + end + local out = { "'" } + local i, n = 1, #s + local wide: number? = nil -- 4 (\X2\) or 8 (\X4\) while in an extended run + local function close() + if wide then + table.insert(out, "\\X0\\") + wide = nil + end + end + while i <= n do + local c = sbyte(s, i) :: number + if c >= 32 and c < 127 then + close() + if c == 39 then + table.insert(out, "''") + elseif c == 92 then + table.insert(out, "\\\\") + else + table.insert(out, string.char(c)) + end + i += 1 + else + -- a UTF-8 sequence -> code point + local cp: number? = nil + local len = 1 + if c >= 0xC2 and c < 0xE0 then + local c2 = sbyte(s, i + 1) + if c2 and c2 >= 0x80 and c2 < 0xC0 then + cp, len = (c - 0xC0) * 64 + (c2 - 0x80), 2 + end + elseif c >= 0xE0 and c < 0xF0 then + local c2, c3 = sbyte(s, i + 1, i + 2) + if c2 and c3 and c2 >= 0x80 and c2 < 0xC0 and c3 >= 0x80 and c3 < 0xC0 then + local v = (c - 0xE0) * 4096 + (c2 - 0x80) * 64 + (c3 - 0x80) + if v >= 0x800 and (v < 0xD800 or v >= 0xE000) then + cp, len = v, 3 + end + end + elseif c >= 0xF0 and c < 0xF5 then + local c2, c3, c4 = sbyte(s, i + 1, i + 3) + if c2 and c3 and c4 and c2 >= 0x80 and c2 < 0xC0 and c3 >= 0x80 and c3 < 0xC0 and c4 >= 0x80 and c4 < 0xC0 then + local v = (c - 0xF0) * 262144 + (c2 - 0x80) * 4096 + (c3 - 0x80) * 64 + (c4 - 0x80) + if v >= 0x10000 and v < 0x110000 then + cp, len = v, 4 + end + end + end + if cp == nil then + close() + table.insert(out, "\\X\\" .. hex(c, 2)) + i += 1 + else + local k = if cp >= 0x10000 then 8 else 4 + if wide ~= k then + close() + table.insert(out, if k == 4 then "\\X2\\" else "\\X4\\") + wide = k + end + table.insert(out, hex(cp, k)) + i += len + end + end + end + close() + table.insert(out, "'") + return table.concat(out) +end + +local function isName(s: any): boolean + return type(s) == "string" and sfind(s, "^!?[%a_][%w_]*$") ~= nil +end +Write.isName = isName + +export type Ctx = { out: { string }, null: any, derived: any, err: string? } + +local value: (ctx: Ctx, v: any, real: boolean, depth: number) -> boolean + +local function reals(t: any): { [any]: boolean }? + local mt = getmetatable(t) + return if type(mt) == "table" and type(mt.__reals) == "table" then mt.__reals else nil +end + +local function list(ctx: Ctx, t: { any }, depth: number): boolean + local out = ctx.out + table.insert(out, "(") + local marks = reals(t) + local n = #t + for i = 1, n do + if i > 1 then + table.insert(out, ",") + end + if not value(ctx, t[i], marks ~= nil and marks[i] == true, depth + 1) then + return false + end + end + table.insert(out, ")") + return true +end +Write.list = list + +value = function(ctx: Ctx, v: any, real: boolean, depth: number): boolean + local out = ctx.out + if depth > MAX_DEPTH then + ctx.err = "values nested too deeply (or a cycle)" + return false + end + local tv = type(v) + if tv == "number" then + if not real and v == floor(v) and v > -2 ^ 53 and v < 2 ^ 53 then + table.insert(out, sformat("%.0f", v)) + return true + end + local r = Write.real(v) + if not r then + ctx.err = "a number that STEP cannot hold (nan / inf)" + return false + end + table.insert(out, r) + return true + elseif tv == "string" then + table.insert(out, Write.str(v)) + return true + elseif tv == "boolean" then + table.insert(out, if v then ".T." else ".F.") + return true + elseif tv == "table" then + if v == ctx.null then + table.insert(out, "$") + return true + elseif v == ctx.derived then + table.insert(out, "*") + return true + end + local ref = v.ref + if ref ~= nil then + if type(ref) ~= "number" or ref ~= floor(ref) or ref < 0 then + ctx.err = "bad entity reference " .. tostring(ref) + return false + end + table.insert(out, sformat("#%.0f", ref)) + return true + end + local enum = v.enum + if enum ~= nil then + if type(enum) ~= "string" or not sfind(enum, "^[%a_][%w_]*$") then + ctx.err = "bad enumeration " .. tostring(enum) + return false + end + table.insert(out, "." .. string.upper(enum) .. ".") + return true + end + local bin = v.binary + if bin ~= nil then + if type(bin) ~= "string" or not sfind(bin, "^[0-3]%x*$") then + ctx.err = "bad binary literal" + return false + end + table.insert(out, "\"" .. string.upper(bin) .. "\"") + return true + end + local typed = v.typed + if typed ~= nil then + if not isName(typed) then + ctx.err = "bad typed parameter name " .. tostring(typed) + return false + end + if v.value == nil then + ctx.err = "typed parameter " .. typed .. " without a value" + return false + end + local marks = reals(v) + table.insert(out, string.upper(typed) .. "(") + if not value(ctx, v.value, marks ~= nil and marks.value == true, depth + 1) then + return false + end + table.insert(out, ")") + return true + end + return list(ctx, v, depth) + end + ctx.err = "cannot write a " .. tv .. " value" + return false +end +Write.value = value + +-- record(ctx, type, args) -> appends TYPE(args) +function Write.record(ctx: Ctx, t: any, args: any): boolean + if not isName(t) then + ctx.err = "bad entity type " .. tostring(t) + return false + end + if type(args) ~= "table" then + ctx.err = "entity " .. t .. " without an args list" + return false + end + table.insert(ctx.out, string.upper(t)) + return list(ctx, args, 0) +end + +return Write diff --git a/src/Formats/cad/step/init.luau b/src/Formats/cad/step/init.luau new file mode 100644 index 0000000..1062a7a --- /dev/null +++ b/src/Formats/cad/step/init.luau @@ -0,0 +1,412 @@ +--!strict +-- cad/step: STEP physical files (ISO 10303-21 editions 1-3, "Part 21": AP203 / AP214 / AP242 and any other schema). +-- New code. Reads and writes the entity graph (Types.Cad) fully in-library: the header (FILE_DESCRIPTION / FILE_NAME / +-- FILE_SCHEMA + any other header entity), every DATA section (edition 3 named sections: entity.section), simple and +-- complex instances (type "COMPLEX", parts = { { type, args } }), every parameter kind: integers and reals (numbers; +-- integral reals such as `0.` keep their real-ness through a metatable mark, see Parse), strings (escapes decoded to +-- UTF-8: \S\ \X\ \X2\ \X4\, '' and \\), { enum = "T" } (.T. / .F. booleans too), { ref = id }, { binary = "0FF" }, +-- { typed = "LENGTH_MEASURE", value = v }, lists, Step.NULL ($) and Step.DERIVED (*), comments; ANCHOR / REFERENCE / +-- SIGNATURE sections kept as raw text (meta.source.extra) and written back. parse -> write -> parse gives the same +-- entities. Writes one instance per line in id order, strings escaped as Part 21 requires (\X2\ for non-ASCII). +-- +-- B-rep bodies and tessellation come from an injected kernel, never required by formats-luau: +-- F.plugins.brep = { read = fn(text, opts) -> { bodies, stats? }, write = fn(bodies, opts) -> text, +-- tessellate = fn(body, opts) -> { positions, normals?, indices (1-based), faceOf? } } +-- or brep-luau's modules as they are: F.plugins.brep = { Step = , StepBrep = , StepWrite = , Tess = } +-- (the full contract is in cad/step/Brep). Step.toBodies(cad, opts) / Step.fromBodies(bodies, opts) / +-- Step.tessellate(cad | bodies, opts) take it from opts.brep or opts.plugins.brep; F.cad.toBodies / fromBodies / +-- tessellate pass F.plugins. Tessellated scenes: one node + mesh per body, one primitive per face colour, z up, +-- millimetres (meta.unit = 0.001). +-- Not supported: STEP-XML (ISO 10303-28), compressed .stpZ, edition 3 value instances (#NAME, @constants: CORRUPT), +-- code pages other than ISO 8859-1 in \S\ escapes (\P?\ is ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Parse = require("@formats/cad/step/Parse") +local Write = require("@formats/cad/step/Write") +local Brep = require("@formats/cad/step/Brep") + +-- ------------------------------------------------------------------------------------------------ contract +local Step = { + name = "step", + category = "cad", + extensions = { "step", "stp", "p21" }, + mime = { "model/step", "application/step", "application/p21" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxBytes: number?, -- refuse larger files (default 2^30) + maxEntities: number?, -- refuse more instances (default 2^24) +} +export type EncodeOptions = { + schema: string?, -- "AP203" | "AP214" | "AP242" | a schema name: overrides the header's FILE_SCHEMA + name: string?, -- FILE_NAME name (default: the header's, else "model") + timestamp: string?, -- FILE_NAME time_stamp when the header has none (default "1970-01-01T00:00:00") + crlf: boolean?, -- CRLF line ends (default LF) +} +export type BrepOptions = { + brep: any?, -- the plug-in (else opts.plugins.brep) + plugins: { [string]: any }?, + chord: number?, -- tessellation sag in millimetres (default 0.05); opts.tess = the kernel's own options instead + tess: { [string]: any }?, +} + +-- ------------------------------------------------------------------------------------------------ constants +Step.NULL = table.freeze({ null = true }) -- $ +Step.DERIVED = table.freeze({ derived = true }) -- * + +local SCHEMAS = { + AP203 = "CONFIG_CONTROL_DESIGN", + AP214 = "AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }", + AP242 = "AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }", +} +Step.SCHEMAS = SCHEMAS + +-- a FILE_SCHEMA name -> "AP203" | "AP214" | "AP242" | the name itself +local function schemaOf(name: string): string + local n = string.upper(string.match(name, "^%s*([^%s{]+)") or name) + if n == "CONFIG_CONTROL_DESIGN" or string.find(n, "^AP203") then + return "AP203" + elseif n == "AUTOMOTIVE_DESIGN" or n == "AUTOMOTIVE_DESIGN_CC2" or string.find(n, "^AP214") then + return "AP214" + elseif string.find(n, "^AP242") then + return "AP242" + end + return n +end +Step.schemaOf = schemaOf + +-- ------------------------------------------------------------------------------------------------ sniff +function Step.sniff(r: Bytes.Reader): number + local head = r:peek(256) + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + head = string.gsub(head, "^%s*/%*.-%*/", "") + if string.find(head, "^%s*ISO%-10303%-21%s*;") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Step.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Cad?, Err.Err?) + local size = r.limit - r.base + if size > (opts and opts.maxBytes or 2 ^ 30) then + return nil, Err.new(Err.LIMIT, "file over maxBytes") + end + local s = buffer.readstring(r.buf, r.base, size) + local bom = 0 + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + bom = 3 + end + local res, msg, at = Parse.parse(s, Step.NULL, Step.DERIVED, opts and opts.maxEntities or 2 ^ 24) + if not res then + local off = if at then r.base + bom + at - 1 else nil + if msg == "LIMIT" then + return nil, Err.new(Err.LIMIT, "more entity instances than maxEntities", off) + end + local m = msg or "parse error" + if string.find(m, "^truncated") or string.find(m, "^unterminated") or (at and at > #s) then + return nil, Err.new(Err.TRUNCATED, m, off) + end + return nil, Err.new(Err.CORRUPT, m, off) + end + local fs = res.header.FILE_SCHEMA + local schemaName = if fs and type(fs[1]) == "table" and type(fs[1][1]) == "string" then fs[1][1] else "" + local cad: Types.Cad = { + kind = "cad", + schema = if schemaName ~= "" then schemaOf(schemaName) else "unknown", + header = res.header, + entities = res.entities, + meta = { + count = res.count, + headerOrder = res.headerOrder, + source = { + format = "step", + schemaName = schemaName, + sections = res.sections, + extra = if #res.extra > 0 then res.extra else nil, + duplicates = if res.duplicates > 0 then res.duplicates else nil, + terminated = res.terminated, + }, + }, + } + return cad, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function headerArgs(cad: Types.Cad, o: EncodeOptions): { [string]: { any } } + local h = if type(cad.header) == "table" then cad.header else {} + local out: { [string]: { any } } = {} + for k, v in h do + out[k] = v + end + if type(out.FILE_DESCRIPTION) ~= "table" then + out.FILE_DESCRIPTION = { { "formats-luau" }, "2;1" } + end + if type(out.FILE_NAME) ~= "table" then + out.FILE_NAME = { o.name or "model", o.timestamp or "1970-01-01T00:00:00", { "" }, { "" }, "formats-luau", "formats-luau", "" } + end + local schema = o.schema or (if type(out.FILE_SCHEMA) ~= "table" then cad.schema else nil) + if schema then + out.FILE_SCHEMA = { { SCHEMAS[schema] or schema } } + end + return out +end + +function Step.encode(cad: Types.Cad, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(cad) ~= "table" or cad.kind ~= "cad" or type(cad.entities) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Cad (kind = \"cad\", entities)") + end + local o: EncodeOptions = opts or {} + local nl = if o.crlf then "\r\n" else "\n" + local ctx: Write.Ctx = { out = {}, null = Step.NULL, derived = Step.DERIVED, err = nil } + local out = ctx.out + table.insert(out, "ISO-10303-21;" .. nl .. "HEADER;" .. nl) + local header = headerArgs(cad, o) + local order = { "FILE_DESCRIPTION", "FILE_NAME", "FILE_SCHEMA" } + local seen = { FILE_DESCRIPTION = true, FILE_NAME = true, FILE_SCHEMA = true } + local meta: any = if type(cad.meta) == "table" then cad.meta else {} + local rest = {} + for _, k in (if type(meta.headerOrder) == "table" then meta.headerOrder else {}) do + if type(k) == "string" and header[k] and not seen[k] then + seen[k] = true + table.insert(order, k) + end + end + for k in header do + if type(k) == "string" and not seen[k] then + table.insert(rest, k) + end + end + table.sort(rest) + for _, k in rest do + table.insert(order, k) + end + for _, k in order do + if not Write.record(ctx, k, header[k]) then + return nil, Err.new(Err.ARG, "header " .. tostring(k) .. ": " .. tostring(ctx.err)) + end + table.insert(out, ";" .. nl) + end + table.insert(out, "ENDSEC;" .. nl) + local source = if type(meta.source) == "table" then meta.source else {} + if type(source.extra) == "table" then + for _, x in source.extra do + if type(x) == "table" and type(x.name) == "string" and type(x.text) == "string" then + table.insert(out, x.name .. x.text .. "ENDSEC;" .. nl) + end + end + end + -- entities by section, in id order + local ids = {} + for id, e in cad.entities do + if type(id) ~= "number" or id ~= math.floor(id) or id < 0 or type(e) ~= "table" then + return nil, Err.new(Err.ARG, "entity ids must be non-negative integers (" .. tostring(id) .. ")") + end + table.insert(ids, id) + end + table.sort(ids) + local sections = if type(source.sections) == "table" and #source.sections > 1 then source.sections else { {} } + for si, sec in sections do + if #sections > 1 then + table.insert(out, "DATA") + local params = {} + if sec.name ~= nil then + params[1] = sec.name + params[2] = if sec.schema ~= nil then sec.schema else {} + if not Write.list(ctx, params, 0) then + return nil, Err.new(Err.ARG, "section " .. si .. ": " .. tostring(ctx.err)) + end + end + table.insert(out, ";" .. nl) + else + table.insert(out, "DATA;" .. nl) + end + for _, id in ids do + local e: any = cad.entities[id] + local esec = if type(e.section) == "number" then e.section else 1 + if #sections == 1 or esec == si or (si == 1 and (esec < 1 or esec > #sections)) then + table.insert(out, string.format("#%.0f=", id)) + if e.type == "COMPLEX" or type(e.parts) == "table" then + if type(e.parts) ~= "table" or #e.parts == 0 then + return nil, Err.new(Err.ARG, "#" .. id .. ": a complex instance without parts") + end + table.insert(out, "(") + for _, p in e.parts do + if type(p) ~= "table" or not Write.record(ctx, p.type, p.args) then + return nil, Err.new(Err.ARG, "#" .. id .. ": " .. tostring(ctx.err or "bad part")) + end + end + table.insert(out, ")") + elseif not Write.record(ctx, e.type, e.args) then + return nil, Err.new(Err.ARG, "#" .. id .. ": " .. tostring(ctx.err)) + end + table.insert(out, ";" .. nl) + end + end + table.insert(out, "ENDSEC;" .. nl) + end + table.insert(out, "END-ISO-10303-21;" .. nl) + return buffer.fromstring(table.concat(out)), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- get(cad, id | { ref = id }) -> the entity +function Step.get(cad: Types.Cad, id: any): Types.StepEntity? + if type(id) == "table" then + id = id.ref + end + return cad.entities[id] +end + +-- ids(cad) -> the instance ids in ascending order +function Step.ids(cad: Types.Cad): { number } + local out = {} + for id in cad.entities do + table.insert(out, id) + end + table.sort(out) + return out +end + +-- byType(cad, "ADVANCED_FACE") -> the ids of the instances of that type (complex ones with such a part too), ascending +function Step.byType(cad: Types.Cad, name: string): { number } + local n = string.upper(name) + local out = {} + for id, e in cad.entities do + if e.type == n then + table.insert(out, id) + elseif e.parts then + for _, p in e.parts do + if p.type == n then + table.insert(out, id) + break + end + end + end + end + table.sort(out) + return out +end + +-- part(entity, "TYPE") -> the args of that type (the entity's own, or one part of a complex instance) +function Step.part(e: Types.StepEntity?, name: string): { any }? + if not e then + return nil + end + if e.type == name then + return e.args + end + if e.parts then + for _, p in e.parts do + if p.type == name then + return p.args + end + end + end + return nil +end + +-- add(cad, type, args) -> id: a new instance after the highest id +function Step.add(cad: Types.Cad, type: string, args: { any }): number + local top = 0 + for id in cad.entities do + if id > top then + top = id + end + end + local id = top + 1 + cad.entities[id] = { id = id, type = string.upper(type), args = args } + cad.meta.count = (cad.meta.count or 0) + 1 + return id +end + +-- real(list, index) -> list: marks list[index] as a real (an integral value is then written `3.`, not `3`) +function Step.real(t: { [any]: any }, key: any): { [any]: any } + local mt: any = getmetatable(t) + if not mt then + mt = { __reals = {} } + setmetatable(t, mt) + end + mt.__reals[key] = true + return t +end + +-- new(schema?) -> an empty Cad ("AP214" by default) +function Step.new(schema: string?): Types.Cad + return { kind = "cad", schema = schema or "AP214", header = {}, entities = {}, meta = { count = 0 } } +end + +-- plugin(p) -> the normalised B-rep plug-in interface (see cad/step/Brep) | nil, reason +Step.plugin = Brep.plugin + +local function textOf(cad: Types.Cad): (string?, Err.Err?) + local buf, err = Step.encode(cad) + if not buf then + return nil, err + end + return buffer.tostring(buf), nil +end + +-- toBodies(cad, opts) -> bodies, result (the plug-in's read result: stats, warnings, ...) | nil, Err +function Step.toBodies(cad: Types.Cad, opts: BrepOptions?): (({ any })?, any) + local plug, perr = Brep.find(opts) + if not plug then + return nil, perr + end + local text, err = textOf(cad) + if not text then + return nil, err + end + local bodies, res, rerr = Brep.read(plug, text, opts) + if not bodies then + return nil, rerr + end + return bodies, res +end + +-- fromBodies(bodies, opts) -> Cad (the plug-in writes STEP text, parsed here) | nil, Err +function Step.fromBodies(bodies: { any }, opts: BrepOptions?): (Types.Cad?, Err.Err?) + if type(bodies) ~= "table" then + return nil, Err.new(Err.ARG, "needs a list of bodies") + end + local plug, perr = Brep.find(opts) + if not plug then + return nil, perr + end + local text, err = Brep.write(plug, bodies, opts) + if not text then + return nil, err + end + return Step.decode(Bytes.reader(buffer.fromstring(text))) +end + +-- tessellate(cad | bodies, opts) -> Scene (one node + mesh per body, z up, millimetres) | nil, Err +function Step.tessellate(value: any, opts: BrepOptions?): (Types.Scene?, Err.Err?) + local plug, perr = Brep.find(opts) + if not plug then + return nil, perr + end + local bodies = value + if type(value) == "table" and value.kind == "cad" then + local b, err = Step.toBodies(value, opts) + if not b then + return nil, err + end + bodies = b + end + if type(bodies) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Cad or a list of bodies") + end + return Brep.scene(plug, bodies, opts) +end + +return Step diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 19fd6c7..d4e6dbe 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -255,11 +255,15 @@ end -- so the api hands decoders opts.decodeImage(buf) -> Image | nil, Err and encoders opts.encodeImage(img, format) -> -- buffer | nil, Err (unless the caller passed its own). Formats work without them (returning Err.UNSUPPORTED for -- the embedded parts) when called directly. +-- They also see the injected plug-ins as opts.plugins (F.plugins: the B-rep kernel for cad/step) unless given their own. local function withHooks(o: Options): Options - if o.decodeImage ~= nil and o.encodeImage ~= nil then + if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil then return o end local c = table.clone(o) + if c.plugins == nil then + c.plugins = F.plugins + end if c.decodeImage == nil then c.decodeImage = function(b: buffer): (any, Err.Err?) return F.load(b, { category = "image" }) @@ -539,6 +543,31 @@ for category in Types.CATEGORIES do end F.data.null = Types.null +-- F.cad.toBodies(cad, opts?) -> bodies, result | nil, Err; F.cad.fromBodies(bodies, opts?) -> Cad | nil, Err; +-- F.cad.tessellate(cad | bodies, opts?) -> Scene | nil, Err: cad/step's B-rep calls with the injected kernel +-- (F.plugins.brep, unless opts.brep / opts.plugins is given). Without a plug-in they return Err.UNSUPPORTED. +for _, fn in { "toBodies", "fromBodies", "tessellate" } do + local name: string = fn + F.cad[name] = function(value: any, opts: Options?): (any, any) + local o = if opts then table.clone(opts) else {} + if o.plugins == nil then + o.plugins = F.plugins + end + local m, err = F.format("step") + if not m then + return nil, err + end + local ok, a, b = pcall(m[name], value, o) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, name .. " threw: " .. tostring(a)), "step") + end + if a == nil and type(b) == "table" and b.code then + return nil, Err.wrap(b, "step") + end + return a, b + end +end + -- F.model.loadTextures(scene, opts?) -> scene, { [index]: Err }: decodes each texture's encoded bytes (texture.data, or -- texture.uri through opts.resolve) into texture.image with F.image.load. Model formats never decode images -- themselves (a format does not require another format); this is the lazy step at the api layer. Textures whose diff --git a/tests/cad/step.luau b/tests/cad/step.luau new file mode 100644 index 0000000..0ebfb4b --- /dev/null +++ b/tests/cad/step.luau @@ -0,0 +1,392 @@ +-- cad/step tests: STEP files written by OCCT (solids modelled in gmsh's OpenCASCADE kernel) and public sample files, +-- against an independent Python Part 21 census (instances, count per type); our writer's output read back by OCCT +-- (solids, volume, faces, area, bounding box equal to the originals); parse -> write -> parse equality; every +-- parameter kind and string escape, complex instances, edition 3 sections, comments; the api (F.load / F.save / +-- F.cad.*); the B-rep plug-in path through brep-luau (luau CLI only: the alias in tests/gen/.luaurc) against OCCT's +-- volumes and bounds, and a custom plug-in table; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/step.py. +local T = require("@tests/T") +local F = require("@formats") +local Step = require("@formats/cad/step") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/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 + +-- 1. contract +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") + +-- deep equality of two decoded values (buffers, the real marks of lists included) +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 + +-- 2. fixtures: census, round trips; OCCT read our output like the original +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) + +-- 3. every parameter kind, escapes, complex instances, sections, comments +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") + +-- 4. building a file +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") + +-- 5. errors and sniff +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") + +-- 6. the api +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") + +-- 7. the plug-in: a custom interface table +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 + +-- 8. brep-luau (luau CLI: tests/gen/.luaurc aliases it; LuaJIT has no `vector` type: skipped) +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 + -- kernel bodies -> our Cad -> our text -> bodies again + 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 + +-- 9. fuzz +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() diff --git a/tools/bench.luau b/tools/bench.luau index 710195d..0d68d9a 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -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 diff --git a/tools/fixtures/_step_encode.luau b/tools/fixtures/_step_encode.luau new file mode 100644 index 0000000..b11c247 --- /dev/null +++ b/tools/fixtures/_step_encode.luau @@ -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_.step\t" 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 diff --git a/tools/fixtures/step.py b/tools/fixtures/step.py new file mode 100644 index 0000000..3c2099a --- /dev/null +++ b/tools/fixtures/step.py @@ -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 {}; 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)