Files
rosetta/src/Formats/model/lwo/Parse.luau
T

552 lines
17 KiB
Luau

--!strict
-- model/lwo/Parse: the LightWave object chunks -> layers, tags, surfaces and clips (plain tables; model/lwo/Build
-- makes the Scene). From the LWO2 specification (LightWave 6 "Object Files", Ernie Wright) and the LWOB one (LightWave
-- 5.x), checked against what assimp's LWO importer reads (no code taken).
-- LWO2 / LXOB: TAGS, LAYR (index, pivot, name, parent), PNTS (more than one per layer: later POLS / VMAP indices are
-- relative to the latest), VMAP / VMAD (TXUV, RGB, RGBA, WGHT, MNVW, NORM (Modo), MORF, SPOT; others skipped), POLS
-- (FACE, PTCH, SUBD kept; CURV, BONE, MBAL and unknown types counted and skipped), PTAG (SURF, and MATR in Modo
-- files), SURF (COLR, DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SIDE, SMAN, RIND, VCOL, BLOK image / procedural
-- / gradient / shader blocks with their header and IMAP sub-chunks; derived surfaces), CLIP (STIL, ISEQ, XREF).
-- LWOB: SRFS, PNTS, POLS (detail polygons flattened), SURF (COLR, FLAG, the U2 and V* float values, GLOS, SMAN,
-- CTEX ... TTEX with TIMG / TFLG / TVAL). Not read: envelopes (ENVL), LWO3, Modo ITEM / ACTN chunks.
-- Plain code (the caller wraps it in pcall); bad data returns nil, message.
local Bytes = require("@formats/core/Bytes")
local Chunks = require("@formats/containers/Chunks")
local Parse = {}
export type Map = {
kind: string, -- "uv" | "color" | "normal" | "weight" | "morph" | "spot"
name: string,
dims: number,
vals: { number }, -- per point: vals[point * dims + c + 1]
has: { [number]: boolean },
mad: { [number]: { [number]: { number } } }, -- VMAD: mad[poly][point] = values
}
export type Poly = { kind: string, surf: number?, corners: { number } } -- corners: 0-based point indices
export type Layer = {
index: number,
name: string?,
parent: number?,
pivot: { number },
pts: { number }, -- x, y, z flat
polys: { Poly },
maps: { Map },
implicit: boolean?, -- the layer before any LAYR
}
export type Block = {
kind: string, -- IMAP / PROC / GRAD / SHDR, or "TEX" (LWOB)
ordinal: string,
channel: string, -- COLR, DIFF, LUMI, SPEC, GLOS, REFL, TRAN, RIND, TRNL, BUMP
enabled: boolean,
opacity: number,
projection: number?, -- 0 planar, 1 cylindrical, 2 spherical, 3 cubic, 4 front, 5 UV
axis: number?,
clip: number?,
file: string?, -- LWOB: the TIMG path
uvmap: string?,
wrap: { number }?,
negative: boolean?,
}
export type Surface = {
name: string,
values: { [string]: number }, -- COLR is separate; DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SMAN, RIND
color: { number },
side: number,
vcol: { name: string, kind: string, intensity: number }?,
blocks: { Block },
source: string?,
}
export type Model = {
version: string, -- "LWO2" | "LWOB" | "LXOB"
tags: { string },
layers: { Layer },
surfaces: { Surface },
clips: { [number]: string }, -- clip index -> path
skipped: { [string]: number },
corners: number,
}
local MAP_KINDS: { [string]: string } = {
TXUV = "uv",
RGB = "color",
RGBA = "color",
WGHT = "weight",
MNVW = "weight",
NORM = "normal",
MORF = "morph",
SPOT = "spot",
}
-- ------------------------------------------------------------------------------------------------ primitives
-- S0: a NUL-terminated string padded to an even length
local function s0(r: Bytes.Reader): string
local start = r.pos
local s = r:cstring()
if (r.pos - start) % 2 == 1 and r.pos < r.limit then
r.pos += 1
end
return s
end
-- VX: a variable-length index (2 bytes, or 4 bytes after an 0xFF byte)
local function vx(r: Bytes.Reader): number
if r:peekU8() == 0xFF then
return r:u32be() - 0xFF000000
end
return r:u16be()
end
local function id4(r: Bytes.Reader): string
local s = r:string(4)
return (string.gsub(s, " +$", ""))
end
-- sub-chunks (LWO2: 4-byte id, 2-byte size, padded to even) of [p, e): calls f(id, reader over the body)
local function subchunks(buf: buffer, p: number, e: number, f: (string, Bytes.Reader) -> ())
while p + 6 <= e do
local id = buffer.readstring(buf, p, 4)
local n = buffer.readu8(buf, p + 4) * 256 + buffer.readu8(buf, p + 5)
local body = p + 6
local avail = math.min(n, e - body)
f((string.gsub(id, " +$", "")), Bytes.reader(buf, body, avail))
p = body + n + (n % 2)
end
end
-- ------------------------------------------------------------------------------------------------ geometry
local function newLayer(index: number): Layer
return { index = index, name = nil, parent = nil, pivot = { 0, 0, 0 }, pts = {}, polys = {}, maps = {} }
end
local function readPoints(r: Bytes.Reader, layer: Layer, limit: number): string?
local n = r:remaining() // 12
if #layer.pts // 3 + n > limit then
return "limit: more than " .. limit .. " points"
end
local pts = layer.pts
local k = #pts
for _ = 1, n * 3 do
k += 1
pts[k] = r:f32be()
end
return nil
end
-- POLS (LWO2): returns nil or an error
local function readPolys(r: Bytes.Reader, layer: Layer, kind: string, ptBase: number, budget: { number }): string?
local polys = layer.polys
local npts = #layer.pts // 3
while r:remaining() >= 2 do
local n = bit32.band(r:u16be(), 0x3FF)
local corners = table.create(n)
for i = 1, n do
local p = vx(r) + ptBase
if p >= npts and not r.err then
return "polygon point index " .. p .. " out of range (" .. npts .. " points)"
end
corners[i] = p
end
if r.err then
return "truncated polygon list"
end
budget[1] -= n
if budget[1] < 0 then
return "limit: too many polygon corners"
end
table.insert(polys, { kind = kind, surf = nil, corners = corners })
end
return nil
end
-- POLS (LWOB): n, n x U2, surface I2 (negative: detail polygons follow, after a U2 count)
local function readPolysB(r: Bytes.Reader, layer: Layer, budget: { number }): string?
local polys = layer.polys
local npts = #layer.pts // 3
while r:remaining() >= 4 do
local n = r:u16be()
local corners = table.create(n)
for i = 1, n do
local p = r:u16be()
if p >= npts and not r.err then
return "polygon point index " .. p .. " out of range (" .. npts .. " points)"
end
corners[i] = p
end
local surf = r:i16be()
if r.err then
return "truncated polygon list"
end
if surf < 0 then
surf = -surf
r:u16be() -- the detail polygon count: they follow as ordinary records
end
budget[1] -= n
if budget[1] < 0 then
return "limit: too many polygon corners"
end
if n > 0 then
table.insert(polys, { kind = "FACE", surf = surf - 1, corners = corners })
end
end
return nil
end
local function findMap(layer: Layer, kind: string, name: string, dims: number): Map
for _, m in layer.maps do
if m.kind == kind and m.name == name then
return m
end
end
local m: Map = { kind = kind, name = name, dims = dims, vals = {}, has = {}, mad = {} }
table.insert(layer.maps, m)
return m
end
local function readVmap(r: Bytes.Reader, layer: Layer, perPoly: boolean, ptBase: number, polyBase: number, skipped: { [string]: number })
local typ = id4(r)
local dims = r:u16be()
local name = s0(r)
local kind = MAP_KINDS[typ]
if r.err or not kind then
skipped["VMAP." .. typ] = (skipped["VMAP." .. typ] or 0) + 1
return
end
local want = if kind == "uv" then 2 elseif kind == "color" then 4 elseif kind == "weight" then 1 else 3
if dims < 1 or dims > 16 or (kind ~= "color" and dims < want) or (kind == "color" and dims < 3) then
skipped["VMAP." .. typ] = (skipped["VMAP." .. typ] or 0) + 1
return
end
local m = findMap(layer, kind, name, want)
local npts = #layer.pts // 3
local npolys = #layer.polys
local vals, has, mad = m.vals, m.has, m.mad
while r:remaining() >= 2 do
local p = vx(r) + ptBase
local f = if perPoly then vx(r) + polyBase else -1
local v = table.create(want, 1)
for c = 1, dims do
local x = r:f32be()
if c <= want then
v[c] = x
end
end
if r.err then
break
end
if p < npts then
if perPoly then
if f < npolys then
local row = mad[f]
if not row then
row = {}
mad[f] = row
end
row[p] = v
end
else
has[p] = true
for c = 1, want do
vals[p * want + c] = v[c]
end
end
end
end
end
local function readPtag(r: Bytes.Reader, layer: Layer, polyBase: number)
local typ = id4(r)
if typ ~= "SURF" and typ ~= "MATR" then
return
end
local polys = layer.polys
while r:remaining() >= 4 do
local f = vx(r) + polyBase
local tag = r:u16be()
if r.err then
break
end
local poly = polys[f + 1]
if poly then
poly.surf = tag
end
end
end
-- ------------------------------------------------------------------------------------------------ surfaces
local function newSurface(name: string): Surface
return { name = name, values = {}, color = { 0.78, 0.78, 0.78 }, side = 1, vcol = nil, blocks = {}, source = nil }
end
local SURF_VALUES = { DIFF = true, LUMI = true, SPEC = true, REFL = true, TRAN = true, TRNL = true, GLOS = true, BUMP = true, SMAN = true, RIND = true }
local function readBlock(r: Bytes.Reader, surf: Surface)
-- the header sub-chunk: IMAP / PROC / GRAD / SHDR, ordinal string, header sub-chunks
if r:remaining() < 6 then
return
end
local kind = id4(r)
local hn = r:u16be()
local hend = math.min(r.pos + hn, r.limit)
local blk: Block = { kind = kind, ordinal = "", channel = "COLR", enabled = true, opacity = 1 }
local hr = Bytes.reader(r.buf, r.pos, hend - r.pos)
blk.ordinal = s0(hr)
subchunks(r.buf, hr.pos, hend, function(id: string, sr: Bytes.Reader)
if id == "CHAN" then
blk.channel = id4(sr)
elseif id == "ENAB" then
blk.enabled = sr:u16be() ~= 0
elseif id == "OPAC" then
sr:u16be()
blk.opacity = sr:f32be()
elseif id == "NEGA" then
blk.negative = sr:u16be() ~= 0
elseif id == "AXIS" then
blk.axis = sr:u16be()
end
end)
subchunks(r.buf, hend + (hn % 2), r.limit, function(id: string, sr: Bytes.Reader)
if id == "PROJ" then
blk.projection = sr:u16be()
elseif id == "AXIS" then
blk.axis = sr:u16be()
elseif id == "IMAG" then
blk.clip = vx(sr)
elseif id == "VMAP" then
blk.uvmap = s0(sr)
elseif id == "WRAP" then
blk.wrap = { sr:u16be(), sr:u16be() }
end
end)
table.insert(surf.blocks, blk)
end
local function readSurface(r: Bytes.Reader, surfaces: { Surface })
local name = s0(r)
local source = s0(r)
local surf = newSurface(name)
if source ~= "" then
for _, s in surfaces do
if s.name == source then
surf.values = table.clone(s.values)
surf.color = table.clone(s.color)
surf.side = s.side
surf.vcol = s.vcol
surf.blocks = table.clone(s.blocks)
break
end
end
surf.source = source
end
subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader)
if id == "COLR" then
local c = { sr:f32be(), sr:f32be(), sr:f32be() }
if not sr.err then
surf.color = c
end
elseif SURF_VALUES[id] then
local v = sr:f32be()
if not sr.err then
surf.values[id] = v
end
elseif id == "SIDE" then
surf.side = sr:u16be()
elseif id == "VCOL" then
local intensity = sr:f32be()
vx(sr)
local kind = id4(sr)
local vname = s0(sr)
if not sr.err then
surf.vcol = { name = vname, kind = kind, intensity = intensity }
end
elseif id == "BLOK" then
readBlock(sr, surf)
end
end)
table.insert(surfaces, surf)
end
-- LWOB surfaces: U2 percentages (256 = 100%), V* floats, texture sub-chunks
local B_VALUES = { DIFF = "DIFF", LUMI = "LUMI", SPEC = "SPEC", REFL = "REFL", TRAN = "TRAN" }
local B_FLOATS = { VDIF = "DIFF", VLUM = "LUMI", VSPC = "SPEC", VRFL = "REFL", VTRN = "TRAN" }
local B_TEX = { CTEX = "COLR", DTEX = "DIFF", STEX = "SPEC", RTEX = "REFL", TTEX = "TRAN", LTEX = "LUMI", BTEX = "BUMP" }
local B_PROJ: { [string]: number } = { Planar = 0, Cylindrical = 1, Spherical = 2, Cubic = 3, Front = 4 }
local function readSurfaceB(r: Bytes.Reader, surfaces: { Surface })
local surf = newSurface(s0(r))
local tex: Block? = nil
subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader)
if id == "COLR" then
local c = { sr:u8() / 255, sr:u8() / 255, sr:u8() / 255 }
if not sr.err then
surf.color = c
end
elseif B_VALUES[id] then
local v = sr:u16be()
if not sr.err and surf.values[B_VALUES[id] .. "!"] == nil then
surf.values[B_VALUES[id]] = v / 256
end
elseif B_FLOATS[id] then
local v = sr:f32be()
if not sr.err then
surf.values[B_FLOATS[id]] = v
surf.values[B_FLOATS[id] .. "!"] = 1 -- a float value wins over the U2 one
end
elseif id == "GLOS" then
local v = sr:u16be()
if not sr.err then
-- 16, 64, 256, 1024 = low .. very high: as LWO2's 0..1 glossiness
surf.values.GLOS = math.clamp(math.log(math.max(v, 1), 2) / 10, 0, 1)
end
elseif id == "SMAN" then
surf.values.SMAN = sr:f32be()
elseif id == "FLAG" then
local fl = sr:u16be()
if bit32.band(fl, 0x100) ~= 0 then
surf.side = 3
end
elseif B_TEX[id] then
local desc = sr:cstring()
local proj: number? = nil
for word, v in B_PROJ do
if string.find(desc, word, 1, true) then
proj = v
end
end
local blk: Block = { kind = if string.find(desc, "Image Map", 1, true) then "TEX" else "PROC", ordinal = tostring(#surf.blocks + 1), channel = B_TEX[id], enabled = true, opacity = 1, projection = proj }
table.insert(surf.blocks, blk)
tex = blk
elseif id == "TIMG" and tex then
local path = sr:cstring()
if path ~= "" and path ~= "(none)" then
tex.file = path
end
elseif id == "TFLG" and tex then
local fl = sr:u16be()
tex.axis = if bit32.band(fl, 1) ~= 0 then 0 elseif bit32.band(fl, 2) ~= 0 then 1 else 2
tex.negative = bit32.band(fl, 16) ~= 0
elseif id == "TVAL" and tex then
tex.opacity = sr:u16be() / 256
end
end)
for k in surf.values do
if string.sub(k, -1) == "!" then
surf.values[k] = nil
end
end
table.insert(surfaces, surf)
end
local function readClip(r: Bytes.Reader, clips: { [number]: string }, refs: { [number]: number })
local index = r:u32be()
if r.err then
return
end
subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader)
if id == "STIL" then
clips[index] = s0(sr)
elseif id == "ISEQ" then
local digits = sr:u8()
sr:u8()
local offset = sr:i16be()
sr:u16be()
local start = sr:i16be()
sr:u16be()
local prefix = s0(sr)
local suffix = s0(sr)
if not sr.err then
clips[index] = prefix .. string.format("%0" .. math.clamp(digits, 1, 9) .. "d", offset + start) .. suffix
end
elseif id == "XREF" then
refs[index] = sr:u32be()
end
end)
end
-- ------------------------------------------------------------------------------------------------ the file
-- parse(buf, from, limit, opts) -> Model | nil, message
function Parse.model(buf: buffer, from: number, limit: number, maxCorners: number): (Model?, string?)
local version = buffer.readstring(buf, from + 8, 4)
local declared = bit32.byteswap(buffer.readu32(buf, from + 4))
local e = math.min(limit, from + 8 + declared)
local model: Model = { version = version, tags = {}, layers = {}, surfaces = {}, clips = {}, skipped = {}, corners = 0 }
local layer = newLayer(0)
layer.implicit = true
table.insert(model.layers, layer)
local ptBase, polyBase = 0, 0
local budget = { maxCorners }
local refs: { [number]: number } = {}
local lwob = version == "LWOB"
local list = Chunks.walk(buf, from + 12, e, Chunks.IFF)
for _, c in list do
local id = c.id
local r = Bytes.reader(buf, c.offset, c.avail)
local err: string? = nil
if id == "TAGS" or id == "SRFS" then
while r:remaining() > 0 do
table.insert(model.tags, s0(r))
end
elseif id == "LAYR" and not lwob then
local index = r:u16be()
r:u16be() -- flags (hidden)
local px, py, pz = r:f32be(), r:f32be(), r:f32be()
local name = s0(r)
local parent: number? = if r:remaining() >= 2 then r:u16be() else nil
if r.err then
return nil, "truncated LAYR chunk"
end
if layer.implicit and #layer.pts == 0 and #layer.polys == 0 then
table.remove(model.layers, #model.layers)
end
layer = newLayer(index)
layer.name = name
layer.parent = if parent == 0xFFFF then nil else parent
layer.pivot = { px, py, pz }
table.insert(model.layers, layer)
ptBase, polyBase = 0, 0
elseif id == "PNTS" then
ptBase = #layer.pts // 3
err = readPoints(r, layer, maxCorners)
elseif id == "POLS" then
polyBase = #layer.polys
if lwob then
err = readPolysB(r, layer, budget)
else
local kind = id4(r)
if kind == "FACE" or kind == "PTCH" or kind == "SUBD" then
err = readPolys(r, layer, kind, ptBase, budget)
else
-- keep the polygon numbering (PTAG / VMAD refer to it) but skip the geometry
local before = #layer.polys
err = readPolys(r, layer, kind, ptBase, budget)
model.skipped[kind] = (model.skipped[kind] or 0) + #layer.polys - before
end
end
elseif id == "VMAP" or id == "VMAD" then
readVmap(r, layer, id == "VMAD", ptBase, polyBase, model.skipped)
elseif id == "PTAG" then
readPtag(r, layer, polyBase)
elseif id == "SURF" then
if lwob then
readSurfaceB(r, model.surfaces)
else
readSurface(r, model.surfaces)
end
elseif id == "CLIP" then
readClip(r, model.clips, refs)
end
if err then
return nil, err
end
end
for index, target in refs do
if model.clips[index] == nil and model.clips[target] then
model.clips[index] = model.clips[target]
end
end
model.corners = maxCorners - budget[1]
return model, nil
end
return Parse