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