Files

204 lines
9.7 KiB
Markdown

# CAD (STEP)
STEP files (ISO 10303-21, "Part 21": AP203, AP214, AP242 and any other schema) load as a `Cad`: the file's header and
its *entity graph*, every `#id = TYPE(...)` instance with its arguments, exactly as written. Reading and writing the
graph is built in and lossless (parse, write, parse gives the same entities).
Turning the graph into solid geometry needs a B-rep kernel, which rosetta does not include: B-rep bodies and
tessellated meshes come from a plug-in you inject as `F.plugins.brep` (for example
brep-luau's modules). Without it, `F.cad.toBodies` / `fromBodies` / `tessellate` return
`UNSUPPORTED` and everything else on this page still works.
```luau
local cad = assert(F.cad.load(stepText))
print(cad.schema, cad.meta.count) -- AP214 6
local step = assert(F.format("step")) -- the helpers below live on the format module
for _, id in step.byType(cad, "CARTESIAN_POINT") do
local e = cad.entities[id]
print(id, e.args[1], e.args[2][1], e.args[2][2], e.args[2][3]) -- 1 origin 0 0 0 / 5 tip 10 20 5.5
end
```
## The type
`Cad`:
| Field | Type | Meaning |
|---|---|---|
| `kind` | `"cad"` | |
| `schema` | string | `"AP203"`, `"AP214"`, `"AP242"`, or the `FILE_SCHEMA` name as written |
| `header` | table | header entities by name: `FILE_DESCRIPTION`, `FILE_NAME`, `FILE_SCHEMA` (and any other), each a list of its arguments |
| `entities` | `{ [id]: StepEntity }` | the DATA instances by their `#id` (a sparse table: ids need not be contiguous) |
| `meta` | table | `source.format`, `count` (number of instances), `headerOrder` |
`StepEntity`:
| Field | Type | Meaning |
|---|---|---|
| `id` | number | the instance number (`#12` -> 12) |
| `type` | string | the entity type in upper case (`"CARTESIAN_POINT"`), or `"COMPLEX"` |
| `args` | `{ any }` | the parameters (below); empty for a complex instance |
| `parts` | `{ { type, args } }?` | complex instances `#6 = (A() B(*) C(...))`: one part per type, in file order |
| `section` | number? | the DATA section, in files with several (edition 3) |
Parameters map to Luau values:
| STEP | Luau |
|---|---|
| `12`, `1.5`, `0.` | a number (integral reals keep their real-ness when written back) |
| `'text'` | a string (Part 21 escapes `\X2\...` decoded to UTF-8) |
| `.T.`, `.MILLI.` | `{ enum = "T" }`, `{ enum = "MILLI" }` |
| `#4` | `{ ref = 4 }` |
| `(1., 2., 3.)` | a list |
| `LENGTH_MEASURE(2.5)` | `{ typed = "LENGTH_MEASURE", value = 2.5 }` |
| `"0FF"` | `{ binary = "0FF" }` |
| `$` / `*` | `step.NULL` / `step.DERIVED` (sentinels on the format module) |
## Inspect
`F.format("step")` has helpers for walking the graph:
| Function | Returns |
|---|---|
| `get(cad, id | { ref = id })` | the entity (follows a reference) |
| `ids(cad)` | every instance id, ascending |
| `byType(cad, "TYPE")` | the ids of instances of a type (complex instances with such a part too), ascending |
| `part(entity, "TYPE")` | the args of that type: the entity's own, or one part of a complex instance |
| `add(cad, type, args)` | adds an instance after the highest id and returns its id |
| `real(list, index)` | marks `list[index]` as a real, so an integral value is written `3.` rather than `3` |
| `new(schema?)` | an empty Cad (`"AP214"` by default) |
| `NULL`, `DERIVED`, `SCHEMAS` | `$`, `*`, and the full `FILE_SCHEMA` names of AP203 / AP214 / AP242 |
```luau
local cad = assert(F.cad.load(stepText))
local step = assert(F.format("step"))
local placement = cad.entities[step.byType(cad, "AXIS2_PLACEMENT_3D")[1]]
local origin = assert(step.get(cad, placement.args[2])) -- args[2] is { ref = 1 }
assert(origin.type == "CARTESIAN_POINT" and origin.args[1] == "origin")
local axis = step.get(cad, placement.args[3])
assert(axis.args[2][3] == 1) -- DIRECTION('z', (0., 0., 1.))
local unit = cad.entities[6] -- (LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT(.MILLI., .METRE.))
assert(unit.type == "COMPLEX" and #unit.parts == 3)
local si = assert(step.part(unit, "SI_UNIT"))
assert(si[1].enum == "MILLI" and si[2].enum == "METRE")
assert(step.part(unit, "NAMED_UNIT")[1] == step.DERIVED)
local name = cad.header.FILE_NAME -- name, time stamp, authors, organisations, ...
assert(name[1] == "part.step")
```
## Edit and save
Edit `entities` / `header` directly, or add instances with `add`. `F.save` writes Part 21 text, one instance per line
in id order.
| Encode option | Meaning |
|---|---|
| `schema` | `"AP203"`, `"AP214"`, `"AP242"` or a schema name: replaces `FILE_SCHEMA` |
| `name` | the `FILE_NAME` name (default: the header's, else `"model"`) |
| `timestamp` | the `FILE_NAME` time stamp when the header has none |
| `crlf` | CRLF line ends (default LF) |
```luau
local cad = assert(F.cad.load(stepText))
local step = assert(F.format("step"))
local coords = step.real(step.real(step.real({ 1, 2, 3 }, 1), 2), 3) -- written (1.,2.,3.)
local id = step.add(cad, "CARTESIAN_POINT", { "corner", coords })
assert(id == 7)
local text = assert(F.saveString(cad, { schema = "AP242" }))
assert(string.find(text, "#7=CARTESIAN_POINT('corner',(1.,2.,3.));", 1, true))
assert(string.find(text, "AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF", 1, true))
local back = assert(F.cad.load(text))
assert(back.schema == "AP242" and back.meta.count == 7)
```
A new file from scratch:
```luau
local step = assert(F.format("step"))
local cad = step.new("AP203")
local p = step.add(cad, "CARTESIAN_POINT", { "p", step.real(step.real(step.real({ 0, 0, 0 }, 1), 2), 3) })
step.add(cad, "VERTEX_POINT", { "", { ref = p } })
local text = assert(F.saveString(cad, { format = "step", name = "vertex.step" })) -- built here: no source format
assert(string.find(text, "CONFIG_CONTROL_DESIGN", 1, true) and string.find(text, "#2=VERTEX_POINT('',#1);", 1, true))
```
## B-rep and meshes: the plug-in
STEP stores solids as boundary representations (faces on surfaces, trimmed by edges on curves). Evaluating them takes
a geometry kernel, which you inject:
<!-- doc:display needs the brep-luau plug-in -->
```luau
F.plugins.brep = { -- brep-luau's modules as they are
Step = require(path.to.brep.Step),
StepBrep = require(path.to.brep.StepBrep),
StepWrite = require(path.to.brep.StepWrite),
Tess = require(path.to.brep.Tess),
}
local cad = assert(F.cad.load(stepBytes))
local scene = assert(F.cad.tessellate(cad, { chord = 0.05 })) -- a Scene: one node + mesh per solid
local glb = assert(F.save(scene, nil, { format = "glb" }))
local bodies = assert(F.cad.toBodies(cad)) -- the kernel's own body objects
local copy = assert(F.cad.fromBodies(bodies)) -- a Cad written by the kernel
```
| Function | Returns |
|---|---|
| `F.cad.toBodies(cad, opts?)` | `bodies, result`: the kernel's bodies, and its whole read result (stats, warnings) |
| `F.cad.fromBodies(bodies, opts?)` | a `Cad` (the kernel writes STEP text, parsed back) |
| `F.cad.tessellate(cad | bodies, opts?)` | a `Scene`: one node and mesh per body, one primitive per face colour, **z up, millimetres** (`meta.unit = 0.001`) |
Options: `brep` (a plug-in for this call instead of `F.plugins.brep`), `chord` (the tessellation sag in millimetres,
default 0.05) or `tess` (the kernel's own tessellation options).
Any kernel works if it has this shape (every function may throw; the library catches it and returns `nil, err`):
| Function | Contract |
|---|---|
| `read(text, opts)` | STEP text -> `{ bodies = { body }, stats = ...? }`; a body may have `name` and `color` (`{ r, g, b }` 0..1) |
| `write(bodies, opts)` | bodies -> STEP text |
| `tessellate(body, opts)` | -> `{ positions = { {x, y, z} }, normals = { ... }?, indices = { 1-based, three per triangle }, faceOf = { [triangle] = face }? }` (a face may have `color`) |
A minimal stand-in kernel shows the contract (and is handy in tests): every file is one triangle.
```luau
local fake = {
read = function(text, opts)
return { bodies = { { name = "plate", color = { 1, 0, 0 } } }, stats = { bytes = #text } }
end,
tessellate = function(body, opts)
return { positions = { { 0, 0, 0 }, { 10, 0, 0 }, { 0, 10, 0 } }, indices = { 1, 2, 3 } }
end,
}
local cad = assert(F.cad.load(stepText))
local none, err = F.cad.tessellate(cad) -- no plug-in installed
assert(none == nil and err.code == F.Err.UNSUPPORTED)
local scene = assert(F.cad.tessellate(cad, { brep = fake }))
assert(scene.kind == "scene" and scene.meta.up == "z" and scene.meta.unit == 0.001)
assert(scene.meshes[1].name == "plate" and scene.meshes[1].primitives[1].indices.count == 3)
assert(scene.materials[1].extras.color[1] == 1) -- the body colour (baseColor is linear)
local _, werr = F.cad.fromBodies({}, { brep = fake }) -- this kernel cannot write
assert(werr.code == F.Err.UNSUPPORTED)
```
## Formats
| Format | Read | Write | Notes |
|---|---|---|---|
| step (`.step .stp .p21`) | yes | yes | editions 1 to 3, complex instances, several DATA sections; B-rep and tessellation through the plug-in |
STEP-XML (ISO 10303-28) and compressed `.stpZ` are not supported. See [FORMATS.md](../FORMATS.md).
## Gotchas
- **Ids are sparse.** `#entities` is meaningless; iterate `step.ids(cad)` (ordered) or `pairs(cad.entities)`.
- **References are tables.** `{ ref = 4 }` is not the entity; resolve it with `step.get(cad, ref)`.
- **Reals vs integers.** Luau has one number type. Values read as reals stay reals when written back; for new
values, mark integral reals with `step.real(list, index)`, or the file will contain `3` where the schema wants `3.`.
- **Complex instances** have `type = "COMPLEX"` and empty `args`; use `step.part(e, "TYPE")` or `e.parts`.
- **Tessellated scenes are z up in millimetres.** Convert for y-up engines with `F.ops.mesh.setUp(scene, "y")` and
`F.ops.mesh.setUnit(scene, 1)` (see [Scene](scene.md)).