Merge branch 'ws/3d2-step' into ws/3d2

This commit is contained in:
4DBug committed 2026-10-31 09:47:00 -05:00
commit b275bdb498
12 files changed
+2154 -2

No files matched your search

+12
View File
@@ -314,6 +314,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",
+3 -1
View File
@@ -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", ...
+248
View File
@@ -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
+573
View File
@@ -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
+252
View File
@@ -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
+412
View File
@@ -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
+30 -1
View File
@@ -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