merge ws/3d3-d (model/b3d, model/ldraw)
This commit is contained in:
commit
de2695b87d
14 files changed
+2843
-1
No files matched your search
@@ -35,9 +35,11 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` |
|
||||
| video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` |
|
||||
| model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` |
|
||||
| model | b3d | .b3d | yes | - | materials: true, textures: true, skins: true, animation: true, colors: true | `tests/model/b3d.luau` |
|
||||
| model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` |
|
||||
| model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` |
|
||||
| model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, draco: true | `tests/model/gltf.luau` |
|
||||
| model | ldraw | .ldr .mpd .dat | yes | - | materials: true, lines: true, instancing: true | `tests/model/ldraw.luau` |
|
||||
| model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` |
|
||||
| model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` |
|
||||
| model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` |
|
||||
|
||||
+75
-1
@@ -1,6 +1,6 @@
|
||||
# Scene (3D models) and Voxels
|
||||
|
||||
Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX) loads as one `Scene`, a structure
|
||||
Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, B3D, LDraw) loads as one `Scene`, a structure
|
||||
shaped like glTF 2.0: a node tree, meshes made of primitives, flat attribute buffers (accessors), PBR materials,
|
||||
textures, cameras, lights, skins and animations. Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel
|
||||
files also carry voxel grids (`scene.voxels`). Editing goes through `F.ops.mesh`.
|
||||
@@ -397,6 +397,78 @@ local vox = assert(F.save(grid, nil, { format = "vox" })) -- a grid alone saves
|
||||
assert(F.load(vox).voxels[1].size[1] == 4)
|
||||
```
|
||||
|
||||
## Blitz3D (B3D)
|
||||
|
||||
`.b3d` files (Blitz3D, also written by many old game tools) load read-only. The node tree keeps its names and TRS;
|
||||
each `MESH` becomes one mesh whose primitives (one per `TRIS` chunk) share the vertex accessors; brushes become
|
||||
materials (colour, alpha, shininess, the first texture as `baseColorTexture` with its position / scale / rotation as
|
||||
`transform`, the full brush in `extras.b3d`); `BONE` weights become a skin (the 4 strongest weights per vertex) and
|
||||
`KEYS` + `ANIM` one animation sampled at `frame / fps`. Texture files come through `files` / `resolve` like any other
|
||||
model's (by the stored path, then by its base name: B3D files often store absolute Windows paths).
|
||||
|
||||
Blitz3D is **left-handed**: the reader mirrors z (and turns the triangle winding and rotations to match), so the scene
|
||||
is glTF's right-handed Y-up with the model looking as it did in Blitz3D. `meta.source.handedness = "left"` records
|
||||
the origin, `meta.source.fps` / `frames` the `ANIM` chunk.
|
||||
|
||||
## LDraw
|
||||
|
||||
LDraw files (`.ldr` models, `.dat` parts, `.mpd` multi-part files) load read-only. Every reference to a **part**
|
||||
becomes a node with the reference's matrix, and each part is baked once per colour into a mesh those nodes share;
|
||||
**sub-models** (`.ldr` / `.mpd` files, MPD sections that are not parts) become nodes with children. Colour 16 takes the
|
||||
colour of the reference above it, 24 its edge colour; codes come from the LDConfig.ldr table built in (one material per
|
||||
colour, `extras.ldraw.code` / `name`), `0x2RRGGBB` is a direct colour. BFC (`CERTIFY`, `CW` / `CCW`, `INVERTNEXT`,
|
||||
`NOCLIP`) turns every face counter-clockwise; faces of uncertified parts get double-sided materials. Edge lines (type 2)
|
||||
are `"lines"` primitives (`lines = false` drops them); optional lines only on request (`optionalLines = true`).
|
||||
|
||||
```luau
|
||||
local mpd = [[
|
||||
0 FILE house.ldr
|
||||
1 4 0 0 0 1 0 0 0 1 0 0 0 1 wall.dat
|
||||
1 4 50 0 0 1 0 0 0 1 0 0 0 1 wall.dat
|
||||
1 1 0 -30 0 1 0 0 0 1 0 0 0 1 roof.dat
|
||||
0 FILE wall.dat
|
||||
0 !LDRAW_ORG Unofficial_Part
|
||||
0 BFC CERTIFY CCW
|
||||
4 16 -10 0 -10 10 0 -10 10 0 10 -10 0 10
|
||||
2 24 -10 0 -10 10 0 -10
|
||||
0 FILE roof.dat
|
||||
0 BFC CERTIFY CCW
|
||||
3 16 0 -10 0 10 0 0 -10 0 0
|
||||
]]
|
||||
local scene = assert(F.model.load(mpd, { format = "ldraw" }))
|
||||
print(#scene.meshes) -- 2: wall.dat in red (both walls share it), roof.dat in blue
|
||||
local root = scene.nodes[scene.roots[1]] -- "LDraw": turns LDraw's -Y up into Y up
|
||||
local a, b = scene.nodes[root.children[1]], scene.nodes[root.children[2]]
|
||||
assert(a.mesh == b.mesh and b.matrix[13] == 50)
|
||||
local red = scene.materials[scene.meshes[a.mesh].primitives[1].material]
|
||||
print(red.name, red.extras.ldraw.code) -- Red 4
|
||||
assert(scene.meta.up == "y" and scene.meta.unit == 0.0004) -- 1 LDU = 0.4 mm
|
||||
```
|
||||
|
||||
Parts and primitives that are not in the file come through `files` or `resolve`, asked for by their LDraw library
|
||||
path: the name as written (backslashes turned into slashes), then in lower case, under `""`, `parts/`, `p/`,
|
||||
`parts/s/` and `models/`. Point `resolve` at an LDraw library folder to load real models; missing files are skipped and
|
||||
listed in `meta.source.missing`:
|
||||
|
||||
```luau
|
||||
local library = {
|
||||
["p/box.dat"] = "0 BFC CERTIFY CCW\n4 16 -1 -1 -1 1 -1 -1 1 -1 1 -1 -1 1\n4 16 -1 1 -1 -1 1 1 1 1 1 1 1 -1\n",
|
||||
["parts/plate.dat"] = "0 !LDRAW_ORG Part\n1 16 0 4 0 20 0 0 0 4 0 0 0 10 box.dat\n",
|
||||
}
|
||||
local model = "0 two plates\n1 14 0 0 0 1 0 0 0 1 0 0 0 1 plate.dat\n1 0x2FF8000 0 -8 0 1 0 0 0 1 0 0 0 1 plate.dat\n"
|
||||
.. "1 4 0 -16 0 1 0 0 0 1 0 0 0 1 3001.dat\n"
|
||||
local scene = assert(F.model.load(model, { format = "ldraw", files = library }))
|
||||
assert(#scene.meshes == 2 and scene.meta.source.missing[1] == "3001.dat")
|
||||
local same = assert(F.model.load(model, { format = "ldraw", resolve = function(path)
|
||||
return library[path] -- or: read ldrawFolder .. "/" .. path
|
||||
end }))
|
||||
local flat = assert(F.model.load(model, { format = "ldraw", files = library, flatten = true }))
|
||||
assert(#flat.meshes == 1) -- one mesh, one primitive per colour
|
||||
```
|
||||
|
||||
`upright = false` leaves out the root node (LDraw's axes as stored, `meta.source.up = "-y"`); `ldconfig` takes the
|
||||
text of another LDConfig.ldr, and `color` the colour of code 16 at the top (default 16, "Main_Colour").
|
||||
|
||||
## Formats
|
||||
|
||||
| Format | Read | Write | Notes |
|
||||
@@ -411,6 +483,8 @@ assert(F.load(vox).voxels[1].size[1] == 4)
|
||||
| 3MF | yes | yes | |
|
||||
| USDA (+ USDZ read) | yes | yes | |
|
||||
| VOX | yes | yes | voxel grids, scene graph, materials |
|
||||
| B3D (Blitz3D) | yes | | brushes, textures, skins, keyframe animation; left-handed source mirrored to glTF's frame |
|
||||
| LDraw (LDR / DAT / MPD) | yes | | parts as shared meshes per colour, sub-models as nodes, BFC, LDConfig colours, `files` / `resolve` for the library |
|
||||
| STEP | via the CAD plug-in | | see [cad.md](cad.md) |
|
||||
|
||||
Capabilities per format: [FORMATS.md](../FORMATS.md).
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
LDraw colour table (src/Formats/model/ldraw/Colors.luau)
|
||||
|
||||
The built-in colour list of model/ldraw is the list of !COLOUR definitions of LDConfig.ldr from the LDraw.org Parts
|
||||
Library ("0 !LDRAW_ORG Configuration UPDATE 2025-05-20", Author: LDraw.org), reformatted (one line per colour, the
|
||||
"0 !COLOUR" prefix dropped, MATERIAL parameters cut after the material type). Modified from the original.
|
||||
|
||||
Creator: LDraw.org (https://www.ldraw.org/)
|
||||
Work: LDConfig.ldr, LDraw.org Parts Library, https://library.ldraw.org/library/updates/complete.zip
|
||||
Licence: Creative Commons Attribution 2.0 (CC BY 2.0) and Creative Commons Attribution 4.0 International (CC BY 4.0),
|
||||
as specified by the LDraw Contributor Agreement (see the library's CAreadme.txt):
|
||||
https://creativecommons.org/licenses/by/2.0/
|
||||
https://creativecommons.org/licenses/by/4.0/
|
||||
|
||||
LDraw is a trademark of the Estate of James Jessiman. LEGO is a trademark of the LEGO Group, which does not sponsor,
|
||||
authorize or endorse this software.
|
||||
@@ -39,6 +39,8 @@
|
||||
| `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) |
|
||||
| `src/Formats/codecs/model/Draco/` | Luau port of the Draco 1.5.7 decoder (Google): compression/{decode, mesh, attributes, entropy, bit_coders, point_cloud}, mesh/corner_table, mesh/mesh_attribute_corner_table, core/{decoder_buffer, varint_decoding, math_utils}, attributes/attribute_{quantization,octahedron}_transform | Apache-2.0: [draco-LICENSE.txt](draco-LICENSE.txt) |
|
||||
| `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data |
|
||||
| `src/Formats/model/ldraw/Colors.luau` (the built-in colour table) | the !COLOUR list of LDConfig.ldr (LDraw.org Parts Library, UPDATE 2025-05-20), reformatted | CC BY 2.0 / CC BY 4.0: [LDRAW_COLOURS.txt](LDRAW_COLOURS.txt) |
|
||||
| `tests/gen/ldraw_*` (read at fixture time from the nix store, not committed) | LDraw.org Parts Library parts and sample models (complete.zip, as packaged for nixpkgs' LeoCAD) | CC BY 2.0 / CC BY 4.0, test data |
|
||||
|
||||
Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this
|
||||
folder (see docs/STYLE.md, "Absorbing an existing repo").
|
||||
@@ -374,6 +374,18 @@ local list: { Entry } = {
|
||||
return require("@formats/model/3mf")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "b3d",
|
||||
category = "model",
|
||||
path = "model/b3d",
|
||||
extensions = { "b3d" },
|
||||
mime = { "model/x-b3d" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/model/Mat4" },
|
||||
caps = { decode = true, encode = false, materials = true, textures = true, skins = true, animation = true, colors = true },
|
||||
load = function()
|
||||
return require("@formats/model/b3d")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "dae",
|
||||
category = "model",
|
||||
@@ -410,6 +422,18 @@ local list: { Entry } = {
|
||||
return require("@formats/model/gltf")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ldraw",
|
||||
category = "model",
|
||||
path = "model/ldraw",
|
||||
extensions = { "ldr", "mpd", "dat" },
|
||||
mime = { "application/x-ldraw", "application/x-multi-part-ldraw" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
|
||||
caps = { decode = true, encode = false, materials = true, lines = true, instancing = true },
|
||||
load = function()
|
||||
return require("@formats/model/ldraw")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "obj",
|
||||
category = "model",
|
||||
|
||||
@@ -0,0 +1,576 @@
|
||||
--!strict
|
||||
-- model/b3d/Read: the BB3D chunk tree -> Types.Scene (see model/b3d for what is read and how it is mapped). Chunks are
|
||||
-- walked with containers/Chunks (4-byte id, u32 little-endian size, no padding); fields are read through core/Bytes
|
||||
-- readers over each chunk body, so a short body sets the reader's sticky error instead of reading past the end.
|
||||
-- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from).
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Chunks = require("@formats/containers/Chunks")
|
||||
local Mat4 = require("@formats/codecs/model/Mat4")
|
||||
|
||||
local Read = {}
|
||||
|
||||
export type Options = {
|
||||
resolve: ((uri: string) -> any)?,
|
||||
files: { [string]: any }?,
|
||||
maxVertices: number?,
|
||||
maxDepth: number?,
|
||||
}
|
||||
|
||||
local LAYOUT: Chunks.Layout = { maxChunks = 1000000 }
|
||||
local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" }
|
||||
|
||||
type Brush = { name: string, color: { number }, shininess: number, blend: number, fx: number, textures: { number } }
|
||||
type TexInfo = { file: string, flags: number, blend: number, offset: { number }, scale: { number }, rotation: number, index: number }
|
||||
type MeshRec = { mesh: number, node: number, count: number, joints: { { number } }, weights: { { number } } }
|
||||
type Bone = { node: number, target: MeshRec?, list: { number } }
|
||||
type Keys = { t: { [number]: { number } }, s: { [number]: { number } }, r: { [number]: { number } } }
|
||||
|
||||
-- the file's left-handed Y-up values in glTF's right-handed frame: z mirrored; quaternions as w x y z, conjugated
|
||||
-- (Blitz3D stores the inverse rotation, as assimp's reader reads them) then mirrored
|
||||
local function vec(r: Bytes.Reader): { number }
|
||||
local x, y, z = r:f32le(), r:f32le(), r:f32le()
|
||||
return { x, y, -z }
|
||||
end
|
||||
local function quat(r: Bytes.Reader): { number }
|
||||
local w, x, y, z = r:f32le(), r:f32le(), r:f32le(), r:f32le()
|
||||
local l = math.sqrt(w * w + x * x + y * y + z * z)
|
||||
if l < 1e-12 or l ~= l then
|
||||
return { 0, 0, 0, 1 }
|
||||
end
|
||||
return { x / l, y / l, -z / l, w / l }
|
||||
end
|
||||
|
||||
local function fetcher(opts: Options?): (string) -> buffer?
|
||||
local files = opts and opts.files
|
||||
local resolve = opts and opts.resolve
|
||||
return function(uri: string): buffer?
|
||||
local v: any = if type(files) == "table" then files[uri] else nil
|
||||
if v == nil and type(resolve) == "function" then
|
||||
local ok, res = pcall(resolve, uri)
|
||||
v = if ok then res else nil
|
||||
end
|
||||
return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil
|
||||
end
|
||||
end
|
||||
|
||||
-- scene(r, opts) -> Scene | nil, message, kind
|
||||
function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, string?)
|
||||
local buf = src.buf
|
||||
local maxVertices = opts and opts.maxVertices or 2 ^ 24
|
||||
local maxDepth = opts and opts.maxDepth or 256
|
||||
local fetch = fetcher(opts)
|
||||
local top = Chunks.walk(buf, src.base, src.limit, LAYOUT)
|
||||
local head = top[1]
|
||||
if not head or head.id ~= "BB3D" then
|
||||
return nil, "not a BB3D file", nil
|
||||
end
|
||||
if head.truncated then
|
||||
return nil, "truncated", "truncated"
|
||||
end
|
||||
local hr = Bytes.reader(buf, head.offset, head.size)
|
||||
local version = hr:i32le()
|
||||
if hr.err then
|
||||
return nil, "truncated", "truncated"
|
||||
end
|
||||
|
||||
local scene = Types.Scene.new()
|
||||
local texs: { TexInfo } = {}
|
||||
local brushes: { Brush } = {}
|
||||
local materialOf: { [number]: number } = {} -- brush index (0-based) -> material
|
||||
local meshes: { MeshRec } = {}
|
||||
local bones: { Bone } = {}
|
||||
local nodeKeys: { [number]: Keys } = {}
|
||||
local anim: { frames: number, fps: number, flags: number }? = nil
|
||||
local lastMesh: MeshRec? = nil
|
||||
local totalVertices = 0
|
||||
local failure: string?, failKind: string? = nil, nil
|
||||
|
||||
local function fail(msg: string, kind: string?)
|
||||
if not failure then
|
||||
failure, failKind = msg, kind
|
||||
end
|
||||
end
|
||||
local function body(c: Chunks.Chunk): Bytes.Reader
|
||||
if c.truncated then
|
||||
fail("truncated " .. c.id .. " chunk", "truncated")
|
||||
end
|
||||
return Bytes.reader(buf, c.offset, c.avail)
|
||||
end
|
||||
|
||||
local function readTexs(r: Bytes.Reader)
|
||||
while r.pos < r.limit and not r.err do
|
||||
local file = r:cstring()
|
||||
local t: TexInfo = { file = file, flags = r:i32le(), blend = r:i32le(), offset = { r:f32le(), r:f32le() }, scale = { r:f32le(), r:f32le() }, rotation = r:f32le(), index = 0 }
|
||||
if r.err then
|
||||
return fail("truncated TEXS entry", "truncated")
|
||||
end
|
||||
local tex: Types.Texture = { name = string.match(file, "([^/\\]+)$") or file, uri = file, mime = MIME[string.lower(string.match(file, "%.(%w+)$") or "")] }
|
||||
local data = fetch(file)
|
||||
if not data then
|
||||
local base = string.match(file, "([^/\\]+)$")
|
||||
if base and base ~= file then
|
||||
data = fetch(base)
|
||||
end
|
||||
end
|
||||
tex.data = data
|
||||
if bit32.band(t.flags, 48) ~= 0 then
|
||||
tex.sampler = { wrapS = if bit32.band(t.flags, 16) ~= 0 then "clamp" else "repeat", wrapT = if bit32.band(t.flags, 32) ~= 0 then "clamp" else "repeat" }
|
||||
end
|
||||
tex.extras = { b3d = { flags = t.flags, blend = t.blend } }
|
||||
table.insert(scene.textures, tex)
|
||||
t.index = #scene.textures
|
||||
table.insert(texs, t)
|
||||
end
|
||||
end
|
||||
|
||||
local function readBrus(r: Bytes.Reader)
|
||||
local n = r:i32le()
|
||||
if r.err or n < 0 or n > 8 then
|
||||
return fail("bad BRUS texture count")
|
||||
end
|
||||
while r.pos < r.limit and not r.err do
|
||||
local b: Brush = { name = r:cstring(), color = { r:f32le(), r:f32le(), r:f32le(), r:f32le() }, shininess = r:f32le(), blend = r:i32le(), fx = r:i32le(), textures = {} }
|
||||
for i = 1, n do
|
||||
b.textures[i] = r:i32le()
|
||||
end
|
||||
if r.err then
|
||||
return fail("truncated BRUS entry", "truncated")
|
||||
end
|
||||
table.insert(brushes, b)
|
||||
end
|
||||
end
|
||||
|
||||
-- the material of brush id (0-based) | nil for -1 / out of range
|
||||
local function material(id: number): number?
|
||||
if id < 0 or id >= #brushes then
|
||||
return nil
|
||||
end
|
||||
local have = materialOf[id]
|
||||
if have then
|
||||
return have
|
||||
end
|
||||
local b = brushes[id + 1]
|
||||
local m = Types.Scene.material(b.name ~= "" and b.name or nil)
|
||||
local c = b.color
|
||||
local function clamp01(v: number): number
|
||||
return if v ~= v then 1 else math.clamp(v, 0, 1)
|
||||
end
|
||||
m.baseColor = { clamp01(c[1]), clamp01(c[2]), clamp01(c[3]), clamp01(c[4]) }
|
||||
m.metallic = 0
|
||||
m.roughness = 1 - 0.8 * clamp01(b.shininess)
|
||||
m.doubleSided = bit32.band(b.fx, 16) ~= 0
|
||||
if m.baseColor[4] < 1 or bit32.band(b.fx, 32) ~= 0 then
|
||||
m.alphaMode = "blend"
|
||||
end
|
||||
if bit32.band(b.fx, 1) ~= 0 then
|
||||
m.extensions = { KHR_materials_unlit = {} }
|
||||
end
|
||||
local extraTex: { number } = {}
|
||||
for i, tid in b.textures do
|
||||
local t = texs[tid + 1]
|
||||
if tid >= 0 and t then
|
||||
if not m.baseColorTexture then
|
||||
local ref: Types.TextureRef = { texture = t.index, texCoord = if bit32.band(t.flags, 65536) ~= 0 then 1 else nil }
|
||||
local o, s, rot = t.offset, t.scale, t.rotation
|
||||
if o[1] ~= 0 or o[2] ~= 0 or s[1] ~= 1 or s[2] ~= 1 or rot ~= 0 then
|
||||
ref.transform = { offset = { o[1], o[2] }, scale = { s[1], s[2] }, rotation = rot }
|
||||
end
|
||||
m.baseColorTexture = ref
|
||||
if bit32.band(t.flags, 4) ~= 0 then
|
||||
m.alphaMode = "mask"
|
||||
elseif bit32.band(t.flags, 2) ~= 0 then
|
||||
m.alphaMode = "blend"
|
||||
end
|
||||
else
|
||||
extraTex[i] = t.index
|
||||
end
|
||||
end
|
||||
end
|
||||
m.extras = { b3d = { shininess = b.shininess, blend = b.blend, fx = b.fx, textures = if next(extraTex) then extraTex else nil } }
|
||||
table.insert(scene.materials, m)
|
||||
materialOf[id] = #scene.materials
|
||||
return #scene.materials
|
||||
end
|
||||
|
||||
local function readMesh(r: Bytes.Reader, nodeIndex: number): number?
|
||||
local master = r:i32le()
|
||||
if r.err then
|
||||
fail("truncated MESH", "truncated")
|
||||
return nil
|
||||
end
|
||||
local list = Chunks.walk(buf, r.pos, r.limit, LAYOUT)
|
||||
local attrs: { [string]: Types.Accessor }? = nil
|
||||
local count = 0
|
||||
local mesh: Types.Mesh = { primitives = {} }
|
||||
local rec: MeshRec = { mesh = 0, node = nodeIndex, count = 0, joints = {}, weights = {} }
|
||||
for _, c in list do
|
||||
local cr = body(c)
|
||||
if c.id == "VRTS" and not attrs then
|
||||
local flags, sets, size = cr:i32le(), cr:i32le(), cr:i32le()
|
||||
if cr.err or sets < 0 or sets > 8 or size < 0 or size > 4 then
|
||||
fail("bad VRTS header")
|
||||
return nil
|
||||
end
|
||||
local hasN, hasC = bit32.band(flags, 1) ~= 0, bit32.band(flags, 2) ~= 0
|
||||
local stride = 12 + (if hasN then 12 else 0) + (if hasC then 16 else 0) + sets * size * 4
|
||||
local n = (cr.limit - cr.pos) // stride
|
||||
totalVertices += n
|
||||
if totalVertices > maxVertices then
|
||||
fail(string.format("limit: %d vertices is over the %d vertex limit", totalVertices, maxVertices), "limit")
|
||||
return nil
|
||||
end
|
||||
local pos = buffer.create(n * 12)
|
||||
local nrm = if hasN then buffer.create(n * 12) else nil
|
||||
local col = if hasC then buffer.create(n * 16) else nil
|
||||
local uvs: { buffer } = {}
|
||||
for s = 1, sets do
|
||||
uvs[s] = buffer.create(n * 8)
|
||||
end
|
||||
local readf32, writef32 = buffer.readf32, buffer.writef32
|
||||
local p = cr.pos
|
||||
for i = 0, n - 1 do
|
||||
writef32(pos, i * 12, readf32(buf, p))
|
||||
writef32(pos, i * 12 + 4, readf32(buf, p + 4))
|
||||
writef32(pos, i * 12 + 8, -readf32(buf, p + 8))
|
||||
p += 12
|
||||
if nrm then
|
||||
writef32(nrm, i * 12, readf32(buf, p))
|
||||
writef32(nrm, i * 12 + 4, readf32(buf, p + 4))
|
||||
writef32(nrm, i * 12 + 8, -readf32(buf, p + 8))
|
||||
p += 12
|
||||
end
|
||||
if col then
|
||||
for k = 0, 3 do
|
||||
writef32(col, i * 16 + k * 4, readf32(buf, p + k * 4))
|
||||
end
|
||||
p += 16
|
||||
end
|
||||
for s = 1, sets do
|
||||
if size >= 1 then
|
||||
writef32(uvs[s], i * 8, readf32(buf, p))
|
||||
end
|
||||
if size >= 2 then
|
||||
writef32(uvs[s], i * 8 + 4, readf32(buf, p + 4))
|
||||
end
|
||||
p += size * 4
|
||||
end
|
||||
end
|
||||
local a: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, n) }
|
||||
if nrm then
|
||||
a.NORMAL = Types.Scene.accessor(nrm, "f32", 3, n)
|
||||
end
|
||||
if col then
|
||||
a.COLOR_0 = Types.Scene.accessor(col, "f32", 4, n)
|
||||
end
|
||||
if size > 0 then
|
||||
for s = 1, sets do
|
||||
a["TEXCOORD_" .. (s - 1)] = Types.Scene.accessor(uvs[s], "f32", 2, n)
|
||||
end
|
||||
end
|
||||
attrs, count = a, n
|
||||
mesh.extras = { b3d = { vertexFlags = flags, texCoordSets = sets, texCoordSize = size } }
|
||||
elseif c.id == "TRIS" then
|
||||
local brush = cr:i32le()
|
||||
if cr.err then
|
||||
fail("truncated TRIS", "truncated")
|
||||
return nil
|
||||
end
|
||||
if not attrs then
|
||||
fail("TRIS before VRTS")
|
||||
return nil
|
||||
end
|
||||
local nt = (cr.limit - cr.pos) // 12
|
||||
local idx = buffer.create(nt * 12)
|
||||
local readu32, writeu32 = buffer.readu32, buffer.writeu32
|
||||
local p = cr.pos
|
||||
for i = 0, nt - 1 do
|
||||
local a, b, cc = readu32(buf, p), readu32(buf, p + 4), readu32(buf, p + 8)
|
||||
if a >= count or b >= count or cc >= count then
|
||||
fail(string.format("triangle %d: vertex index out of range", i))
|
||||
return nil
|
||||
end
|
||||
-- mirrored z: reverse the winding to keep the faces front-facing
|
||||
writeu32(idx, i * 12, a)
|
||||
writeu32(idx, i * 12 + 4, cc)
|
||||
writeu32(idx, i * 12 + 8, b)
|
||||
p += 12
|
||||
end
|
||||
local prim: Types.Primitive = { attributes = attrs, indices = Types.Scene.accessor(idx, "u32", 1, nt * 3), mode = "triangles" }
|
||||
prim.material = material(if brush == -1 then master else brush)
|
||||
table.insert(mesh.primitives, prim)
|
||||
end
|
||||
end
|
||||
if not attrs then
|
||||
return nil -- a mesh without vertices: the node stays a pivot
|
||||
end
|
||||
if #mesh.primitives == 0 then
|
||||
table.insert(mesh.primitives, { attributes = attrs, mode = "points" :: "points" })
|
||||
end
|
||||
table.insert(scene.meshes, mesh)
|
||||
rec.mesh, rec.count = #scene.meshes, count
|
||||
table.insert(meshes, rec)
|
||||
lastMesh = rec
|
||||
return #scene.meshes
|
||||
end
|
||||
|
||||
local function readBone(r: Bytes.Reader, nodeIndex: number)
|
||||
local b: Bone = { node = nodeIndex, target = lastMesh, list = {} }
|
||||
table.insert(bones, b)
|
||||
local list = b.list
|
||||
while r.pos + 8 <= r.limit do
|
||||
local v, w = r:i32le(), r:f32le()
|
||||
table.insert(list, v)
|
||||
table.insert(list, w)
|
||||
end
|
||||
end
|
||||
|
||||
local function readKeys(r: Bytes.Reader, nodeIndex: number)
|
||||
local flags = r:i32le()
|
||||
local per = 4 + (if bit32.band(flags, 1) ~= 0 then 12 else 0) + (if bit32.band(flags, 2) ~= 0 then 12 else 0) + (if bit32.band(flags, 4) ~= 0 then 16 else 0)
|
||||
local k = nodeKeys[nodeIndex]
|
||||
if not k then
|
||||
k = { t = {}, s = {}, r = {} }
|
||||
nodeKeys[nodeIndex] = k
|
||||
end
|
||||
while not r.err and r.pos + per <= r.limit do
|
||||
local frame = r:i32le()
|
||||
if bit32.band(flags, 1) ~= 0 then
|
||||
k.t[frame] = vec(r)
|
||||
end
|
||||
if bit32.band(flags, 2) ~= 0 then
|
||||
local x, y, z = r:f32le(), r:f32le(), r:f32le()
|
||||
k.s[frame] = { x, y, z }
|
||||
end
|
||||
if bit32.band(flags, 4) ~= 0 then
|
||||
k.r[frame] = quat(r)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function readNode(c: Chunks.Chunk, depth: number): number?
|
||||
if depth > maxDepth then
|
||||
fail("limit: nodes nested deeper than " .. maxDepth, "limit")
|
||||
return nil
|
||||
end
|
||||
local r = body(c)
|
||||
local name = r:cstring()
|
||||
local t = vec(r)
|
||||
local sx, sy, sz = r:f32le(), r:f32le(), r:f32le()
|
||||
local q = quat(r)
|
||||
if r.err then
|
||||
fail("truncated NODE", "truncated")
|
||||
return nil
|
||||
end
|
||||
local node: Types.Node = { name = name, children = {} }
|
||||
if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then
|
||||
node.translation = t
|
||||
end
|
||||
if q[1] ~= 0 or q[2] ~= 0 or q[3] ~= 0 then
|
||||
node.rotation = q
|
||||
end
|
||||
if sx ~= 1 or sy ~= 1 or sz ~= 1 then
|
||||
node.scale = { sx, sy, sz }
|
||||
end
|
||||
table.insert(scene.nodes, node)
|
||||
local index = #scene.nodes
|
||||
for _, sub in Chunks.walk(buf, r.pos, r.limit, LAYOUT) do
|
||||
if failure then
|
||||
break
|
||||
end
|
||||
local id = sub.id
|
||||
if id == "NODE" then
|
||||
local child = readNode(sub, depth + 1)
|
||||
if child then
|
||||
table.insert(node.children, child)
|
||||
end
|
||||
elseif id == "MESH" and not node.mesh then
|
||||
node.mesh = readMesh(body(sub), index)
|
||||
elseif id == "BONE" then
|
||||
readBone(body(sub), index)
|
||||
elseif id == "KEYS" then
|
||||
readKeys(body(sub), index)
|
||||
elseif id == "ANIM" then
|
||||
local ar = body(sub)
|
||||
local flags, frames, fps = ar:i32le(), ar:i32le(), ar:f32le()
|
||||
if not ar.err and not anim then
|
||||
anim = { flags = flags, frames = frames, fps = if fps > 0 and fps < 1e6 then fps else 60 }
|
||||
end
|
||||
end
|
||||
end
|
||||
return index
|
||||
end
|
||||
|
||||
for _, c in Chunks.walk(buf, hr.pos, head.offset + head.size, LAYOUT) do
|
||||
if failure then
|
||||
break
|
||||
end
|
||||
if c.id == "TEXS" then
|
||||
readTexs(body(c))
|
||||
elseif c.id == "BRUS" then
|
||||
readBrus(body(c))
|
||||
elseif c.id == "NODE" then
|
||||
local n = readNode(c, 1)
|
||||
if n then
|
||||
table.insert(scene.roots, n)
|
||||
end
|
||||
end
|
||||
end
|
||||
if failure then
|
||||
return nil, failure, failKind
|
||||
end
|
||||
if #scene.nodes == 0 then
|
||||
return nil, "no NODE chunk", nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ skins
|
||||
local parent: { [number]: number } = {}
|
||||
for i, n in scene.nodes do
|
||||
for _, ch in n.children do
|
||||
parent[ch] = i
|
||||
end
|
||||
end
|
||||
local worldCache: { [number]: { number } } = {}
|
||||
local function world(i: number): { number }
|
||||
local w = worldCache[i]
|
||||
if not w then
|
||||
local n = scene.nodes[i]
|
||||
local l = Mat4.compose(n.translation, n.rotation, n.scale)
|
||||
w = if parent[i] then Mat4.mul(world(parent[i]), l) else l
|
||||
worldCache[i] = w
|
||||
end
|
||||
return w
|
||||
end
|
||||
local bonesOf: { [MeshRec]: { Bone } } = {}
|
||||
for _, b in bones do
|
||||
local m = b.target
|
||||
if m then
|
||||
local l = bonesOf[m] or {}
|
||||
bonesOf[m] = l
|
||||
table.insert(l, b)
|
||||
end
|
||||
end
|
||||
for _, rec in meshes do
|
||||
local list = bonesOf[rec]
|
||||
if list then
|
||||
local nv = rec.count
|
||||
local inf: { { number } } = {}
|
||||
local joints: { number } = {}
|
||||
for j, b in list do
|
||||
joints[j] = b.node
|
||||
local l = b.list
|
||||
for k = 1, #l, 2 do
|
||||
local v, w = l[k], l[k + 1]
|
||||
if v >= 0 and v < nv and w > 0 and w == w then
|
||||
local e = inf[v + 1]
|
||||
if not e then
|
||||
e = {}
|
||||
inf[v + 1] = e
|
||||
end
|
||||
table.insert(e, j - 1)
|
||||
table.insert(e, w)
|
||||
end
|
||||
end
|
||||
end
|
||||
local self: number? = nil -- the mesh node as a joint, for vertices no bone moves
|
||||
local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16)
|
||||
for v = 0, nv - 1 do
|
||||
local e = inf[v + 1]
|
||||
if not e then
|
||||
if not self then
|
||||
table.insert(joints, rec.node)
|
||||
self = #joints - 1
|
||||
end
|
||||
buffer.writeu16(jb, v * 8, self :: number)
|
||||
buffer.writef32(wb, v * 16, 1)
|
||||
else
|
||||
-- the 4 strongest, normalised
|
||||
local order = {}
|
||||
for k = 1, #e, 2 do
|
||||
table.insert(order, k)
|
||||
end
|
||||
table.sort(order, function(a: number, b: number): boolean
|
||||
return e[a + 1] > e[b + 1]
|
||||
end)
|
||||
local sum = 0
|
||||
for k = 1, math.min(4, #order) do
|
||||
sum += e[order[k] + 1]
|
||||
end
|
||||
for k = 1, math.min(4, #order) do
|
||||
buffer.writeu16(jb, v * 8 + (k - 1) * 2, e[order[k]])
|
||||
buffer.writef32(wb, v * 16 + (k - 1) * 4, e[order[k] + 1] / sum)
|
||||
end
|
||||
end
|
||||
end
|
||||
local meshWorld = world(rec.node)
|
||||
local ibm = buffer.create(#joints * 64)
|
||||
for j, ni in joints do
|
||||
local inv = Mat4.inverse(world(ni)) or Mat4.identity()
|
||||
local m = Mat4.mul(inv, meshWorld)
|
||||
for k = 1, 16 do
|
||||
buffer.writef32(ibm, (j - 1) * 64 + (k - 1) * 4, m[k])
|
||||
end
|
||||
end
|
||||
local ia = Types.Scene.accessor(ibm, "f32", 16, #joints)
|
||||
ia.matrix = true
|
||||
table.insert(scene.skins, { joints = joints, inverseBindMatrices = ia })
|
||||
scene.nodes[rec.node].skin = #scene.skins
|
||||
local J, W = Types.Scene.accessor(jb, "u16", 4, nv), Types.Scene.accessor(wb, "f32", 4, nv)
|
||||
for _, prim in scene.meshes[rec.mesh].primitives do
|
||||
prim.attributes.JOINTS_0 = J
|
||||
prim.attributes.WEIGHTS_0 = W
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ animation
|
||||
local fps = if anim then anim.fps else 60
|
||||
local channels: { Types.Channel } = {}
|
||||
for ni = 1, #scene.nodes do
|
||||
local k = nodeKeys[ni]
|
||||
if k then
|
||||
for _, path in { "translation", "rotation", "scale" } do
|
||||
local map = if path == "translation" then k.t elseif path == "rotation" then k.r else k.s
|
||||
local frames = {}
|
||||
for f in map do
|
||||
table.insert(frames, f)
|
||||
end
|
||||
if #frames > 0 then
|
||||
table.sort(frames)
|
||||
local nc = if path == "rotation" then 4 else 3
|
||||
local input, output = buffer.create(#frames * 4), buffer.create(#frames * nc * 4)
|
||||
for i, f in frames do
|
||||
buffer.writef32(input, (i - 1) * 4, f / fps)
|
||||
local v = map[f]
|
||||
for c = 1, nc do
|
||||
buffer.writef32(output, ((i - 1) * nc + c - 1) * 4, v[c])
|
||||
end
|
||||
end
|
||||
table.insert(channels, {
|
||||
node = ni,
|
||||
path = path :: any,
|
||||
input = Types.Scene.accessor(input, "f32", 1, #frames),
|
||||
output = Types.Scene.accessor(output, "f32", nc, #frames),
|
||||
interpolation = "LINEAR" :: "LINEAR",
|
||||
})
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if #channels > 0 then
|
||||
table.insert(scene.animations, { name = "b3d", channels = channels })
|
||||
end
|
||||
|
||||
scene.meta.up = "y"
|
||||
scene.meta.source = {
|
||||
format = "b3d",
|
||||
version = version,
|
||||
brushes = #brushes,
|
||||
frames = if anim then anim.frames else nil,
|
||||
fps = if anim then anim.fps else nil,
|
||||
handedness = "left", -- converted: z mirrored, winding reversed
|
||||
}
|
||||
return scene, nil, nil
|
||||
end
|
||||
|
||||
return Read
|
||||
@@ -0,0 +1,68 @@
|
||||
--!strict
|
||||
-- model/b3d: Blitz3D .b3d (BB3D chunk format, version 1), read. Written from the Blitz3D file format description
|
||||
-- (blitzbasic.com "b3dfile_specs.txt") and checked against assimp's B3D importer.
|
||||
-- Reads: TEXS (texture files -> scene.textures, data through opts.files / opts.resolve, clamp flags -> sampler,
|
||||
-- position / scale / rotation -> the first texture's KHR_texture_transform, flag 65536 = second UV set), BRUS (brushes ->
|
||||
-- materials: colour + alpha, shininess -> roughness, FX 1 = unlit, 16 = double sided, 32 = blend; the first texture is
|
||||
-- baseColorTexture, the others are listed in extras.b3d.textures; texture flags 2 / 4 -> blend / mask), the NODE tree
|
||||
-- (name, position, scale, rotation; MESH -> one Mesh per node: VRTS -> POSITION / NORMAL / COLOR_0 (f32 RGBA) /
|
||||
-- TEXCOORD_0..7 shared by the mesh's primitives, one "triangles" primitive per TRIS chunk with its brush, else the
|
||||
-- mesh's master brush), BONE vertex weights -> a skin on the mesh read last before the bone (the 4 strongest weights
|
||||
-- per vertex, normalised, JOINTS_0 / WEIGHTS_0; vertices no bone moves follow the mesh node, which then joins the
|
||||
-- joints; inverse bind matrices from the bind pose), KEYS (position / scale / rotation keys) + ANIM (frames, fps,
|
||||
-- default 60) -> one animation of LINEAR channels at frame / fps seconds.
|
||||
-- Blitz3D is left-handed and Y up: z is mirrored (positions, normals, translations, keys), the triangle winding
|
||||
-- reversed and the rotations mirrored, so the scene is glTF's right-handed Y up (meta.up = "y"). UVs keep their
|
||||
-- top-left origin (= glTF). meta.source = { format, version, brushes, frames?, fps?, handedness = "left" }.
|
||||
-- Not supported: writing; multiple VRTS chunks in one MESH (the first is used); per-brush blend modes beyond the
|
||||
-- extras; texture coordinate sets of 3 / 4 components keep their first two.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Read = require("@formats/model/b3d/Read")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local B3d = {
|
||||
name = "b3d",
|
||||
category = "model",
|
||||
extensions = { "b3d" },
|
||||
mime = { "model/x-b3d" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/model/Mat4" },
|
||||
caps = { decode = true, encode = false, materials = true, textures = true, skins = true, animation = true, colors = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
resolve: ((uri: string) -> any)?, -- texture files (the api sets it for paths)
|
||||
files: { [string]: any }?, -- or: the files by name
|
||||
maxVertices: number?, -- default 2^24
|
||||
maxDepth: number?, -- node nesting (default 256)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function B3d.sniff(r: Bytes.Reader): number
|
||||
if r:peek(4) == "BB3D" then
|
||||
return if r:peek(4, 8) ~= "" then 1 else 0.8
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function B3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
if r:peek(4) ~= "BB3D" then
|
||||
return nil, Err.new(Err.CORRUPT, "no BB3D chunk")
|
||||
end
|
||||
-- the scene builder is plain (not native) code: a bug there must not escape as an error
|
||||
local ok, scene, msg, kind = pcall(Read.scene, r, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "bad chunk tree: " .. tostring(scene))
|
||||
end
|
||||
if not scene then
|
||||
return nil, Err.from(msg, nil, kind)
|
||||
end
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return B3d
|
||||
@@ -0,0 +1,319 @@
|
||||
--!strict
|
||||
-- model/ldraw/Colors: the LDraw colour table: code -> { name, rgb, edge, alpha, luminance, finish }, parsed from
|
||||
-- !COLOUR lines. The built-in table is the colour list of LDraw.org's LDConfig.ldr (UPDATE 2025-05-20; CC BY 2.0, see
|
||||
-- licenses/LDRAW_COLOURS.txt), one line per colour without the "0 !COLOUR " prefix and with the MATERIAL parameters cut
|
||||
-- after the material's type. Colours are 0xRRGGBB (sRGB); an edge is a colour code or a direct colour 0x2RRGGBB.
|
||||
local Colors = {}
|
||||
|
||||
export type Colour = { name: string, rgb: number, edge: number, alpha: number, luminance: number, finish: string? }
|
||||
export type Table = { [number]: Colour }
|
||||
|
||||
local FINISHES = { CHROME = true, PEARLESCENT = true, RUBBER = true, MATTE_METALLIC = true, METAL = true }
|
||||
|
||||
-- entry(rest) -> code, Colour | nil: one "Name CODE n VALUE #RRGGBB EDGE #RRGGBB|code [ALPHA a] [LUMINANCE l] ..."
|
||||
function Colors.entry(rest: string): (number?, Colour?)
|
||||
local words: { string } = {}
|
||||
for w in string.gmatch(rest, "%S+") do
|
||||
table.insert(words, w)
|
||||
end
|
||||
local name = words[1]
|
||||
local code, rgb, edge: number?, alpha, lum, finish = nil, nil, nil, 255, 0, nil
|
||||
local i = 2
|
||||
while i <= #words do
|
||||
local k, v = words[i], words[i + 1]
|
||||
if k == "CODE" and v then
|
||||
code = tonumber(v)
|
||||
i += 1
|
||||
elseif k == "VALUE" and v and rgb == nil then
|
||||
rgb = tonumber(string.match(v, "^#(%x%x%x%x%x%x)$") or "", 16)
|
||||
i += 1
|
||||
elseif k == "EDGE" and v then
|
||||
local hex = string.match(v, "^#(%x%x%x%x%x%x)$")
|
||||
edge = if hex then 0x2000000 + (tonumber(hex, 16) :: number) else tonumber(v)
|
||||
i += 1
|
||||
elseif k == "ALPHA" and v then
|
||||
alpha = math.clamp(tonumber(v) or 255, 0, 255)
|
||||
i += 1
|
||||
elseif k == "LUMINANCE" and v then
|
||||
lum = math.clamp(tonumber(v) or 0, 0, 255)
|
||||
i += 1
|
||||
elseif FINISHES[k] then
|
||||
finish = k
|
||||
elseif k == "MATERIAL" and v then
|
||||
finish = v
|
||||
break
|
||||
end
|
||||
i += 1
|
||||
end
|
||||
if not name or not code or not rgb or code % 1 ~= 0 then
|
||||
return nil, nil
|
||||
end
|
||||
return code, { name = name, rgb = rgb :: number, edge = edge or 0x2333333, alpha = alpha, luminance = lum, finish = finish }
|
||||
end
|
||||
|
||||
-- parse(text, into?) -> into (a new table by default) with every "0 !COLOUR" line of text added
|
||||
function Colors.parse(text: string, into: Table?): Table
|
||||
local t: Table = into or {}
|
||||
for line in string.gmatch(text, "[^\n]+") do
|
||||
local rest = string.match(line, "^%s*0%s+!COLOUR%s+(.-)%s*$")
|
||||
if rest then
|
||||
local code, c = Colors.entry(rest)
|
||||
if code and c then
|
||||
t[code] = c
|
||||
end
|
||||
end
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
local BUILTIN = [[
|
||||
Black CODE 0 VALUE #1B2A34 EDGE #808080
|
||||
Blue CODE 1 VALUE #1E5AA8 EDGE #333333
|
||||
Green CODE 2 VALUE #00852B EDGE #333333
|
||||
Dark_Turquoise CODE 3 VALUE #069D9F EDGE #333333
|
||||
Red CODE 4 VALUE #B40000 EDGE #333333
|
||||
Dark_Pink CODE 5 VALUE #D3359D EDGE #333333
|
||||
Brown CODE 6 VALUE #543324 EDGE #1E1E1E
|
||||
Light_Grey CODE 7 VALUE #8A928D EDGE #333333
|
||||
Dark_Grey CODE 8 VALUE #545955 EDGE #333333
|
||||
Light_Blue CODE 9 VALUE #97CBD9 EDGE #333333
|
||||
Bright_Green CODE 10 VALUE #58AB41 EDGE #333333
|
||||
Light_Turquoise CODE 11 VALUE #00AAA4 EDGE #333333
|
||||
Salmon CODE 12 VALUE #F06D61 EDGE #333333
|
||||
Pink CODE 13 VALUE #F6A9BB EDGE #333333
|
||||
Yellow CODE 14 VALUE #FAC80A EDGE #333333
|
||||
White CODE 15 VALUE #F4F4F4 EDGE #333333
|
||||
Light_Green CODE 17 VALUE #ADD9A8 EDGE #333333
|
||||
Light_Yellow CODE 18 VALUE #FFD67F EDGE #333333
|
||||
Tan CODE 19 VALUE #D7BA8C EDGE #333333
|
||||
Light_Violet CODE 20 VALUE #AFBED6 EDGE #333333
|
||||
Purple CODE 22 VALUE #671F81 EDGE #333333
|
||||
Dark_Blue_Violet CODE 23 VALUE #0E3E9A EDGE #333333
|
||||
Orange CODE 25 VALUE #D67923 EDGE #333333
|
||||
Magenta CODE 26 VALUE #901F76 EDGE #333333
|
||||
Lime CODE 27 VALUE #A5CA18 EDGE #333333
|
||||
Dark_Tan CODE 28 VALUE #897D62 EDGE #333333
|
||||
Bright_Pink CODE 29 VALUE #FF9ECD EDGE #333333
|
||||
Medium_Lavender CODE 30 VALUE #A06EB9 EDGE #333333
|
||||
Lavender CODE 31 VALUE #CDA4DE EDGE #333333
|
||||
Very_Light_Orange CODE 68 VALUE #FDC383 EDGE #333333
|
||||
Bright_Reddish_Lilac CODE 69 VALUE #8A12A8 EDGE #333333
|
||||
Reddish_Brown CODE 70 VALUE #5F3109 EDGE #808080
|
||||
Light_Bluish_Grey CODE 71 VALUE #969696 EDGE #333333
|
||||
Dark_Bluish_Grey CODE 72 VALUE #646464 EDGE #333333
|
||||
Medium_Blue CODE 73 VALUE #7396C8 EDGE #333333
|
||||
Medium_Green CODE 74 VALUE #7FC475 EDGE #333333
|
||||
Light_Pink CODE 77 VALUE #FECCCF EDGE #333333
|
||||
Light_Nougat CODE 78 VALUE #FFC995 EDGE #333333
|
||||
Medium_Nougat CODE 84 VALUE #AA7D55 EDGE #333333
|
||||
Medium_Lilac CODE 85 VALUE #441A91 EDGE #333333
|
||||
Light_Brown CODE 86 VALUE #7B5D41 EDGE #333333
|
||||
Blue_Violet CODE 89 VALUE #1C58A7 EDGE #333333
|
||||
Nougat CODE 92 VALUE #BB805A EDGE #333333
|
||||
Light_Salmon CODE 100 VALUE #F9B7A5 EDGE #333333
|
||||
Violet CODE 110 VALUE #26469A EDGE #333333
|
||||
Medium_Violet CODE 112 VALUE #4861AC EDGE #333333
|
||||
Medium_Lime CODE 115 VALUE #B7D425 EDGE #333333
|
||||
Aqua CODE 118 VALUE #9CD6CC EDGE #333333
|
||||
Light_Lime CODE 120 VALUE #DEEA92 EDGE #333333
|
||||
Light_Orange CODE 125 VALUE #F9A777 EDGE #333333
|
||||
Dark_Nougat CODE 128 VALUE #AD6140 EDGE #333333
|
||||
Very_Light_Bluish_Grey CODE 151 VALUE #C8C8C8 EDGE #333333
|
||||
Bright_Light_Orange CODE 191 VALUE #FCAC00 EDGE #333333
|
||||
Bright_Light_Blue CODE 212 VALUE #9DC3F7 EDGE #333333
|
||||
Rust CODE 216 VALUE #872B17 EDGE #333333
|
||||
Reddish_Lilac CODE 218 VALUE #8E5597 EDGE #333333
|
||||
Lilac CODE 219 VALUE #564E9D EDGE #333333
|
||||
Bright_Light_Yellow CODE 226 VALUE #FFEC6C EDGE #333333
|
||||
Sky_Blue CODE 232 VALUE #77C9D8 EDGE #333333
|
||||
Dark_Blue CODE 272 VALUE #19325A EDGE #333333
|
||||
Dark_Green CODE 288 VALUE #00451A EDGE #808080
|
||||
Flamingo_Pink CODE 295 VALUE #FF94C2 EDGE #333333
|
||||
Dark_Brown CODE 308 VALUE #352100 EDGE #808080
|
||||
Maersk_Blue CODE 313 VALUE #ABD9FF EDGE #333333
|
||||
Dark_Red CODE 320 VALUE #720012 EDGE #333333
|
||||
Dark_Azure CODE 321 VALUE #469BC3 EDGE #333333
|
||||
Medium_Azure CODE 322 VALUE #68C3E2 EDGE #333333
|
||||
Light_Aqua CODE 323 VALUE #D3F2EA EDGE #333333
|
||||
Yellowish_Green CODE 326 VALUE #E2F99A EDGE #333333
|
||||
Olive_Green CODE 330 VALUE #77774E EDGE #333333
|
||||
Sand_Red CODE 335 VALUE #88605E EDGE #333333
|
||||
Medium_Dark_Pink CODE 351 VALUE #F785B1 EDGE #333333
|
||||
Coral CODE 353 VALUE #FF6D77 EDGE #333333
|
||||
Earth_Orange CODE 366 VALUE #D86D2C EDGE #333333
|
||||
Neon_Yellow CODE 368 VALUE #EDFF21 EDGE #333333
|
||||
Medium_Brown CODE 370 VALUE #755945 EDGE #333333
|
||||
Medium_Tan CODE 371 VALUE #CCA373 EDGE #333333
|
||||
Sand_Purple CODE 373 VALUE #75657D EDGE #333333
|
||||
Sand_Green CODE 378 VALUE #708E7C EDGE #333333
|
||||
Sand_Blue CODE 379 VALUE #70819A EDGE #333333
|
||||
Reddish_Orange CODE 402 VALUE #CA4C0B EDGE #333333
|
||||
Sienna_Brown CODE 422 VALUE #915C3C EDGE #333333
|
||||
Umber_Brown CODE 423 VALUE #543F33 EDGE #333333
|
||||
Fabuland_Brown CODE 450 VALUE #D27744 EDGE #333333
|
||||
Medium_Orange CODE 462 VALUE #F58624 EDGE #333333
|
||||
Dark_Orange CODE 484 VALUE #91501C EDGE #333333
|
||||
Very_Light_Grey CODE 503 VALUE #BCB4A5 EDGE #333333
|
||||
Light_Orange_Brown CODE 507 VALUE #FA9C1C EDGE #333333
|
||||
Fabuland_Red CODE 508 VALUE #C65127 EDGE #333333
|
||||
Fabuland_Orange CODE 509 VALUE #CF8A47 EDGE #333333
|
||||
Fabuland_Lime CODE 510 VALUE #78FC78 EDGE #333333
|
||||
Trans_Dark_Blue CODE 33 VALUE #0020A0 EDGE #000B38 ALPHA 128
|
||||
Trans_Green CODE 34 VALUE #237841 EDGE #174F2B ALPHA 128
|
||||
Trans_Bright_Green CODE 35 VALUE #56E646 EDGE #27AF18 ALPHA 128
|
||||
Trans_Red CODE 36 VALUE #C91A09 EDGE #660D05 ALPHA 128
|
||||
Trans_Dark_Pink CODE 37 VALUE #DF6695 EDGE #B9275F ALPHA 128
|
||||
Trans_Neon_Orange CODE 38 VALUE #FF800D EDGE #A85100 ALPHA 128
|
||||
Trans_Very_Light_Blue CODE 39 VALUE #C1DFF0 EDGE #6FB4DC ALPHA 128
|
||||
Trans_Brown CODE 40 VALUE #635F52 EDGE #2A2823 ALPHA 128
|
||||
Trans_Medium_Blue CODE 41 VALUE #559AB7 EDGE #326276 ALPHA 128
|
||||
Trans_Neon_Green CODE 42 VALUE #C0FF00 EDGE #739900 ALPHA 128
|
||||
Trans_Light_Blue CODE 43 VALUE #AEE9EF EDGE #59D1DE ALPHA 128
|
||||
Trans_Bright_Reddish_Lilac CODE 44 VALUE #96709F EDGE #5F4365 ALPHA 128
|
||||
Trans_Pink CODE 45 VALUE #FC97AC EDGE #F9345B ALPHA 128
|
||||
Trans_Yellow CODE 46 VALUE #F5CD2F EDGE #B49208 ALPHA 128
|
||||
Trans_Clear CODE 47 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 128
|
||||
Trans_Purple CODE 52 VALUE #A5A5CB EDGE #6464A6 ALPHA 128
|
||||
Trans_Neon_Yellow CODE 54 VALUE #DAB000 EDGE #755E00 ALPHA 128
|
||||
Trans_Orange CODE 57 VALUE #F08F1C EDGE #9E5C0A ALPHA 128
|
||||
Trans_Black_IR_Lens CODE 32 VALUE #000000 EDGE #333333 ALPHA 210
|
||||
Trans_Neon_Red CODE 158 VALUE #F18EBB EDGE #E63384 ALPHA 128
|
||||
Trans_Bright_Light_Green CODE 227 VALUE #B5D96C EDGE #86B22E ALPHA 128
|
||||
Trans_Bright_Light_Orange CODE 231 VALUE #FCB76D EDGE #FA860A ALPHA 128
|
||||
Trans_Fire_Yellow CODE 234 VALUE #FBE890 EDGE #F7D22B ALPHA 128
|
||||
Trans_Reddish_Lilac CODE 284 VALUE #C281A5 EDGE #944771 ALPHA 128
|
||||
Trans_Light_Green CODE 285 VALUE #7DC291 EDGE #46955D ALPHA 128
|
||||
Trans_Light_Blue_Violet CODE 293 VALUE #6BABE4 EDGE #247BC6 ALPHA 128
|
||||
Trans_Black CODE 10375 VALUE #212121 EDGE #545454 ALPHA 128
|
||||
Chrome_Antique_Brass CODE 60 VALUE #645A4C EDGE #665B4D CHROME
|
||||
Chrome_Blue CODE 61 VALUE #6C96BF EDGE #3D638A CHROME
|
||||
Chrome_Green CODE 62 VALUE #3CB371 EDGE #226741 CHROME
|
||||
Chrome_Pink CODE 63 VALUE #AA4D8E EDGE #632C52 CHROME
|
||||
Chrome_Black CODE 64 VALUE #1B2A34 EDGE #3D5F76 CHROME
|
||||
Chrome_Gold CODE 334 VALUE #DFC176 EDGE #C2982E CHROME
|
||||
Chrome_Silver CODE 383 VALUE #CECECE EDGE #9C9C9C CHROME
|
||||
Pearl_Black CODE 83 VALUE #0A1327 EDGE #333333 PEARLESCENT
|
||||
Copper CODE 134 VALUE #764D3B EDGE #333333 PEARLESCENT
|
||||
Pearl_Light_Grey CODE 135 VALUE #A0A0A0 EDGE #333333 PEARLESCENT
|
||||
Metallic_Blue CODE 137 VALUE #5B7590 EDGE #333333 PEARLESCENT
|
||||
Pearl_Light_Gold CODE 142 VALUE #DEAC66 EDGE #333333 PEARLESCENT
|
||||
Pearl_Dark_Gold CODE 147 VALUE #83724F EDGE #333333 PEARLESCENT
|
||||
Pearl_Dark_Grey CODE 148 VALUE #484D48 EDGE #333333 PEARLESCENT
|
||||
Pearl_Very_Light_Grey CODE 150 VALUE #989B99 EDGE #333333 PEARLESCENT
|
||||
Pearl_Red CODE 176 VALUE #945148 EDGE #333333 PEARLESCENT
|
||||
Pearl_Yellow CODE 178 VALUE #AB673A EDGE #333333 PEARLESCENT
|
||||
Pearl_Silver CODE 179 VALUE #898788 EDGE #333333 PEARLESCENT
|
||||
Pearl_White CODE 183 VALUE #F6F2DF EDGE #333333 PEARLESCENT
|
||||
Metallic_Bright_Red CODE 184 VALUE #D60026 EDGE #333333 PEARLESCENT
|
||||
Metallic_Bright_Blue CODE 185 VALUE #0059A3 EDGE #333333 PEARLESCENT
|
||||
Metallic_Dark_Green CODE 186 VALUE #008E3C EDGE #333333 PEARLESCENT
|
||||
Pearl_Brown CODE 187 VALUE #57392C EDGE #333333 PEARLESCENT
|
||||
Reddish_Gold CODE 189 VALUE #AC8247 EDGE #333333 PEARLESCENT
|
||||
Lemon_Metallic CODE 200 VALUE #708224 EDGE #333333 PEARLESCENT
|
||||
Pearl_Gold CODE 297 VALUE #AA7F2E EDGE #333333 PEARLESCENT
|
||||
Metallic_Silver CODE 80 VALUE #767676 EDGE #333333 METAL
|
||||
Metallic_Green CODE 81 VALUE #C2C06F EDGE #333333 METAL
|
||||
Metallic_Gold CODE 82 VALUE #DBAC34 EDGE #333333 METAL
|
||||
Metallic_Dark_Grey CODE 87 VALUE #3E3C39 EDGE #333333 METAL
|
||||
Metallic_Copper CODE 300 VALUE #C27F53 EDGE #333333 METAL
|
||||
Metallic_Light_Blue CODE 10045 VALUE #97CBD9 EDGE #333333 METAL
|
||||
Metallic_Pink CODE 10046 VALUE #AD659A EDGE #333333 METAL
|
||||
Metallic_Light_Pink CODE 10049 VALUE #FECCCF EDGE #333333 METAL
|
||||
Milky_White CODE 79 VALUE #EEEEEE EDGE #BABABA ALPHA 240
|
||||
Glow_In_Dark_Opaque CODE 21 VALUE #E0FFB0 EDGE #B8FF4D ALPHA 240 LUMINANCE 15
|
||||
Glow_In_Dark_Trans CODE 294 VALUE #BDC6AD EDGE #8D9D72 ALPHA 240 LUMINANCE 15
|
||||
Glow_In_Dark_White CODE 329 VALUE #F5F3D7 EDGE #E0DA85 ALPHA 240 LUMINANCE 15
|
||||
Glitter_Trans_Dark_Pink CODE 114 VALUE #DF6695 EDGE #B9275F ALPHA 128 MATERIAL GLITTER
|
||||
Glitter_Trans_Clear CODE 117 VALUE #EEEEEE EDGE #BABABA ALPHA 128 MATERIAL GLITTER
|
||||
Glitter_Trans_Purple CODE 129 VALUE #640061 EDGE #000000 ALPHA 128 MATERIAL GLITTER
|
||||
Glitter_Trans_Light_Blue CODE 302 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 MATERIAL GLITTER
|
||||
Glitter_Trans_Neon_Green CODE 339 VALUE #C0FF00 EDGE #739900 ALPHA 128 MATERIAL GLITTER
|
||||
Glitter_Trans_Orange CODE 341 VALUE #F08F1C EDGE #9E5C0A ALPHA 128 MATERIAL GLITTER
|
||||
Opal_Trans_Clear CODE 360 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 240 LUMINANCE 5 MATERIAL GLITTER
|
||||
Opal_Trans_Light_Blue CODE 362 VALUE #AEE9EF EDGE #59D1DE ALPHA 200 LUMINANCE 5 MATERIAL GLITTER
|
||||
Opal_Trans_Black CODE 363 VALUE #635F52 EDGE #2A2823 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER
|
||||
Opal_Trans_Dark_Pink CODE 364 VALUE #DF6695 EDGE #B9275F ALPHA 200 LUMINANCE 5 MATERIAL GLITTER
|
||||
Opal_Trans_Purple CODE 365 VALUE #671F81 EDGE #441456 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER
|
||||
Opal_Trans_Green CODE 367 VALUE #237841 EDGE #174F2B ALPHA 200 LUMINANCE 5 MATERIAL GLITTER
|
||||
Glitter_Trans_Bright_Green CODE 10351 VALUE #56E646 EDGE #27AF18 ALPHA 128 MATERIAL GLITTER
|
||||
Opal_Trans_Dark_Blue CODE 10366 VALUE #0020A0 EDGE #000B38 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER
|
||||
Speckle_Black_Copper CODE 75 VALUE #000000 EDGE #AB6038 MATERIAL SPECKLE
|
||||
Speckle_Dark_Bluish_Grey_Silver CODE 76 VALUE #635F61 EDGE #898788 MATERIAL SPECKLE
|
||||
Speckle_Black_Silver CODE 132 VALUE #000000 EDGE #898788 MATERIAL SPECKLE
|
||||
Speckle_Black_Gold CODE 133 VALUE #000000 EDGE #DBAC34 MATERIAL SPECKLE
|
||||
Rubber_Yellow CODE 65 VALUE #FAC80A EDGE #333333 RUBBER
|
||||
Rubber_Black CODE 256 VALUE #1B2A34 EDGE #808080 RUBBER
|
||||
Rubber_Blue CODE 273 VALUE #1E5AA8 EDGE #333333 RUBBER
|
||||
Rubber_Red CODE 324 VALUE #B40000 EDGE #333333 RUBBER
|
||||
Rubber_Orange CODE 350 VALUE #D67923 EDGE #333333 RUBBER
|
||||
Rubber_Light_Grey CODE 375 VALUE #8A928D EDGE #333333 RUBBER
|
||||
Rubber_Dark_Blue CODE 406 VALUE #19325A EDGE #333333 RUBBER
|
||||
Rubber_Purple CODE 449 VALUE #671F81 EDGE #333333 RUBBER
|
||||
Rubber_Lime CODE 490 VALUE #A5CA18 EDGE #333333 RUBBER
|
||||
Rubber_Light_Bluish_Grey CODE 496 VALUE #969696 EDGE #333333 RUBBER
|
||||
Rubber_Flat_Silver CODE 504 VALUE #898788 EDGE #333333 RUBBER
|
||||
Rubber_White CODE 511 VALUE #F4F4F4 EDGE #333333 RUBBER
|
||||
Rubber_Green CODE 10002 VALUE #00852B EDGE #333333 RUBBER
|
||||
Rubber_Bright_Green CODE 10010 VALUE #58AB41 EDGE #333333 RUBBER
|
||||
Rubber_Tan CODE 10019 VALUE #D7BA8C EDGE #333333 RUBBER
|
||||
Rubber_Magenta CODE 10026 VALUE #901F76 EDGE #333333 RUBBER
|
||||
Rubber_Bright_Pink CODE 10029 VALUE #FF9ECD EDGE #333333 RUBBER
|
||||
Rubber_Medium_Lavender CODE 10030 VALUE #A06EB9 EDGE #333333 RUBBER
|
||||
Rubber_Lavender CODE 10031 VALUE #CDA4DE EDGE #333333 RUBBER
|
||||
Rubber_Reddish_Brown CODE 10070 VALUE #5F3109 EDGE #808080 RUBBER
|
||||
Rubber_Dark_Bluish_Grey CODE 10072 VALUE #646464 EDGE #333333 RUBBER
|
||||
Rubber_Medium_Blue CODE 10073 VALUE #7396C8 EDGE #333333 RUBBER
|
||||
Rubber_Light_Nougat CODE 10078 VALUE #FFC995 EDGE #333333 RUBBER
|
||||
Rubber_Bright_Light_Yellow CODE 10226 VALUE #FFEC6C EDGE #333333 RUBBER
|
||||
Rubber_Dark_Brown CODE 10308 VALUE #352100 EDGE #808080 RUBBER
|
||||
Rubber_Dark_Red CODE 10320 VALUE #720012 EDGE #333333 RUBBER
|
||||
Rubber_Dark_Azure CODE 10321 VALUE #469BC3 EDGE #333333 RUBBER
|
||||
Rubber_Medium_Azure CODE 10322 VALUE #68C3E2 EDGE #333333 RUBBER
|
||||
Rubber_Light_Aqua CODE 10323 VALUE #D3F2EA EDGE #333333 RUBBER
|
||||
Rubber_Sand_Green CODE 10378 VALUE #708E7C EDGE #333333 RUBBER
|
||||
Rubber_Dark_Orange CODE 10484 VALUE #91501C EDGE #333333 RUBBER
|
||||
Rubber_Trans_Yellow CODE 66 VALUE #F5CD2F EDGE #B49208 ALPHA 128 RUBBER
|
||||
Rubber_Trans_Clear CODE 67 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 128 RUBBER
|
||||
Rubber_Trans_Bright_Green CODE 10035 VALUE #56E646 EDGE #27AF18 ALPHA 128 RUBBER
|
||||
Rubber_Trans_Red CODE 10036 VALUE #C91A09 EDGE #660D05 ALPHA 128 RUBBER
|
||||
Rubber_Trans_Light_Blue CODE 10043 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 RUBBER
|
||||
Canvas_Black CODE 20000 VALUE #1B2A34 EDGE #808080 MATERIAL FABRIC
|
||||
Canvas_Blue CODE 20001 VALUE #1E5AA8 EDGE #333333 MATERIAL FABRIC
|
||||
Canvas_Green CODE 20002 VALUE #00852B EDGE #333333 MATERIAL FABRIC
|
||||
Canvas_Red CODE 20004 VALUE #B40000 EDGE #333333 MATERIAL FABRIC
|
||||
Canvas_Bright_Green CODE 20010 VALUE #58AB41 EDGE #333333 MATERIAL FABRIC
|
||||
Canvas_Yellow CODE 20014 VALUE #FAC80A EDGE #333333 MATERIAL FABRIC
|
||||
Canvas_White CODE 20015 VALUE #F4F4F4 EDGE #333333 MATERIAL FABRIC
|
||||
Canvas_Reddish_Brown CODE 20070 VALUE #5F3109 EDGE #808080 MATERIAL FABRIC
|
||||
Canvas_Light_Brown CODE 20086 VALUE #7B5D41 EDGE #333333 MATERIAL FABRIC
|
||||
Canvas_Dark_Green CODE 20288 VALUE #00451A EDGE #808080 MATERIAL FABRIC
|
||||
Canvas_Cream CODE 20500 VALUE #F8F3E4 EDGE #333333 MATERIAL FABRIC
|
||||
Main_Colour CODE 16 VALUE #FFFF80 EDGE #333333
|
||||
Edge_Colour CODE 24 VALUE #7F7F7F EDGE #333333
|
||||
Magnet CODE 493 VALUE #656761 EDGE #333333 METAL
|
||||
Electric_Contact_Alloy CODE 494 VALUE #D0D0D0 EDGE #333333 METAL
|
||||
Electric_Contact_Copper CODE 495 VALUE #AE7A59 EDGE #333333 METAL
|
||||
Trans_Sticker CODE 10047 VALUE #FFFFFF EDGE #FFFFFF ALPHA 16
|
||||
]]
|
||||
|
||||
local cache: Table? = nil
|
||||
-- builtin() -> a fresh copy of the LDConfig.ldr table (callers may add to it)
|
||||
function Colors.builtin(): Table
|
||||
if not cache then
|
||||
local t: Table = {}
|
||||
for line in string.gmatch(BUILTIN, "[^\n]+") do
|
||||
local code, c = Colors.entry(line)
|
||||
if code and c then
|
||||
t[code] = c
|
||||
end
|
||||
end
|
||||
cache = t
|
||||
end
|
||||
local copy: Table = {}
|
||||
for k, v in cache :: Table do
|
||||
copy[k] = v
|
||||
end
|
||||
return copy
|
||||
end
|
||||
|
||||
return Colors
|
||||
@@ -0,0 +1,580 @@
|
||||
--!strict
|
||||
-- model/ldraw/Read: LDraw text -> Types.Scene (see model/ldraw for the mapping). Files are parsed once into command
|
||||
-- lists (MPD sections, then sub-files through opts.files / opts.resolve with the library paths); parts are baked into
|
||||
-- one mesh per (part, colour, inversion), with the BFC rules applied inside the part; model files become nodes.
|
||||
-- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from).
|
||||
local Types = require("@formats/Types")
|
||||
local Colors = require("@formats/model/ldraw/Colors")
|
||||
|
||||
local Read = {}
|
||||
|
||||
export type Options = {
|
||||
resolve: ((uri: string) -> any)?,
|
||||
files: { [string]: any }?,
|
||||
ldconfig: string?,
|
||||
color: number?,
|
||||
upright: boolean?,
|
||||
flatten: boolean?,
|
||||
lines: boolean?,
|
||||
optionalLines: boolean?,
|
||||
maxDepth: number?,
|
||||
maxTriangles: number?,
|
||||
maxNodes: number?,
|
||||
}
|
||||
|
||||
-- a parsed line: k = 0 (a BFC state change: cw / clip), 1 (a reference: v = x y z a b c d e f g h i), 2..5
|
||||
type Cmd = { k: number, c: number, v: { number }, name: string?, inv: boolean?, step: number?, cw: boolean?, clip: boolean? }
|
||||
type File = {
|
||||
name: string,
|
||||
key: string,
|
||||
cmds: { Cmd },
|
||||
certified: boolean,
|
||||
org: string?,
|
||||
refs: number,
|
||||
library: boolean,
|
||||
main: boolean,
|
||||
title: string?,
|
||||
author: string?,
|
||||
model: boolean?,
|
||||
}
|
||||
type Group = { mode: string, colour: number, ds: boolean, pos: { number }, ctrl: { number }? }
|
||||
|
||||
local PREFIXES = { "", "parts/", "p/", "parts/s/", "models/" }
|
||||
local LIBRARY = { ["parts/"] = true, ["p/"] = true, ["parts/s/"] = true }
|
||||
local FLIP = { 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1 }
|
||||
local IDENTITY12 = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 }
|
||||
|
||||
local function norm(name: string): string
|
||||
return string.lower((string.gsub(string.match(name, "^%s*(.-)%s*$") or name, "\\", "/")))
|
||||
end
|
||||
|
||||
local function srgbToLinear(v: number): number
|
||||
return if v <= 0.04045 then v / 12.92 else ((v + 0.055) / 1.055) ^ 2.4
|
||||
end
|
||||
|
||||
-- parse(text, name) -> File (colour definitions go into colours as they are met)
|
||||
local function parse(text: string, name: string, colours: Colors.Table, stats: { bad: number, lines: number }): File
|
||||
local f: File = { name = name, key = norm(name), cmds = {}, certified = false, refs = 0, library = false, main = false }
|
||||
local cmds = f.cmds
|
||||
local invert, step, first = false, 1, true
|
||||
for line in string.gmatch(text, "[^\n]+") do
|
||||
local t = string.match(line, "^%s*(%d)%s")
|
||||
if t then
|
||||
stats.lines += 1
|
||||
end
|
||||
if t == "0" then
|
||||
local w1, rest = string.match(line, "^%s*0%s+(%S+)%s*(.-)%s*$")
|
||||
if w1 == "BFC" and rest then
|
||||
local u = string.upper(rest)
|
||||
local cmd: Cmd? = nil
|
||||
for word in string.gmatch(u, "%S+") do
|
||||
if word == "CERTIFY" then
|
||||
f.certified = true
|
||||
elseif word == "NOCERTIFY" then
|
||||
f.certified = false
|
||||
elseif word == "INVERTNEXT" then
|
||||
invert = true
|
||||
elseif word == "CW" or word == "CCW" or word == "CLIP" or word == "NOCLIP" then
|
||||
local c: Cmd = cmd or { k = 0, c = 0, v = IDENTITY12 }
|
||||
cmd = c
|
||||
if word == "CW" or word == "CCW" then
|
||||
c.cw = word == "CW"
|
||||
else
|
||||
c.clip = word == "CLIP"
|
||||
end
|
||||
end
|
||||
end
|
||||
if cmd then
|
||||
table.insert(cmds, cmd)
|
||||
end
|
||||
elseif w1 == "!COLOUR" then
|
||||
Colors.parse(line, colours)
|
||||
elseif w1 == "!LDRAW_ORG" and rest then
|
||||
f.org = string.match(rest, "^(%S+)")
|
||||
elseif w1 == "STEP" then
|
||||
step += 1
|
||||
elseif w1 == "Author:" then
|
||||
f.author = rest
|
||||
elseif w1 == "Name:" or w1 == "FILE" or w1 == "NOFILE" or w1 == "!HISTORY" or w1 == "!LICENSE" then
|
||||
-- (headers)
|
||||
elseif first and w1 and string.sub(w1, 1, 1) ~= "!" and w1 ~= "//" then
|
||||
f.title = (string.match(line, "^%s*0%s+(.-)%s*$"))
|
||||
end
|
||||
first = false
|
||||
elseif t then
|
||||
first = false
|
||||
local k = tonumber(t) :: number
|
||||
local inv = invert
|
||||
invert = false
|
||||
if k == 1 then
|
||||
local c, x, y, z, a, b, cc, d, e, ff, g, h, i, file = string.match(line, "^%s*1%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(.-)%s*$")
|
||||
local v = { tonumber(a), tonumber(b), tonumber(cc), tonumber(x), tonumber(d), tonumber(e), tonumber(ff), tonumber(y), tonumber(g), tonumber(h), tonumber(i), tonumber(z) }
|
||||
local code = tonumber(c)
|
||||
local complete = true
|
||||
for j = 1, 12 do
|
||||
if v[j] == nil then
|
||||
complete = false
|
||||
end
|
||||
end
|
||||
if file and file ~= "" and complete and code and code >= 0 and code % 1 == 0 then
|
||||
table.insert(cmds, { k = 1, c = code, v = v :: { number }, name = file, inv = inv, step = step })
|
||||
f.refs += 1
|
||||
else
|
||||
stats.bad += 1
|
||||
end
|
||||
elseif k >= 2 and k <= 5 then
|
||||
local need = if k == 2 then 6 elseif k == 3 then 9 else 12
|
||||
local v: { number } = {}
|
||||
local code: number? = nil
|
||||
local n = 0
|
||||
for w in string.gmatch(line, "%S+") do
|
||||
n += 1
|
||||
if n == 2 then
|
||||
code = tonumber(w)
|
||||
elseif n > 2 and n <= need + 2 then
|
||||
local num = tonumber(w)
|
||||
if not num then
|
||||
break
|
||||
end
|
||||
v[n - 2] = num
|
||||
end
|
||||
end
|
||||
if code and code >= 0 and code % 1 == 0 and #v == need then
|
||||
table.insert(cmds, { k = k, c = code, v = v })
|
||||
else
|
||||
stats.bad += 1
|
||||
end
|
||||
elseif k ~= 0 then
|
||||
stats.bad += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
return f
|
||||
end
|
||||
|
||||
-- scene(text, opts) -> Scene | nil, message, kind
|
||||
function Read.scene(text: string, opts: Options?): (Types.Scene?, string?, string?)
|
||||
local o: Options = opts or {}
|
||||
local colours = Colors.builtin()
|
||||
if type(o.ldconfig) == "string" then
|
||||
Colors.parse(o.ldconfig, colours)
|
||||
end
|
||||
local maxDepth = o.maxDepth or 64
|
||||
local maxTriangles = o.maxTriangles or 2 ^ 24
|
||||
local maxNodes = o.maxNodes or 2 ^ 20
|
||||
local withLines = o.lines ~= false
|
||||
local withOptional = o.optionalLines == true
|
||||
local stats = { bad = 0, lines = 0 }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ MPD sections
|
||||
text = string.gsub(text, "\r", "")
|
||||
local sections: { [string]: string } = {}
|
||||
local mainName: string? = nil
|
||||
local mpd = string.find(text, "^%s*0%s+FILE%s") ~= nil or string.find(text, "\n%s*0%s+FILE%s") ~= nil
|
||||
local mainText = text
|
||||
if mpd then
|
||||
local cur: string? = nil
|
||||
local buf: { string } = {}
|
||||
local function close()
|
||||
if cur and sections[cur] == nil then
|
||||
sections[cur] = table.concat(buf, "\n")
|
||||
end
|
||||
cur, buf = nil, {}
|
||||
end
|
||||
for line in string.gmatch(text, "[^\n]+") do
|
||||
local fname = string.match(line, "^%s*0%s+FILE%s+(.-)%s*$")
|
||||
if fname then
|
||||
close()
|
||||
cur = norm(fname)
|
||||
if not mainName then
|
||||
mainName = fname
|
||||
end
|
||||
elseif string.find(line, "^%s*0%s+NOFILE%f[%W]") then
|
||||
close()
|
||||
elseif cur then
|
||||
table.insert(buf, line)
|
||||
end
|
||||
end
|
||||
close()
|
||||
mainText = sections[norm(mainName or "")] or ""
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ files
|
||||
local cache: { [string]: File | false } = {}
|
||||
local missing: { [string]: boolean } = {}
|
||||
local fetchFiles = o.files
|
||||
local resolve = o.resolve
|
||||
local function fetch(uri: string): string?
|
||||
local v: any = if type(fetchFiles) == "table" then fetchFiles[uri] else nil
|
||||
if v == nil and type(resolve) == "function" then
|
||||
local ok, res = pcall(resolve, uri)
|
||||
v = if ok then res else nil
|
||||
end
|
||||
return if type(v) == "buffer" then buffer.tostring(v) elseif type(v) == "string" then v else nil
|
||||
end
|
||||
local function lookup(name: string): File?
|
||||
local key = norm(name)
|
||||
local have = cache[key]
|
||||
if have ~= nil then
|
||||
return have or nil
|
||||
end
|
||||
local sec = sections[key]
|
||||
if sec then
|
||||
local f = parse(sec, name, colours, stats)
|
||||
cache[key] = f
|
||||
return f
|
||||
end
|
||||
local slash = string.gsub(string.match(name, "^%s*(.-)%s*$") or name, "\\", "/")
|
||||
for _, prefix in PREFIXES do
|
||||
for _, cand in { prefix .. slash, prefix .. key } do
|
||||
local data = fetch(cand)
|
||||
if data then
|
||||
local f = parse((string.gsub(data, "\r", "")), name, colours, stats)
|
||||
f.library = LIBRARY[prefix] == true
|
||||
cache[key] = f
|
||||
return f
|
||||
end
|
||||
end
|
||||
end
|
||||
missing[key] = true
|
||||
cache[key] = false
|
||||
return nil
|
||||
end
|
||||
local function isModel(f: File): boolean
|
||||
local m = f.model
|
||||
if m == nil then
|
||||
local org = string.lower(f.org or "")
|
||||
local orgPart = org ~= "" and not string.find(org, "model", 1, true)
|
||||
if f.main then
|
||||
m = not orgPart and f.refs > 0
|
||||
else
|
||||
local ext = string.match(f.key, "%.(%w+)$")
|
||||
m = not orgPart and not f.library and (ext == "ldr" or ext == "mpd")
|
||||
end
|
||||
f.model = m
|
||||
end
|
||||
return m :: boolean
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ colours, materials
|
||||
local scene = Types.Scene.new()
|
||||
local function edgeOf(c: number): number
|
||||
local e = colours[c]
|
||||
if e then
|
||||
return e.edge
|
||||
end
|
||||
return if c >= 0x2000000 then 0x2000000 else 0x2333333
|
||||
end
|
||||
local function resolveColour(code: number, cur: number): number
|
||||
if code == 16 then
|
||||
return cur
|
||||
elseif code == 24 then
|
||||
return edgeOf(cur)
|
||||
end
|
||||
return code
|
||||
end
|
||||
local materialOf: { [string]: number } = {}
|
||||
local function material(col: number, ds: boolean): number
|
||||
local key = col .. (if ds then "d" else "")
|
||||
local have = materialOf[key]
|
||||
if have then
|
||||
return have
|
||||
end
|
||||
local entry = colours[col]
|
||||
local rgb, alpha, name, finish = 0x7F7F7F, 255, "Unknown_" .. col, nil
|
||||
if entry then
|
||||
rgb, alpha, name, finish = entry.rgb, entry.alpha, entry.name, entry.finish
|
||||
elseif col >= 0x2000000 and col < 0x4000000 then
|
||||
rgb = col % 0x1000000
|
||||
alpha = if col >= 0x3000000 then 128 else 255
|
||||
name = string.format("#%06X", rgb)
|
||||
elseif col >= 0x4000000 and col < 0x8000000 then
|
||||
-- dithered: two 12-bit colours, shown as their mean
|
||||
local lo, hi = col % 0x1000, (col // 0x1000) % 0x1000
|
||||
local function ch(v: number, s: number): number
|
||||
return ((v // s) % 16) * 17
|
||||
end
|
||||
rgb = ((ch(lo, 256) + ch(hi, 256)) // 2) * 65536 + ((ch(lo, 16) + ch(hi, 16)) // 2) * 256 + (ch(lo, 1) + ch(hi, 1)) // 2
|
||||
alpha = if col >= 0x7000000 then 0 elseif col >= 0x5000000 then 128 else 255
|
||||
name = string.format("Dither_%X", col)
|
||||
end
|
||||
local m = Types.Scene.material(name)
|
||||
m.baseColor = { srgbToLinear((rgb // 65536) / 255), srgbToLinear(((rgb // 256) % 256) / 255), srgbToLinear((rgb % 256) / 255), alpha / 255 }
|
||||
if alpha < 255 then
|
||||
m.alphaMode = "blend"
|
||||
end
|
||||
m.doubleSided = ds
|
||||
m.metallic = 0
|
||||
m.roughness = 0.35
|
||||
if finish == "CHROME" or finish == "METAL" then
|
||||
m.metallic, m.roughness = 1, if finish == "CHROME" then 0.15 else 0.4
|
||||
elseif finish == "PEARLESCENT" or finish == "MATTE_METALLIC" then
|
||||
m.metallic, m.roughness = 0.6, 0.45
|
||||
elseif finish == "RUBBER" then
|
||||
m.roughness = 0.9
|
||||
end
|
||||
m.extras = { ldraw = { code = col, name = name, edge = edgeOf(col), finish = finish, luminance = if entry and entry.luminance > 0 then entry.luminance else nil } }
|
||||
table.insert(scene.materials, m)
|
||||
materialOf[key] = #scene.materials
|
||||
return #scene.materials
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ baking
|
||||
local failure: string?, failKind: string? = nil, nil
|
||||
local triangles = 0
|
||||
local cycles = 0
|
||||
local function fail(msg: string, kind: string?)
|
||||
if not failure then
|
||||
failure, failKind = msg, kind
|
||||
end
|
||||
end
|
||||
|
||||
-- bake(file, m (3x4 row-major), colour, inv, certified, depth, stack, groups, order, direct)
|
||||
local function bake(f: File, m: { number }, colour: number, inv: boolean, certified: boolean, depth: number, stack: { [File]: boolean }, groups: { [string]: Group }, order: { Group }, direct: boolean)
|
||||
if failure then
|
||||
return
|
||||
end
|
||||
if depth > maxDepth then
|
||||
return fail("limit: sub-files nested deeper than " .. maxDepth, "limit")
|
||||
end
|
||||
stack[f] = true
|
||||
local model = isModel(f)
|
||||
local m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12 = table.unpack(m)
|
||||
local det = m1 * (m6 * m11 - m7 * m10) - m2 * (m5 * m11 - m7 * m9) + m3 * (m5 * m10 - m6 * m9)
|
||||
local cw, clip = false, true
|
||||
local function group(mode: string, col: number, ds: boolean): Group
|
||||
local key = mode .. col .. (if ds then "d" else "")
|
||||
local g = groups[key]
|
||||
if not g then
|
||||
g = { mode = mode, colour = col, ds = ds, pos = {}, ctrl = if mode == "optional" then {} else nil }
|
||||
groups[key] = g
|
||||
table.insert(order, g)
|
||||
end
|
||||
return g
|
||||
end
|
||||
local function put(list: { number }, x: number, y: number, z: number)
|
||||
local n = #list
|
||||
list[n + 1] = m1 * x + m2 * y + m3 * z + m4
|
||||
list[n + 2] = m5 * x + m6 * y + m7 * z + m8
|
||||
list[n + 3] = m9 * x + m10 * y + m11 * z + m12
|
||||
end
|
||||
for _, cmd in f.cmds do
|
||||
if failure then
|
||||
break
|
||||
end
|
||||
local k = cmd.k
|
||||
local v = cmd.v
|
||||
if k == 0 then
|
||||
if cmd.cw ~= nil then
|
||||
cw = cmd.cw :: boolean
|
||||
end
|
||||
if cmd.clip ~= nil then
|
||||
clip = cmd.clip :: boolean
|
||||
end
|
||||
elseif k == 1 then
|
||||
if not direct then
|
||||
local sub = lookup(cmd.name :: string)
|
||||
if sub and stack[sub] then
|
||||
cycles += 1
|
||||
elseif sub then
|
||||
local a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12 = table.unpack(v)
|
||||
local child = {
|
||||
m1 * a1 + m2 * a5 + m3 * a9, m1 * a2 + m2 * a6 + m3 * a10, m1 * a3 + m2 * a7 + m3 * a11, m1 * a4 + m2 * a8 + m3 * a12 + m4,
|
||||
m5 * a1 + m6 * a5 + m7 * a9, m5 * a2 + m6 * a6 + m7 * a10, m5 * a3 + m6 * a7 + m7 * a11, m5 * a4 + m6 * a8 + m7 * a12 + m8,
|
||||
m9 * a1 + m10 * a5 + m11 * a9, m9 * a2 + m10 * a6 + m11 * a10, m9 * a3 + m10 * a7 + m11 * a11, m9 * a4 + m10 * a8 + m11 * a12 + m12,
|
||||
}
|
||||
local childCert = if model then true else certified and f.certified and clip
|
||||
bake(sub, child, resolveColour(cmd.c, colour), inv ~= (cmd.inv == true), childCert, depth + 1, stack, groups, order, false)
|
||||
end
|
||||
end
|
||||
elseif k == 3 or k == 4 then
|
||||
local col = resolveColour(cmd.c, colour)
|
||||
local one = certified and f.certified and clip
|
||||
local g = group("triangles", col, not one)
|
||||
local rev = cw ~= inv ~= (det < 0)
|
||||
local p = g.pos
|
||||
local nt = if k == 3 then 1 else 2
|
||||
triangles += nt
|
||||
if triangles > maxTriangles then
|
||||
return fail(string.format("limit: more than %d triangles", maxTriangles), "limit")
|
||||
end
|
||||
local function tri(a: number, b: number, c: number)
|
||||
if rev then
|
||||
a, c = c, a
|
||||
end
|
||||
put(p, v[a * 3 + 1], v[a * 3 + 2], v[a * 3 + 3])
|
||||
put(p, v[b * 3 + 1], v[b * 3 + 2], v[b * 3 + 3])
|
||||
put(p, v[c * 3 + 1], v[c * 3 + 2], v[c * 3 + 3])
|
||||
end
|
||||
tri(0, 1, 2)
|
||||
if k == 4 then
|
||||
tri(0, 2, 3)
|
||||
end
|
||||
elseif k == 2 and withLines then
|
||||
local g = group("lines", resolveColour(cmd.c, colour), false)
|
||||
put(g.pos, v[1], v[2], v[3])
|
||||
put(g.pos, v[4], v[5], v[6])
|
||||
elseif k == 5 and withOptional then
|
||||
local g = group("optional", resolveColour(cmd.c, colour), false)
|
||||
put(g.pos, v[1], v[2], v[3])
|
||||
put(g.pos, v[4], v[5], v[6])
|
||||
local ctrl = g.ctrl :: { number }
|
||||
for _ = 1, 2 do
|
||||
put(ctrl, v[7], v[8], v[9])
|
||||
put(ctrl, v[10], v[11], v[12])
|
||||
end
|
||||
end
|
||||
end
|
||||
stack[f] = nil
|
||||
end
|
||||
|
||||
local function f32(list: { number }, from: number, step: number, count: number): Types.Accessor
|
||||
local b = buffer.create(count * 12)
|
||||
for i = 0, count - 1 do
|
||||
local s = from + i * step
|
||||
buffer.writef32(b, i * 12, list[s])
|
||||
buffer.writef32(b, i * 12 + 4, list[s + 1])
|
||||
buffer.writef32(b, i * 12 + 8, list[s + 2])
|
||||
end
|
||||
return Types.Scene.accessor(b, "f32", 3, count)
|
||||
end
|
||||
|
||||
-- the mesh of a file baked at the identity (nil when it has no geometry)
|
||||
local meshOf: { [string]: number | false } = {}
|
||||
local function meshFor(f: File, colour: number, inv: boolean, direct: boolean): number?
|
||||
local key = f.key .. "|" .. colour .. "|" .. (if inv then "i" else "") .. (if direct then "d" else "")
|
||||
local have = meshOf[key]
|
||||
if have ~= nil then
|
||||
return have or nil
|
||||
end
|
||||
local groups: { [string]: Group } = {}
|
||||
local order: { Group } = {}
|
||||
bake(f, IDENTITY12, colour, inv, true, 0, {}, groups, order, direct)
|
||||
local mesh: Types.Mesh = { name = f.name, primitives = {} }
|
||||
for _, g in order do
|
||||
local count = #g.pos // 3
|
||||
if count > 0 then
|
||||
local prim: Types.Primitive = { attributes = { POSITION = f32(g.pos, 1, 3, count) }, mode = if g.mode == "triangles" then "triangles" else "lines" }
|
||||
prim.material = material(g.colour, g.ds)
|
||||
if g.mode == "optional" then
|
||||
local ctrl = g.ctrl :: { number }
|
||||
prim.attributes._CONTROL_0 = f32(ctrl, 1, 6, count)
|
||||
prim.attributes._CONTROL_1 = f32(ctrl, 4, 6, count)
|
||||
prim.extras = { ldraw = { optional = true } }
|
||||
end
|
||||
table.insert(mesh.primitives, prim)
|
||||
end
|
||||
end
|
||||
if #mesh.primitives == 0 then
|
||||
meshOf[key] = false
|
||||
return nil
|
||||
end
|
||||
table.insert(scene.meshes, mesh)
|
||||
meshOf[key] = #scene.meshes
|
||||
return #scene.meshes
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ the node tree
|
||||
local mainFile = parse(mainText, mainName or "main", colours, stats)
|
||||
mainFile.main = true
|
||||
if stats.lines == 0 then
|
||||
return nil, "no LDraw lines", nil
|
||||
end
|
||||
if mainName then
|
||||
cache[norm(mainName)] = mainFile
|
||||
end
|
||||
local mainColour = o.color or 16
|
||||
local function newNode(node: Types.Node): number
|
||||
table.insert(scene.nodes, node)
|
||||
if #scene.nodes > maxNodes then
|
||||
fail(string.format("limit: more than %d nodes", maxNodes), "limit")
|
||||
end
|
||||
return #scene.nodes
|
||||
end
|
||||
local function expand(f: File, colour: number, inv: boolean, out: { number }, depth: number, stack: { [File]: boolean })
|
||||
if failure then
|
||||
return
|
||||
end
|
||||
if depth > maxDepth then
|
||||
return fail("limit: sub-models nested deeper than " .. maxDepth, "limit")
|
||||
end
|
||||
stack[f] = true
|
||||
local direct = meshFor(f, colour, inv, true)
|
||||
if direct then
|
||||
table.insert(out, newNode({ name = f.name, children = {}, mesh = direct }))
|
||||
end
|
||||
for _, cmd in f.cmds do
|
||||
if failure then
|
||||
break
|
||||
end
|
||||
if cmd.k == 1 then
|
||||
local sub = lookup(cmd.name :: string)
|
||||
if sub and stack[sub] then
|
||||
cycles += 1
|
||||
elseif sub then
|
||||
local v = cmd.v
|
||||
local c = resolveColour(cmd.c, colour)
|
||||
local subInv = inv ~= (cmd.inv == true)
|
||||
local node: Types.Node = {
|
||||
name = cmd.name,
|
||||
children = {},
|
||||
matrix = { v[1], v[5], v[9], 0, v[2], v[6], v[10], 0, v[3], v[7], v[11], 0, v[4], v[8], v[12], 1 },
|
||||
extras = { ldraw = { file = sub.name, color = c, step = cmd.step, invert = if subInv then true else nil } },
|
||||
}
|
||||
local index = newNode(node)
|
||||
if isModel(sub) then
|
||||
expand(sub, c, subInv, node.children, depth + 1, stack)
|
||||
else
|
||||
node.mesh = meshFor(sub, c, subInv, false)
|
||||
end
|
||||
table.insert(out, index)
|
||||
end
|
||||
end
|
||||
end
|
||||
stack[f] = nil
|
||||
end
|
||||
local top: { number } = {}
|
||||
if o.flatten or not isModel(mainFile) then
|
||||
local mesh = meshFor(mainFile, mainColour, false, false)
|
||||
table.insert(top, newNode({ name = mainFile.name, children = {}, mesh = mesh }))
|
||||
else
|
||||
expand(mainFile, mainColour, false, top, 0, {})
|
||||
end
|
||||
if failure then
|
||||
return nil, failure, failKind
|
||||
end
|
||||
if o.upright == false then
|
||||
scene.roots = top
|
||||
else
|
||||
table.insert(scene.nodes, { name = "LDraw", children = top, matrix = table.clone(FLIP) })
|
||||
scene.roots = { #scene.nodes }
|
||||
scene.meta.up = "y"
|
||||
end
|
||||
scene.meta.unit = 0.0004
|
||||
local missingList: { string } = {}
|
||||
for k in missing do
|
||||
table.insert(missingList, k)
|
||||
end
|
||||
table.sort(missingList)
|
||||
local nfiles = 0
|
||||
for _, f in cache do
|
||||
if f then
|
||||
nfiles += 1
|
||||
end
|
||||
end
|
||||
scene.meta.source = {
|
||||
format = "ldraw",
|
||||
mpd = mpd,
|
||||
name = mainName,
|
||||
title = mainFile.title,
|
||||
author = mainFile.author,
|
||||
files = nfiles,
|
||||
missing = missingList,
|
||||
cycles = cycles,
|
||||
badLines = stats.bad,
|
||||
up = if o.upright == false then "-y" else nil,
|
||||
}
|
||||
return scene, nil, nil
|
||||
end
|
||||
|
||||
return Read
|
||||
@@ -0,0 +1,105 @@
|
||||
--!strict
|
||||
-- model/ldraw: LDraw (.ldr / .dat / .mpd), read. Written from the LDraw File Format specification 1.0.2, the MPD and
|
||||
-- BFC (back face culling) language extensions and the colour definition (!COLOUR) extension (ldraw.org); checked
|
||||
-- against an independent expansion in the fixture generator and LeoCAD's OBJ export of library parts and models.
|
||||
-- Reads: line types 0 (meta: Name / Author / !LDRAW_ORG / STEP / !COLOUR / BFC), 1 (sub-file references: colour +
|
||||
-- 3x4 matrix), 2 (lines), 3 (triangles), 4 (quads, split in two), 5 (optional lines: skipped, or opts.optionalLines
|
||||
-- -> "lines" primitives with _CONTROL_0 / _CONTROL_1 attributes and prim.extras.ldraw.optional). MPD files split at
|
||||
-- `0 FILE` / `0 NOFILE` (the first file is the model); other sub-files come through opts.files / opts.resolve, tried
|
||||
-- as written (backslashes as slashes), then lower case, under "", "parts/", "p/", "parts/s/" and "models/". Missing
|
||||
-- sub-files are skipped and listed (meta.source.missing); a file that places itself is skipped (meta.source.cycles).
|
||||
-- Scene: parts (files whose !LDRAW_ORG type is not a model, library files, .dat sub-files, a main file without
|
||||
-- references) are baked into one mesh per (part, colour, INVERTNEXT), shared by every placement; models (the main
|
||||
-- file, .ldr / .mpd sub-models) become nodes: one node per reference with the reference's matrix (node.extras.ldraw =
|
||||
-- { file, color, step, invert? }), a model's own geometry on an extra node. opts.flatten bakes the whole model into one
|
||||
-- mesh. Primitives: one "triangles" primitive per colour (and per one- / double-sided), "lines" for type 2 (opts.lines
|
||||
-- = false drops them); no normals, no indices (each triangle has its own three vertices).
|
||||
-- BFC, inside a part: CERTIFY / NOCERTIFY, CW / CCW, CLIP / NOCLIP and INVERTNEXT; faces are written counter-clockwise
|
||||
-- (glTF's front faces) after the reference matrices' mirroring; faces of uncertified files (and their sub-files) or
|
||||
-- under NOCLIP get double-sided materials. Model files do not limit the certification of the parts they place.
|
||||
-- Colours: 16 (the parent's colour; opts.color at the top, default 16 "Main_Colour"), 24 (the parent colour's edge
|
||||
-- colour), codes from the built-in LDConfig.ldr table (model/ldraw/Colors; !COLOUR lines in the files and opts.ldconfig
|
||||
-- text add or replace entries), direct colours 0x2RRGGBB (opaque) / 0x3RRGGBB (transparent) and the old dithered
|
||||
-- 0x4-0x7 codes. One material per colour (baseColor linear, ALPHA -> blend, CHROME / METAL / PEARLESCENT / RUBBER ->
|
||||
-- metallic / roughness; extras.ldraw = { code, name, edge, finish?, luminance? }).
|
||||
-- Axes: LDraw is right-handed with -Y up, 1 LDU = 0.4 mm. The vertices and matrices keep LDraw's values; a root node
|
||||
-- "LDraw" turns the model 180 degrees about X so the scene is Y up (meta.up = "y", meta.unit = 0.0004); opts.upright =
|
||||
-- false leaves it out (meta.up = nil, meta.source.up = "-y").
|
||||
-- meta.source = { format, mpd, name?, title?, author?, files, missing, cycles, badLines, up? }.
|
||||
-- Not supported: writing; !TEXMAP and !DATA (texture mapping, embedded images: ignored); the LDCad / MLCad / LPub meta
|
||||
-- commands (ignored); BFC in model files' references (models place parts as certified).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
local Read = require("@formats/model/ldraw/Read")
|
||||
local Colors = require("@formats/model/ldraw/Colors")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ldraw = {
|
||||
name = "ldraw",
|
||||
category = "model",
|
||||
extensions = { "ldr", "mpd", "dat" },
|
||||
mime = { "application/x-ldraw", "application/x-multi-part-ldraw" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
|
||||
caps = { decode = true, encode = false, materials = true, lines = true, instancing = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
resolve: ((uri: string) -> any)?, -- sub-files (parts, primitives) by library path (the api sets it for paths)
|
||||
files: { [string]: any }?, -- or: the files by library path ("parts/3001.dat", "p/stud.dat", ...)
|
||||
ldconfig: string?, -- LDConfig.ldr text: its !COLOUR lines add to / replace the built-in colours
|
||||
color: number?, -- the colour of code 16 at the top (default 16, "Main_Colour")
|
||||
upright: boolean?, -- add the root node turning -Y up into Y up (default true)
|
||||
flatten: boolean?, -- one mesh for the whole model instead of a node per reference (default false)
|
||||
lines: boolean?, -- type 2 edge lines as "lines" primitives (default true)
|
||||
optionalLines: boolean?, -- type 5 optional lines too (default false)
|
||||
maxDepth: number?, -- sub-file nesting (default 64)
|
||||
maxTriangles: number?, -- default 2^24
|
||||
maxNodes: number?, -- default 2^20
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ldraw.sniff(r: Bytes.Reader): number
|
||||
local head = Sniff.text(r, 2048, true)
|
||||
if string.find(head, "^0%s+FILE%s") then
|
||||
return 0.9
|
||||
end
|
||||
if string.find(head, "\n%s*1%s+%S+" .. string.rep("%s+[-+%deE.]+", 12) .. "%s+[^\n]+%.[dDlL][aAdD][tTrR]%s*\r?\n") then
|
||||
return 0.8
|
||||
end
|
||||
if string.find(head, "^0[ \t]+%a") and string.find(head, "\n%s*[1-5]%s+%S+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]") then
|
||||
return 0.4
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Ldraw.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base))
|
||||
-- the scene builder is plain (not native) code: a bug there must not escape as an error
|
||||
local ok, scene, msg, kind = pcall(Read.scene, text, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "bad model: " .. tostring(scene))
|
||||
end
|
||||
if not scene then
|
||||
return nil, Err.from(msg, nil, kind)
|
||||
end
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- colors(ldconfig?) -> { [code] = { name, rgb (0xRRGGBB sRGB), edge (a code or 0x2RRGGBB), alpha (0..255), luminance,
|
||||
-- finish? } }: the built-in LDConfig.ldr table, with the !COLOUR lines of ldconfig added
|
||||
function Ldraw.colors(ldconfig: string?): { [number]: any }
|
||||
local t = Colors.builtin()
|
||||
if ldconfig then
|
||||
Colors.parse(ldconfig, t)
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
return Ldraw
|
||||
@@ -0,0 +1,230 @@
|
||||
-- model/b3d tests: assimp's Blitz3D models (WusonBlitz, dwarf2, turtle1) and generated files (textures, brushes,
|
||||
-- vertex colours, two UV sets, nested rotated / scaled / mirrored nodes, pivots, master brushes, bones, keys + ANIM)
|
||||
-- against assimp (meshes, faces, materials, animations, channels, bones; world bounds, triangle area and signed
|
||||
-- volume from its PreTransformVertices export: the left- to right-handed conversion and the winding) and the counts
|
||||
-- the generator wrote; the skin's bind pose; error codes; the fuzz no-throw pass. Fixtures: tools/fixtures/b3d.py.
|
||||
local T = require("@tests/T")
|
||||
local B3d = require("@formats/model/b3d")
|
||||
local MeshOps = require("@formats/ops/MeshOps")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Cases = require("@tests/gen/b3d_cases")
|
||||
|
||||
local t = T.suite("b3d")
|
||||
|
||||
local function decode(data: any, opts: any?): (any, any)
|
||||
local b = if type(data) == "string" then buffer.fromstring(data) else data
|
||||
return B3d.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
t:eq(B3d.name, "b3d", "name")
|
||||
t:eq(B3d.category, "model", "category")
|
||||
t:check(B3d.caps.decode and not B3d.caps.encode, "caps")
|
||||
t:eq(B3d.sniff(Bytes.reader(buffer.fromstring("BB3D\0\0\0\0\1\0\0\0"))), 1, "sniff")
|
||||
t:eq(B3d.sniff(Bytes.reader(buffer.fromstring("BX3D\0\0\0\0\1\0\0\0"))), 0, "sniff other")
|
||||
|
||||
local function near(a: number, b: number, eps: number): boolean
|
||||
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
|
||||
end
|
||||
|
||||
-- world triangles of the merged scene: area and signed volume
|
||||
local function measure(prim: any): (number, number)
|
||||
local get = assert(Types.Scene.reader(prim.attributes.POSITION))
|
||||
local idx = prim.indices and Types.Scene.reader(prim.indices)
|
||||
local n = if idx then prim.indices.count else prim.attributes.POSITION.count
|
||||
local area, vol = 0, 0
|
||||
for k = 0, n // 3 - 1 do
|
||||
local i0, i1, i2 = 3 * k, 3 * k + 1, 3 * k + 2
|
||||
if idx then
|
||||
i0, i1, i2 = idx(i0, 0), idx(i1, 0), idx(i2, 0)
|
||||
end
|
||||
local ax, ay, az = get(i0, 0), get(i0, 1), get(i0, 2)
|
||||
local bx, by, bz = get(i1, 0), get(i1, 1), get(i1, 2)
|
||||
local cx, cy, cz = get(i2, 0), get(i2, 1), get(i2, 2)
|
||||
local ux, uy, uz, vx, vy, vz = bx - ax, by - ay, bz - az, cx - ax, cy - ay, cz - az
|
||||
local x, y, z = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
|
||||
area += math.sqrt(x * x + y * y + z * z) / 2
|
||||
vol += (ax * (by * cz - bz * cy) - ay * (bx * cz - bz * cx) + az * (bx * cy - by * cx)) / 6
|
||||
end
|
||||
return area, vol
|
||||
end
|
||||
|
||||
-- assimp's bone count: per primitive, the joints that weight one of its vertices (not the mesh node's own joint)
|
||||
local function boneCount(scene: any): number
|
||||
local n = 0
|
||||
for ni, node in scene.nodes do
|
||||
if node.mesh and node.skin then
|
||||
local skin = scene.skins[node.skin]
|
||||
for _, p in scene.meshes[node.mesh].primitives do
|
||||
local J, W = Types.Scene.reader(p.attributes.JOINTS_0), Types.Scene.reader(p.attributes.WEIGHTS_0)
|
||||
local idx = assert(Types.Scene.reader(p.indices))
|
||||
local seen = {}
|
||||
for i = 0, p.indices.count - 1 do
|
||||
local v = idx(i, 0)
|
||||
for k = 0, 3 do
|
||||
local j = (J :: any)(v, k)
|
||||
if (W :: any)(v, k) > 0 and skin.joints[j + 1] ~= ni and not seen[j] then
|
||||
seen[j] = true
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ cases
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
local scene, err = decode(c.data, { files = c.files })
|
||||
local a = c.assimp
|
||||
t:check(scene, c.name .. ": decode: " .. tostring(err))
|
||||
if scene and not a.failed then
|
||||
local prims, faces = 0, 0
|
||||
for _, pl in Types.Scene.flatten(scene) do
|
||||
prims += 1
|
||||
faces += pl.primitive.indices.count // 3
|
||||
end
|
||||
t:eq(prims, a.meshes, c.name .. ": meshes (assimp)")
|
||||
t:eq(faces, a.faces, c.name .. ": faces (assimp)")
|
||||
t:eq(math.max(1, scene.meta.source.brushes), a.materials, c.name .. ": materials (assimp)")
|
||||
t:eq(#scene.animations, a.animations, c.name .. ": animations (assimp)")
|
||||
local animated = {}
|
||||
local nAnimated = 0
|
||||
for _, anim in scene.animations do
|
||||
for _, ch in anim.channels do
|
||||
if not animated[ch.node] then
|
||||
animated[ch.node] = true
|
||||
nAnimated += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
if a.animations > 0 then
|
||||
t:eq(nAnimated, a.animation_channels, c.name .. ": animated nodes (assimp)")
|
||||
end
|
||||
t:eq(boneCount(scene), a.bones, c.name .. ": bones (assimp)")
|
||||
local merged = assert(MeshOps.merge(scene))
|
||||
local lo, hi = MeshOps.bounds(merged)
|
||||
local ok = lo ~= nil
|
||||
for k = 1, 3 do
|
||||
ok = ok and near((lo :: any)[k], a.min[k], 1e-4) and near((hi :: any)[k], a.max[k], 1e-4)
|
||||
end
|
||||
t:check(ok, string.format("%s: world bounds (assimp) %s / %s", c.name, table.concat(lo or {}, " "), table.concat(hi or {}, " ")))
|
||||
local area, vol = measure(merged)
|
||||
t:check(near(area, a.area, 1e-4), string.format("%s: area %.6g (assimp %.6g)", c.name, area, a.area))
|
||||
-- (a mirrored node: glTF turns its faces back, assimp's PreTransformVertices does not; skip the volume there)
|
||||
if not (c.want and c.want.mirrored) then
|
||||
t:check(near(vol, a.volume, 1e-3), string.format("%s: signed volume %.6g (assimp %.6g)", c.name, vol, a.volume))
|
||||
end
|
||||
-- textures resolved through files
|
||||
for _, tex in scene.textures do
|
||||
local base = string.match(tex.uri, "([^/\\]+)$")
|
||||
t:check((tex.data ~= nil) == (c.files[base] ~= nil), c.name .. ": texture data " .. tostring(tex.uri))
|
||||
end
|
||||
local w = c.want
|
||||
if w then
|
||||
local nv, nt = 0, 0
|
||||
for _, m in scene.meshes do
|
||||
nv += m.primitives[1].attributes.POSITION.count
|
||||
for _, p in m.primitives do
|
||||
nt += p.indices.count // 3
|
||||
end
|
||||
end
|
||||
t:eq(nv, w.vertices, c.name .. ": vertices")
|
||||
t:eq(nt, w.triangles, c.name .. ": triangles")
|
||||
t:eq(#scene.textures, w.textures, c.name .. ": textures")
|
||||
t:eq(#scene.materials, w.materials, c.name .. ": materials")
|
||||
t:eq(#scene.nodes, w.nodes, c.name .. ": nodes")
|
||||
local attrs = scene.meshes[1].primitives[1].attributes
|
||||
t:eq(attrs.COLOR_0 ~= nil, w.colors, c.name .. ": COLOR_0")
|
||||
local sets = 0
|
||||
while attrs["TEXCOORD_" .. sets] do
|
||||
sets += 1
|
||||
end
|
||||
t:eq(sets, w.uvSets, c.name .. ": uv sets")
|
||||
if w.joints then
|
||||
t:eq(#scene.skins, 1, c.name .. ": one skin")
|
||||
t:eq(#scene.skins[1].joints, w.joints, c.name .. ": joints")
|
||||
t:eq(#scene.animations[1].channels, w.channels, c.name .. ": channels")
|
||||
t:eq(scene.meta.source.fps, w.fps, c.name .. ": fps")
|
||||
t:eq(scene.meta.source.frames, w.frames, c.name .. ": frames")
|
||||
end
|
||||
end
|
||||
if c.name == "gen/textured" then
|
||||
local m1, m2 = scene.materials[1], scene.materials[2]
|
||||
t:check(m1.name == "red" and m1.baseColorTexture and m1.baseColorTexture.texture == 1, "textured: brush texture")
|
||||
local tr = m1.baseColorTexture and m1.baseColorTexture.transform
|
||||
t:check(tr and tr.offset[1] == 0.25 and tr.scale[2] == 3 and tr.rotation == 0.5, "textured: texture transform")
|
||||
t:check(m1.extras.b3d.textures[2] == 2, "textured: second brush texture in extras")
|
||||
t:check(m2.name == "glass" and m2.alphaMode == "blend" and m2.doubleSided and m2.extensions.KHR_materials_unlit, "textured: alpha, FX")
|
||||
t:check(m2.baseColorTexture and m2.baseColorTexture.texCoord == 1, "textured: second UV set flag")
|
||||
t:check(scene.textures[2].sampler and scene.textures[2].sampler.wrapS == "clamp", "textured: clamp")
|
||||
end
|
||||
-- the bind pose: skinning the vertices with the inverse bind matrices gives the static placement
|
||||
for ni, node in scene.nodes do
|
||||
if node.skin then
|
||||
local skin = scene.skins[node.skin]
|
||||
local worlds = {}
|
||||
for _, pl in Types.Scene.flatten(scene) do
|
||||
worlds[pl.node] = pl.matrix
|
||||
end
|
||||
local ibm = assert(Types.Scene.reader(skin.inverseBindMatrices))
|
||||
local function world(i: number): { number }
|
||||
local parent
|
||||
for pi, n in scene.nodes do
|
||||
if table.find(n.children, i) then
|
||||
parent = pi
|
||||
end
|
||||
end
|
||||
local l = Types.Scene.nodeMatrix(scene.nodes[i])
|
||||
return if parent then Types.Scene.mul(world(parent), l) else l
|
||||
end
|
||||
local maxErr = 0
|
||||
local meshWorld = world(ni)
|
||||
for j, jn in skin.joints do
|
||||
local m = {}
|
||||
for k = 1, 16 do
|
||||
m[k] = ibm(j - 1, k - 1)
|
||||
end
|
||||
local jm = Types.Scene.mul(world(jn), m)
|
||||
for k = 1, 16 do
|
||||
maxErr = math.max(maxErr, math.abs(jm[k] - meshWorld[k]))
|
||||
end
|
||||
end
|
||||
t:check(maxErr < 1e-3, c.name .. ": joint * inverse bind = the mesh's world matrix (" .. maxErr .. ")")
|
||||
end
|
||||
end
|
||||
end
|
||||
if #c.data < 100000 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ errors
|
||||
do
|
||||
local _, e = decode("BB3D\4\0\0\0\1\0\0\0")
|
||||
t:check(e and e.code == Err.CORRUPT, "no NODE: CORRUPT")
|
||||
_, e = decode("BB3D\100\0\0\0\1\0\0\0")
|
||||
t:check(e and e.code == Err.TRUNCATED, "short BB3D: TRUNCATED")
|
||||
_, e = decode("RIFF\0\0\0\0")
|
||||
t:check(e and e.code == Err.CORRUPT, "not B3D: CORRUPT")
|
||||
local s = Cases[#Cases].data
|
||||
local _, e2 = decode(string.sub(s, 1, #s - 7))
|
||||
t:check(e2 and e2.code == Err.TRUNCATED, "truncated file: TRUNCATED (" .. tostring(e2) .. ")")
|
||||
local _, e3 = decode(s, { maxVertices = 4 })
|
||||
t:check(e3 and e3.code == Err.LIMIT, "maxVertices: LIMIT")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fuzz
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local s = B3d.decode(Bytes.reader(b))
|
||||
if s then
|
||||
MeshOps.merge(s)
|
||||
end
|
||||
return s
|
||||
end, samples, { mutations = 16, keepHeader = 4 })
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,226 @@
|
||||
-- model/ldraw tests: hand-written LDraw files (a brick of primitives found through library paths, an MPD with
|
||||
-- embedded parts and sub-models, BFC CW / CCW / INVERTNEXT / NOCLIP / uncertified files, mirrored references, colours
|
||||
-- 16 / 24 / direct / local !COLOUR, optional lines, a missing part, a self-reference, bad lines, CRLF) and real library
|
||||
-- parts and models (3001, 3062b, 4073, 3626c, car.ldr, pyramid.ldr) against an independent expansion in the generator
|
||||
-- (world triangles per colour, double-sided faces, lines, area, signed volume of the one-sided faces, bounds, missing
|
||||
-- files) and LeoCAD's OBJ export (bounds, area); node / flattened / un-flipped scenes agree; mesh sharing; the
|
||||
-- built-in colour table against LDConfig.ldr; resolve; error codes; the fuzz no-throw pass. Fixtures:
|
||||
-- tools/fixtures/ldraw.py.
|
||||
local T = require("@tests/T")
|
||||
local Ldraw = require("@formats/model/ldraw")
|
||||
local MeshOps = require("@formats/ops/MeshOps")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Cases = require("@tests/gen/ldraw_cases")
|
||||
local Config = require("@tests/gen/ldraw_config")
|
||||
|
||||
local t = T.suite("ldraw")
|
||||
|
||||
local function decode(data: any, opts: any?): (any, any)
|
||||
local b = if type(data) == "string" then buffer.fromstring(data) else data
|
||||
return Ldraw.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
local function near(a: number, b: number, eps: number): boolean
|
||||
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
|
||||
end
|
||||
|
||||
t:eq(Ldraw.name, "ldraw", "name")
|
||||
t:eq(Ldraw.category, "model", "category")
|
||||
t:check(Ldraw.caps.decode and not Ldraw.caps.encode, "caps")
|
||||
t:check(Ldraw.sniff(Bytes.reader(buffer.fromstring("0 FILE main.ldr\n1 16 0 0 0 1 0 0 0 1 0 0 0 1 a.dat\n"))) >= 0.9, "sniff MPD")
|
||||
t:check(Ldraw.sniff(Bytes.reader(buffer.fromstring("0 x\n1 16 0 0 0 1 0 0 0 1 0 0 0 1 3001.dat\n"))) >= 0.8, "sniff LDR")
|
||||
t:eq(Ldraw.sniff(Bytes.reader(buffer.fromstring("solid cube\n facet normal 0 0 1\n"))), 0, "sniff other")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ colour table
|
||||
do
|
||||
local tbl = Ldraw.colors()
|
||||
local bad = 0
|
||||
for _, c in Config.colours do
|
||||
local e = tbl[c[1]]
|
||||
if not e or e.rgb ~= c[2] or e.edge ~= c[3] or e.alpha ~= c[4] then
|
||||
bad += 1
|
||||
end
|
||||
end
|
||||
t:eq(bad, 0, "built-in colours = LDConfig.ldr (" .. #Config.colours .. " colours)")
|
||||
local over = Ldraw.colors("0 !COLOUR Mine CODE 4 VALUE #010203 EDGE 0\n")
|
||||
t:check(over[4].rgb == 0x010203 and over[4].edge == 0 and over[4].name == "Mine", "ldconfig overrides")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ measuring
|
||||
type Stats = { triangles: number, lines: number, optional: number, ds: number, area: number, volume: number, colours: { [number]: number } }
|
||||
|
||||
local function det3(m: { number }): number
|
||||
return m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3])
|
||||
end
|
||||
|
||||
local function measure(scene: any): Stats
|
||||
local s: Stats = { triangles = 0, lines = 0, optional = 0, ds = 0, area = 0, volume = 0, colours = {} }
|
||||
for _, pl in Types.Scene.flatten(scene) do
|
||||
local p = pl.primitive
|
||||
local n = p.attributes.POSITION.count
|
||||
if p.mode == "lines" then
|
||||
if p.extras and p.extras.ldraw and p.extras.ldraw.optional then
|
||||
s.optional += n // 2
|
||||
else
|
||||
s.lines += n // 2
|
||||
end
|
||||
else
|
||||
local mat = scene.materials[p.material]
|
||||
local code = mat.extras.ldraw.code
|
||||
s.colours[code] = (s.colours[code] or 0) + n // 3
|
||||
s.triangles += n // 3
|
||||
if mat.doubleSided then
|
||||
s.ds += n // 3
|
||||
end
|
||||
local m = pl.matrix
|
||||
local flip = det3(m) < 0
|
||||
local get = assert(Types.Scene.reader(p.attributes.POSITION))
|
||||
for tri = 0, n // 3 - 1 do
|
||||
local q = {}
|
||||
for k = 0, 2 do
|
||||
local x, y, z = get(tri * 3 + k, 0), get(tri * 3 + k, 1), get(tri * 3 + k, 2)
|
||||
q[k + 1] = { m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] }
|
||||
end
|
||||
local a, b, c = q[1], q[2], q[3]
|
||||
if flip then
|
||||
a, c = c, a
|
||||
end
|
||||
local ux, uy, uz, vx, vy, vz = b[1] - a[1], b[2] - a[2], b[3] - a[3], c[1] - a[1], c[2] - a[2], c[3] - a[3]
|
||||
local x, y, z = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
|
||||
s.area += math.sqrt(x * x + y * y + z * z) / 2
|
||||
if not mat.doubleSided then
|
||||
s.volume += (a[1] * (b[2] * c[3] - b[3] * c[2]) - a[2] * (b[1] * c[3] - b[3] * c[1]) + a[3] * (b[1] * c[2] - b[2] * c[1])) / 6
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
local function compare(label: string, s: Stats, w: any)
|
||||
t:eq(s.triangles, w.triangles, label .. ": triangles")
|
||||
t:eq(s.ds, w.doubleSided, label .. ": double-sided triangles")
|
||||
t:eq(s.lines, w.lines, label .. ": lines")
|
||||
local bad = {}
|
||||
for _, pair in w.colours do
|
||||
if s.colours[pair[1]] ~= pair[2] then
|
||||
table.insert(bad, string.format("%d: %s / %d", pair[1], tostring(s.colours[pair[1]]), pair[2]))
|
||||
end
|
||||
end
|
||||
t:check(#bad == 0 and #w.colours == #(function()
|
||||
local keys = {}
|
||||
for k in s.colours do
|
||||
table.insert(keys, k)
|
||||
end
|
||||
return keys
|
||||
end)(), label .. ": triangles per colour " .. table.concat(bad, ", "))
|
||||
t:check(near(s.area, w.area, 1e-5), string.format("%s: area %.6f / %.6f", label, s.area, w.area))
|
||||
t:check(near(s.volume, w.volume, 1e-5), string.format("%s: signed volume %.6f / %.6f", label, s.volume, w.volume))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ cases
|
||||
local samples = {}
|
||||
local lib: any = nil
|
||||
for _, c in Cases do
|
||||
local opts = table.clone(c.opts or {})
|
||||
opts.files = c.files
|
||||
local scene, err = decode(c.data, opts)
|
||||
t:check(scene, c.name .. ": decode: " .. tostring(err))
|
||||
local w = c.want
|
||||
compare(c.name, measure(scene), w)
|
||||
local lo, hi = MeshOps.bounds(assert(MeshOps.merge(scene)))
|
||||
local ok = lo ~= nil and w.min ~= nil
|
||||
for k = 1, 3 do
|
||||
ok = ok and near((lo :: any)[k], w.min[k], 1e-5) and near((hi :: any)[k], w.max[k], 1e-5)
|
||||
end
|
||||
t:check(ok, string.format("%s: bounds %s / %s", c.name, table.concat(lo or {}, " "), table.concat(hi or {}, " ")))
|
||||
t:eq(table.concat(scene.meta.source.missing, ","), table.concat(w.missing, ","), c.name .. ": missing files")
|
||||
t:check(scene.meta.up == "y" and scene.meta.unit == 0.0004, c.name .. ": meta.up / unit")
|
||||
-- LeoCAD: its axes are (x, -z, y) of ours, 2 decimals
|
||||
local lc = c.leocad
|
||||
if lc then
|
||||
local lmin = { lo[1], -hi[3], lo[2] }
|
||||
local lmax = { hi[1], -lo[3], hi[2] }
|
||||
local good = true
|
||||
for k = 1, 3 do
|
||||
good = good and math.abs(lmin[k] - lc.min[k]) < 0.02 and math.abs(lmax[k] - lc.max[k]) < 0.02
|
||||
end
|
||||
t:check(good, c.name .. ": bounds (LeoCAD)")
|
||||
local s = measure(scene)
|
||||
t:check(near(s.area, lc.area, 2e-4), string.format("%s: area %.3f (LeoCAD %.3f)", c.name, s.area, lc.area))
|
||||
end
|
||||
-- the same model flattened into one mesh, and without the root flip
|
||||
local flat = assert(decode(c.data, { files = c.files, flatten = true }))
|
||||
t:eq(#flat.meshes <= 1, true, c.name .. ": flatten: one mesh")
|
||||
compare(c.name .. " (flatten)", measure(flat), w)
|
||||
local raw = assert(decode(c.data, { files = c.files, upright = false }))
|
||||
local rlo, rhi = MeshOps.bounds(assert(MeshOps.merge(raw)))
|
||||
t:check(rlo and near(rlo[2], -hi[2], 1e-6) and near(rhi[3], -lo[3], 1e-6) and raw.meta.source.up == "-y", c.name .. ": upright = false")
|
||||
if #c.data < 4000 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
if c.name == "two.ldr" then
|
||||
lib = c.files
|
||||
-- one mesh per (part, colour): four colours, the missing part has no node
|
||||
t:eq(#scene.meshes, 4, "two.ldr: meshes per colour")
|
||||
local root = scene.nodes[scene.roots[1]]
|
||||
t:eq(#root.children, 4, "two.ldr: one node per placed part")
|
||||
local steps = {}
|
||||
for _, ci in root.children do
|
||||
table.insert(steps, scene.nodes[ci].extras.ldraw.step)
|
||||
end
|
||||
t:eq(table.concat(steps, ","), "1,1,1,2", "two.ldr: steps")
|
||||
-- through resolve instead of files
|
||||
local viaResolve = assert(decode(c.data, { resolve = function(uri: string): any
|
||||
return c.files[uri]
|
||||
end }))
|
||||
t:eq(measure(viaResolve).triangles, w.triangles, "two.ldr: resolve")
|
||||
-- optional lines on request
|
||||
local withOpt = assert(decode(c.data, { files = c.files, optionalLines = true, lines = false }))
|
||||
local so = measure(withOpt)
|
||||
t:check(so.optional == w.optional and so.lines == 0, "two.ldr: optional lines only")
|
||||
elseif c.name == "model.mpd" then
|
||||
t:check(scene.meta.source.mpd, "model.mpd: mpd")
|
||||
local meshNodes = 0
|
||||
for _, n in scene.nodes do
|
||||
if n.mesh then
|
||||
meshNodes += 1
|
||||
end
|
||||
end
|
||||
t:check(#scene.meshes < meshNodes, string.format("model.mpd: meshes shared (%d meshes, %d mesh nodes)", #scene.meshes, meshNodes))
|
||||
local purple
|
||||
for _, m in scene.materials do
|
||||
if m.extras.ldraw.code == 1000 then
|
||||
purple = m
|
||||
end
|
||||
end
|
||||
t:check(purple and purple.name == "Test_Purple" and purple.alphaMode == "blend", "model.mpd: local !COLOUR")
|
||||
elseif c.name == "badrefs.ldr" then
|
||||
t:check(scene.meta.source.cycles > 0 and scene.meta.source.badLines == 2, "badrefs.ldr: cycle and bad lines counted")
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ errors
|
||||
do
|
||||
local _, e = decode("")
|
||||
t:check(e and e.code == Err.CORRUPT, "empty: CORRUPT")
|
||||
_, e = decode("hello world\nthis is not ldraw\n")
|
||||
t:check(e and e.code == Err.CORRUPT, "text: CORRUPT")
|
||||
_, e = decode(Cases[1].data, { files = Cases[1].files, maxTriangles = 10 })
|
||||
t:check(e and e.code == Err.LIMIT, "maxTriangles: LIMIT")
|
||||
_, e = decode(Cases[1].data, { files = Cases[1].files, maxDepth = 0 })
|
||||
t:check(e and e.code == Err.LIMIT, "maxDepth: LIMIT")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fuzz
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local s = Ldraw.decode(Bytes.reader(b), { files = lib, optionalLines = true })
|
||||
if s then
|
||||
MeshOps.merge(s)
|
||||
end
|
||||
return s
|
||||
end, samples, { mutations = 24 })
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,204 @@
|
||||
# B3D fixtures (tools/fixtures.py): assimp's Blitz3D test models (WusonBlitz, dwarf2, turtle1: read from the nixpkgs
|
||||
# assimp source, never committed; their textures next to them go into `files`) and B3D files written here (textures
|
||||
# with transforms and clamp flags, brushes with alpha / FX, vertex colours, two UV sets, nested rotated / scaled nodes,
|
||||
# pivots, master brushes, bones with weights, KEYS + ANIM), with reference values from assimp: `assimp info -r`
|
||||
# (meshes, faces, materials, animations, channels, bones) and its PreTransformVertices OBJ export (world bounds,
|
||||
# triangle area, signed volume: the handedness conversion and winding), plus the counts the generator wrote.
|
||||
# tests/gen/b3d_cases.luau { name, data, files = { name -> bytes }, assimp = {...}, want? = {...} }
|
||||
import importlib.util, math, os, re, struct, subprocess
|
||||
|
||||
INPUTS = ["tools/fixtures/_model_ref.py"]
|
||||
|
||||
|
||||
def ref_module(ctx):
|
||||
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def assimp_src():
|
||||
out = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True)
|
||||
return out.stdout.decode().strip().split("\n")[-1]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------- B3D writer
|
||||
def chunk(tag, *parts):
|
||||
body = b"".join(parts)
|
||||
return tag.encode() + struct.pack("<I", len(body)) + body
|
||||
|
||||
|
||||
def cstr(s):
|
||||
return s.encode() + b"\0"
|
||||
|
||||
|
||||
def f32(*v):
|
||||
return struct.pack("<%df" % len(v), *v)
|
||||
|
||||
|
||||
def i32(*v):
|
||||
return struct.pack("<%di" % len(v), *v)
|
||||
|
||||
|
||||
def quat_axis(ax, ay, az, deg):
|
||||
# Blitz3D order: w, x, y, z
|
||||
l = math.sqrt(ax * ax + ay * ay + az * az)
|
||||
h = math.radians(deg) / 2
|
||||
s = math.sin(h) / l
|
||||
return (math.cos(h), ax * s, ay * s, az * s)
|
||||
|
||||
|
||||
def node(name, pos=(0, 0, 0), scale=(1, 1, 1), rot=(1, 0, 0, 0), *children):
|
||||
return chunk("NODE", cstr(name), f32(*pos), f32(*scale), f32(*rot), *children)
|
||||
|
||||
|
||||
def box_mesh(sx, sy, sz, flags=0, sets=1, size=2, brushes=(-1,), master=-1):
|
||||
# 8 corners, 12 triangles; split between the brushes round-robin by face
|
||||
verts = []
|
||||
for i in range(8):
|
||||
x, y, z = (sx if i & 1 else -sx), (sy if i & 2 else -sy), (sz if i & 4 else -sz)
|
||||
v = f32(x, y, z)
|
||||
if flags & 1:
|
||||
l = math.sqrt(x * x + y * y + z * z)
|
||||
v += f32(x / l, y / l, z / l)
|
||||
if flags & 2:
|
||||
v += f32((i & 1) * 1.0, ((i >> 1) & 1) * 1.0, ((i >> 2) & 1) * 1.0, 1.0)
|
||||
for s in range(sets):
|
||||
v += f32(*[(i * 0.1 + s + k * 0.5) for k in range(size)])
|
||||
verts.append(v)
|
||||
# Blitz3D front faces are clockwise seen from outside (left-handed, Direct3D culling)
|
||||
quads = [(0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)]
|
||||
tris = []
|
||||
for a, b, c, d in quads:
|
||||
tris += [(a, b, c), (a, c, d)]
|
||||
tchunks = []
|
||||
for k, br in enumerate(brushes):
|
||||
mine = [t for j, t in enumerate(tris) if j % len(brushes) == k]
|
||||
tchunks.append(chunk("TRIS", i32(br), b"".join(i32(*t) for t in mine)))
|
||||
return chunk("MESH", i32(master), chunk("VRTS", i32(flags, sets, size), b"".join(verts)), *tchunks), 8, 12
|
||||
|
||||
|
||||
def textured():
|
||||
texs = chunk("TEXS", cstr("tex/a.png"), i32(1, 2), f32(0.25, 0.5), f32(2, 3), f32(0.5),
|
||||
cstr("b.png"), i32(1 | 16 | 32 | 65536, 2), f32(0, 0), f32(1, 1), f32(0))
|
||||
brus = chunk("BRUS", i32(2),
|
||||
cstr("red"), f32(1, 0, 0, 1), f32(0.5), i32(1, 0), i32(0, 1),
|
||||
cstr("glass"), f32(0.2, 0.4, 1, 0.5), f32(0), i32(1, 16 | 1), i32(1, -1))
|
||||
m1, _, _ = box_mesh(1, 2, 3, flags=3, sets=2, size=2, brushes=(0, 1))
|
||||
m2, _, _ = box_mesh(0.5, 0.5, 0.5, flags=1, sets=1, size=2, brushes=(-1,), master=1)
|
||||
child = node("child", (3, 1, -2), (1, 2, 1), quat_axis(0, 1, 1, 50), m2)
|
||||
root = node("root", (1, 2, 3), (2, 1, 0.5), quat_axis(1, 1, 0, 30), m1, child)
|
||||
data = chunk("BB3D", i32(1), texs, brus, root)
|
||||
return data, {"vertices": 16, "triangles": 24, "textures": 2, "materials": 2, "colors": True, "uvSets": 2, "nodes": 2}
|
||||
|
||||
|
||||
def pivots():
|
||||
m1, _, _ = box_mesh(1, 1, 1, brushes=(-1,))
|
||||
m2, _, _ = box_mesh(2, 0.5, 1, sets=0, brushes=(-1,))
|
||||
a = node("a", (5, 0, 0), (1, 1, 1), quat_axis(0, 0, 1, 90), m1)
|
||||
b = node("b", (0, 0, 5), (-1, 1, 1), quat_axis(0, 1, 0, -45), m2)
|
||||
pivot = node("pivot", (0, 3, 0), (1, 1, 1), quat_axis(1, 0, 0, 20), a, b)
|
||||
data = chunk("BB3D", i32(1), node("top", (0, 0, 0), (1, 1, 1), (1, 0, 0, 0), pivot))
|
||||
return data, {"vertices": 16, "triangles": 24, "textures": 0, "materials": 0, "colors": False, "uvSets": 1, "nodes": 4, "mirrored": True}
|
||||
|
||||
|
||||
def skinned():
|
||||
# a bar along y: 3 rings of 4 vertices; two bones (nested), each weighting rings; keys on both bones
|
||||
verts, tris = [], []
|
||||
for ring in range(3):
|
||||
for k in range(4):
|
||||
a = math.radians(90 * k)
|
||||
verts.append(f32(math.cos(a), ring * 2.0, math.sin(a)))
|
||||
for ring in range(2):
|
||||
for k in range(4):
|
||||
a, b = ring * 4 + k, ring * 4 + (k + 1) % 4
|
||||
tris += [(a, b + 4, b), (a, a + 4, b + 4)]
|
||||
mesh = chunk("MESH", i32(-1), chunk("VRTS", i32(0, 0, 0), b"".join(verts)), chunk("TRIS", i32(-1), b"".join(i32(*t) for t in tris)))
|
||||
w1 = b"".join(i32(v) + f32(1.0 if v < 4 else 0.5) for v in range(8))
|
||||
w2 = b"".join(i32(v) + f32(0.5 if v < 8 else 1.0) for v in range(4, 12))
|
||||
keys1 = chunk("KEYS", i32(4), *[i32(f) + f32(*quat_axis(0, 0, 1, f * 10)) for f in (1, 5, 10)])
|
||||
keys2 = chunk("KEYS", i32(1 | 2), *[i32(f) + f32(0, 2 + f * 0.1, 0) + f32(1, 1 + f * 0.05, 1) for f in (1, 10)])
|
||||
bone2 = node("bone2", (0, 2, 0), (1, 1, 1), (1, 0, 0, 0), chunk("BONE", w2), keys2)
|
||||
bone1 = node("bone1", (0, 0, 0), (1, 1, 1), (1, 0, 0, 0), chunk("BONE", w1), keys1, bone2)
|
||||
root = node("body", (0, 1, 0), (1, 1, 1), quat_axis(0, 1, 0, 15), mesh, bone1, chunk("ANIM", i32(0, 10), f32(25)))
|
||||
data = chunk("BB3D", i32(1), root)
|
||||
return data, {"vertices": 12, "triangles": 16, "textures": 0, "materials": 0, "colors": False, "uvSets": 0, "nodes": 3,
|
||||
"joints": 2, "channels": 3, "fps": 25.0, "frames": 10}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------- references
|
||||
def info(ctx, path):
|
||||
try:
|
||||
txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace")
|
||||
except subprocess.CalledProcessError:
|
||||
return {"failed": True}
|
||||
out = {}
|
||||
for label in ("Meshes", "Materials", "Faces", "Vertices", "Animations", "Bones", "Animation Channels", "Nodes"):
|
||||
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
|
||||
out[label.lower().replace(" ", "_")] = int(m.group(1)) if m else -1
|
||||
return out
|
||||
|
||||
|
||||
def ptv(ctx, path, tmp):
|
||||
# world-space triangles from assimp's PreTransformVertices OBJ export: bounds, area, signed volume
|
||||
out = os.path.join(tmp, "ptv.obj")
|
||||
ctx.nix("assimp", ["assimp", "export", path, out, "-ptv"])
|
||||
vs, area, vol = [], 0.0, 0.0
|
||||
lo, hi = [1e30] * 3, [-1e30] * 3
|
||||
with open(out) as f:
|
||||
for line in f:
|
||||
p = line.split()
|
||||
if not p:
|
||||
continue
|
||||
if p[0] == "v":
|
||||
v = [float(x) for x in p[1:4]]
|
||||
vs.append(v)
|
||||
lo = [min(a, b) for a, b in zip(lo, v)]
|
||||
hi = [max(a, b) for a, b in zip(hi, v)]
|
||||
elif p[0] == "f":
|
||||
idx = [int(x.split("/")[0]) for x in p[1:]]
|
||||
idx = [i - 1 if i > 0 else len(vs) + i for i in idx]
|
||||
for k in range(1, len(idx) - 1):
|
||||
a, b, c = vs[idx[0]], vs[idx[k]], vs[idx[k + 1]]
|
||||
e1 = [b[j] - a[j] for j in range(3)]
|
||||
e2 = [c[j] - a[j] for j in range(3)]
|
||||
cr = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]
|
||||
area += math.sqrt(sum(x * x for x in cr)) / 2
|
||||
vol += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6
|
||||
os.remove(out)
|
||||
return {"min": lo, "max": hi, "area": area, "volume": vol}
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
M = ref_module(ctx)
|
||||
tmp = M.tempdir()
|
||||
cases = []
|
||||
src = assimp_src()
|
||||
for rel in ("models/B3D/WusonBlitz.b3d", "models-nonbsd/B3D/dwarf2.b3d", "models-nonbsd/B3D/turtle1.b3d"):
|
||||
p = os.path.join(src, "test", rel)
|
||||
if not os.path.exists(p):
|
||||
continue
|
||||
d = os.path.dirname(p)
|
||||
files = {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d))
|
||||
if f.lower().endswith((".png", ".jpg")) and os.path.getsize(os.path.join(d, f)) < 300000}
|
||||
cases.append({"name": "assimp/" + rel, "path": p, "files": files})
|
||||
for name, fn in (("textured", textured), ("pivots", pivots), ("skinned", skinned)):
|
||||
data, want = fn()
|
||||
p = os.path.join(tmp, name + ".b3d")
|
||||
with open(p, "wb") as f:
|
||||
f.write(data)
|
||||
files = {"a.png": M_PNG, "b.png": M_PNG} if name == "textured" else {}
|
||||
cases.append({"name": "gen/" + name, "path": p, "files": files, "want": want})
|
||||
for c in cases:
|
||||
a = info(ctx, c["path"])
|
||||
if not a.get("failed"):
|
||||
a.update(ptv(ctx, c["path"], tmp))
|
||||
c["assimp"] = a
|
||||
c["data"] = open(c["path"], "rb").read()
|
||||
del c["path"]
|
||||
ctx.emit("b3d_cases", cases)
|
||||
|
||||
|
||||
# a 1x1 PNG (texture data for the generated files)
|
||||
M_PNG = bytes.fromhex("89504e470d0a1a0a0000000d4948445200000001000000010806000000"
|
||||
"1f15c4890000000d49444154789c63f8cfc0f01f0005000201a2b3d6bd0000000049454e44ae426082")
|
||||
@@ -0,0 +1,417 @@
|
||||
# LDraw fixtures (tools/fixtures.py): hand-written LDraw files (a brick built from primitives that come through
|
||||
# `files` with library paths, an MPD with embedded sub-files and sub-models, BFC CERTIFY CW / CCW, INVERTNEXT,
|
||||
# mirrored references, NOCERTIFY / NOCLIP, colour inheritance 16 / 24, direct colours, local !COLOUR definitions,
|
||||
# optional lines, a missing part) and real parts and the sample models car.ldr / pyramid.ldr from the LDraw parts
|
||||
# library (complete.zip, CC BY 2.0 / 4.0, the copy nixpkgs' LeoCAD package uses; read from the nix store, never
|
||||
# committed: each case carries the files it needs). References: an independent expansion written here (world
|
||||
# triangles after the decoder's root flip, per colour, lines, area, bounds, signed volume of the one-sided faces) and
|
||||
# LeoCAD's OBJ export (`leocad -obj`: bounds and area of the real models), plus LDConfig.ldr itself for the built-in
|
||||
# colour table.
|
||||
# tests/gen/ldraw_cases.luau { name, data, files = { path -> text }, opts?, want = {...}, leocad? = {...} }
|
||||
# tests/gen/ldraw_config.luau { text = LDConfig.ldr, colours = { { code, rgb, edge, alpha } } }
|
||||
import math, os, re, subprocess, zipfile
|
||||
|
||||
INPUTS = []
|
||||
|
||||
|
||||
def nix_out(attr):
|
||||
out = subprocess.run(["nix", "build", attr, "--no-link", "--print-out-paths"], capture_output=True, check=True)
|
||||
return out.stdout.decode().strip().split("\n")[-1]
|
||||
|
||||
|
||||
def library_zip(leocad):
|
||||
# LeoCAD's wrapper points LEOCAD_LIB at the parts library zip
|
||||
wrapper = open(os.path.join(leocad, "bin", "leocad"), "rb").read().decode("latin-1")
|
||||
m = re.search(r"(/nix/store/[^'\" ]*complete\.zip)", wrapper)
|
||||
return m.group(1) if m else None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------- reference
|
||||
def norm(name):
|
||||
return name.strip().replace("\\", "/").lower()
|
||||
|
||||
|
||||
class Ref:
|
||||
"""an independent LDraw expansion: every triangle in world space (after the root flip y -> -y, z -> -z)"""
|
||||
|
||||
PREFIXES = ("", "parts/", "p/", "parts/s/", "models/")
|
||||
|
||||
def __init__(self, main, files, colours):
|
||||
self.files = {norm(k): v for k, v in files.items()}
|
||||
self.colours = colours # code -> (rgb, edge)
|
||||
self.mpd = {}
|
||||
self.missing = set()
|
||||
self.tris = [] # (colour, ds, (v0, v1, v2))
|
||||
self.lines = 0
|
||||
self.optional = 0
|
||||
text = main
|
||||
if re.search(r"^\s*0\s+FILE\s", text, re.M):
|
||||
cur = None
|
||||
first = None
|
||||
for line in text.splitlines():
|
||||
m = re.match(r"^\s*0\s+FILE\s+(.*?)\s*$", line)
|
||||
if m:
|
||||
cur = norm(m.group(1))
|
||||
first = first or cur
|
||||
self.mpd[cur] = []
|
||||
continue
|
||||
if re.match(r"^\s*0\s+NOFILE\b", line):
|
||||
cur = None
|
||||
continue
|
||||
if cur:
|
||||
self.mpd[cur].append(line)
|
||||
self.main = "\n".join(self.mpd[first])
|
||||
else:
|
||||
self.main = text
|
||||
org = re.search(r"^\s*0\s+!LDRAW_ORG\s+(\S+)", self.main, re.M)
|
||||
refs = re.search(r"^\s*1\s", self.main, re.M)
|
||||
self.main_part = bool(org and "model" not in org.group(1).lower()) or not refs
|
||||
|
||||
def lookup(self, name):
|
||||
n = norm(name)
|
||||
if n in self.mpd:
|
||||
return "\n".join(self.mpd[n])
|
||||
for p in self.PREFIXES:
|
||||
if p + n in self.files:
|
||||
return self.files[p + n]
|
||||
self.missing.add(n)
|
||||
return None
|
||||
|
||||
def colour(self, code, cur):
|
||||
if code == 16:
|
||||
return cur
|
||||
if code == 24:
|
||||
return self.edge(cur)
|
||||
return code
|
||||
|
||||
def edge(self, c):
|
||||
if c in self.colours:
|
||||
e = self.colours[c][1]
|
||||
return e
|
||||
return 0x2333333 if c < 0x2000000 else 0x2000000
|
||||
|
||||
def walk(self, text, m, colour, inv, certified, depth, model, stack=()):
|
||||
# model files (the main file, .ldr / .mpd sub-models) do not limit the certification of what they place
|
||||
if depth > 64:
|
||||
return
|
||||
st = {"cw": False, "cert": None, "clip": True, "invert": False}
|
||||
for raw in text.splitlines():
|
||||
t = raw.split()
|
||||
if not t:
|
||||
continue
|
||||
if t[0] == "0":
|
||||
if len(t) >= 3 and t[1] == "!COLOUR":
|
||||
self.colours.update({k: (v[0], v[1]) for k, v in parse_ldconfig(raw).items()})
|
||||
if len(t) >= 3 and t[1] == "BFC":
|
||||
words = [w.upper() for w in t[2:]]
|
||||
if "NOCERTIFY" in words:
|
||||
st["cert"] = False
|
||||
elif "CERTIFY" in words:
|
||||
st["cert"] = True
|
||||
if "CW" in words:
|
||||
st["cw"] = True
|
||||
if "CCW" in words:
|
||||
st["cw"] = False
|
||||
if "NOCLIP" in words:
|
||||
st["clip"] = False
|
||||
elif "CLIP" in words:
|
||||
st["clip"] = True
|
||||
if "INVERTNEXT" in words:
|
||||
st["invert"] = True
|
||||
continue
|
||||
invert_next = st["invert"]
|
||||
st["invert"] = False
|
||||
try:
|
||||
kind = int(t[0])
|
||||
code = int(t[1], 0)
|
||||
cert = certified and st["cert"] is True and st["clip"]
|
||||
if kind == 1 and len(t) >= 15:
|
||||
x, y, z, a, b, c, d, e, f, g, h, i = [float(v) for v in t[2:14]]
|
||||
loc = [[a, b, c, x], [d, e, f, y], [g, h, i, z]]
|
||||
name = raw.split(None, 14)[14].strip()
|
||||
if norm(name) in stack:
|
||||
continue # a file that (indirectly) places itself
|
||||
sub = self.lookup(name)
|
||||
if sub is None:
|
||||
continue
|
||||
sub_model = norm(name).endswith((".ldr", ".mpd"))
|
||||
self.walk(sub, mul(m, loc), self.colour(code, colour), inv ^ invert_next,
|
||||
(True if model else cert), depth + 1, sub_model, stack + (norm(name),))
|
||||
elif kind in (3, 4) and len(t) >= 2 + 3 * kind:
|
||||
pts = [apply(m, [float(v) for v in t[2 + 3 * k:5 + 3 * k]]) for k in range(kind)]
|
||||
if st["cw"] ^ inv ^ (det(m) < 0):
|
||||
pts = pts[::-1]
|
||||
col = self.colour(code, colour)
|
||||
one = cert and not model or (model and st["cert"] is True and st["clip"])
|
||||
self.tris.append((col, not one, (pts[0], pts[1], pts[2])))
|
||||
if kind == 4:
|
||||
self.tris.append((col, not one, (pts[0], pts[2], pts[3])))
|
||||
elif kind == 2 and len(t) >= 8:
|
||||
[float(v) for v in t[2:8]]
|
||||
self.lines += 1
|
||||
elif kind == 5 and len(t) >= 14:
|
||||
[float(v) for v in t[2:14]]
|
||||
self.optional += 1
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
def run(self, main_colour=16):
|
||||
flip = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0]]
|
||||
self.walk(self.main, flip, main_colour, False, True, 0, not self.main_part)
|
||||
return self
|
||||
|
||||
def summary(self):
|
||||
per = {}
|
||||
area, vol = 0.0, 0.0
|
||||
lo, hi = [1e30] * 3, [-1e30] * 3
|
||||
for col, ds, (a, b, c) in self.tris:
|
||||
per[col] = per.get(col, 0) + 1
|
||||
for p in (a, b, c):
|
||||
lo = [min(u, v) for u, v in zip(lo, p)]
|
||||
hi = [max(u, v) for u, v in zip(hi, p)]
|
||||
area += tri_area(a, b, c)
|
||||
if not ds:
|
||||
vol += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6
|
||||
out = {"triangles": len(self.tris), "lines": self.lines, "optional": self.optional, "area": area, "volume": vol,
|
||||
"doubleSided": sum(1 for x in self.tris if x[1]),
|
||||
"colours": [[k, v] for k, v in sorted(per.items())], "missing": sorted(self.missing)}
|
||||
if self.tris:
|
||||
out["min"], out["max"] = lo, hi
|
||||
return out
|
||||
|
||||
|
||||
def mul(m, l):
|
||||
# 3x4 affine product m * l
|
||||
r = [[0.0] * 4 for _ in range(3)]
|
||||
for i in range(3):
|
||||
for j in range(4):
|
||||
s = sum(m[i][k] * l[k][j] for k in range(3))
|
||||
r[i][j] = s + (m[i][3] if j == 3 else 0)
|
||||
return r
|
||||
|
||||
|
||||
def apply(m, p):
|
||||
return [m[i][0] * p[0] + m[i][1] * p[1] + m[i][2] * p[2] + m[i][3] for i in range(3)]
|
||||
|
||||
|
||||
def det(m):
|
||||
return (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
|
||||
+ m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]))
|
||||
|
||||
|
||||
def tri_area(a, b, c):
|
||||
e1 = [b[i] - a[i] for i in range(3)]
|
||||
e2 = [c[i] - a[i] for i in range(3)]
|
||||
x = e1[1] * e2[2] - e1[2] * e2[1]
|
||||
y = e1[2] * e2[0] - e1[0] * e2[2]
|
||||
z = e1[0] * e2[1] - e1[1] * e2[0]
|
||||
return math.sqrt(x * x + y * y + z * z) / 2
|
||||
|
||||
|
||||
def parse_ldconfig(text):
|
||||
out = {}
|
||||
for line in text.splitlines():
|
||||
m = re.match(r"^\s*0\s+!COLOUR\s+(\S+)\s+(.*)$", line)
|
||||
if not m:
|
||||
continue
|
||||
t = m.group(2).split()
|
||||
kv = {}
|
||||
for i in range(0, len(t) - 1):
|
||||
if t[i] in ("CODE", "VALUE", "EDGE", "ALPHA") and t[i] not in kv:
|
||||
kv[t[i]] = t[i + 1]
|
||||
code = int(kv["CODE"])
|
||||
rgb = int(kv["VALUE"][1:], 16)
|
||||
e = kv["EDGE"]
|
||||
edge = (0x2000000 | int(e[1:], 16)) if e.startswith("#") else int(e)
|
||||
out[code] = (rgb, edge, int(kv.get("ALPHA", "255")), m.group(1))
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------- hand-written
|
||||
BOX = """0 a unit box primitive (faces outward, CCW)
|
||||
0 BFC CERTIFY CCW
|
||||
4 16 -1 -1 -1 1 -1 -1 1 -1 1 -1 -1 1
|
||||
4 16 -1 1 -1 -1 1 1 1 1 1 1 1 -1
|
||||
4 16 -1 -1 -1 -1 -1 1 -1 1 1 -1 1 -1
|
||||
4 16 1 -1 -1 1 1 -1 1 1 1 1 -1 1
|
||||
4 16 -1 -1 -1 -1 1 -1 1 1 -1 1 -1 -1
|
||||
4 16 -1 -1 1 1 -1 1 1 1 1 -1 1 1
|
||||
2 24 -1 -1 -1 1 -1 -1
|
||||
2 24 -1 -1 -1 -1 1 -1
|
||||
5 24 -1 -1 -1 -1 1 -1 1 -1 -1 -1 -1 1
|
||||
"""
|
||||
|
||||
BOX_CW = """0 the same box written clockwise
|
||||
0 BFC CERTIFY CW
|
||||
4 16 -1 -1 1 1 -1 1 1 -1 -1 -1 -1 -1
|
||||
4 16 1 1 -1 1 1 1 -1 1 1 -1 1 -1
|
||||
4 16 -1 1 -1 -1 1 1 -1 -1 1 -1 -1 -1
|
||||
4 16 1 -1 1 1 1 1 1 1 -1 1 -1 -1
|
||||
4 16 1 -1 -1 1 1 -1 -1 1 -1 -1 -1 -1
|
||||
4 16 -1 1 1 1 1 1 1 -1 1 -1 -1 1
|
||||
"""
|
||||
|
||||
TRI = """0 an uncertified triangle
|
||||
3 16 0 0 0 1 0 0 0 0 1
|
||||
"""
|
||||
|
||||
# a brick: an outer box, an inner box turned inside out (INVERTNEXT), a mirrored stud box, an uncertified triangle
|
||||
BRICK = """0 Test Brick 1 x 2
|
||||
0 Name: testbrick.dat
|
||||
0 Author: formats-luau
|
||||
0 !LDRAW_ORG Unofficial_Part
|
||||
0 BFC CERTIFY CCW
|
||||
1 16 0 12 0 20 0 0 0 12 0 0 0 10 box.dat
|
||||
0 BFC INVERTNEXT
|
||||
1 16 0 14 0 18 0 0 0 10 0 0 0 8 box.dat
|
||||
1 4 10 -2 0 -6 0 0 0 2 0 0 0 6 s\\stud box.dat
|
||||
1 16 0 -4 0 1 0 0 0 1 0 0 0 1 48\\cwbox.dat
|
||||
1 16 0 30 0 5 0 0 0 5 0 0 0 5 tri.dat
|
||||
"""
|
||||
|
||||
PLAIN_LDR = """0 Two bricks
|
||||
0 Name: two.ldr
|
||||
1 1 0 0 0 1 0 0 0 1 0 0 0 1 testbrick.dat
|
||||
1 14 60 -24 0 0 0 1 0 1 0 -1 0 0 testbrick.dat
|
||||
1 16 -60 0 0 -1 0 0 0 1 0 0 0 1 testbrick.dat
|
||||
0 STEP
|
||||
1 0x2FF8000 0 -60 0 1 0 0 0 1 0 0 0 1 testbrick.dat
|
||||
1 4 0 -90 0 1 0 0 0 1 0 0 0 1 nosuchpart.dat
|
||||
"""
|
||||
|
||||
MPD = """0 FILE main.ldr
|
||||
0 MPD main
|
||||
0 Name: main.ldr
|
||||
0 !COLOUR Test_Purple CODE 1000 VALUE #8000FF EDGE #200040 ALPHA 200
|
||||
1 16 0 0 0 1 0 0 0 1 0 0 0 1 sub.ldr
|
||||
1 1000 0 -100 0 1 0 0 0 1 0 0 0 1 sub.ldr
|
||||
1 2 0 50 50 1 0 0 0 -1 0 0 0 1 Embedded Part.dat
|
||||
3 24 0 0 0 10 0 0 0 10 0
|
||||
0 NOFILE
|
||||
0 FILE sub.ldr
|
||||
0 a sub-model: two parts and a nested sub-model
|
||||
1 16 0 0 0 1 0 0 0 1 0 0 0 1 embedded part.dat
|
||||
1 4 30 0 0 1 0 0 0 1 0 0 0 1 embedded part.dat
|
||||
1 16 0 0 40 1 0 0 0 1 0 0 0 1 inner.ldr
|
||||
0 NOFILE
|
||||
0 FILE inner.ldr
|
||||
1 0x3FF0000 0 0 0 2 0 0 0 2 0 0 0 2 embedded part.dat
|
||||
0 FILE Embedded Part.dat
|
||||
0 !LDRAW_ORG Unofficial_Part
|
||||
0 BFC CERTIFY CCW
|
||||
1 16 0 0 0 5 0 0 0 5 0 0 0 5 box.dat
|
||||
0 BFC NOCLIP
|
||||
3 24 0 -5 0 5 -5 0 0 -5 5
|
||||
0 BFC CLIP
|
||||
4 16 -5 -6 -5 5 -6 -5 5 -6 5 -5 -6 5
|
||||
"""
|
||||
|
||||
BAD_REFS = """0 cycles and bad lines are survived
|
||||
1 16 0 0 0 1 0 0 0 1 0 0 0 1 loop.dat
|
||||
1 16 0 0 0 1 0 0 0 1
|
||||
3 16 0 0 0 1 x 0 0 0 1
|
||||
4 16 0 0 0 1 0 0 1 1 0 0 1 0
|
||||
"""
|
||||
LOOP = "0 a file that calls itself\n3 16 0 0 0 1 0 0 0 1 0\n1 16 0 0 0 1 0 0 0 1 0 0 0 1 loop.dat\n"
|
||||
|
||||
LIB = {"parts/box.dat": BOX, "p/s/stud box.dat": BOX, "p/48/cwbox.dat": BOX_CW, "p/tri.dat": TRI,
|
||||
"parts/testbrick.dat": BRICK, "loop.dat": LOOP}
|
||||
|
||||
|
||||
def hand_cases(colours):
|
||||
cases = []
|
||||
|
||||
def add(name, text, files, opts=None):
|
||||
ref = Ref(text, files, colours).run()
|
||||
c = {"name": name, "data": text, "files": files, "want": ref.summary()}
|
||||
if opts:
|
||||
c["opts"] = opts
|
||||
cases.append(c)
|
||||
|
||||
add("brick.dat", BRICK, {k: v for k, v in LIB.items() if k != "parts/testbrick.dat"})
|
||||
add("two.ldr", PLAIN_LDR, dict(LIB))
|
||||
add("model.mpd", MPD, {"parts/box.dat": BOX})
|
||||
add("badrefs.ldr", BAD_REFS, {"loop.dat": LOOP})
|
||||
add("crlf.ldr", PLAIN_LDR.replace("\n", "\r\n"), dict(LIB))
|
||||
return cases
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------- real parts
|
||||
def closure(z, names, text_of):
|
||||
"""the library files a set of references needs: { library path -> text }"""
|
||||
have = {}
|
||||
index = {}
|
||||
for n in z.namelist():
|
||||
if n.startswith("ldraw/") and n.lower().endswith(".dat"):
|
||||
index[n[6:].lower()] = n
|
||||
todo = list(names)
|
||||
while todo:
|
||||
n = norm(todo.pop())
|
||||
for p in Ref.PREFIXES:
|
||||
key = p + n
|
||||
if key in index:
|
||||
if key not in have:
|
||||
t = z.read(index[key]).decode("utf-8", "replace")
|
||||
have[key] = t
|
||||
for line in t.splitlines():
|
||||
parts = line.split(None, 14)
|
||||
if len(parts) == 15 and parts[0] == "1":
|
||||
todo.append(parts[14].strip())
|
||||
break
|
||||
return have
|
||||
|
||||
|
||||
def leocad_obj(leocad, libzip, path, tmp):
|
||||
out = os.path.join(tmp, "leocad.obj")
|
||||
env = dict(os.environ, QT_QPA_PLATFORM="offscreen")
|
||||
subprocess.run([os.path.join(leocad, "bin", "leocad"), "-l", libzip, path, "-obj", out], env=env, capture_output=True, timeout=300, check=True)
|
||||
vs, area = [], 0.0
|
||||
lo, hi = [1e30] * 3, [-1e30] * 3
|
||||
with open(out) as f:
|
||||
for line in f:
|
||||
p = line.split()
|
||||
if not p:
|
||||
continue
|
||||
if p[0] == "v":
|
||||
v = [float(x) for x in p[1:4]]
|
||||
vs.append(v)
|
||||
lo = [min(a, b) for a, b in zip(lo, v)]
|
||||
hi = [max(a, b) for a, b in zip(hi, v)]
|
||||
elif p[0] == "f":
|
||||
idx = [int(x.split("/")[0]) - 1 for x in p[1:]]
|
||||
for k in range(1, len(idx) - 1):
|
||||
area += tri_area(vs[idx[0]], vs[idx[k]], vs[idx[k + 1]])
|
||||
return {"min": lo, "max": hi, "area": area}
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
import tempfile
|
||||
tmp = tempfile.mkdtemp(prefix="formats-ldraw-")
|
||||
leocad = nix_out("nixpkgs#leocad")
|
||||
libzip = library_zip(leocad)
|
||||
z = zipfile.ZipFile(libzip)
|
||||
config = z.read("ldraw/LDConfig.ldr").decode("utf-8")
|
||||
colours = {k: (v[0], v[1]) for k, v in parse_ldconfig(config).items()}
|
||||
ctx.emit("ldraw_config", {"text": config, "colours": [[k, v[0], v[1], v[2]] for k, v in sorted(parse_ldconfig(config).items())]})
|
||||
|
||||
cases = hand_cases(colours)
|
||||
# real parts and the library's sample models, with LeoCAD's export
|
||||
reals = [("3001.dat", None), ("3062b.dat", None), ("4073.dat", None), ("3626c.dat", None), ("car.ldr", "ldraw/models/car.ldr"),
|
||||
("pyramid.ldr", "ldraw/models/pyramid.ldr")]
|
||||
for name, member in reals:
|
||||
if member:
|
||||
text = z.read(member).decode("utf-8", "replace")
|
||||
else:
|
||||
text = "0 one part\n1 4 0 0 0 1 0 0 0 1 0 0 0 1 %s\n" % name
|
||||
files = closure(z, [l.split(None, 14)[14].strip() for l in text.splitlines() if l.split(None, 14)[:1] == ["1"]], None)
|
||||
ref = Ref(text, files, colours).run()
|
||||
c = {"name": "library/" + name, "data": text, "files": files, "want": ref.summary()}
|
||||
p = os.path.join(tmp, "model.ldr")
|
||||
with open(p, "w") as f:
|
||||
f.write(text)
|
||||
try:
|
||||
c["leocad"] = leocad_obj(leocad, libzip, p, tmp)
|
||||
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError):
|
||||
pass
|
||||
cases.append(c)
|
||||
ctx.emit("ldraw_cases", cases)
|
||||
Reference in new issue
Block a user