merge ws/3d3-d (model/b3d, model/ldraw)

This commit is contained in:
4DBug committed 2026-10-31 14:30:17 -05:00
commit de2695b87d
14 files changed
+2843 -1

No files matched your search

+24
View File
@@ -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",
+576
View File
@@ -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
+68
View File
@@ -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
+319
View File
@@ -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
+580
View File
@@ -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
+105
View File
@@ -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