rename: src/Formats -> src/Rosetta, @formats -> @rosetta requires, build/luajit/rosetta + rosetta._compat, build/roblox/Rosetta, ROSETTA_* env/globals, writer vendor strings
This commit is contained in:
1 parent
2956576d7f
commit
22ddcd78fa
941 files changed
+3364
-3364
No files matched your search
@@ -0,0 +1,479 @@
|
||||
--!strict
|
||||
-- codecs/model/Draco/Attributes: Draco attribute decoding. The attributes decoders (one per connectivity: linear
|
||||
-- sequencer for sequential meshes and point clouds, traversal sequencers for Edgebreaker), their attribute
|
||||
-- descriptors, and the sequential attribute decoders: generic (raw values), integer, quantization (dequantized to
|
||||
-- f32 exactly like the C++) and octahedral normals; prediction through codecs/model/Draco/Predict. Bitstream
|
||||
-- versions 1.0 - 2.2. Ported from Google's Draco 1.5.7 (compression/attributes/*, compression/point_cloud/
|
||||
-- point_cloud_decoder.cc, attributes/attribute_quantization_transform.cc, attribute_octahedron_transform.cc;
|
||||
-- Apache-2.0, licenses/draco-LICENSE.txt).
|
||||
local Reader = require("@rosetta/codecs/model/Draco/Reader")
|
||||
local Connectivity = require("@rosetta/codecs/model/Draco/Connectivity")
|
||||
local Predict = require("@rosetta/codecs/model/Draco/Predict")
|
||||
local KdTree = require("@rosetta/codecs/model/Draco/KdTree")
|
||||
|
||||
local Attributes = {}
|
||||
|
||||
type D = Reader.D
|
||||
|
||||
-- data type ids (draco::DataType) -> byte length
|
||||
local DT_LENGTH = { [1] = 1, [2] = 1, [3] = 2, [4] = 2, [5] = 4, [6] = 4, [7] = 8, [8] = 8, [9] = 4, [10] = 8, [11] = 1 }
|
||||
Attributes.DT_LENGTH = DT_LENGTH
|
||||
|
||||
export type Attr = {
|
||||
id: number, -- 0-based attribute id
|
||||
type: number, -- GeometryAttribute::Type (0 POSITION, 1 NORMAL, 2 COLOR, 3 TEX_COORD, 4 GENERIC, 5.. transcoder types)
|
||||
dataType: number,
|
||||
comps: number,
|
||||
normalized: boolean,
|
||||
uniqueId: number,
|
||||
seqType: number, -- 0 generic, 1 integer, 2 quantization, 3 normals
|
||||
map: { number }?, -- point -> value (0-based values at [point + 1]); nil = identity
|
||||
numValues: number,
|
||||
portable: { number }?, -- the integer (portable) values
|
||||
values: { number }?, -- the final values (numbers), flat
|
||||
raw: buffer?, -- generic attributes: the raw values
|
||||
quant: { min: { number }, range: number, bits: number }?,
|
||||
octBits: number?,
|
||||
scheme: Predict.Scheme?,
|
||||
}
|
||||
|
||||
type Decoder = {
|
||||
attrs: { Attr },
|
||||
traversal: { ct: Connectivity.CT, enc: Connectivity.Enc, method: number }?,
|
||||
md: Predict.MeshData?,
|
||||
points: { number }?,
|
||||
}
|
||||
|
||||
-- the geometry the attributes decode against
|
||||
export type Geom = { numPoints: number, mesh: Connectivity.Mesh?, edgebreaker: boolean, kdTree: boolean }
|
||||
|
||||
local function zigzag(v: number): number
|
||||
if v % 2 == 1 then
|
||||
return -(v // 2) - 1
|
||||
end
|
||||
return v // 2
|
||||
end
|
||||
|
||||
-- the parent (position) getter for a scheme: portable integers from 2.0 on, the final values before (truncated to
|
||||
-- integers unless the scheme works in floats)
|
||||
local function parentGetter(ver: number, pos: Attr, floats: boolean): Predict.Parent?
|
||||
local old = ver < 0x0200
|
||||
local vals = if old then pos.values else pos.portable
|
||||
if not vals or pos.comps ~= 3 or (not old and pos.seqType == 3) then
|
||||
return nil
|
||||
end
|
||||
local map = pos.map
|
||||
local trunc = old and not floats
|
||||
return function(point: number): (number, number, number)
|
||||
local e = if map then (map[point + 1] or 0) else point
|
||||
local o = e * 3
|
||||
local x, y, z = vals[o + 1] or 0, vals[o + 2] or 0, vals[o + 3] or 0
|
||||
if trunc then
|
||||
x = if x < 0 then math.ceil(x) else math.floor(x)
|
||||
y = if y < 0 then math.ceil(y) else math.floor(y)
|
||||
z = if z < 0 then math.ceil(z) else math.floor(z)
|
||||
end
|
||||
return x, y, z
|
||||
end
|
||||
end
|
||||
|
||||
local function decodeIntegerValues(d: D, a: Attr, points: { number }, scheme: Predict.Scheme?): (boolean, string?)
|
||||
local comps = if a.seqType == 3 then 2 else a.comps
|
||||
local n = #points
|
||||
local numValues = n * comps
|
||||
if n == 0 then
|
||||
return false, "no values"
|
||||
end
|
||||
local compressed = Reader.u8(d)
|
||||
if d.bad then
|
||||
return false, d.bad
|
||||
end
|
||||
local vals: { number }
|
||||
if compressed > 0 then
|
||||
local s = Reader.symbols(d, numValues, comps)
|
||||
if not s then
|
||||
return false, d.bad or "bad values"
|
||||
end
|
||||
vals = s
|
||||
else
|
||||
local nb = Reader.u8(d)
|
||||
if d.bad then
|
||||
return false, d.bad
|
||||
end
|
||||
if nb < 1 or nb > 4 then
|
||||
return false, "bad value byte count"
|
||||
end
|
||||
if Reader.remaining(d) < nb * numValues then
|
||||
return false, "truncated values"
|
||||
end
|
||||
vals = table.create(numValues, 0)
|
||||
local b, p = d.b, d.pos
|
||||
if nb == 4 then
|
||||
for i = 1, numValues do
|
||||
vals[i] = buffer.readu32(b, p)
|
||||
p += 4
|
||||
end
|
||||
elseif nb == 1 then
|
||||
for i = 1, numValues do
|
||||
vals[i] = buffer.readu8(b, p)
|
||||
p += 1
|
||||
end
|
||||
elseif nb == 2 then
|
||||
for i = 1, numValues do
|
||||
vals[i] = buffer.readu16(b, p)
|
||||
p += 2
|
||||
end
|
||||
else
|
||||
for i = 1, numValues do
|
||||
vals[i] = buffer.readu16(b, p) + buffer.readu8(b, p + 2) * 65536
|
||||
p += 3
|
||||
end
|
||||
end
|
||||
d.pos = p
|
||||
end
|
||||
if not scheme or not scheme.tr.positive then
|
||||
for i = 1, numValues do
|
||||
vals[i] = zigzag(vals[i])
|
||||
end
|
||||
else
|
||||
local i32 = Predict.i32
|
||||
for i = 1, numValues do
|
||||
vals[i] = i32(vals[i])
|
||||
end
|
||||
end
|
||||
if scheme then
|
||||
if not Predict.decodeData(scheme, d) then
|
||||
return false, d.bad or "bad prediction data"
|
||||
end
|
||||
local ok, err = Predict.compute(scheme, vals, n, comps, points)
|
||||
if not ok then
|
||||
return false, err
|
||||
end
|
||||
end
|
||||
a.portable = vals
|
||||
a.numValues = n
|
||||
return true, nil
|
||||
end
|
||||
|
||||
local function decodeQuantInfo(d: D, a: Attr): boolean
|
||||
local mins = table.create(a.comps, 0)
|
||||
for c = 1, a.comps do
|
||||
mins[c] = Reader.f32(d)
|
||||
end
|
||||
local range = Reader.f32(d)
|
||||
local bits = Reader.u8(d)
|
||||
if d.bad or bits < 1 or bits > 30 then
|
||||
return false
|
||||
end
|
||||
a.quant = { min = mins, range = range, bits = bits }
|
||||
return true
|
||||
end
|
||||
|
||||
-- StoreValues: integer -> the data type; quantized -> f32; octahedral -> unit vectors
|
||||
local function storeValues(a: Attr): (boolean, string?)
|
||||
local src = a.portable :: { number }
|
||||
local n = a.numValues
|
||||
local fround = Predict.fround
|
||||
if a.seqType == 1 then
|
||||
local dt = a.dataType
|
||||
local out = table.create(n * a.comps, 0)
|
||||
for i = 1, n * a.comps do
|
||||
local v = src[i]
|
||||
if dt == 1 then
|
||||
v = (v + 128) % 256 - 128
|
||||
elseif dt == 2 or dt == 11 then
|
||||
v %= 256
|
||||
elseif dt == 3 then
|
||||
v = (v + 32768) % 65536 - 32768
|
||||
elseif dt == 4 then
|
||||
v %= 65536
|
||||
elseif dt == 6 then
|
||||
v %= 4294967296
|
||||
elseif dt ~= 5 then
|
||||
return false, "unsupported: integer attribute of data type " .. dt
|
||||
end
|
||||
out[i] = v
|
||||
end
|
||||
a.values = out
|
||||
elseif a.seqType == 2 then
|
||||
local q = a.quant
|
||||
if not q then
|
||||
return false, "no quantization data"
|
||||
end
|
||||
local maxQ = 2 ^ q.bits - 1
|
||||
local delta = fround(q.range / fround(maxQ))
|
||||
local comps = a.comps
|
||||
local mins = q.min
|
||||
local out = table.create(n * comps, 0)
|
||||
local k = 1
|
||||
for _ = 1, n do
|
||||
for c = 1, comps do
|
||||
out[k] = fround(fround(fround(src[k]) * delta) + mins[c])
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
a.values = out
|
||||
elseif a.seqType == 3 then
|
||||
local o = Predict.octahedron(a.octBits or 0)
|
||||
if not o then
|
||||
return false, "bad normal quantization"
|
||||
end
|
||||
local out = table.create(n * 3, 0)
|
||||
for i = 0, n - 1 do
|
||||
local x, y, z = Predict.octToVector(o, src[i * 2 + 1], src[i * 2 + 2])
|
||||
out[i * 3 + 1], out[i * 3 + 2], out[i * 3 + 3] = x, y, z
|
||||
end
|
||||
a.values = out
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- decodes every attribute; returns them in attribute id order
|
||||
function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?)
|
||||
local ver = d.ver
|
||||
local numDecoders = Reader.u8(d)
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
local mesh = g.mesh
|
||||
local decoders: { Decoder } = {}
|
||||
for i = 0, numDecoders - 1 do
|
||||
local dec: Decoder = { attrs = {}, traversal = nil, md = nil, points = nil }
|
||||
if g.edgebreaker and mesh then
|
||||
local attDataId = Reader.i8(d)
|
||||
local decoderType = Reader.u8(d)
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
local ad = nil
|
||||
if attDataId >= 0 then
|
||||
ad = mesh.attrData[attDataId + 1]
|
||||
if not ad or ad.decoderId >= 0 then
|
||||
return nil, "bad attribute data id"
|
||||
end
|
||||
ad.decoderId = i
|
||||
else
|
||||
if mesh.posDecoderId >= 0 then
|
||||
return nil, "two position decoders"
|
||||
end
|
||||
mesh.posDecoderId = i
|
||||
end
|
||||
local method = 0
|
||||
if ver >= 0x0102 then
|
||||
method = Reader.u8(d)
|
||||
if d.bad or method >= 2 then
|
||||
return nil, "bad traversal method"
|
||||
end
|
||||
end
|
||||
local ct = mesh.ct :: Connectivity.CT
|
||||
local enc
|
||||
if decoderType == 0 then
|
||||
if ad then
|
||||
enc = ad.enc
|
||||
ad.used = false
|
||||
else
|
||||
enc = mesh.posEnc :: Connectivity.Enc
|
||||
end
|
||||
dec.traversal = { ct = ct, enc = enc, method = method }
|
||||
else
|
||||
if method ~= 0 or not ad then
|
||||
return nil, "bad corner attribute decoder"
|
||||
end
|
||||
local cad = ad :: Connectivity.AttrData
|
||||
enc = cad.enc
|
||||
dec.traversal = { ct = cad.ct :: Connectivity.CT, enc = enc, method = 0 }
|
||||
end
|
||||
-- prediction data: the attribute's own corner table when its seams are in use
|
||||
local pct = if ad and ad.used then ad.ct :: Connectivity.CT else ct
|
||||
dec.md = { ct = pct, e2c = enc.e2c, v2e = enc.v2e }
|
||||
end
|
||||
decoders[i + 1] = dec
|
||||
end
|
||||
-- the attribute descriptors
|
||||
local all: { Attr } = {}
|
||||
for _, dec in decoders do
|
||||
local n = Reader.count(d, 0x0200)
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
if n == 0 or n > 5 * Reader.remaining(d) then
|
||||
return nil, "bad attribute count"
|
||||
end
|
||||
for _ = 1, n do
|
||||
local attType, dataType, comps, normalized = Reader.u8(d), Reader.u8(d), Reader.u8(d), Reader.u8(d)
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
if attType >= 9 or dataType == 0 or dataType >= 12 or comps == 0 then
|
||||
return nil, "bad attribute descriptor"
|
||||
end
|
||||
local uniqueId = if ver < 0x0103 then Reader.u16(d) else Reader.varint(d)
|
||||
local a: Attr = {
|
||||
id = #all,
|
||||
type = attType,
|
||||
dataType = dataType,
|
||||
comps = comps,
|
||||
normalized = normalized > 0,
|
||||
uniqueId = uniqueId,
|
||||
seqType = 0,
|
||||
map = nil,
|
||||
numValues = 0,
|
||||
}
|
||||
table.insert(all, a)
|
||||
table.insert(dec.attrs, a)
|
||||
end
|
||||
for _, a in (if g.kdTree then {} else dec.attrs) do
|
||||
local t = Reader.u8(d)
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
if t > 3 then
|
||||
return nil, "unknown attribute decoder " .. t
|
||||
end
|
||||
if (t == 2 or t == 3) and a.dataType ~= 9 then
|
||||
return nil, "quantized attribute is not f32"
|
||||
end
|
||||
if t == 3 and a.comps ~= 3 then
|
||||
return nil, "normal attribute without 3 components"
|
||||
end
|
||||
a.seqType = t
|
||||
end
|
||||
end
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
local function named(t: number): Attr?
|
||||
for _, a in all do
|
||||
if a.type == t then
|
||||
return a
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
-- decode
|
||||
for _, dec in decoders do
|
||||
if g.kdTree then
|
||||
local ok, err = KdTree.decode(d, dec.attrs, g.numPoints)
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
continue
|
||||
end
|
||||
local points: { number }
|
||||
local trav = dec.traversal
|
||||
if trav then
|
||||
local faces = (mesh :: Connectivity.Mesh).faces
|
||||
local p = Connectivity.traverse(trav.ct, faces, trav.enc, trav.method)
|
||||
if not p then
|
||||
return nil, "bad attribute traversal"
|
||||
end
|
||||
points = p
|
||||
local numPoints = (mesh :: Connectivity.Mesh).numPoints
|
||||
for _, a in dec.attrs do
|
||||
local m = Connectivity.mapping(trav.ct, faces, trav.enc, numPoints)
|
||||
if not m then
|
||||
return nil, "bad attribute mapping"
|
||||
end
|
||||
a.map = m
|
||||
end
|
||||
else
|
||||
points = table.create(g.numPoints, 0)
|
||||
for i = 1, g.numPoints do
|
||||
points[i] = i - 1
|
||||
end
|
||||
end
|
||||
dec.points = points
|
||||
-- portable values
|
||||
for _, a in dec.attrs do
|
||||
if a.seqType == 0 then
|
||||
local stride = DT_LENGTH[a.dataType] * a.comps
|
||||
local size = #points * stride
|
||||
if Reader.remaining(d) < size then
|
||||
return nil, "truncated attribute values"
|
||||
end
|
||||
local raw = buffer.create(size)
|
||||
buffer.copy(raw, 0, d.b, d.pos, size)
|
||||
d.pos += size
|
||||
a.raw = raw
|
||||
a.numValues = #points
|
||||
continue
|
||||
end
|
||||
local psm = Reader.i8(d)
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
if psm < -2 or psm >= 7 then
|
||||
return nil, "bad prediction scheme"
|
||||
end
|
||||
local scheme: Predict.Scheme? = nil
|
||||
if psm ~= -2 then
|
||||
local ptt = Reader.i8(d)
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
if ptt < -1 or ptt >= 4 then
|
||||
return nil, "bad prediction transform"
|
||||
end
|
||||
if a.seqType == 3 then
|
||||
if ptt == 2 or ptt == 3 then
|
||||
scheme = Predict.new(psm, Predict.transform(ptt), dec.md)
|
||||
end
|
||||
elseif ptt == 1 then
|
||||
scheme = Predict.new(psm, Predict.transform(1), dec.md)
|
||||
end
|
||||
end
|
||||
if scheme and Predict.needsParent(scheme) then
|
||||
local pos = named(0)
|
||||
local getter = pos and parentGetter(ver, pos, scheme.method == 3)
|
||||
if not getter then
|
||||
return nil, "prediction needs the decoded positions"
|
||||
end
|
||||
scheme.parent = getter
|
||||
end
|
||||
if ver < 0x0200 then
|
||||
if a.seqType == 2 and not decodeQuantInfo(d, a) then
|
||||
return nil, d.bad or "bad quantization data"
|
||||
elseif a.seqType == 3 then
|
||||
a.octBits = Reader.u8(d)
|
||||
end
|
||||
end
|
||||
local ok, err = decodeIntegerValues(d, a, points, scheme)
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
a.scheme = scheme
|
||||
if ver < 0x0200 then
|
||||
local ok2, err2 = storeValues(a)
|
||||
if not ok2 then
|
||||
return nil, err2
|
||||
end
|
||||
end
|
||||
end
|
||||
-- data needed by the transforms
|
||||
if ver >= 0x0200 then
|
||||
for _, a in dec.attrs do
|
||||
if a.seqType == 2 then
|
||||
if not decodeQuantInfo(d, a) then
|
||||
return nil, d.bad or "bad quantization data"
|
||||
end
|
||||
elseif a.seqType == 3 then
|
||||
a.octBits = Reader.u8(d)
|
||||
end
|
||||
end
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
for _, a in dec.attrs do
|
||||
if a.seqType ~= 0 then
|
||||
local ok, err = storeValues(a)
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return all, nil
|
||||
end
|
||||
|
||||
return Attributes
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,156 @@
|
||||
--!strict
|
||||
-- codecs/model/Draco/Int64: the 64-bit integer arithmetic Draco's portable tex coord predictor relies on (int64 /
|
||||
-- uint64 with wrap-around, truncating division, IntSqrt), on (hi, lo) pairs of 32-bit halves held in numbers (both
|
||||
-- runtimes: no native 64-bit integers). Two's complement: hi >= 2^31 is negative when read as signed.
|
||||
local Int64 = {}
|
||||
|
||||
local P32 = 4294967296
|
||||
local P31 = 2147483648
|
||||
|
||||
function Int64.from(n: number): (number, number)
|
||||
if n >= 0 then
|
||||
return (n // P32) % P32, n % P32
|
||||
end
|
||||
local h, l = Int64.from(-n)
|
||||
return Int64.neg(h, l)
|
||||
end
|
||||
|
||||
function Int64.neg(h: number, l: number): (number, number)
|
||||
if l == 0 then
|
||||
return (P32 - h) % P32, 0
|
||||
end
|
||||
return P32 - 1 - h, P32 - l
|
||||
end
|
||||
|
||||
function Int64.add(ah: number, al: number, bh: number, bl: number): (number, number)
|
||||
local l = al + bl
|
||||
local c = 0
|
||||
if l >= P32 then
|
||||
l -= P32
|
||||
c = 1
|
||||
end
|
||||
return (ah + bh + c) % P32, l
|
||||
end
|
||||
|
||||
function Int64.sub(ah: number, al: number, bh: number, bl: number): (number, number)
|
||||
local nh, nl = Int64.neg(bh, bl)
|
||||
return Int64.add(ah, al, nh, nl)
|
||||
end
|
||||
|
||||
-- the product mod 2^64 (the same bits for signed and unsigned operands)
|
||||
function Int64.mul(ah: number, al: number, bh: number, bl: number): (number, number)
|
||||
local a0, a1, a2, a3 = al % 65536, al // 65536, ah % 65536, ah // 65536
|
||||
local b0, b1, b2, b3 = bl % 65536, bl // 65536, bh % 65536, bh // 65536
|
||||
local c0 = a0 * b0
|
||||
local c1 = a1 * b0 + a0 * b1
|
||||
local c2 = a2 * b0 + a1 * b1 + a0 * b2
|
||||
local c3 = a3 * b0 + a2 * b1 + a1 * b2 + a0 * b3
|
||||
local lo = c0 + (c1 % 65536) * 65536
|
||||
local carry = lo // P32
|
||||
lo %= P32
|
||||
local hi = (c1 // 65536 + c2 + (c3 % 65536) * 65536 + carry) % P32
|
||||
return hi, lo
|
||||
end
|
||||
|
||||
function Int64.isNeg(h: number): boolean
|
||||
return h >= P31
|
||||
end
|
||||
|
||||
-- the signed value as a number (exact below 2^53 in magnitude)
|
||||
function Int64.signed(h: number, l: number): number
|
||||
if h >= P31 then
|
||||
return (h - P32) * P32 + l
|
||||
end
|
||||
return h * P32 + l
|
||||
end
|
||||
|
||||
-- the unsigned value as a number (rounded past 2^53)
|
||||
function Int64.unsigned(h: number, l: number): number
|
||||
return h * P32 + l
|
||||
end
|
||||
|
||||
-- unsigned compare: -1, 0, 1
|
||||
function Int64.ucmp(ah: number, al: number, bh: number, bl: number): number
|
||||
if ah ~= bh then
|
||||
return if ah < bh then -1 else 1
|
||||
end
|
||||
if al ~= bl then
|
||||
return if al < bl then -1 else 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- signed compare: -1, 0, 1
|
||||
function Int64.cmp(ah: number, al: number, bh: number, bl: number): number
|
||||
local sa = if ah >= P31 then ah - P32 else ah
|
||||
local sb = if bh >= P31 then bh - P32 else bh
|
||||
if sa ~= sb then
|
||||
return if sa < sb then -1 else 1
|
||||
end
|
||||
return Int64.ucmp(0, al, 0, bl)
|
||||
end
|
||||
|
||||
-- unsigned division (b ~= 0): quotient, remainder
|
||||
function Int64.udivmod(ah: number, al: number, bh: number, bl: number): (number, number, number, number)
|
||||
if ah == 0 and bh == 0 then
|
||||
return 0, al // bl, 0, al % bl
|
||||
end
|
||||
local qh, ql, rh, rl = 0, 0, 0, 0
|
||||
for i = 63, 0, -1 do
|
||||
-- r = r * 2 + bit i of a
|
||||
local bit = if i >= 32 then (ah // 2 ^ (i - 32)) % 2 else (al // 2 ^ i) % 2
|
||||
local over = rh >= P31
|
||||
rh = (rh * 2 + rl // P31) % P32
|
||||
rl = (rl * 2) % P32 + bit
|
||||
if over or Int64.ucmp(rh, rl, bh, bl) >= 0 then
|
||||
rh, rl = Int64.sub(rh, rl, bh, bl)
|
||||
if i >= 32 then
|
||||
qh += 2 ^ (i - 32)
|
||||
else
|
||||
ql += 2 ^ i
|
||||
end
|
||||
end
|
||||
end
|
||||
return qh, ql, rh, rl
|
||||
end
|
||||
|
||||
-- signed division truncating toward zero (b ~= 0)
|
||||
function Int64.div(ah: number, al: number, bh: number, bl: number): (number, number)
|
||||
local na, nb = ah >= P31, bh >= P31
|
||||
if na then
|
||||
ah, al = Int64.neg(ah, al)
|
||||
end
|
||||
if nb then
|
||||
bh, bl = Int64.neg(bh, bl)
|
||||
end
|
||||
local qh, ql = Int64.udivmod(ah, al, bh, bl)
|
||||
if na ~= nb then
|
||||
return Int64.neg(qh, ql)
|
||||
end
|
||||
return qh, ql
|
||||
end
|
||||
|
||||
-- IntSqrt (draco/core/math_utils.h) on a uint64, step for step (wrap-around included)
|
||||
function Int64.isqrt(h: number, l: number): (number, number)
|
||||
if h == 0 and l == 0 then
|
||||
return 0, 0
|
||||
end
|
||||
local acth, actl = h, l
|
||||
local sh, sl = 0, 1
|
||||
while Int64.ucmp(acth, actl, 0, 2) >= 0 do
|
||||
sh, sl = Int64.add(sh, sl, sh, sl)
|
||||
acth, actl = Int64.udivmod(acth, actl, 0, 4)
|
||||
end
|
||||
repeat
|
||||
local qh, ql = Int64.udivmod(h, l, sh, sl)
|
||||
local th, tl = Int64.add(sh, sl, qh, ql)
|
||||
sh, sl = Int64.udivmod(th, tl, 0, 2)
|
||||
if sh == 0 and sl == 0 then
|
||||
return 0, 0
|
||||
end
|
||||
local pph, ppl = Int64.mul(sh, sl, sh, sl)
|
||||
until Int64.ucmp(pph, ppl, h, l) <= 0
|
||||
return sh, sl
|
||||
end
|
||||
|
||||
return Int64
|
||||
@@ -0,0 +1,363 @@
|
||||
--!strict
|
||||
-- codecs/model/Draco/KdTree: kd-tree coded point cloud attributes (bitstream 2.3): DynamicIntegerPointsKdTreeDecoder
|
||||
-- at compression levels 0 - 6 (direct bits, rANS bits, folded 32-bit rANS numbers, selected axes) over all the
|
||||
-- attributes of a decoder at once, then the signed offsets and the dequantization of f32 attributes. Ported from
|
||||
-- Google's Draco 1.5.7 (compression/attributes/kd_tree_attributes_decoder.cc, compression/point_cloud/algorithms/
|
||||
-- dynamic_integer_points_kd_tree_decoder.h, compression/bit_coders/{direct,folded_integer}_bit_decoder; Apache-2.0,
|
||||
-- licenses/draco-LICENSE.txt). The pre-2.3 kd-tree layouts are not supported.
|
||||
local Reader = require("@rosetta/codecs/model/Draco/Reader")
|
||||
local Predict = require("@rosetta/codecs/model/Draco/Predict")
|
||||
|
||||
local KdTree = {}
|
||||
|
||||
type D = Reader.D
|
||||
|
||||
-- a bit source: next() -> 0 / 1, bits(n) -> value (MSB first); bits returns nil when a direct decoder runs out
|
||||
type Src = { next: () -> number, bits: (n: number) -> number? }
|
||||
|
||||
local function direct(d: D): Src?
|
||||
local size = Reader.u32(d)
|
||||
if d.bad or size == 0 or size % 4 ~= 0 or size > Reader.remaining(d) then
|
||||
Reader.fail(d, "kd-tree: bad direct bits")
|
||||
return nil
|
||||
end
|
||||
local b, base, words = d.b, d.pos, size // 4
|
||||
d.pos += size
|
||||
local pos, used = 0, 0
|
||||
return {
|
||||
next = function(): number
|
||||
if pos >= words then
|
||||
return 0
|
||||
end
|
||||
local w = buffer.readu32(b, base + pos * 4)
|
||||
local bit = bit32.extract(w, 31 - used)
|
||||
used += 1
|
||||
if used == 32 then
|
||||
pos += 1
|
||||
used = 0
|
||||
end
|
||||
return bit
|
||||
end,
|
||||
bits = function(n: number): number?
|
||||
local remaining = 32 - used
|
||||
if n <= remaining then
|
||||
if pos >= words then
|
||||
return nil
|
||||
end
|
||||
local w = buffer.readu32(b, base + pos * 4)
|
||||
local v = bit32.extract(w, 32 - used - n, n)
|
||||
used += n
|
||||
if used == 32 then
|
||||
pos += 1
|
||||
used = 0
|
||||
end
|
||||
return v
|
||||
end
|
||||
if pos + 1 >= words then
|
||||
return nil
|
||||
end
|
||||
local hiBits = bit32.extract(buffer.readu32(b, base + pos * 4), 0, remaining)
|
||||
local lo = n - remaining
|
||||
pos += 1
|
||||
used = lo
|
||||
local loBits = bit32.extract(buffer.readu32(b, base + pos * 4), 32 - lo, lo)
|
||||
return hiBits * 2 ^ lo + loBits
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
local function rans(d: D): Src?
|
||||
local bd = Reader.bitDecoder(d)
|
||||
if not bd then
|
||||
return nil
|
||||
end
|
||||
local function nextBit(): number
|
||||
return if Reader.bit(bd) then 1 else 0
|
||||
end
|
||||
return {
|
||||
next = nextBit,
|
||||
bits = function(n: number): number?
|
||||
local v = 0
|
||||
for _ = 1, n do
|
||||
v = v * 2 + nextBit()
|
||||
end
|
||||
return v
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
local function folded(d: D): Src?
|
||||
local parts: { Reader.Bits } = {}
|
||||
for i = 1, 32 do
|
||||
local bd = Reader.bitDecoder(d)
|
||||
if not bd then
|
||||
return nil
|
||||
end
|
||||
parts[i] = bd
|
||||
end
|
||||
local main = Reader.bitDecoder(d)
|
||||
if not main then
|
||||
return nil
|
||||
end
|
||||
return {
|
||||
next = function(): number
|
||||
return if Reader.bit(main :: Reader.Bits) then 1 else 0
|
||||
end,
|
||||
bits = function(n: number): number?
|
||||
local v = 0
|
||||
for i = 1, n do
|
||||
v = v * 2 + (if Reader.bit(parts[i]) then 1 else 0)
|
||||
end
|
||||
return v
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
local function msb(n: number): number
|
||||
local k = -1
|
||||
while n >= 1 do
|
||||
n = n // 2
|
||||
k += 1
|
||||
end
|
||||
return k
|
||||
end
|
||||
|
||||
-- DynamicIntegerPointsKdTreeDecoder::DecodePoints -> points (each a table of `dim` u32 values), or nil
|
||||
local function decodePoints(d: D, level: number, dim: number, expected: number): ({ { number } }?, string?)
|
||||
local bitLength = Reader.u32(d)
|
||||
local numPoints = Reader.u32(d)
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
if bitLength > 32 then
|
||||
return nil, "kd-tree: bad bit length"
|
||||
end
|
||||
if numPoints ~= expected then
|
||||
return nil, "kd-tree: point count mismatch"
|
||||
end
|
||||
local out: { { number } } = {}
|
||||
if numPoints == 0 then
|
||||
return out, nil
|
||||
end
|
||||
local numbers = if level >= 4 then folded(d) elseif level >= 2 then rans(d) else direct(d)
|
||||
local remainingBits = numbers and direct(d)
|
||||
local axisDec = remainingBits and direct(d)
|
||||
local half = axisDec and direct(d)
|
||||
if not numbers or not remainingBits or not axisDec or not half then
|
||||
return nil, d.bad or "kd-tree: bad bit decoders"
|
||||
end
|
||||
local selectAxis = level >= 6
|
||||
local zero = table.create(dim, 0)
|
||||
local baseStack: { { number } } = { table.clone(zero) }
|
||||
local levelStack: { { number } } = { table.clone(zero) }
|
||||
local stack = { { numPoints, 0, 0 } }
|
||||
local decoded = 0
|
||||
local p = table.create(dim, 0)
|
||||
while #stack > 0 do
|
||||
local st = stack[#stack]
|
||||
stack[#stack] = nil
|
||||
local n, lastAxis, sp = st[1], st[2], st[3]
|
||||
local oldBase, levels = baseStack[sp + 1], levelStack[sp + 1]
|
||||
if n > numPoints then
|
||||
return nil, "kd-tree: bad point count"
|
||||
end
|
||||
local axis
|
||||
if not selectAxis then
|
||||
axis = if lastAxis == dim - 1 then 0 else lastAxis + 1
|
||||
elseif n < 64 then
|
||||
axis = 0
|
||||
for a = 1, dim - 1 do
|
||||
if levels[axis + 1] > levels[a + 1] then
|
||||
axis = a
|
||||
end
|
||||
end
|
||||
else
|
||||
axis = (axisDec :: Src).bits(4) or 0
|
||||
end
|
||||
if axis >= dim then
|
||||
return nil, "kd-tree: bad axis"
|
||||
end
|
||||
local lvl = levels[axis + 1]
|
||||
if bitLength - lvl == 0 then
|
||||
for _ = 1, n do
|
||||
table.insert(out, table.clone(oldBase))
|
||||
decoded += 1
|
||||
end
|
||||
if decoded > numPoints then
|
||||
return nil, "kd-tree: too many points"
|
||||
end
|
||||
continue
|
||||
end
|
||||
if n <= 2 then
|
||||
for _ = 1, n do
|
||||
local a = axis
|
||||
for _ = 1, dim do
|
||||
local rb = bitLength - levels[a + 1]
|
||||
local v = 0
|
||||
if rb > 0 then
|
||||
local got = remainingBits.bits(rb)
|
||||
if got == nil then
|
||||
return nil, "kd-tree: remaining bits run out"
|
||||
end
|
||||
v = got
|
||||
end
|
||||
p[a + 1] = bit32.bor(oldBase[a + 1], v)
|
||||
a = if a == dim - 1 then 0 else a + 1
|
||||
end
|
||||
table.insert(out, table.clone(p))
|
||||
decoded += 1
|
||||
end
|
||||
if decoded > numPoints then
|
||||
return nil, "kd-tree: too many points"
|
||||
end
|
||||
continue
|
||||
end
|
||||
if decoded > numPoints then
|
||||
return nil, "kd-tree: too many points"
|
||||
end
|
||||
local rbits = bitLength - lvl
|
||||
local modifier = 2 ^ (rbits - 1)
|
||||
local nb = table.clone(oldBase)
|
||||
nb[axis + 1] = (nb[axis + 1] + modifier) % 4294967296
|
||||
baseStack[sp + 2] = nb
|
||||
local number = numbers.bits(msb(n)) or 0
|
||||
local first = n // 2
|
||||
if first < number then
|
||||
return nil, "kd-tree: bad split"
|
||||
end
|
||||
first -= number
|
||||
local second = n - first
|
||||
if first ~= second and half.next() == 0 then
|
||||
first, second = second, first
|
||||
end
|
||||
levels[axis + 1] += 1
|
||||
levelStack[sp + 2] = table.clone(levels)
|
||||
if sp + 2 > 32 * dim + 1 then
|
||||
return nil, "kd-tree: too deep"
|
||||
end
|
||||
if first > 0 then
|
||||
table.insert(stack, { first, axis, sp })
|
||||
end
|
||||
if second > 0 then
|
||||
table.insert(stack, { second, axis, sp + 1 })
|
||||
end
|
||||
end
|
||||
if decoded ~= expected then
|
||||
return nil, "kd-tree: point count mismatch"
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
local SIGNED = { [1] = 8, [3] = 16, [5] = 32 }
|
||||
|
||||
-- decodes the attributes of one kd-tree decoder (Attributes.Attr records: dataType, comps; sets values / numValues)
|
||||
function KdTree.decode(d: D, attrs: { any }, numPoints: number): (boolean, string?)
|
||||
if d.ver < 0x0203 then
|
||||
return false, "unsupported: kd-tree point clouds before bitstream 2.3"
|
||||
end
|
||||
local level = Reader.u8(d)
|
||||
if d.bad then
|
||||
return false, d.bad
|
||||
end
|
||||
if level > 6 then
|
||||
return false, "kd-tree: bad compression level"
|
||||
end
|
||||
local dim = 0
|
||||
for _, a in attrs do
|
||||
local dt = a.dataType
|
||||
if dt ~= 2 and dt ~= 4 and dt ~= 6 and dt ~= 1 and dt ~= 3 and dt ~= 5 and dt ~= 9 then
|
||||
return false, "unsupported: kd-tree attribute of data type " .. dt
|
||||
end
|
||||
dim += a.comps
|
||||
end
|
||||
local points, err = decodePoints(d, level, dim, numPoints)
|
||||
if not points then
|
||||
return false, err
|
||||
end
|
||||
-- the portable values per attribute: the low bytes of each u32 for 8 / 16-bit types
|
||||
local off = 0
|
||||
for _, a in attrs do
|
||||
local comps = a.comps
|
||||
local vals = table.create(numPoints * comps, 0)
|
||||
local mod = if a.dataType == 1 or a.dataType == 2 then 256 elseif a.dataType == 3 or a.dataType == 4 then 65536 else 4294967296
|
||||
local raw = a.dataType == 9
|
||||
for i, pt in points do
|
||||
for c = 1, comps do
|
||||
local v = pt[off + c]
|
||||
vals[(i - 1) * comps + c] = if raw then v else v % mod
|
||||
end
|
||||
end
|
||||
a.portable = vals
|
||||
a.values = vals
|
||||
a.numValues = numPoints
|
||||
a.map = nil
|
||||
off += comps
|
||||
end
|
||||
-- the data needed by the transforms: f32 quantization, then the signed minima
|
||||
for _, a in attrs do
|
||||
if a.dataType == 9 then
|
||||
local mins = table.create(a.comps, 0)
|
||||
for c = 1, a.comps do
|
||||
mins[c] = Reader.f32(d)
|
||||
end
|
||||
local range = Reader.f32(d)
|
||||
local bits = Reader.u8(d)
|
||||
if d.bad or bits < 1 or bits > 30 then
|
||||
return false, d.bad or "kd-tree: bad quantization"
|
||||
end
|
||||
a.quant = { min = mins, range = range, bits = bits }
|
||||
end
|
||||
end
|
||||
for _, a in attrs do
|
||||
if SIGNED[a.dataType] then
|
||||
local mins = table.create(a.comps, 0)
|
||||
for c = 1, a.comps do
|
||||
local v = Reader.varint(d)
|
||||
mins[c] = if v % 2 == 1 then -(v // 2) - 1 else v // 2
|
||||
end
|
||||
if d.bad then
|
||||
return false, d.bad
|
||||
end
|
||||
a.signedMin = mins
|
||||
end
|
||||
end
|
||||
-- back to the original values
|
||||
local fround = Predict.fround
|
||||
for _, a in attrs do
|
||||
local vals = a.portable :: { number }
|
||||
local comps = a.comps
|
||||
if a.dataType == 9 then
|
||||
local q = a.quant
|
||||
local delta = fround(q.range / fround(2 ^ q.bits - 1))
|
||||
local out = table.create(#vals, 0)
|
||||
for i = 1, #vals do
|
||||
local c = (i - 1) % comps + 1
|
||||
local v = vals[i]
|
||||
if v >= 2147483648 then
|
||||
v -= 4294967296
|
||||
end
|
||||
out[i] = fround(fround(fround(v) * delta) + q.min[c])
|
||||
end
|
||||
a.values = out
|
||||
elseif SIGNED[a.dataType] then
|
||||
-- the C++ reads the stored (already narrowed) unsigned values back
|
||||
local bits = SIGNED[a.dataType]
|
||||
local mins = a.signedMin
|
||||
local out = table.create(#vals, 0)
|
||||
for i = 1, #vals do
|
||||
local c = (i - 1) % comps + 1
|
||||
local u = vals[i]
|
||||
if u > 2147483647 then
|
||||
return false, "kd-tree: signed value out of range"
|
||||
end
|
||||
local s = Predict.i32(u + mins[c])
|
||||
local m = 2 ^ bits
|
||||
out[i] = (s + m / 2) % m - m / 2
|
||||
end
|
||||
a.values = out
|
||||
end
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
return KdTree
|
||||
@@ -0,0 +1,977 @@
|
||||
--!strict
|
||||
-- codecs/model/Draco/Predict: Draco attribute prediction schemes and their decoding transforms. Schemes: difference
|
||||
-- (delta), parallelogram, multi-parallelogram, constrained multi-parallelogram, tex coords (deprecated, float) and
|
||||
-- portable tex coords, geometric normal; transforms: wrap, normal octahedron and canonicalized normal octahedron.
|
||||
-- Integer semantics follow the C++ (int32 wrap, truncating division, exact 64-bit products where they can pass 2^53;
|
||||
-- float math rounded to f32 at every step). Ported from Google's Draco 1.5.7
|
||||
-- (compression/attributes/prediction_schemes/*, compression/attributes/normal_compression_utils.h; Apache-2.0,
|
||||
-- licenses/draco-LICENSE.txt).
|
||||
local Reader = require("@rosetta/codecs/model/Draco/Reader")
|
||||
local Connectivity = require("@rosetta/codecs/model/Draco/Connectivity")
|
||||
local Int64 = require("@rosetta/codecs/model/Draco/Int64")
|
||||
|
||||
local Predict = {}
|
||||
|
||||
type D = Reader.D
|
||||
type CT = Connectivity.CT
|
||||
|
||||
local nextC, prevC = Connectivity.next, Connectivity.prev
|
||||
|
||||
local F32 = buffer.create(4)
|
||||
local function fround(x: number): number
|
||||
buffer.writef32(F32, 0, x)
|
||||
return buffer.readf32(F32, 0)
|
||||
end
|
||||
Predict.fround = fround
|
||||
|
||||
local function i32(x: number): number
|
||||
return (x + 2147483648) % 4294967296 - 2147483648
|
||||
end
|
||||
Predict.i32 = i32
|
||||
|
||||
local function tdiv(a: number, b: number): number
|
||||
local q = a / b
|
||||
return if q < 0 then math.ceil(q) else math.floor(q)
|
||||
end
|
||||
|
||||
-- static_cast<int> of a float with the decoder's NaN / range guard (INT_MIN)
|
||||
local function truncInt(x: number): number
|
||||
if x ~= x or x > 2147483647 or x < -2147483648 then
|
||||
return -2147483648
|
||||
end
|
||||
return tdiv(x, 1)
|
||||
end
|
||||
|
||||
-- exact a * b = p + e (Dekker), for integers below 2^53
|
||||
local SPLIT = 134217729
|
||||
local function twoProd(a: number, b: number): (number, number)
|
||||
local p = a * b
|
||||
local t = SPLIT * a
|
||||
local ah = t - (t - a)
|
||||
local al = a - ah
|
||||
t = SPLIT * b
|
||||
local bh = t - (t - b)
|
||||
local bl = b - bh
|
||||
return p, ((ah * bh - p) + ah * bl + al * bh) + al * bl
|
||||
end
|
||||
|
||||
-- trunc(a * b / c) for integers, exact while the true product is below 2^106 (c > 0)
|
||||
local function mulDiv(a: number, b: number, c: number): number
|
||||
local neg = (a < 0) ~= (b < 0)
|
||||
a, b = math.abs(a), math.abs(b)
|
||||
local p = a * b
|
||||
local q
|
||||
if p < 9007199254740992 then
|
||||
q = p // c
|
||||
else
|
||||
q = math.floor(p / c)
|
||||
local ph, pl = twoProd(a, b)
|
||||
local qh, ql = twoProd(q, c)
|
||||
local r = (ph - qh) + (pl - ql)
|
||||
while r < 0 do
|
||||
q -= 1
|
||||
r += c
|
||||
end
|
||||
while r >= c do
|
||||
q += 1
|
||||
r -= c
|
||||
end
|
||||
end
|
||||
return if neg then -q else q
|
||||
end
|
||||
|
||||
-- floor(sqrt(a * b)) (IntSqrt of a 64-bit product), exact for a, b < 2^53
|
||||
local function isqrtProd(a: number, b: number): number
|
||||
if a == 0 or b == 0 then
|
||||
return 0
|
||||
end
|
||||
local s = math.floor(math.sqrt(a) * math.sqrt(b))
|
||||
local ph, pl = twoProd(a, b)
|
||||
local function le(x: number): boolean -- x * x <= a * b
|
||||
local xh, xl = twoProd(x, x)
|
||||
if xh ~= ph then
|
||||
return xh < ph
|
||||
end
|
||||
return xl <= pl
|
||||
end
|
||||
while s > 0 and not le(s) do
|
||||
s -= 1
|
||||
end
|
||||
while le(s + 1) do
|
||||
s += 1
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ octahedron toolbox
|
||||
export type Oct = { bits: number, maxQ: number, maxV: number, center: number, scale: number }
|
||||
|
||||
function Predict.octahedron(bits: number): Oct?
|
||||
if bits < 2 or bits > 30 then
|
||||
return nil
|
||||
end
|
||||
local maxQ = 2 ^ bits - 1
|
||||
local maxV = maxQ - 1
|
||||
return { bits = bits, maxQ = maxQ, maxV = maxV, center = maxV // 2, scale = fround(2 / fround(maxV)) }
|
||||
end
|
||||
|
||||
local function canonicalizeCoords(o: Oct, s: number, t: number): (number, number)
|
||||
local maxV, center = o.maxV, o.center
|
||||
if (s == 0 and t == 0) or (s == 0 and t == maxV) or (s == maxV and t == 0) then
|
||||
return maxV, maxV
|
||||
elseif s == 0 and t > center then
|
||||
t = center - (t - center)
|
||||
elseif s == maxV and t < center then
|
||||
t = center + (center - t)
|
||||
elseif t == maxV and s < center then
|
||||
s = center + (center - s)
|
||||
elseif t == 0 and s > center then
|
||||
s = center - (s - center)
|
||||
end
|
||||
return s, t
|
||||
end
|
||||
|
||||
local function intVectorToOct(o: Oct, x: number, y: number, z: number): (number, number)
|
||||
local s, t
|
||||
local center, maxV = o.center, o.maxV
|
||||
if x >= 0 then
|
||||
s, t = y + center, z + center
|
||||
else
|
||||
s = if y < 0 then math.abs(z) else maxV - math.abs(z)
|
||||
t = if z < 0 then math.abs(y) else maxV - math.abs(y)
|
||||
end
|
||||
return canonicalizeCoords(o, s, t)
|
||||
end
|
||||
|
||||
local function canonicalizeVector(o: Oct, x: number, y: number, z: number): (number, number, number)
|
||||
local sum = math.abs(x) + math.abs(y) + math.abs(z)
|
||||
local center = o.center
|
||||
if sum == 0 then
|
||||
return center, y, z
|
||||
end
|
||||
x = mulDiv(x, center, sum)
|
||||
y = mulDiv(y, center, sum)
|
||||
if z >= 0 then
|
||||
z = center - math.abs(x) - math.abs(y)
|
||||
else
|
||||
z = -(center - math.abs(x) - math.abs(y))
|
||||
end
|
||||
return x, y, z
|
||||
end
|
||||
|
||||
local function invertDiamond(o: Oct, s: number, t: number): (number, number)
|
||||
local signS, signT
|
||||
if s >= 0 and t >= 0 then
|
||||
signS, signT = 1, 1
|
||||
elseif s <= 0 and t <= 0 then
|
||||
signS, signT = -1, -1
|
||||
else
|
||||
signS = if s > 0 then 1 else -1
|
||||
signT = if t > 0 then 1 else -1
|
||||
end
|
||||
local cs, ctv = signS * o.center, signT * o.center
|
||||
local us, ut = s + s - cs, t + t - ctv
|
||||
if signS * signT >= 0 then
|
||||
us, ut = -ut, -us
|
||||
else
|
||||
us, ut = ut, us
|
||||
end
|
||||
return tdiv(i32(us + cs), 2), tdiv(i32(ut + ctv), 2)
|
||||
end
|
||||
|
||||
local function modMax(o: Oct, x: number): number
|
||||
if x > o.center then
|
||||
return x - o.maxQ
|
||||
elseif x < -o.center then
|
||||
return x + o.maxQ
|
||||
end
|
||||
return x
|
||||
end
|
||||
|
||||
-- quantized octahedral (s, t) -> unit vector, in f32 like the C++
|
||||
function Predict.octToVector(o: Oct, s: number, t: number): (number, number, number)
|
||||
local y = fround(fround(fround(s) * o.scale) - 1)
|
||||
local z = fround(fround(fround(t) * o.scale) - 1)
|
||||
local x = fround(fround(1 - math.abs(y)) - math.abs(z))
|
||||
local xo = -x
|
||||
if xo < 0 then
|
||||
xo = 0
|
||||
end
|
||||
y = fround(if y < 0 then y + xo else y - xo)
|
||||
z = fround(if z < 0 then z + xo else z - xo)
|
||||
local n2 = fround(fround(fround(x * x) + fround(y * y)) + fround(z * z))
|
||||
if n2 < 1e-6 then
|
||||
return 0, 0, 0
|
||||
end
|
||||
local dd = fround(1 / fround(math.sqrt(n2)))
|
||||
return fround(x * dd), fround(y * dd), fround(z * dd)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ transforms
|
||||
-- tr.apply(pred, data, off): data[off + 1 ..] holds the corrections and receives the original values
|
||||
export type Transform = {
|
||||
kind: number, -- 1 wrap, 2 octahedron, 3 octahedron canonicalized
|
||||
positive: boolean, -- corrections are stored without the zig-zag sign mapping
|
||||
min: number,
|
||||
max: number,
|
||||
maxDif: number,
|
||||
oct: Oct?,
|
||||
}
|
||||
|
||||
function Predict.transform(kind: number): Transform
|
||||
return { kind = kind, positive = kind ~= 1, min = 0, max = 0, maxDif = 0, oct = nil }
|
||||
end
|
||||
|
||||
function Predict.decodeTransform(tr: Transform, d: D): boolean
|
||||
if tr.kind == 1 then
|
||||
local mn, mx = Reader.i32(d), Reader.i32(d)
|
||||
if d.bad or mn > mx then
|
||||
return false
|
||||
end
|
||||
local dif = mx - mn
|
||||
if dif >= 2147483647 then
|
||||
return false
|
||||
end
|
||||
tr.min, tr.max, tr.maxDif = mn, mx, dif + 1
|
||||
return true
|
||||
end
|
||||
local maxQ = Reader.i32(d)
|
||||
if tr.kind == 3 or d.ver < 0x0202 then
|
||||
Reader.i32(d) -- center value (unused)
|
||||
end
|
||||
if d.bad or maxQ <= 0 or maxQ % 2 == 0 then
|
||||
return false
|
||||
end
|
||||
local bits = 0
|
||||
while 2 ^ bits <= maxQ do
|
||||
bits += 1
|
||||
end
|
||||
local o = Predict.octahedron(bits)
|
||||
if not o then
|
||||
return false
|
||||
end
|
||||
tr.oct = o
|
||||
return true
|
||||
end
|
||||
|
||||
-- the original values from a prediction (pred[1 .. comps]) and the corrections at data[off + 1 ..]
|
||||
local function apply(tr: Transform, pred: { number }, data: { number }, off: number, comps: number)
|
||||
if tr.kind == 1 then
|
||||
local mn, mx, dif = tr.min, tr.max, tr.maxDif
|
||||
for c = 1, comps do
|
||||
local p = pred[c]
|
||||
if p > mx then
|
||||
p = mx
|
||||
elseif p < mn then
|
||||
p = mn
|
||||
end
|
||||
local v = i32(p + data[off + c])
|
||||
if v > mx then
|
||||
v -= dif
|
||||
elseif v < mn then
|
||||
v += dif
|
||||
end
|
||||
data[off + c] = v
|
||||
end
|
||||
return
|
||||
end
|
||||
local o = tr.oct :: Oct
|
||||
local center = o.center
|
||||
local ps, pt = pred[1] - center, pred[2] - center
|
||||
local cs, ct = data[off + 1], data[off + 2]
|
||||
local inDiamond = math.abs(ps) + math.abs(pt) <= center
|
||||
if not inDiamond then
|
||||
ps, pt = invertDiamond(o, ps, pt)
|
||||
end
|
||||
local os_: number, ot: number = 0, 0
|
||||
if tr.kind == 2 then
|
||||
os_ = modMax(o, i32(ps + cs))
|
||||
ot = modMax(o, i32(pt + ct))
|
||||
else
|
||||
local bottomLeft = (ps == 0 and pt == 0) or (ps < 0 and pt <= 0)
|
||||
local rot = 0
|
||||
if ps == 0 then
|
||||
rot = if pt == 0 then 0 elseif pt > 0 then 3 else 1
|
||||
elseif ps > 0 then
|
||||
rot = if pt >= 0 then 2 else 1
|
||||
else
|
||||
rot = if pt <= 0 then 0 else 3
|
||||
end
|
||||
local function rotate(x: number, y: number, r: number): (number, number)
|
||||
if r == 1 then
|
||||
return y, -x
|
||||
elseif r == 2 then
|
||||
return -x, -y
|
||||
elseif r == 3 then
|
||||
return -y, x
|
||||
end
|
||||
return x, y
|
||||
end
|
||||
if not bottomLeft then
|
||||
ps, pt = rotate(ps, pt, rot)
|
||||
end
|
||||
os_ = modMax(o, i32(ps + cs))
|
||||
ot = modMax(o, i32(pt + ct))
|
||||
if not bottomLeft then
|
||||
os_, ot = rotate(os_, ot, (4 - rot) % 4)
|
||||
end
|
||||
end
|
||||
if not inDiamond then
|
||||
os_, ot = invertDiamond(o, os_, ot)
|
||||
end
|
||||
data[off + 1] = os_ + center
|
||||
data[off + 2] = ot + center
|
||||
end
|
||||
Predict.apply = apply
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ schemes
|
||||
-- the mesh data of a scheme: corner table, value -> corner, vertex -> value
|
||||
export type MeshData = { ct: CT, e2c: { number }, v2e: { number } }
|
||||
-- the parent position attribute: pos(point) -> x, y, z (portable integers, or floats before 2.0)
|
||||
export type Parent = (point: number) -> (number, number, number)
|
||||
|
||||
export type Scheme = {
|
||||
method: number,
|
||||
tr: Transform,
|
||||
md: MeshData?,
|
||||
parent: Parent?,
|
||||
-- per-scheme decoded data
|
||||
crease: { { boolean } }?,
|
||||
orient: { boolean }?,
|
||||
flips: Reader.Bits?,
|
||||
areaMode: boolean,
|
||||
ver: number,
|
||||
}
|
||||
|
||||
local DELTA, PARALLELOGRAM, MULTI, TEXDEP, CONSTRAINED, TEXPORT, GEONORMAL = 0, 1, 2, 3, 4, 5, 6
|
||||
Predict.GEOMETRIC_NORMAL = GEONORMAL
|
||||
|
||||
-- whether the scheme needs the position attribute
|
||||
function Predict.needsParent(s: Scheme): boolean
|
||||
return s.md ~= nil and (s.method == TEXDEP or s.method == TEXPORT or s.method == GEONORMAL)
|
||||
end
|
||||
|
||||
-- CreatePredictionSchemeForDecoder: md = nil (no corner table: sequential connectivity, point clouds) gives delta
|
||||
function Predict.new(method: number, tr: Transform, md: MeshData?): Scheme
|
||||
local m = method
|
||||
if not md then
|
||||
m = DELTA
|
||||
elseif tr.kind ~= 1 then
|
||||
if m ~= GEONORMAL then
|
||||
m = DELTA
|
||||
md = nil
|
||||
end
|
||||
elseif m < PARALLELOGRAM or m > GEONORMAL then
|
||||
m = DELTA
|
||||
md = nil
|
||||
end
|
||||
return { method = m, tr = tr, md = if m == DELTA then nil else md, parent = nil, areaMode = true, ver = 0x0202 }
|
||||
end
|
||||
|
||||
-- DecodePredictionData
|
||||
function Predict.decodeData(s: Scheme, d: D): boolean
|
||||
local m = s.method
|
||||
s.ver = d.ver
|
||||
if m == CONSTRAINED then
|
||||
if d.ver < 0x0202 then
|
||||
local mode = Reader.u8(d)
|
||||
if d.bad or mode ~= 0 then
|
||||
return false
|
||||
end
|
||||
end
|
||||
local md = s.md :: MeshData
|
||||
local crease = {}
|
||||
for i = 1, 4 do
|
||||
local n = Reader.varint(d)
|
||||
if d.bad or n > md.ct.nf * 3 then
|
||||
return false
|
||||
end
|
||||
local flags = table.create(n, false)
|
||||
if n > 0 then
|
||||
local bd = Reader.bitDecoder(d)
|
||||
if not bd then
|
||||
return false
|
||||
end
|
||||
for j = 1, n do
|
||||
flags[j] = Reader.bit(bd)
|
||||
end
|
||||
end
|
||||
crease[i] = flags
|
||||
end
|
||||
s.crease = crease
|
||||
elseif m == TEXPORT then
|
||||
local n = Reader.i32(d)
|
||||
if d.bad or n < 0 or n > (s.md :: MeshData).ct.nf * 3 then
|
||||
return false
|
||||
end
|
||||
local bd = Reader.bitDecoder(d)
|
||||
if not bd then
|
||||
return false
|
||||
end
|
||||
local orient = table.create(n, false)
|
||||
local last = true
|
||||
for i = 1, n do
|
||||
if not Reader.bit(bd) then
|
||||
last = not last
|
||||
end
|
||||
orient[i] = last
|
||||
end
|
||||
s.orient = orient
|
||||
elseif m == TEXDEP then
|
||||
local n = Reader.count(d, 0x0202)
|
||||
local md = s.md :: MeshData
|
||||
if d.bad or n == 0 or n > md.ct.nf * 3 then
|
||||
return false
|
||||
end
|
||||
local bd = Reader.bitDecoder(d)
|
||||
if not bd then
|
||||
return false
|
||||
end
|
||||
local orient = table.create(n, false)
|
||||
local last = true
|
||||
for i = 1, n do
|
||||
if not Reader.bit(bd) then
|
||||
last = not last
|
||||
end
|
||||
orient[i] = last
|
||||
end
|
||||
s.orient = orient
|
||||
elseif m == GEONORMAL then
|
||||
if not Predict.decodeTransform(s.tr, d) then
|
||||
return false
|
||||
end
|
||||
if d.ver < 0x0202 then
|
||||
local mode = Reader.u8(d)
|
||||
if d.bad or mode > 1 then
|
||||
return false
|
||||
end
|
||||
s.areaMode = mode == 1
|
||||
end
|
||||
local bd = Reader.bitDecoder(d)
|
||||
if not bd then
|
||||
return false
|
||||
end
|
||||
s.flips = bd
|
||||
return true
|
||||
end
|
||||
return Predict.decodeTransform(s.tr, d)
|
||||
end
|
||||
|
||||
local function parallelogram(md: MeshData, p: number, ci: number, data: { number }, comps: number, out: { number }): boolean
|
||||
local ct = md.ct
|
||||
local oci = if ci < 0 then -1 else (ct.opp[ci + 1] or -1)
|
||||
if oci == -1 then
|
||||
return false
|
||||
end
|
||||
local c2v, v2e = ct.c2v, md.v2e
|
||||
local vo, vn, vp = c2v[oci + 1] or -1, c2v[nextC(oci) + 1] or -1, c2v[prevC(oci) + 1] or -1
|
||||
if vo < 0 or vn < 0 or vp < 0 then
|
||||
return false
|
||||
end
|
||||
local eo, en, ep = v2e[vo + 1] or 0, v2e[vn + 1] or 0, v2e[vp + 1] or 0
|
||||
if eo < p and en < p and ep < p then
|
||||
for c = 1, comps do
|
||||
out[c] = i32((data[en * comps + c] + data[ep * comps + c]) - data[eo * comps + c])
|
||||
end
|
||||
return true
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
local function swingRight(ct: CT, c: number): number
|
||||
local p = prevC(c)
|
||||
local o = if p < 0 then -1 else (ct.opp[p + 1] or -1)
|
||||
return prevC(o)
|
||||
end
|
||||
local function swingLeft(ct: CT, c: number): number
|
||||
local n = nextC(c)
|
||||
local o = if n < 0 then -1 else (ct.opp[n + 1] or -1)
|
||||
return nextC(o)
|
||||
end
|
||||
|
||||
-- the portable tex coord prediction when both neighbours are decoded (MeshPredictionSchemeTexCoordsPortablePredictor
|
||||
-- ::ComputePredictedValue), in int64 / uint64 arithmetic like the C++. Returns "ok", u, v; "fallback" (degenerate
|
||||
-- edge: predict from a neighbour); or "fail", message.
|
||||
local function texPortable(nu: number, nv: number, pu: number, pv: number, tx: number, ty: number, tz: number, nx: number, ny: number, nz: number, qx: number, qy: number, qz: number, pop: () -> boolean?): (string, any, any)
|
||||
local pnx, pny, pnz = qx - nx, qy - ny, qz - nz
|
||||
local cnx, cny, cnz = tx - nx, ty - ny, tz - nz
|
||||
local pnu, pnv = pu - nu, pv - nv
|
||||
local B = 67108864 -- 2^26: below it every product and sum stays exact in a double
|
||||
local small = math.abs(pnx) < B and math.abs(pny) < B and math.abs(pnz) < B and math.abs(cnx) < B and math.abs(cny) < B and math.abs(cnz) < B
|
||||
if small then
|
||||
local pn2 = pnx * pnx + pny * pny + pnz * pnz
|
||||
local dot = pnx * cnx + pny * cny + pnz * cnz
|
||||
if pn2 < B and math.abs(dot) < B and math.abs(nu) < B and math.abs(nv) < B and math.abs(pnu) < B and math.abs(pnv) < B then
|
||||
if pn2 == 0 then
|
||||
return "fallback"
|
||||
end
|
||||
local xu, xv = nu * pn2 + dot * pnu, nv * pn2 + dot * pnv
|
||||
local dx = tx - (nx + tdiv(dot * pnx, pn2))
|
||||
local dy = ty - (ny + tdiv(dot * pny, pn2))
|
||||
local dz = tz - (nz + tdiv(dot * pnz, pn2))
|
||||
local cx2 = dx * dx + dy * dy + dz * dz
|
||||
if cx2 < B then
|
||||
local norm = isqrtProd(cx2, pn2)
|
||||
local cxu, cxv = pnv * norm, -pnu * norm
|
||||
local o = pop()
|
||||
if o == nil then
|
||||
return "fail", "prediction: orientations run out"
|
||||
end
|
||||
if o then
|
||||
return "ok", i32(tdiv(xu + cxu, pn2)), i32(tdiv(xv + cxv, pn2))
|
||||
end
|
||||
return "ok", i32(tdiv(xu - cxu, pn2)), i32(tdiv(xv - cxv, pn2))
|
||||
end
|
||||
end
|
||||
end
|
||||
-- the general case: int64
|
||||
local from, add, sub, mul, div = Int64.from, Int64.add, Int64.sub, Int64.mul, Int64.div
|
||||
local function dot3(ax: number, ay: number, az: number, bx: number, by: number, bz: number): (number, number)
|
||||
local xh, xl = from(ax)
|
||||
local yh, yl = from(ay)
|
||||
local zh, zl = from(az)
|
||||
local uh, ul = from(bx)
|
||||
local vh, vl = from(by)
|
||||
local wh, wl = from(bz)
|
||||
local h1, l1 = mul(xh, xl, uh, ul)
|
||||
local h2, l2 = mul(yh, yl, vh, vl)
|
||||
local h3, l3 = mul(zh, zl, wh, wl)
|
||||
h1, l1 = add(h1, l1, h2, l2)
|
||||
return add(h1, l1, h3, l3)
|
||||
end
|
||||
local p2h, p2l = dot3(pnx, pny, pnz, pnx, pny, pnz)
|
||||
if p2h == 0 and p2l == 0 then
|
||||
return "fallback"
|
||||
end
|
||||
local dh, dl = dot3(pnx, pny, pnz, cnx, cny, cnz)
|
||||
local MAXH, MAXL = 2147483647, 4294967295 -- INT64_MAX
|
||||
local function absmax(...: number): (number, number)
|
||||
local m = 0
|
||||
for _, x in { ... } do
|
||||
m = math.max(m, math.abs(x))
|
||||
end
|
||||
return from(m)
|
||||
end
|
||||
local function absI(h: number, l: number): (number, number)
|
||||
if Int64.isNeg(h) then
|
||||
return Int64.neg(h, l)
|
||||
end
|
||||
return h, l
|
||||
end
|
||||
-- the overflow guards (unsigned divisions as in the C++)
|
||||
local nmh, nml = absmax(nu, nv)
|
||||
local lh, ll = Int64.udivmod(MAXH, MAXL, p2h, p2l)
|
||||
if Int64.ucmp(nmh, nml, lh, ll) > 0 then
|
||||
return "fail", "prediction: tex coord overflow"
|
||||
end
|
||||
local adh, adl = absI(dh, dl)
|
||||
local pmh, pml = absmax(pnu, pnv)
|
||||
lh, ll = Int64.div(MAXH, MAXL, pmh, pml)
|
||||
if Int64.cmp(adh, adl, lh, ll) > 0 then
|
||||
return "fail", "prediction: tex coord overflow"
|
||||
end
|
||||
local nuh, nul = from(nu)
|
||||
local nvh, nvl = from(nv)
|
||||
local puh, pul = from(pnu)
|
||||
local pvh, pvl = from(pnv)
|
||||
local xuh, xul
|
||||
do
|
||||
local ah, al = mul(nuh, nul, p2h, p2l)
|
||||
local bh, bl = mul(dh, dl, puh, pul)
|
||||
xuh, xul = add(ah, al, bh, bl)
|
||||
end
|
||||
local xvh, xvl
|
||||
do
|
||||
local ah, al = mul(nvh, nvl, p2h, p2l)
|
||||
local bh, bl = mul(dh, dl, pvh, pvl)
|
||||
xvh, xvl = add(ah, al, bh, bl)
|
||||
end
|
||||
local pam = math.max(math.abs(pnx), math.abs(pny), math.abs(pnz))
|
||||
local pah, pal = from(pam)
|
||||
lh, ll = Int64.div(MAXH, MAXL, pah, pal)
|
||||
if Int64.cmp(adh, adl, lh, ll) > 0 then
|
||||
return "fail", "prediction: tex coord overflow"
|
||||
end
|
||||
-- x_pos = next + (dot * pn) / pn2; cx = tip - x_pos
|
||||
local function proj(n: number, pc: number, t: number): (number, number)
|
||||
local ph, pl = from(pc)
|
||||
local mh, ml = mul(dh, dl, ph, pl)
|
||||
local qh, ql = div(mh, ml, p2h, p2l)
|
||||
local nh, nl = from(n)
|
||||
local xh, xl = add(nh, nl, qh, ql)
|
||||
local th, tl = from(t)
|
||||
return sub(th, tl, xh, xl)
|
||||
end
|
||||
local ax, axl = proj(nx, pnx, tx)
|
||||
local ay, ayl = proj(ny, pny, ty)
|
||||
local az, azl = proj(nz, pnz, tz)
|
||||
local c2h, c2l = mul(ax, axl, ax, axl)
|
||||
do
|
||||
local h, l = mul(ay, ayl, ay, ayl)
|
||||
c2h, c2l = add(c2h, c2l, h, l)
|
||||
h, l = mul(az, azl, az, azl)
|
||||
c2h, c2l = add(c2h, c2l, h, l)
|
||||
end
|
||||
local prh, prl = mul(c2h, c2l, p2h, p2l)
|
||||
local sh, sl = Int64.isqrt(prh, prl)
|
||||
-- cx_uv = (pn_uv.v, -pn_uv.u) * norm
|
||||
local cuh, cul = mul(pvh, pvl, sh, sl)
|
||||
local nh, nl = Int64.neg(puh, pul)
|
||||
local cvh, cvl = mul(nh, nl, sh, sl)
|
||||
local o = pop()
|
||||
if o == nil then
|
||||
return "fail", "prediction: orientations run out"
|
||||
end
|
||||
local uh, ul, vh, vl
|
||||
if o then
|
||||
uh, ul = add(xuh, xul, cuh, cul)
|
||||
vh, vl = add(xvh, xvl, cvh, cvl)
|
||||
else
|
||||
uh, ul = sub(xuh, xul, cuh, cul)
|
||||
vh, vl = sub(xvh, xvl, cvh, cvl)
|
||||
end
|
||||
uh, ul = div(uh, ul, p2h, p2l)
|
||||
vh, vl = div(vh, vl, p2h, p2l)
|
||||
-- static_cast<int>: the low 32 bits
|
||||
return "ok", i32(ul), i32(vl)
|
||||
end
|
||||
|
||||
-- ComputeOriginalValues over data (corrections in, values out, in place); points = the entry -> point map
|
||||
function Predict.compute(s: Scheme, data: { number }, numEntries: number, comps: number, points: { number }): (boolean, string?)
|
||||
local tr = s.tr
|
||||
local m = s.method
|
||||
local pred = table.create(math.max(comps, 3), 0)
|
||||
if m == DELTA then
|
||||
if numEntries == 0 then
|
||||
return true, nil
|
||||
end
|
||||
apply(tr, pred, data, 0, comps)
|
||||
for e = 1, numEntries - 1 do
|
||||
local off = e * comps
|
||||
for c = 1, comps do
|
||||
pred[c] = data[off - comps + c]
|
||||
end
|
||||
apply(tr, pred, data, off, comps)
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
local md = s.md :: MeshData
|
||||
local e2c = md.e2c
|
||||
local n = #e2c
|
||||
if n ~= numEntries then
|
||||
return false, "prediction: value count mismatch"
|
||||
end
|
||||
local ct = md.ct
|
||||
local function previous(p: number)
|
||||
local off = (p - 1) * comps
|
||||
for c = 1, comps do
|
||||
pred[c] = data[off + c]
|
||||
end
|
||||
end
|
||||
if m == PARALLELOGRAM or m == MULTI or m == CONSTRAINED then
|
||||
if n == 0 then
|
||||
return true, nil
|
||||
end
|
||||
apply(tr, pred, data, 0, comps)
|
||||
local para = table.create(comps, 0)
|
||||
local preds: { { number } } = { table.create(comps, 0), table.create(comps, 0), table.create(comps, 0), table.create(comps, 0) }
|
||||
local creasePos = { 0, 0, 0, 0 }
|
||||
local nc = ct.nf * 3
|
||||
for p = 1, n - 1 do
|
||||
local start = e2c[p + 1]
|
||||
local off = p * comps
|
||||
if m == PARALLELOGRAM then
|
||||
if parallelogram(md, p, start, data, comps, pred) then
|
||||
apply(tr, pred, data, off, comps)
|
||||
else
|
||||
previous(p)
|
||||
apply(tr, pred, data, off, comps)
|
||||
end
|
||||
elseif m == MULTI then
|
||||
for c = 1, comps do
|
||||
pred[c] = 0
|
||||
end
|
||||
local count = 0
|
||||
local ci = start
|
||||
local guard = 0
|
||||
while ci ~= -1 do
|
||||
if parallelogram(md, p, ci, data, comps, para) then
|
||||
for c = 1, comps do
|
||||
pred[c] = i32(pred[c] + para[c])
|
||||
end
|
||||
count += 1
|
||||
end
|
||||
ci = swingRight(ct, ci)
|
||||
if ci == start then
|
||||
ci = -1
|
||||
end
|
||||
guard += 1
|
||||
if guard > nc then
|
||||
return false, "prediction: bad vertex fan"
|
||||
end
|
||||
end
|
||||
if count == 0 then
|
||||
previous(p)
|
||||
else
|
||||
for c = 1, comps do
|
||||
pred[c] = tdiv(pred[c], count)
|
||||
end
|
||||
end
|
||||
apply(tr, pred, data, off, comps)
|
||||
else
|
||||
local count = 0
|
||||
local ci = start
|
||||
local first = true
|
||||
local guard = 0
|
||||
while ci ~= -1 do
|
||||
if parallelogram(md, p, ci, data, comps, preds[count + 1]) then
|
||||
count += 1
|
||||
if count == 4 then
|
||||
break
|
||||
end
|
||||
end
|
||||
if first then
|
||||
ci = swingLeft(ct, ci)
|
||||
else
|
||||
ci = swingRight(ct, ci)
|
||||
end
|
||||
if ci == start then
|
||||
break
|
||||
end
|
||||
if ci == -1 and first then
|
||||
first = false
|
||||
ci = swingRight(ct, start)
|
||||
end
|
||||
guard += 1
|
||||
if guard > nc then
|
||||
return false, "prediction: bad vertex fan"
|
||||
end
|
||||
end
|
||||
local used = 0
|
||||
if count > 0 then
|
||||
for c = 1, comps do
|
||||
pred[c] = 0
|
||||
end
|
||||
local crease = s.crease :: { { boolean } }
|
||||
for i = 1, count do
|
||||
local pos = creasePos[count] + 1
|
||||
creasePos[count] = pos
|
||||
local flag = crease[count][pos]
|
||||
if flag == nil then
|
||||
return false, "prediction: crease flags run out"
|
||||
end
|
||||
if not flag then
|
||||
used += 1
|
||||
for c = 1, comps do
|
||||
pred[c] = i32(pred[c] + preds[i][c])
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if used == 0 then
|
||||
previous(p)
|
||||
else
|
||||
for c = 1, comps do
|
||||
pred[c] = tdiv(pred[c], used)
|
||||
end
|
||||
end
|
||||
apply(tr, pred, data, off, comps)
|
||||
end
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
local parent = s.parent
|
||||
if not parent then
|
||||
return false, "prediction: no position attribute"
|
||||
end
|
||||
local c2v, v2e = ct.c2v, md.v2e
|
||||
local function entryOf(c: number): number
|
||||
local v = if c < 0 then -1 else (c2v[c + 1] or -1)
|
||||
if v < 0 then
|
||||
return math.huge
|
||||
end
|
||||
return v2e[v + 1] or 0
|
||||
end
|
||||
local function posOf(e: number): (number, number, number)
|
||||
local pt = points[e + 1]
|
||||
if pt == nil then
|
||||
return 0, 0, 0
|
||||
end
|
||||
return parent(pt)
|
||||
end
|
||||
if m == TEXPORT or m == TEXDEP then
|
||||
if comps ~= 2 then
|
||||
return false, "prediction: tex coords need 2 components"
|
||||
end
|
||||
local orient = s.orient :: { boolean }
|
||||
local no = #orient
|
||||
for p = 0, n - 1 do
|
||||
local ci = e2c[p + 1]
|
||||
local ne, pe = entryOf(nextC(ci)), entryOf(prevC(ci))
|
||||
local done = false
|
||||
if pe < p and ne < p then
|
||||
local nu, nv = data[ne * 2 + 1], data[ne * 2 + 2]
|
||||
local pu, pv = data[pe * 2 + 1], data[pe * 2 + 2]
|
||||
if m == TEXPORT then
|
||||
if pu == nu and pv == nv then
|
||||
pred[1], pred[2] = pu, pv
|
||||
done = true
|
||||
else
|
||||
local tx, ty, tz = posOf(p)
|
||||
local nx, ny, nz = posOf(ne)
|
||||
local qx, qy, qz = posOf(pe)
|
||||
local status, u, v = texPortable(nu, nv, pu, pv, tx, ty, tz, nx, ny, nz, qx, qy, qz, function(): boolean?
|
||||
if no == 0 then
|
||||
return nil
|
||||
end
|
||||
local o = orient[no]
|
||||
orient[no] = nil
|
||||
no -= 1
|
||||
return o
|
||||
end)
|
||||
if status == "fail" then
|
||||
return false, u :: any
|
||||
elseif status == "ok" then
|
||||
pred[1], pred[2] = u, v
|
||||
done = true
|
||||
end
|
||||
end
|
||||
else
|
||||
local fnu, fnv, fpu, fpv = fround(nu), fround(nv), fround(pu), fround(pv)
|
||||
if fpu == fnu and fpv == fnv then
|
||||
pred[1], pred[2] = truncInt(fpu), truncInt(fpv)
|
||||
done = true
|
||||
else
|
||||
local tx: number, ty: number, tz: number = posOf(p)
|
||||
local nx: number, ny: number, nz: number = posOf(ne)
|
||||
local qx: number, qy: number, qz: number = posOf(pe)
|
||||
tx, ty, tz, nx, ny, nz = fround(tx), fround(ty), fround(tz), fround(nx), fround(ny), fround(nz)
|
||||
qx, qy, qz = fround(qx), fround(qy), fround(qz)
|
||||
local pnx, pny, pnz = fround(qx - nx), fround(qy - ny), fround(qz - nz)
|
||||
local cnx, cny, cnz = fround(tx - nx), fround(ty - ny), fround(tz - nz)
|
||||
local pn2 = fround(fround(fround(pnx * pnx) + fround(pny * pny)) + fround(pnz * pnz))
|
||||
local sv, tv = 0, 0
|
||||
if s.ver < 0x0102 or pn2 > 0 then
|
||||
local dot = fround(fround(fround(pnx * cnx) + fround(pny * cny)) + fround(pnz * cnz))
|
||||
sv = fround(dot / pn2)
|
||||
local ex, ey, ez = fround(cnx - fround(pnx * sv)), fround(cny - fround(pny * sv)), fround(cnz - fround(pnz * sv))
|
||||
local e2 = fround(fround(fround(ex * ex) + fround(ey * ey)) + fround(ez * ez))
|
||||
tv = fround(math.sqrt(fround(e2 / pn2)))
|
||||
end
|
||||
local pnu, pnv = fround(fpu - fnu), fround(fpv - fnv)
|
||||
local pnus = fround(fround(pnu * sv) + fnu)
|
||||
local pnut = fround(pnu * tv)
|
||||
local pnvs = fround(fround(pnv * sv) + fnv)
|
||||
local pnvt = fround(pnv * tv)
|
||||
if no == 0 then
|
||||
return false, "prediction: orientations run out"
|
||||
end
|
||||
local o = orient[no]
|
||||
orient[no] = nil
|
||||
no -= 1
|
||||
local u: number, v: number = 0, 0
|
||||
if o then
|
||||
u = fround(pnus - pnvt)
|
||||
v = fround(pnvs + pnut)
|
||||
else
|
||||
u = fround(pnus + pnvt)
|
||||
v = fround(pnvs - pnut)
|
||||
end
|
||||
local function toInt(x: number): number
|
||||
local r = math.floor(x + 0.5)
|
||||
if r ~= r or r > 2147483647 or r < -2147483648 then
|
||||
return -2147483648
|
||||
end
|
||||
return r
|
||||
end
|
||||
pred[1] = toInt(u)
|
||||
pred[2] = toInt(v)
|
||||
done = true
|
||||
end
|
||||
end
|
||||
end
|
||||
if not done then
|
||||
local off = -1
|
||||
if pe < p then
|
||||
off = pe * 2
|
||||
end
|
||||
if ne < p then
|
||||
off = ne * 2
|
||||
elseif p > 0 then
|
||||
off = (p - 1) * 2
|
||||
else
|
||||
off = -1
|
||||
end
|
||||
if off < 0 then
|
||||
pred[1], pred[2] = 0, 0
|
||||
else
|
||||
pred[1], pred[2] = data[off + 1], data[off + 2]
|
||||
end
|
||||
end
|
||||
apply(tr, pred, data, p * 2, 2)
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
-- geometric normal
|
||||
local o = tr.oct
|
||||
local flips = s.flips
|
||||
if not o or not flips or comps ~= 2 then
|
||||
return false, "prediction: bad geometric normal setup"
|
||||
end
|
||||
local nc = ct.nf * 3
|
||||
for p = 0, n - 1 do
|
||||
local ci = e2c[p + 1]
|
||||
local cx, cy, cz = posOf(entryOf(ci))
|
||||
local sx, sy, sz = 0, 0, 0
|
||||
-- VertexCornersIterator from ci: swing left, then right from the start
|
||||
local c = ci
|
||||
local left = true
|
||||
local guard = 0
|
||||
while c ~= -1 do
|
||||
local cn, cp
|
||||
if s.areaMode then
|
||||
cn, cp = nextC(c), prevC(c)
|
||||
else
|
||||
cn, cp = nextC(ci), prevC(ci)
|
||||
end
|
||||
local ax, ay, az = posOf(entryOf(cn))
|
||||
local bx, by, bz = posOf(entryOf(cp))
|
||||
ax, ay, az = ax - cx, ay - cy, az - cz
|
||||
bx, by, bz = bx - cx, by - cy, bz - cz
|
||||
sx += ay * bz - az * by
|
||||
sy += az * bx - ax * bz
|
||||
sz += ax * by - ay * bx
|
||||
if left then
|
||||
c = swingLeft(ct, c)
|
||||
if c == -1 then
|
||||
c = swingRight(ct, ci)
|
||||
left = false
|
||||
elseif c == ci then
|
||||
c = -1
|
||||
end
|
||||
else
|
||||
c = swingRight(ct, c)
|
||||
end
|
||||
guard += 1
|
||||
if guard > nc then
|
||||
return false, "prediction: bad vertex fan"
|
||||
end
|
||||
end
|
||||
local upper = 2 ^ 29
|
||||
local sum = math.abs(sx) + math.abs(sy) + math.abs(sz)
|
||||
if sum > upper then
|
||||
local q = sum // upper
|
||||
sx, sy, sz = tdiv(sx, q), tdiv(sy, q), tdiv(sz, q)
|
||||
end
|
||||
sx, sy, sz = i32(sx), i32(sy), i32(sz)
|
||||
sx, sy, sz = canonicalizeVector(o, sx, sy, sz)
|
||||
if Reader.bit(flips) then
|
||||
sx, sy, sz = -sx, -sy, -sz
|
||||
end
|
||||
pred[1], pred[2] = intVectorToOct(o, sx, sy, sz)
|
||||
apply(tr, pred, data, p * 2, 2)
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
return Predict
|
||||
@@ -0,0 +1,480 @@
|
||||
--!strict
|
||||
-- codecs/model/Draco/Reader: the Draco decoder buffer (little-endian fields, LEB128 varints, LSB-first bit runs) and
|
||||
-- its entropy decoders: rANS symbol coding (tagged and raw schemes, DecodeSymbols) and the binary rANS / rABS bit
|
||||
-- decoder. Ported from Google's Draco 1.5.7 (core/decoder_buffer, core/varint_decoding, compression/entropy/ans.h,
|
||||
-- rans_symbol_decoder.h, symbol_decoding.cc, compression/bit_coders/rans_bit_decoder.cc; Apache-2.0,
|
||||
-- licenses/draco-LICENSE.txt). Bitstream versions 1.0 - 2.2 (fixed-width counts before 2.0 / 2.2).
|
||||
-- A failed read sets the sticky d.bad message and returns 0; callers check d.bad at their boundaries.
|
||||
local Reader = {}
|
||||
|
||||
local readu8, readu16, readu32, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readf32
|
||||
local band, rshift = bit32.band, bit32.rshift
|
||||
|
||||
export type D = {
|
||||
b: buffer,
|
||||
pos: number, -- absolute offset in b
|
||||
limit: number, -- absolute end
|
||||
ver: number, -- major * 256 + minor
|
||||
bad: string?,
|
||||
bitMode: boolean,
|
||||
bitStart: number, -- absolute byte where the bit run starts
|
||||
bitOff: number, -- bits consumed
|
||||
}
|
||||
|
||||
function Reader.new(b: buffer, pos: number, limit: number, ver: number): D
|
||||
return { b = b, pos = pos, limit = limit, ver = ver, bad = nil, bitMode = false, bitStart = pos, bitOff = 0 }
|
||||
end
|
||||
|
||||
-- a copy (C++ DecoderBuffer is copied by value: positions are independent afterwards)
|
||||
function Reader.copy(d: D): D
|
||||
return { b = d.b, pos = d.pos, limit = d.limit, ver = d.ver, bad = d.bad, bitMode = d.bitMode, bitStart = d.bitStart, bitOff = d.bitOff }
|
||||
end
|
||||
|
||||
function Reader.fail(d: D, msg: string): number
|
||||
if not d.bad then
|
||||
d.bad = msg
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
function Reader.remaining(d: D): number
|
||||
return d.limit - d.pos
|
||||
end
|
||||
|
||||
function Reader.u8(d: D): number
|
||||
local p = d.pos
|
||||
if p + 1 > d.limit then
|
||||
return Reader.fail(d, "truncated")
|
||||
end
|
||||
d.pos = p + 1
|
||||
return readu8(d.b, p)
|
||||
end
|
||||
|
||||
function Reader.i8(d: D): number
|
||||
local v = Reader.u8(d)
|
||||
return if v >= 128 then v - 256 else v
|
||||
end
|
||||
|
||||
function Reader.u16(d: D): number
|
||||
local p = d.pos
|
||||
if p + 2 > d.limit then
|
||||
return Reader.fail(d, "truncated")
|
||||
end
|
||||
d.pos = p + 2
|
||||
return readu16(d.b, p)
|
||||
end
|
||||
|
||||
function Reader.u32(d: D): number
|
||||
local p = d.pos
|
||||
if p + 4 > d.limit then
|
||||
return Reader.fail(d, "truncated")
|
||||
end
|
||||
d.pos = p + 4
|
||||
return readu32(d.b, p)
|
||||
end
|
||||
|
||||
function Reader.i32(d: D): number
|
||||
local p = d.pos
|
||||
if p + 4 > d.limit then
|
||||
return Reader.fail(d, "truncated")
|
||||
end
|
||||
d.pos = p + 4
|
||||
return readi32(d.b, p)
|
||||
end
|
||||
|
||||
-- u64 as a number (exact below 2^53; sizes beyond that fail the bounds checks anyway)
|
||||
function Reader.u64(d: D): number
|
||||
local p = d.pos
|
||||
if p + 8 > d.limit then
|
||||
return Reader.fail(d, "truncated")
|
||||
end
|
||||
d.pos = p + 8
|
||||
return readu32(d.b, p) + readu32(d.b, p + 4) * 4294967296
|
||||
end
|
||||
|
||||
function Reader.f32(d: D): number
|
||||
local p = d.pos
|
||||
if p + 4 > d.limit then
|
||||
return Reader.fail(d, "truncated")
|
||||
end
|
||||
d.pos = p + 4
|
||||
return readf32(d.b, p)
|
||||
end
|
||||
|
||||
-- LEB128 (at most 5 bytes for 32-bit values, 10 for 64-bit); 32-bit values wrap like the C++ shifts
|
||||
function Reader.varint(d: D, wide: boolean?): number
|
||||
local maxBytes = if wide then 10 else 5
|
||||
local v, mul = 0, 1
|
||||
for _ = 1, maxBytes do
|
||||
local p = d.pos
|
||||
if p + 1 > d.limit then
|
||||
return Reader.fail(d, "truncated varint")
|
||||
end
|
||||
local c = readu8(d.b, p)
|
||||
d.pos = p + 1
|
||||
v += band(c, 127) * mul
|
||||
if c < 128 then
|
||||
if not wide then
|
||||
v %= 4294967296
|
||||
end
|
||||
return v
|
||||
end
|
||||
mul *= 128
|
||||
end
|
||||
return Reader.fail(d, "varint too long")
|
||||
end
|
||||
|
||||
-- a count stored as u32 before `fixedBefore` (a version number) and as a varint from then on
|
||||
function Reader.count(d: D, fixedBefore: number): number
|
||||
if d.ver < fixedBefore then
|
||||
return Reader.u32(d)
|
||||
end
|
||||
return Reader.varint(d)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bit runs
|
||||
-- StartBitDecoding(decodeSize): an optional size (u64 before 2.2, varint64 after), then LSB-first bits up to the end
|
||||
-- of the buffer; EndBitDecoding moves pos past the whole bytes consumed.
|
||||
function Reader.startBits(d: D, decodeSize: boolean): number
|
||||
local size = 0
|
||||
if decodeSize then
|
||||
if d.ver < 0x0202 then
|
||||
size = Reader.u64(d)
|
||||
else
|
||||
size = Reader.varint(d, true)
|
||||
end
|
||||
end
|
||||
d.bitMode = true
|
||||
d.bitStart = d.pos
|
||||
d.bitOff = 0
|
||||
return size
|
||||
end
|
||||
|
||||
function Reader.bits(d: D, n: number): number
|
||||
if not d.bitMode then
|
||||
return Reader.fail(d, "bit decoder not active")
|
||||
end
|
||||
if n > 32 then
|
||||
return Reader.fail(d, "bit run over 32 bits")
|
||||
end
|
||||
local b, start, limit = d.b, d.bitStart, d.limit
|
||||
local off = d.bitOff
|
||||
local v, mul = 0, 1
|
||||
for _ = 1, n do
|
||||
local byte = start + rshift(off, 3)
|
||||
if byte < limit then
|
||||
if band(rshift(readu8(b, byte), band(off, 7)), 1) == 1 then
|
||||
v += mul
|
||||
end
|
||||
off += 1
|
||||
end
|
||||
mul *= 2
|
||||
end
|
||||
d.bitOff = off
|
||||
return v
|
||||
end
|
||||
|
||||
function Reader.endBits(d: D)
|
||||
d.bitMode = false
|
||||
d.pos = d.bitStart + (d.bitOff + 7) // 8
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ rANS symbols
|
||||
-- the precision for a symbol alphabet of `bitLength`-bit symbols: (3 * bits) / 2 clamped to 12..20
|
||||
local function precisionBits(bitLength: number): number
|
||||
local p = (3 * bitLength) // 2
|
||||
return if p < 12 then 12 elseif p > 20 then 20 else p
|
||||
end
|
||||
|
||||
export type Rans = {
|
||||
b: buffer,
|
||||
base: number, -- absolute start of the coded bytes
|
||||
off: number, -- bytes left (read backwards from base + off)
|
||||
state: number,
|
||||
lBase: number,
|
||||
precBits: number,
|
||||
lut: { number }, -- rem + 1 -> symbol + 1
|
||||
prob: { number },
|
||||
cum: { number },
|
||||
numSymbols: number,
|
||||
}
|
||||
|
||||
-- RAnsSymbolDecoder::Create: the probability table
|
||||
local function ransCreate(d: D, precBits: number): Rans?
|
||||
local numSymbols = Reader.count(d, 0x0200)
|
||||
if d.bad then
|
||||
return nil
|
||||
end
|
||||
if numSymbols // 64 > Reader.remaining(d) then
|
||||
Reader.fail(d, "rans: too many symbols")
|
||||
return nil
|
||||
end
|
||||
local prec = 2 ^ precBits
|
||||
local prob = table.create(numSymbols, 0)
|
||||
local i = 0
|
||||
while i < numSymbols do
|
||||
local data = Reader.u8(d)
|
||||
if d.bad then
|
||||
return nil
|
||||
end
|
||||
local token = band(data, 3)
|
||||
if token == 3 then
|
||||
local offset = rshift(data, 2)
|
||||
if i + offset >= numSymbols then
|
||||
Reader.fail(d, "rans: bad zero run")
|
||||
return nil
|
||||
end
|
||||
for j = 0, offset do
|
||||
prob[i + j + 1] = 0
|
||||
end
|
||||
i += offset + 1
|
||||
else
|
||||
local p = rshift(data, 2)
|
||||
for k = 1, token do
|
||||
p += Reader.u8(d) * 2 ^ (8 * k - 2)
|
||||
end
|
||||
if d.bad then
|
||||
return nil
|
||||
end
|
||||
prob[i + 1] = p
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
local lut: { number } = {}
|
||||
local cum = table.create(numSymbols, 0)
|
||||
if numSymbols > 0 then
|
||||
lut = table.create(prec, 0)
|
||||
local c, act = 0, 0
|
||||
for s = 1, numSymbols do
|
||||
cum[s] = c
|
||||
c += prob[s]
|
||||
if c > prec then
|
||||
Reader.fail(d, "rans: probabilities over the precision")
|
||||
return nil
|
||||
end
|
||||
for j = act + 1, c do
|
||||
lut[j] = s
|
||||
end
|
||||
act = c
|
||||
end
|
||||
if c ~= prec then
|
||||
Reader.fail(d, "rans: probabilities do not sum to the precision")
|
||||
return nil
|
||||
end
|
||||
end
|
||||
return {
|
||||
b = d.b,
|
||||
base = 0,
|
||||
off = 0,
|
||||
state = 0,
|
||||
lBase = prec * 4,
|
||||
precBits = precBits,
|
||||
lut = lut,
|
||||
prob = prob,
|
||||
cum = cum,
|
||||
numSymbols = numSymbols,
|
||||
}
|
||||
end
|
||||
|
||||
-- read_init over [base, base + size): the final state is stored in the last 1-4 bytes
|
||||
local function ansInit(b: buffer, base: number, size: number, lBase: number, allow4: boolean): (number?, number?)
|
||||
if size < 1 then
|
||||
return nil, nil
|
||||
end
|
||||
local x = rshift(readu8(b, base + size - 1), 6)
|
||||
local off: number, state: number = 0, 0
|
||||
if x == 0 then
|
||||
off = size - 1
|
||||
state = band(readu8(b, base + size - 1), 0x3F)
|
||||
elseif x == 1 then
|
||||
if size < 2 then
|
||||
return nil, nil
|
||||
end
|
||||
off = size - 2
|
||||
state = band(readu16(b, base + size - 2), 0x3FFF)
|
||||
elseif x == 2 then
|
||||
if size < 3 then
|
||||
return nil, nil
|
||||
end
|
||||
off = size - 3
|
||||
state = readu16(b, base + size - 3) + band(readu8(b, base + size - 1), 0x3F) * 65536
|
||||
else
|
||||
if not allow4 or size < 4 then
|
||||
return nil, nil
|
||||
end
|
||||
off = size - 4
|
||||
state = band(readu32(b, base + size - 4), 0x3FFFFFFF)
|
||||
end
|
||||
state += lBase
|
||||
if state >= lBase * 256 then
|
||||
return nil, nil
|
||||
end
|
||||
return off, state
|
||||
end
|
||||
|
||||
-- RAnsSymbolDecoder::StartDecoding: the coded size, then the bytes
|
||||
local function ransStart(d: D, r: Rans): boolean
|
||||
local size
|
||||
if d.ver < 0x0200 then
|
||||
size = Reader.u64(d)
|
||||
else
|
||||
size = Reader.varint(d, true)
|
||||
end
|
||||
if d.bad then
|
||||
return false
|
||||
end
|
||||
if size > Reader.remaining(d) then
|
||||
Reader.fail(d, "rans: data past the end")
|
||||
return false
|
||||
end
|
||||
local off, state = ansInit(d.b, d.pos, size, r.lBase, true)
|
||||
if not off then
|
||||
Reader.fail(d, "rans: bad initial state")
|
||||
return false
|
||||
end
|
||||
r.base, r.off, r.state = d.pos, off, state :: number
|
||||
d.pos += size
|
||||
return true
|
||||
end
|
||||
|
||||
-- decodes n symbols into out[first .. first + n - 1] (0-based symbol values)
|
||||
local function ransRead(r: Rans, n: number, out: { number }, first: number)
|
||||
local b, base, off, state = r.b, r.base, r.off, r.state
|
||||
local lBase, bits = r.lBase, r.precBits
|
||||
local mask = 2 ^ bits - 1
|
||||
local lut, prob, cum = r.lut, r.prob, r.cum
|
||||
for i = first, first + n - 1 do
|
||||
while state < lBase and off > 0 do
|
||||
off -= 1
|
||||
state = state * 256 + readu8(b, base + off)
|
||||
end
|
||||
local quo, rem = rshift(state, bits), band(state, mask)
|
||||
local s = lut[rem + 1]
|
||||
state = quo * prob[s] + rem - cum[s]
|
||||
out[i] = s - 1
|
||||
end
|
||||
r.off, r.state = off, state
|
||||
end
|
||||
|
||||
local function decodeTagged(d: D, n: number, comps: number, out: { number }): boolean
|
||||
local tag = ransCreate(d, precisionBits(5))
|
||||
if not tag or not ransStart(d, tag) then
|
||||
return false
|
||||
end
|
||||
if n > 0 and tag.numSymbols == 0 then
|
||||
Reader.fail(d, "rans: no symbols")
|
||||
return false
|
||||
end
|
||||
Reader.startBits(d, false)
|
||||
local len = { 0 }
|
||||
local k = 1
|
||||
local i = 0
|
||||
while i < n do
|
||||
ransRead(tag, 1, len, 1)
|
||||
local bitLength = len[1]
|
||||
for _ = 1, comps do
|
||||
if k > n then
|
||||
break
|
||||
end
|
||||
out[k] = Reader.bits(d, bitLength)
|
||||
k += 1
|
||||
end
|
||||
if d.bad then
|
||||
return false
|
||||
end
|
||||
i += comps
|
||||
end
|
||||
Reader.endBits(d)
|
||||
return true
|
||||
end
|
||||
|
||||
local function decodeRaw(d: D, n: number, out: { number }): boolean
|
||||
local maxBitLength = Reader.u8(d)
|
||||
if d.bad then
|
||||
return false
|
||||
end
|
||||
if maxBitLength < 1 or maxBitLength > 18 then
|
||||
Reader.fail(d, "rans: bad symbol bit length")
|
||||
return false
|
||||
end
|
||||
local r = ransCreate(d, precisionBits(maxBitLength))
|
||||
if not r then
|
||||
return false
|
||||
end
|
||||
if n > 0 and r.numSymbols == 0 then
|
||||
Reader.fail(d, "rans: no symbols")
|
||||
return false
|
||||
end
|
||||
if not ransStart(d, r) then
|
||||
return false
|
||||
end
|
||||
ransRead(r, n, out, 1)
|
||||
return true
|
||||
end
|
||||
|
||||
-- DecodeSymbols(n, components) -> { u32 } (1-based) | nil (d.bad set)
|
||||
function Reader.symbols(d: D, n: number, comps: number): { number }?
|
||||
local out = table.create(n, 0)
|
||||
if n == 0 then
|
||||
return out
|
||||
end
|
||||
local scheme = Reader.u8(d)
|
||||
if d.bad then
|
||||
return nil
|
||||
end
|
||||
local ok
|
||||
if scheme == 0 then
|
||||
ok = decodeTagged(d, n, math.max(comps, 1), out)
|
||||
elseif scheme == 1 then
|
||||
ok = decodeRaw(d, n, out)
|
||||
else
|
||||
Reader.fail(d, "rans: unknown symbol coding scheme")
|
||||
ok = false
|
||||
end
|
||||
return if ok then out else nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ binary rANS
|
||||
export type Bits = { b: buffer, base: number, off: number, state: number, p0: number, p: number }
|
||||
|
||||
-- RAnsBitDecoder::StartDecoding: prob_zero, the size (u32 before 2.2), the bytes
|
||||
function Reader.bitDecoder(d: D): Bits?
|
||||
local p0 = Reader.u8(d)
|
||||
local size = Reader.count(d, 0x0202)
|
||||
if d.bad then
|
||||
return nil
|
||||
end
|
||||
if size > Reader.remaining(d) then
|
||||
Reader.fail(d, "rabs: data past the end")
|
||||
return nil
|
||||
end
|
||||
local off, state = ansInit(d.b, d.pos, size, 4096, false)
|
||||
if not off then
|
||||
Reader.fail(d, "rabs: bad initial state")
|
||||
return nil
|
||||
end
|
||||
local bd = { b = d.b, base = d.pos, off = off, state = state :: number, p0 = p0, p = 256 - p0 }
|
||||
d.pos += size
|
||||
return bd
|
||||
end
|
||||
|
||||
-- rabs_desc_read: one bit (true / false)
|
||||
function Reader.bit(bd: Bits): boolean
|
||||
local state, off = bd.state, bd.off
|
||||
if state < 4096 and off > 0 then
|
||||
off -= 1
|
||||
state = state * 256 + readu8(bd.b, bd.base + off)
|
||||
bd.off = off
|
||||
end
|
||||
local quot, rem = rshift(state, 8), band(state, 255)
|
||||
local p = bd.p
|
||||
local xn = quot * p
|
||||
if rem < p then
|
||||
bd.state = xn + rem
|
||||
return true
|
||||
end
|
||||
bd.state = state - xn - p
|
||||
return false
|
||||
end
|
||||
|
||||
return Reader
|
||||
@@ -0,0 +1,353 @@
|
||||
--!strict
|
||||
-- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7).
|
||||
-- A codec, not a format: model/gltf (and any format carrying Draco data) calls it on a byte range.
|
||||
-- Ported from Google's Draco 1.5.7 (Apache-2.0, licenses/draco-LICENSE.txt): the decoder only, bitstream versions
|
||||
-- 1.0 - 2.2 for meshes (sequential and Edgebreaker connectivity: standard, predictive and valence traversals; topology
|
||||
-- splits, attribute seams), sequential point clouds and kd-tree point clouds (2.3); attribute decoders generic /
|
||||
-- integer / quantization / octahedral normals; prediction schemes difference, parallelogram, multi-parallelogram,
|
||||
-- constrained multi-parallelogram, tex coords (deprecated and portable), geometric normal, with the wrap and normal
|
||||
-- octahedron transforms; metadata. Values match draco_decoder bit for bit (f32 rounding at every step of the
|
||||
-- dequantization).
|
||||
-- Not supported: the pre-2.3 kd-tree point cloud layouts (Err.UNSUPPORTED).
|
||||
--
|
||||
-- local Draco = require("@rosetta/codecs/model/Draco")
|
||||
-- local g, err = Draco.decode(buf, off?, len?, opts?) -- buffer | string
|
||||
-- g.kind ("mesh" | "points"), g.numPoints, g.numFaces, g.indices (u32 x 3 per face, or nil for points)
|
||||
-- g.attributes[i] = { name = "POSITION" | "NORMAL" | "COLOR" | "TEX_COORD" | "GENERIC" | ..., uniqueId,
|
||||
-- components, type = "f32" | "u8" | "i16" | ..., normalized, data (per point, packed) }
|
||||
-- Draco.attribute(g, uniqueId) -> the attribute with that unique id (glTF's attribute map)
|
||||
-- g.metadata = { entries = { [name] = buffer }, children = { [name] = Metadata }, attributes = { [uniqueId] = Metadata } }
|
||||
--
|
||||
-- Options: maxPoints (default 2^24), maxFaces (default 2^24): larger geometry returns Err.LIMIT.
|
||||
-- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT).
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Reader = require("@rosetta/codecs/model/Draco/Reader")
|
||||
local Connectivity = require("@rosetta/codecs/model/Draco/Connectivity")
|
||||
local Attributes = require("@rosetta/codecs/model/Draco/Attributes")
|
||||
|
||||
local Draco = {}
|
||||
|
||||
local NAMES = { [0] = "POSITION", "NORMAL", "COLOR", "TEX_COORD", "GENERIC", "TANGENT", "MATERIAL", "JOINTS", "WEIGHTS" }
|
||||
local TYPES = { "i8", "u8", "i16", "u16", "i32", "u32", "i64", "u64", "f32", "f64", "bool" }
|
||||
Draco.ATTRIBUTE_NAMES = NAMES
|
||||
Draco.DATA_TYPES = TYPES
|
||||
|
||||
export type Attribute = {
|
||||
name: string,
|
||||
typeId: number,
|
||||
uniqueId: number,
|
||||
components: number,
|
||||
type: string,
|
||||
normalized: boolean,
|
||||
data: buffer,
|
||||
}
|
||||
export type Metadata = { entries: { [string]: buffer }, children: { [string]: Metadata }, attributes: { [number]: Metadata }? }
|
||||
export type Geometry = {
|
||||
kind: "mesh" | "points",
|
||||
version: string,
|
||||
method: string,
|
||||
numPoints: number,
|
||||
numFaces: number,
|
||||
indices: buffer?,
|
||||
attributes: { Attribute },
|
||||
metadata: Metadata?,
|
||||
}
|
||||
export type Header = { major: number, minor: number, kind: "mesh" | "points", method: number, flags: number }
|
||||
|
||||
-- sniff(buf, off?) -> whether the bytes start with "DRACO"
|
||||
function Draco.sniff(buf: buffer, off: number?): boolean
|
||||
local o = off or 0
|
||||
return buffer.len(buf) >= o + 5 and buffer.readstring(buf, o, 5) == "DRACO"
|
||||
end
|
||||
|
||||
local function header(d: Reader.D): (Header?, string?)
|
||||
if Reader.remaining(d) < 11 then
|
||||
return nil, "truncated header"
|
||||
end
|
||||
if buffer.readstring(d.b, d.pos, 5) ~= "DRACO" then
|
||||
return nil, "not Draco data"
|
||||
end
|
||||
d.pos += 5
|
||||
local major, minor, kind, method = Reader.u8(d), Reader.u8(d), Reader.u8(d), Reader.u8(d)
|
||||
local flags = Reader.u16(d)
|
||||
if kind > 1 then
|
||||
return nil, "unsupported: geometry type " .. kind
|
||||
end
|
||||
return { major = major, minor = minor, kind = if kind == 0 then "points" else "mesh", method = method, flags = flags }, nil
|
||||
end
|
||||
|
||||
-- info(buf, off?, len?) -> the header
|
||||
function Draco.info(src: buffer | string, off: number?, len: number?): (Header?, Err.Err?)
|
||||
local buf, o, l, aerr = Bytes.span("draco", src, off, len)
|
||||
if not buf then
|
||||
return nil, aerr
|
||||
end
|
||||
local d = Reader.new(buf, o, o + l, 0)
|
||||
local h, err = header(d)
|
||||
if not h then
|
||||
return nil, Err.from(err, 0)
|
||||
end
|
||||
return h, nil
|
||||
end
|
||||
|
||||
local function metadataElement(d: Reader.D, depth: number): Metadata?
|
||||
if depth > 1000 then
|
||||
return nil
|
||||
end
|
||||
local m: Metadata = { entries = {}, children = {} }
|
||||
local n = Reader.varint(d)
|
||||
if d.bad or n > Reader.remaining(d) then
|
||||
return nil
|
||||
end
|
||||
for _ = 1, n do
|
||||
local nameLen = Reader.u8(d)
|
||||
if d.bad or Reader.remaining(d) < nameLen then
|
||||
return nil
|
||||
end
|
||||
local name = buffer.readstring(d.b, d.pos, nameLen)
|
||||
d.pos += nameLen
|
||||
local size = Reader.varint(d)
|
||||
if d.bad or size == 0 or size > Reader.remaining(d) then
|
||||
return nil
|
||||
end
|
||||
local v = buffer.create(size)
|
||||
buffer.copy(v, 0, d.b, d.pos, size)
|
||||
d.pos += size
|
||||
m.entries[name] = v
|
||||
end
|
||||
local subs = Reader.varint(d)
|
||||
if d.bad or subs > Reader.remaining(d) then
|
||||
return nil
|
||||
end
|
||||
for _ = 1, subs do
|
||||
local nameLen = Reader.u8(d)
|
||||
if d.bad or Reader.remaining(d) < nameLen then
|
||||
return nil
|
||||
end
|
||||
local name = buffer.readstring(d.b, d.pos, nameLen)
|
||||
d.pos += nameLen
|
||||
local child = metadataElement(d, depth + 1)
|
||||
if not child then
|
||||
return nil
|
||||
end
|
||||
m.children[name] = child
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
local function metadata(d: Reader.D): Metadata?
|
||||
local n = Reader.varint(d)
|
||||
if d.bad or n > Reader.remaining(d) then
|
||||
return nil
|
||||
end
|
||||
local atts: { [number]: Metadata } = {}
|
||||
for _ = 1, n do
|
||||
local id = Reader.varint(d)
|
||||
local m = metadataElement(d, 0)
|
||||
if not m then
|
||||
return nil
|
||||
end
|
||||
atts[id] = m
|
||||
end
|
||||
local m = metadataElement(d, 0)
|
||||
if not m then
|
||||
return nil
|
||||
end
|
||||
m.attributes = atts
|
||||
return m
|
||||
end
|
||||
|
||||
local WRITE: { [number]: (buffer, number, number) -> () } = {
|
||||
[1] = buffer.writei8,
|
||||
[2] = buffer.writeu8,
|
||||
[3] = buffer.writei16,
|
||||
[4] = buffer.writeu16,
|
||||
[5] = buffer.writei32,
|
||||
[6] = buffer.writeu32,
|
||||
[9] = buffer.writef32,
|
||||
[11] = buffer.writeu8,
|
||||
}
|
||||
|
||||
-- per point output buffer of an attribute
|
||||
local function expand(a: Attributes.Attr, numPoints: number): (buffer?, string?)
|
||||
local size = Attributes.DT_LENGTH[a.dataType]
|
||||
local comps = a.comps
|
||||
local stride = size * comps
|
||||
local out = buffer.create(numPoints * stride)
|
||||
local map = a.map
|
||||
local n = a.numValues
|
||||
if a.raw then
|
||||
local raw = a.raw :: buffer
|
||||
for p = 0, numPoints - 1 do
|
||||
local e = if map then map[p + 1] else p
|
||||
if e >= n then
|
||||
return nil, "attribute value out of range"
|
||||
end
|
||||
buffer.copy(out, p * stride, raw, e * stride, stride)
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
local vals = a.values :: { number }
|
||||
local w = WRITE[a.dataType]
|
||||
if not w then
|
||||
return nil, "unsupported: data type " .. a.dataType
|
||||
end
|
||||
for p = 0, numPoints - 1 do
|
||||
local e = if map then map[p + 1] else p
|
||||
if e >= n then
|
||||
return nil, "attribute value out of range"
|
||||
end
|
||||
local o = p * stride
|
||||
local k = e * comps
|
||||
for c = 1, comps do
|
||||
w(out, o, vals[k + c])
|
||||
o += size
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
local function decode(buf: buffer, o: number, l: number, opts: any): (Geometry?, string?, string?)
|
||||
local d = Reader.new(buf, o, o + l, 0)
|
||||
local h, herr = header(d)
|
||||
if not h then
|
||||
return nil, herr, nil
|
||||
end
|
||||
local ver = h.major * 256 + h.minor
|
||||
local maxVer = if h.kind == "points" then 0x0203 else 0x0202
|
||||
if h.major < 1 or ver > maxVer then
|
||||
return nil, string.format("unsupported: bitstream version %d.%d", h.major, h.minor), nil
|
||||
end
|
||||
d.ver = ver
|
||||
local maxPoints = (opts and opts.maxPoints) or 2 ^ 24
|
||||
local maxFaces = (opts and opts.maxFaces) or 2 ^ 24
|
||||
local meta: Metadata? = nil
|
||||
if ver >= 0x0103 and bit32.band(h.flags, 0x8000) ~= 0 then
|
||||
meta = metadata(d)
|
||||
if not meta then
|
||||
return nil, d.bad or "bad metadata", nil
|
||||
end
|
||||
end
|
||||
local mesh: Connectivity.Mesh? = nil
|
||||
local numPoints = 0
|
||||
local method
|
||||
if h.kind == "mesh" then
|
||||
if h.method == 0 then
|
||||
method = "sequential"
|
||||
local m, err = Connectivity.sequential(d)
|
||||
if not m then
|
||||
return nil, err, nil
|
||||
end
|
||||
mesh = m
|
||||
elseif h.method == 1 then
|
||||
method = "edgebreaker"
|
||||
local kind = Reader.u8(d)
|
||||
if d.bad then
|
||||
return nil, d.bad, nil
|
||||
end
|
||||
if kind > 2 then
|
||||
return nil, "unknown edgebreaker traversal " .. kind, nil
|
||||
end
|
||||
local m, err = Connectivity.edgebreaker(d, kind)
|
||||
if not m then
|
||||
return nil, err, nil
|
||||
end
|
||||
mesh = m
|
||||
else
|
||||
return nil, "unsupported: mesh encoding method " .. h.method, nil
|
||||
end
|
||||
local m = mesh :: Connectivity.Mesh
|
||||
if m.numFaces > maxFaces then
|
||||
return nil, "too many faces", "limit"
|
||||
end
|
||||
numPoints = m.numPoints
|
||||
else
|
||||
if h.method > 1 then
|
||||
return nil, "unsupported: point cloud encoding method " .. h.method, nil
|
||||
end
|
||||
method = if h.method == 1 then "kdtree" else "sequential"
|
||||
numPoints = Reader.i32(d)
|
||||
if d.bad then
|
||||
return nil, d.bad, nil
|
||||
end
|
||||
if numPoints < 0 then
|
||||
return nil, "bad point count", nil
|
||||
end
|
||||
end
|
||||
if numPoints > maxPoints then
|
||||
return nil, "too many points", "limit"
|
||||
end
|
||||
local attrs, aerr = Attributes.decode(d, { numPoints = numPoints, mesh = mesh, edgebreaker = method == "edgebreaker", kdTree = method == "kdtree" })
|
||||
if not attrs then
|
||||
return nil, aerr, nil
|
||||
end
|
||||
local g: Geometry = {
|
||||
kind = h.kind,
|
||||
version = h.major .. "." .. h.minor,
|
||||
method = method,
|
||||
numPoints = numPoints,
|
||||
numFaces = 0,
|
||||
indices = nil,
|
||||
attributes = {},
|
||||
metadata = meta,
|
||||
}
|
||||
if mesh then
|
||||
local nf = mesh.numFaces
|
||||
local idx = buffer.create(nf * 12)
|
||||
local faces = mesh.faces
|
||||
for i = 1, nf * 3 do
|
||||
local v = faces[i]
|
||||
if v < 0 or v >= numPoints then
|
||||
return nil, "face index out of range", nil
|
||||
end
|
||||
buffer.writeu32(idx, (i - 1) * 4, v)
|
||||
end
|
||||
g.numFaces = nf
|
||||
g.indices = idx
|
||||
end
|
||||
for _, a in attrs do
|
||||
local data, err = expand(a, numPoints)
|
||||
if not data then
|
||||
return nil, err, nil
|
||||
end
|
||||
table.insert(g.attributes, {
|
||||
name = NAMES[a.type] or "GENERIC",
|
||||
typeId = a.type,
|
||||
uniqueId = a.uniqueId,
|
||||
components = a.comps,
|
||||
type = TYPES[a.dataType],
|
||||
normalized = a.normalized,
|
||||
data = data,
|
||||
})
|
||||
end
|
||||
return g, nil, nil
|
||||
end
|
||||
|
||||
-- decode(src, off?, len?, opts?) -> Geometry | nil, Err
|
||||
function Draco.decode(src: buffer | string, off: number?, len: number?, opts: any?): (Geometry?, Err.Err?)
|
||||
local buf, o, l, aerr = Bytes.span("draco", src, off, len)
|
||||
if not buf then
|
||||
return nil, aerr
|
||||
end
|
||||
local ok, g, msg, kind = pcall(decode, buf, o, l, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "draco: internal error: " .. tostring(g))
|
||||
end
|
||||
if not g then
|
||||
return nil, Err.from("draco: " .. tostring(msg), nil, kind or (if string.find(tostring(msg), "^unsupported") then "unsupported" elseif string.find(tostring(msg), "truncated") then "truncated" else nil))
|
||||
end
|
||||
return g, nil
|
||||
end
|
||||
|
||||
-- attribute(g, uniqueId) -> the attribute with that unique id
|
||||
function Draco.attribute(g: Geometry, uniqueId: number): Attribute?
|
||||
for _, a in g.attributes do
|
||||
if a.uniqueId == uniqueId then
|
||||
return a
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
return Draco
|
||||
@@ -0,0 +1,282 @@
|
||||
--!strict
|
||||
-- codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16
|
||||
-- (glTF / FBX / Types.Scene layout: translation at 13..15), quaternions { x, y, z, w }, angles in degrees where a
|
||||
-- format stores degrees. Shared by FBX, Collada, USD and MeshOps instead of a copy in each. New in rosetta (the
|
||||
-- functions come from the former model/fbx/Xform, model/dae/Math and model/usda/Build helpers).
|
||||
--
|
||||
-- local m = Mat4.compose({ 1, 2, 3 }, quat, { 2, 2, 2 }) -- T * R * S
|
||||
-- local t, r, s = Mat4.decompose(m) -- (decomposeStrict: nil for shear / projective / singular)
|
||||
-- local w = Mat4.mul(parent, m) -- = Types.Scene.mul
|
||||
-- local inv = Mat4.inverse(m) -- affine inverse | nil
|
||||
-- local x, y, z = Mat4.point(m, px, py, pz)
|
||||
local Types = require("@rosetta/Types")
|
||||
|
||||
local Mat4 = {}
|
||||
|
||||
export type M4 = { number }
|
||||
|
||||
local sqrt, abs, sin, cos, rad = math.sqrt, math.abs, math.sin, math.cos, math.rad
|
||||
|
||||
function Mat4.identity(): M4
|
||||
return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
|
||||
end
|
||||
|
||||
-- mul(a, b) -> a * b
|
||||
Mat4.mul = Types.Scene.mul
|
||||
|
||||
function Mat4.translation(x: number, y: number, z: number): M4
|
||||
return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 }
|
||||
end
|
||||
|
||||
function Mat4.scaling(x: number, y: number, z: number): M4
|
||||
return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 }
|
||||
end
|
||||
|
||||
-- rotation(axis, degrees) -> the rotation about axis 1 (X), 2 (Y) or 3 (Z)
|
||||
function Mat4.rotation(axis: number, degrees: number): M4
|
||||
local a = rad(degrees)
|
||||
local c, s = cos(a), sin(a)
|
||||
if axis == 1 then
|
||||
return { 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1 }
|
||||
elseif axis == 2 then
|
||||
return { c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1 }
|
||||
end
|
||||
return { c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
|
||||
end
|
||||
|
||||
local AXIS = { x = 1, y = 2, z = 3 }
|
||||
-- euler(x, y, z, order?) -> the rotation applying the axes in order (default "xyz": R = Rz * Ry * Rx), degrees
|
||||
function Mat4.euler(x: number, y: number, z: number, order: string?): M4
|
||||
local o = order or "xyz"
|
||||
local deg = { x = x, y = y, z = z }
|
||||
local m = Mat4.identity()
|
||||
for i = 1, 3 do
|
||||
local a = string.sub(o, i, i)
|
||||
m = Mat4.mul(Mat4.rotation(AXIS[a] or i, deg[a] or 0), m)
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
-- axisAngle(x, y, z, degrees) -> quaternion
|
||||
function Mat4.axisAngle(x: number, y: number, z: number, degrees: number): { number }
|
||||
local l = sqrt(x * x + y * y + z * z)
|
||||
if l < 1e-12 then
|
||||
return { 0, 0, 0, 1 }
|
||||
end
|
||||
local h = rad(degrees) / 2
|
||||
local s = sin(h) / l
|
||||
return { x * s, y * s, z * s, cos(h) }
|
||||
end
|
||||
|
||||
-- fromQuat(q) -> the rotation matrix of a quaternion
|
||||
function Mat4.fromQuat(q: { number }): M4
|
||||
local x, y, z, w = q[1], q[2], q[3], q[4]
|
||||
local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z
|
||||
return {
|
||||
1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0,
|
||||
2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0,
|
||||
2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0,
|
||||
0, 0, 0, 1,
|
||||
}
|
||||
end
|
||||
|
||||
-- quat(m) -> the unit quaternion of the rotation in m's upper 3x3 (columns assumed orthonormal)
|
||||
function Mat4.quat(m: M4): { number }
|
||||
local m00, m01, m02 = m[1], m[5], m[9]
|
||||
local m10, m11, m12 = m[2], m[6], m[10]
|
||||
local m20, m21, m22 = m[3], m[7], m[11]
|
||||
local tr = m00 + m11 + m22
|
||||
local x, y, z, w
|
||||
if tr > 0 then
|
||||
local s = sqrt(tr + 1) * 2
|
||||
w, x, y, z = s / 4, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s
|
||||
elseif m00 > m11 and m00 > m22 then
|
||||
local s = sqrt(math.max(1 + m00 - m11 - m22, 1e-30)) * 2
|
||||
w, x, y, z = (m21 - m12) / s, s / 4, (m01 + m10) / s, (m02 + m20) / s
|
||||
elseif m11 > m22 then
|
||||
local s = sqrt(math.max(1 + m11 - m00 - m22, 1e-30)) * 2
|
||||
w, x, y, z = (m02 - m20) / s, (m01 + m10) / s, s / 4, (m12 + m21) / s
|
||||
else
|
||||
local s = sqrt(math.max(1 + m22 - m00 - m11, 1e-30)) * 2
|
||||
w, x, y, z = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, s / 4
|
||||
end
|
||||
local n = sqrt(x * x + y * y + z * z + w * w)
|
||||
if n == 0 or n ~= n then
|
||||
return { 0, 0, 0, 1 }
|
||||
end
|
||||
return { x / n, y / n, z / n, w / n }
|
||||
end
|
||||
|
||||
-- eulerXYZ(q) -> Euler XYZ degrees (R = Rz * Ry * Rx) of a quaternion
|
||||
function Mat4.eulerXYZ(q: { number }): { number }
|
||||
local m = Mat4.fromQuat(q)
|
||||
local sy = math.clamp(-m[3], -1, 1) -- m[3] = r20 = -sin(y)
|
||||
local y = math.asin(sy)
|
||||
local x, z
|
||||
if abs(sy) < 0.9999999 then
|
||||
x = math.atan2(m[7], m[11])
|
||||
z = math.atan2(m[2], m[1])
|
||||
else
|
||||
x = math.atan2(-m[10], m[6])
|
||||
z = 0
|
||||
end
|
||||
return { math.deg(x), math.deg(y), math.deg(z) }
|
||||
end
|
||||
|
||||
-- compose(t?, r?, s?) -> T * R * S (glTF node semantics)
|
||||
function Mat4.compose(t: { number }?, r: { number }?, s: { number }?): M4
|
||||
local m = if r then Mat4.fromQuat(r) else Mat4.identity()
|
||||
if s then
|
||||
for k = 0, 2 do
|
||||
m[k * 4 + 1] *= s[k + 1]
|
||||
m[k * 4 + 2] *= s[k + 1]
|
||||
m[k * 4 + 3] *= s[k + 1]
|
||||
end
|
||||
end
|
||||
if t then
|
||||
m[13], m[14], m[15] = t[1], t[2], t[3]
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
local function det3(m: M4): 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 split(m: M4, strict: boolean): ({ number }?, { number }?, { number }?)
|
||||
if strict and (abs(m[4]) > 1e-6 or abs(m[8]) > 1e-6 or abs(m[12]) > 1e-6 or abs(m[16] - 1) > 1e-6) then
|
||||
return nil, nil, nil
|
||||
end
|
||||
local sx = sqrt(m[1] * m[1] + m[2] * m[2] + m[3] * m[3])
|
||||
local sy = sqrt(m[5] * m[5] + m[6] * m[6] + m[7] * m[7])
|
||||
local sz = sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11])
|
||||
if strict and (sx < 1e-12 or sy < 1e-12 or sz < 1e-12) then
|
||||
return nil, nil, nil
|
||||
end
|
||||
if det3(m) < 0 then
|
||||
sx = -sx
|
||||
end
|
||||
local ix = if sx ~= 0 then 1 / sx else 0
|
||||
local iy = if sy ~= 0 then 1 / sy else 0
|
||||
local iz = if sz ~= 0 then 1 / sz else 0
|
||||
local r = { m[1] * ix, m[2] * ix, m[3] * ix, 0, m[5] * iy, m[6] * iy, m[7] * iy, 0, m[9] * iz, m[10] * iz, m[11] * iz, 0, 0, 0, 0, 1 }
|
||||
if strict then
|
||||
local dxy = r[1] * r[5] + r[2] * r[6] + r[3] * r[7]
|
||||
local dxz = r[1] * r[9] + r[2] * r[10] + r[3] * r[11]
|
||||
local dyz = r[5] * r[9] + r[6] * r[10] + r[7] * r[11]
|
||||
if abs(dxy) > 1e-4 or abs(dxz) > 1e-4 or abs(dyz) > 1e-4 then
|
||||
return nil, nil, nil
|
||||
end
|
||||
end
|
||||
return { m[13], m[14], m[15] }, Mat4.quat(r), { sx, sy, sz }
|
||||
end
|
||||
|
||||
-- decompose(m) -> translation, rotation (quaternion), scale (a negative determinant flips the x scale; shear is lost)
|
||||
function Mat4.decompose(m: M4): ({ number }, { number }, { number })
|
||||
local t, r, s = split(m, false)
|
||||
return t :: { number }, r :: { number }, s :: { number }
|
||||
end
|
||||
|
||||
-- decomposeStrict(m) -> translation, rotation, scale | nil for matrices TRS cannot express (a projective row, shear,
|
||||
-- a zero scale)
|
||||
function Mat4.decomposeStrict(m: M4): ({ number }?, { number }?, { number }?)
|
||||
return split(m, true)
|
||||
end
|
||||
|
||||
-- inverse(m) -> the inverse of an affine matrix (general upper 3x3) | nil when singular
|
||||
function Mat4.inverse(m: M4): M4?
|
||||
local a, b, c = m[1], m[5], m[9]
|
||||
local d, e, f = m[2], m[6], m[10]
|
||||
local g, h, i = m[3], m[7], m[11]
|
||||
local A, B, C = e * i - f * h, -(d * i - f * g), d * h - e * g
|
||||
local det = a * A + b * B + c * C
|
||||
if det == 0 or det ~= det then
|
||||
return nil
|
||||
end
|
||||
local k = 1 / det
|
||||
local r = {
|
||||
A * k, B * k, C * k, 0,
|
||||
-(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, 0,
|
||||
(b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k, 0,
|
||||
0, 0, 0, 1,
|
||||
}
|
||||
local tx, ty, tz = m[13], m[14], m[15]
|
||||
r[13] = -(r[1] * tx + r[5] * ty + r[9] * tz)
|
||||
r[14] = -(r[2] * tx + r[6] * ty + r[10] * tz)
|
||||
r[15] = -(r[3] * tx + r[7] * ty + r[11] * tz)
|
||||
return r
|
||||
end
|
||||
|
||||
-- inverseFull(m) -> the inverse of any invertible 4x4 (projective rows too) | nil when singular
|
||||
function Mat4.inverseFull(m: M4): M4?
|
||||
local a = m
|
||||
local inv = table.create(16, 0)
|
||||
inv[1] = a[6] * a[11] * a[16] - a[6] * a[12] * a[15] - a[10] * a[7] * a[16] + a[10] * a[8] * a[15] + a[14] * a[7] * a[12] - a[14] * a[8] * a[11]
|
||||
inv[5] = -a[5] * a[11] * a[16] + a[5] * a[12] * a[15] + a[9] * a[7] * a[16] - a[9] * a[8] * a[15] - a[13] * a[7] * a[12] + a[13] * a[8] * a[11]
|
||||
inv[9] = a[5] * a[10] * a[16] - a[5] * a[12] * a[14] - a[9] * a[6] * a[16] + a[9] * a[8] * a[14] + a[13] * a[6] * a[12] - a[13] * a[8] * a[10]
|
||||
inv[13] = -a[5] * a[10] * a[15] + a[5] * a[11] * a[14] + a[9] * a[6] * a[15] - a[9] * a[7] * a[14] - a[13] * a[6] * a[11] + a[13] * a[7] * a[10]
|
||||
inv[2] = -a[2] * a[11] * a[16] + a[2] * a[12] * a[15] + a[10] * a[3] * a[16] - a[10] * a[4] * a[15] - a[14] * a[3] * a[12] + a[14] * a[4] * a[11]
|
||||
inv[6] = a[1] * a[11] * a[16] - a[1] * a[12] * a[15] - a[9] * a[3] * a[16] + a[9] * a[4] * a[15] + a[13] * a[3] * a[12] - a[13] * a[4] * a[11]
|
||||
inv[10] = -a[1] * a[10] * a[16] + a[1] * a[12] * a[14] + a[9] * a[2] * a[16] - a[9] * a[4] * a[14] - a[13] * a[2] * a[12] + a[13] * a[4] * a[10]
|
||||
inv[14] = a[1] * a[10] * a[15] - a[1] * a[11] * a[14] - a[9] * a[2] * a[15] + a[9] * a[3] * a[14] + a[13] * a[2] * a[11] - a[13] * a[3] * a[10]
|
||||
inv[3] = a[2] * a[7] * a[16] - a[2] * a[8] * a[15] - a[6] * a[3] * a[16] + a[6] * a[4] * a[15] + a[14] * a[3] * a[8] - a[14] * a[4] * a[7]
|
||||
inv[7] = -a[1] * a[7] * a[16] + a[1] * a[8] * a[15] + a[5] * a[3] * a[16] - a[5] * a[4] * a[15] - a[13] * a[3] * a[8] + a[13] * a[4] * a[7]
|
||||
inv[11] = a[1] * a[6] * a[16] - a[1] * a[8] * a[14] - a[5] * a[2] * a[16] + a[5] * a[4] * a[14] + a[13] * a[2] * a[8] - a[13] * a[4] * a[6]
|
||||
inv[15] = -a[1] * a[6] * a[15] + a[1] * a[7] * a[14] + a[5] * a[2] * a[15] - a[5] * a[3] * a[14] - a[13] * a[2] * a[7] + a[13] * a[3] * a[6]
|
||||
inv[4] = -a[2] * a[7] * a[12] + a[2] * a[8] * a[11] + a[6] * a[3] * a[12] - a[6] * a[4] * a[11] - a[10] * a[3] * a[8] + a[10] * a[4] * a[7]
|
||||
inv[8] = a[1] * a[7] * a[12] - a[1] * a[8] * a[11] - a[5] * a[3] * a[12] + a[5] * a[4] * a[11] + a[9] * a[3] * a[8] - a[9] * a[4] * a[7]
|
||||
inv[12] = -a[1] * a[6] * a[12] + a[1] * a[8] * a[10] + a[5] * a[2] * a[12] - a[5] * a[4] * a[10] - a[9] * a[2] * a[8] + a[9] * a[4] * a[6]
|
||||
inv[16] = a[1] * a[6] * a[11] - a[1] * a[7] * a[10] - a[5] * a[2] * a[11] + a[5] * a[3] * a[10] + a[9] * a[2] * a[7] - a[9] * a[3] * a[6]
|
||||
local det = a[1] * inv[1] + a[2] * inv[5] + a[3] * inv[9] + a[4] * inv[13]
|
||||
if det == 0 or det ~= det then
|
||||
return nil
|
||||
end
|
||||
for k = 1, 16 do
|
||||
inv[k] /= det
|
||||
end
|
||||
return inv
|
||||
end
|
||||
|
||||
-- transpose3(m) -> m with its upper 3x3 transposed and no translation (the inverse of a pure rotation)
|
||||
function Mat4.transpose3(m: M4): M4
|
||||
return { m[1], m[5], m[9], 0, m[2], m[6], m[10], 0, m[3], m[7], m[11], 0, 0, 0, 0, 1 }
|
||||
end
|
||||
|
||||
-- fromRows(v, at?) -> column-major from 16 row-major values at v[at] (default 1; missing values: identity)
|
||||
function Mat4.fromRows(v: { number }, at: number?): M4
|
||||
local o = (at or 1) - 1
|
||||
local m = table.create(16, 0)
|
||||
for r = 0, 3 do
|
||||
for c = 0, 3 do
|
||||
m[c * 4 + r + 1] = v[o + r * 4 + c + 1] or (if r == c then 1 else 0)
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
-- toRows(m) -> the 16 values row-major
|
||||
function Mat4.toRows(m: M4): { number }
|
||||
local v = table.create(16, 0)
|
||||
for r = 0, 3 do
|
||||
for c = 0, 3 do
|
||||
v[r * 4 + c + 1] = m[c * 4 + r + 1]
|
||||
end
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
-- point(m, x, y, z) -> m * (x, y, z, 1)
|
||||
function Mat4.point(m: M4, x: number, y: number, z: number): (number, number, number)
|
||||
return 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
|
||||
|
||||
-- normalMatrix(m) -> the inverse transpose of the upper 3x3 (for normals) as a 4x4 (identity when singular)
|
||||
function Mat4.normalMatrix(m: M4): M4
|
||||
local inv = Mat4.inverse({ m[1], m[2], m[3], 0, m[5], m[6], m[7], 0, m[9], m[10], m[11], 0, 0, 0, 0, 1 })
|
||||
if not inv then
|
||||
return Mat4.identity()
|
||||
end
|
||||
return Mat4.transpose3(inv)
|
||||
end
|
||||
|
||||
return Mat4
|
||||
@@ -0,0 +1,543 @@
|
||||
--!strict
|
||||
-- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks
|
||||
-- scene.roots recursively (TRS or column-major `matrix` per node; a scene without nodes uses its meshes as they are),
|
||||
-- applies the transforms to POSITION (and the inverse transpose to NORMAL), reverses the winding under mirroring
|
||||
-- transforms, reads every accessor type to numbers and concatenates all primitives (triangles with or without indices,
|
||||
-- polygons, strips, fans, points; lines are skipped). Shared here because a format cannot require another one
|
||||
-- (ops/MeshOps.merge is the editing-side equivalent).
|
||||
-- Never throws: bad input returns nil, message.
|
||||
local Types = require("@rosetta/Types")
|
||||
|
||||
local Flatten = {}
|
||||
|
||||
local readf32, readf64 = buffer.readf32, buffer.readf64
|
||||
local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
|
||||
local readi8, readi16, readi32 = buffer.readi8, buffer.readi16, buffer.readi32
|
||||
|
||||
local SIZE = Types.COMPONENT_SIZE
|
||||
-- normalized integer types: their scale (raw / scale = the normalized value)
|
||||
local NORM: { [string]: number } = { unorm8 = 255, unorm16 = 65535, snorm8 = 127, snorm16 = 32767 }
|
||||
|
||||
export type Attr = {
|
||||
type: string, -- the accessor type shared by every part ("f32" when the parts disagree)
|
||||
components: number,
|
||||
raw: boolean, -- values are raw integers of a normalized type (unorm8: 0..255), else plain numbers
|
||||
values: { number }, -- count * components
|
||||
}
|
||||
export type PartInfo = {
|
||||
prim: Types.Primitive,
|
||||
mesh: Types.Mesh?,
|
||||
node: Types.Node?,
|
||||
firstVertex: number, -- 0-based offset of the part's vertices in the merged mesh
|
||||
vertexCount: number,
|
||||
firstFace: number, -- 0-based offset of the part's faces
|
||||
faceCount: number,
|
||||
identity: boolean, -- no transform was applied
|
||||
}
|
||||
export type Merged = {
|
||||
count: number, -- vertices
|
||||
attrs: { [string]: Attr }, -- POSITION and NORMAL in world space (f32 values), the others as read
|
||||
sizes: { number }?, -- vertices per face (nil: no part has faces, a point cloud)
|
||||
corners: { number }, -- 0-based vertex indices, face after face
|
||||
parts: { PartInfo },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ accessors
|
||||
-- numbers(acc, raw) -> the accessor's count * components values (normalized types divided out unless raw), or nil, msg
|
||||
function Flatten.numbers(acc: any, raw: boolean?): ({ number }?, string?)
|
||||
if type(acc) ~= "table" or type(acc.data) ~= "buffer" then
|
||||
return nil, "accessor without a data buffer"
|
||||
end
|
||||
local t, comps, count = acc.type, acc.components, acc.count
|
||||
local size = SIZE[t]
|
||||
if size == nil then
|
||||
return nil, "unknown accessor type " .. tostring(t)
|
||||
end
|
||||
if type(comps) ~= "number" or type(count) ~= "number" or comps < 1 or comps > 16 or count < 0 or comps % 1 ~= 0 or count % 1 ~= 0 then
|
||||
return nil, "bad accessor components / count"
|
||||
end
|
||||
local n = count * comps
|
||||
local d: buffer = acc.data
|
||||
if buffer.len(d) < n * size then
|
||||
return nil, "accessor data shorter than count * components"
|
||||
end
|
||||
local out = table.create(n) :: { number }
|
||||
if t == "f32" then
|
||||
for i = 0, n - 1 do
|
||||
out[i + 1] = readf32(d, i * 4)
|
||||
end
|
||||
elseif t == "f64" then
|
||||
for i = 0, n - 1 do
|
||||
out[i + 1] = readf64(d, i * 8)
|
||||
end
|
||||
elseif t == "u8" or t == "unorm8" then
|
||||
for i = 0, n - 1 do
|
||||
out[i + 1] = readu8(d, i)
|
||||
end
|
||||
elseif t == "u16" or t == "unorm16" then
|
||||
for i = 0, n - 1 do
|
||||
out[i + 1] = readu16(d, i * 2)
|
||||
end
|
||||
elseif t == "u32" then
|
||||
for i = 0, n - 1 do
|
||||
out[i + 1] = readu32(d, i * 4)
|
||||
end
|
||||
elseif t == "i8" or t == "snorm8" then
|
||||
for i = 0, n - 1 do
|
||||
out[i + 1] = readi8(d, i)
|
||||
end
|
||||
elseif t == "i16" or t == "snorm16" then
|
||||
for i = 0, n - 1 do
|
||||
out[i + 1] = readi16(d, i * 2)
|
||||
end
|
||||
else -- i32
|
||||
for i = 0, n - 1 do
|
||||
out[i + 1] = readi32(d, i * 4)
|
||||
end
|
||||
end
|
||||
local scale = NORM[t]
|
||||
if scale and not raw then
|
||||
local signed = t == "snorm8" or t == "snorm16"
|
||||
for i = 1, n do
|
||||
local v = out[i] / scale
|
||||
out[i] = if signed and v < -1 then -1 else v
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ transforms
|
||||
local IDENTITY = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
|
||||
|
||||
local mul = Types.Scene.mul -- column-major 4x4 product a * b
|
||||
|
||||
local function numList(v: any, n: number): boolean
|
||||
if type(v) ~= "table" then
|
||||
return false
|
||||
end
|
||||
for i = 1, n do
|
||||
if type(v[i]) ~= "number" then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- a node's local matrix (nil: none), or nil, message
|
||||
local function localMatrix(node: any): ({ number }?, string?)
|
||||
if node.matrix ~= nil then
|
||||
if not numList(node.matrix, 16) then
|
||||
return nil, "node matrix is not 16 numbers"
|
||||
end
|
||||
local m = table.create(16) :: { number }
|
||||
for i = 1, 16 do
|
||||
m[i] = node.matrix[i]
|
||||
end
|
||||
return m, nil
|
||||
end
|
||||
local t, q, s = node.translation, node.rotation, node.scale
|
||||
if t == nil and q == nil and s == nil then
|
||||
return nil, nil
|
||||
end
|
||||
if (t ~= nil and not numList(t, 3)) or (q ~= nil and not numList(q, 4)) or (s ~= nil and not numList(s, 3)) then
|
||||
return nil, "bad node translation / rotation / scale"
|
||||
end
|
||||
local x, y, z, w = 0, 0, 0, 1
|
||||
if q then
|
||||
x, y, z, w = q[1], q[2], q[3], q[4]
|
||||
end
|
||||
local sx, sy, sz = 1, 1, 1
|
||||
if s then
|
||||
sx, sy, sz = s[1], s[2], s[3]
|
||||
end
|
||||
local tx, ty, tz = 0, 0, 0
|
||||
if t then
|
||||
tx, ty, tz = t[1], t[2], t[3]
|
||||
end
|
||||
return {
|
||||
(1 - 2 * (y * y + z * z)) * sx,
|
||||
(2 * (x * y + z * w)) * sx,
|
||||
(2 * (x * z - y * w)) * sx,
|
||||
0,
|
||||
(2 * (x * y - z * w)) * sy,
|
||||
(1 - 2 * (x * x + z * z)) * sy,
|
||||
(2 * (y * z + x * w)) * sy,
|
||||
0,
|
||||
(2 * (x * z + y * w)) * sz,
|
||||
(2 * (y * z - x * w)) * sz,
|
||||
(1 - 2 * (x * x + y * y)) * sz,
|
||||
0,
|
||||
tx,
|
||||
ty,
|
||||
tz,
|
||||
1,
|
||||
},
|
||||
nil
|
||||
end
|
||||
|
||||
local function isIdentity(m: { number }): boolean
|
||||
for i = 1, 16 do
|
||||
if m[i] ~= IDENTITY[i] then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
type Instance = { prim: Types.Primitive, mesh: Types.Mesh?, node: Types.Node?, matrix: { number }? }
|
||||
|
||||
-- the primitive instances of a scene in traversal order, or nil, message
|
||||
local function instances(scene: any): ({ Instance }?, string?)
|
||||
local out: { Instance } = {}
|
||||
local nodes, meshes = scene.nodes, scene.meshes
|
||||
if type(nodes) ~= "table" or type(meshes) ~= "table" then
|
||||
return nil, "scene without nodes / meshes tables"
|
||||
end
|
||||
local function addMesh(mi: any, node: Types.Node?, m: { number }?): string?
|
||||
local mesh = meshes[mi]
|
||||
if type(mesh) ~= "table" or type(mesh.primitives) ~= "table" then
|
||||
return "node refers to a missing mesh " .. tostring(mi)
|
||||
end
|
||||
for _, prim in mesh.primitives do
|
||||
if type(prim) ~= "table" or type(prim.attributes) ~= "table" then
|
||||
return "bad primitive"
|
||||
end
|
||||
table.insert(out, { prim = prim, mesh = mesh, node = node, matrix = m })
|
||||
end
|
||||
return nil
|
||||
end
|
||||
local visiting: { [number]: boolean } = {}
|
||||
local function visit(ni: any, parent: { number }?, depth: number): string?
|
||||
local node = nodes[ni]
|
||||
if type(node) ~= "table" then
|
||||
return "missing node " .. tostring(ni)
|
||||
end
|
||||
if depth > 256 or visiting[ni] then
|
||||
return "node hierarchy is cyclic or too deep"
|
||||
end
|
||||
visiting[ni] = true
|
||||
local m, merr = localMatrix(node)
|
||||
if merr then
|
||||
return merr
|
||||
end
|
||||
local world = if m and parent then mul(parent, m) elseif m then m else parent
|
||||
if node.mesh ~= nil then
|
||||
local e = addMesh(node.mesh, node, world)
|
||||
if e then
|
||||
return e
|
||||
end
|
||||
end
|
||||
if type(node.children) == "table" then
|
||||
for _, c in node.children do
|
||||
local e = visit(c, world, depth + 1)
|
||||
if e then
|
||||
return e
|
||||
end
|
||||
end
|
||||
end
|
||||
visiting[ni] = nil
|
||||
return nil
|
||||
end
|
||||
local roots = scene.roots
|
||||
if type(roots) == "table" and #roots > 0 then
|
||||
for _, ri in roots do
|
||||
local e = visit(ri, nil, 0)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
end
|
||||
elseif #nodes > 0 then
|
||||
local isChild: { [number]: boolean } = {}
|
||||
for _, n in nodes do
|
||||
if type(n) == "table" and type(n.children) == "table" then
|
||||
for _, c in n.children do
|
||||
isChild[c] = true
|
||||
end
|
||||
end
|
||||
end
|
||||
for i = 1, #nodes do
|
||||
if not isChild[i] then
|
||||
local e = visit(i, nil, 0)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
for i = 1, #meshes do
|
||||
local e = addMesh(i, nil, nil)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ faces
|
||||
-- the faces of a primitive: sizes (nil = all triangles), corners (0-based), or "points" / "skip", or nil, message
|
||||
local function faces(prim: any, nv: number): (any, any, string?)
|
||||
local mode = prim.mode or "triangles"
|
||||
if mode == "points" then
|
||||
return "points", nil, nil
|
||||
elseif mode == "lines" or mode == "line_strip" or mode == "line_loop" then
|
||||
return "skip", nil, nil
|
||||
end
|
||||
local idx: { number }
|
||||
if prim.indices ~= nil then
|
||||
local v, err = Flatten.numbers(prim.indices, true)
|
||||
if not v then
|
||||
return nil, nil, "indices: " .. tostring(err)
|
||||
end
|
||||
idx = v
|
||||
else
|
||||
idx = table.create(nv) :: { number }
|
||||
for i = 1, nv do
|
||||
idx[i] = i - 1
|
||||
end
|
||||
end
|
||||
for i = 1, #idx do
|
||||
local v = idx[i]
|
||||
if v < 0 or v >= nv or v % 1 ~= 0 then
|
||||
return nil, nil, string.format("index %s out of range (%d vertices)", tostring(v), nv)
|
||||
end
|
||||
end
|
||||
if mode == "triangles" then
|
||||
local n = #idx - #idx % 3
|
||||
if n ~= #idx then
|
||||
local c = table.create(n) :: { number }
|
||||
table.move(idx, 1, n, 1, c)
|
||||
idx = c
|
||||
end
|
||||
return false, idx, nil
|
||||
elseif mode == "polygons" then
|
||||
if prim.faces == nil then
|
||||
return nil, nil, "polygons primitive without faces"
|
||||
end
|
||||
local sizes, err = Flatten.numbers(prim.faces, true)
|
||||
if not sizes then
|
||||
return nil, nil, "faces: " .. tostring(err)
|
||||
end
|
||||
local total = 0
|
||||
for i = 1, #sizes do
|
||||
local s = sizes[i]
|
||||
if s < 0 or s % 1 ~= 0 then
|
||||
return nil, nil, "bad face size"
|
||||
end
|
||||
total += s
|
||||
end
|
||||
if total ~= #idx then
|
||||
return nil, nil, "face sizes do not add up to the index count"
|
||||
end
|
||||
return sizes, idx, nil
|
||||
elseif mode == "triangle_strip" or mode == "triangle_fan" then
|
||||
local c = {}
|
||||
for i = 3, #idx do
|
||||
if mode == "triangle_fan" then
|
||||
table.insert(c, idx[1])
|
||||
table.insert(c, idx[i - 1])
|
||||
table.insert(c, idx[i])
|
||||
elseif i % 2 == 1 then
|
||||
table.insert(c, idx[i - 2])
|
||||
table.insert(c, idx[i - 1])
|
||||
table.insert(c, idx[i])
|
||||
else
|
||||
table.insert(c, idx[i - 1])
|
||||
table.insert(c, idx[i - 2])
|
||||
table.insert(c, idx[i])
|
||||
end
|
||||
end
|
||||
return false, c, nil
|
||||
end
|
||||
return nil, nil, "unknown primitive mode " .. tostring(mode)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ merge
|
||||
-- the fill value of a missing attribute component: colours default to opaque white, everything else to 0
|
||||
local function fill(name: string, t: string, raw: boolean): number
|
||||
if string.sub(name, 1, 6) ~= "COLOR_" then
|
||||
return 0
|
||||
end
|
||||
return if raw and NORM[t] then NORM[t] else 1
|
||||
end
|
||||
|
||||
local function f32(v: number): number
|
||||
local b = buffer.create(4)
|
||||
buffer.writef32(b, 0, v)
|
||||
return buffer.readf32(b, 0)
|
||||
end
|
||||
|
||||
-- merge(scene, keep, opts) -> Merged | nil, message. keep(name) says which attributes to carry (POSITION always).
|
||||
-- opts.triangulate fan-triangulates polygons (faces of fewer than 3 vertices are dropped then).
|
||||
function Flatten.merge(scene: any, keep: (string) -> boolean, opts: { triangulate: boolean? }?): (Merged?, string?)
|
||||
if type(scene) ~= "table" then
|
||||
return nil, "not a scene"
|
||||
end
|
||||
local list, lerr = instances(scene)
|
||||
if not list then
|
||||
return nil, lerr
|
||||
end
|
||||
local triangulate = opts and opts.triangulate or false
|
||||
-- the attribute set: union over parts, a type every part agrees on (else f32), the widest component count
|
||||
local types: { [string]: string } = {}
|
||||
local comps: { [string]: number } = {}
|
||||
local used: { Instance } = {}
|
||||
for _, inst in list do
|
||||
local mode = inst.prim.mode or "triangles"
|
||||
if mode ~= "lines" and mode ~= "line_strip" and mode ~= "line_loop" then
|
||||
local pos = inst.prim.attributes.POSITION
|
||||
if type(pos) ~= "table" then
|
||||
return nil, "primitive without POSITION"
|
||||
end
|
||||
table.insert(used, inst)
|
||||
for name, acc in inst.prim.attributes do
|
||||
if type(name) == "string" and (name == "POSITION" or keep(name)) and type(acc) == "table" then
|
||||
local t = acc.type
|
||||
if types[name] == nil then
|
||||
types[name] = t
|
||||
elseif types[name] ~= t then
|
||||
types[name] = "f32"
|
||||
end
|
||||
comps[name] = math.max(comps[name] or 0, tonumber(acc.components) or 0)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if (comps.POSITION or 3) < 3 then
|
||||
return nil, "POSITION needs 3 components"
|
||||
end
|
||||
local attrs: { [string]: Attr } = {}
|
||||
for name, t in types do
|
||||
local raw = NORM[t] ~= nil
|
||||
if name == "POSITION" or name == "NORMAL" then
|
||||
raw = false
|
||||
end
|
||||
attrs[name] = { type = if name == "POSITION" or name == "NORMAL" then "f32" else t, components = if name == "POSITION" or name == "NORMAL" then 3 else comps[name], raw = raw, values = {} }
|
||||
end
|
||||
local merged: Merged = { count = 0, attrs = attrs, sizes = nil, corners = {}, parts = {} }
|
||||
local sizes: { number } = {}
|
||||
local anyFaces = false
|
||||
local corners = merged.corners
|
||||
for _, inst in used do
|
||||
local prim: any = inst.prim
|
||||
local posAcc = prim.attributes.POSITION
|
||||
local nv = tonumber(posAcc.count) or 0
|
||||
local m = inst.matrix
|
||||
local identity = m == nil or isIdentity(m :: { number })
|
||||
local info: PartInfo = { prim = prim, mesh = inst.mesh, node = inst.node, firstVertex = merged.count, vertexCount = nv, firstFace = #sizes, faceCount = 0, identity = identity }
|
||||
for name, a in attrs do
|
||||
local acc = prim.attributes[name]
|
||||
local dst = a.values
|
||||
local n0 = #dst
|
||||
local ac = a.components
|
||||
if acc == nil then
|
||||
local f = fill(name, a.type, a.raw)
|
||||
for i = 1, nv * ac do
|
||||
dst[n0 + i] = f
|
||||
end
|
||||
else
|
||||
if acc.count ~= nv then
|
||||
return nil, name .. " count differs from POSITION"
|
||||
end
|
||||
local vals, err = Flatten.numbers(acc, a.raw and acc.type == a.type)
|
||||
if not vals then
|
||||
return nil, name .. ": " .. tostring(err)
|
||||
end
|
||||
local sc = acc.components
|
||||
if a.raw and acc.type ~= a.type then
|
||||
return nil, name .. ": mixed accessor types"
|
||||
end
|
||||
local f = fill(name, a.type, a.raw)
|
||||
if name == "POSITION" and not identity then
|
||||
local mm = m :: { number }
|
||||
for i = 0, nv - 1 do
|
||||
local x, y, z = vals[i * sc + 1], vals[i * sc + 2], vals[i * sc + 3]
|
||||
dst[n0 + i * 3 + 1] = f32(mm[1] * x + mm[5] * y + mm[9] * z + mm[13])
|
||||
dst[n0 + i * 3 + 2] = f32(mm[2] * x + mm[6] * y + mm[10] * z + mm[14])
|
||||
dst[n0 + i * 3 + 3] = f32(mm[3] * x + mm[7] * y + mm[11] * z + mm[15])
|
||||
end
|
||||
elseif name == "NORMAL" and not identity and sc >= 3 then
|
||||
local mm = m :: { number }
|
||||
-- the cofactor matrix of the upper 3x3 = det * inverse transpose; the sign of det keeps the direction
|
||||
local a1, a2, a3, b1, b2, b3, c1, c2, c3 = mm[1], mm[2], mm[3], mm[5], mm[6], mm[7], mm[9], mm[10], mm[11]
|
||||
local n11, n12, n13 = b2 * c3 - b3 * c2, b3 * c1 - b1 * c3, b1 * c2 - b2 * c1
|
||||
local n21, n22, n23 = c2 * a3 - c3 * a2, c3 * a1 - c1 * a3, c1 * a2 - c2 * a1
|
||||
local n31, n32, n33 = a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1
|
||||
local sgn = if a1 * n11 + a2 * n12 + a3 * n13 < 0 then -1 else 1
|
||||
for i = 0, nv - 1 do
|
||||
local x, y, z = vals[i * sc + 1], vals[i * sc + 2], vals[i * sc + 3]
|
||||
-- column j of the cofactor matrix multiplies component j: (inverse transpose) * n
|
||||
local nx = n11 * x + n21 * y + n31 * z
|
||||
local ny = n12 * x + n22 * y + n32 * z
|
||||
local nz = n13 * x + n23 * y + n33 * z
|
||||
local l = math.sqrt(nx * nx + ny * ny + nz * nz)
|
||||
if l > 0 then
|
||||
nx, ny, nz = sgn * nx / l, sgn * ny / l, sgn * nz / l
|
||||
end
|
||||
dst[n0 + i * 3 + 1] = f32(nx)
|
||||
dst[n0 + i * 3 + 2] = f32(ny)
|
||||
dst[n0 + i * 3 + 3] = f32(nz)
|
||||
end
|
||||
else
|
||||
for i = 0, nv - 1 do
|
||||
for c = 1, ac do
|
||||
dst[n0 + i * ac + c] = if c <= sc then vals[i * sc + c] else f
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local fs, cs, ferr = faces(prim, nv)
|
||||
if ferr then
|
||||
return nil, ferr
|
||||
end
|
||||
local flip = false
|
||||
if not identity then
|
||||
local mm = m :: { number }
|
||||
local det = mm[1] * (mm[6] * mm[11] - mm[7] * mm[10]) - mm[5] * (mm[2] * mm[11] - mm[3] * mm[10]) + mm[9] * (mm[2] * mm[7] - mm[3] * mm[6])
|
||||
flip = det < 0
|
||||
end
|
||||
if fs ~= "points" and fs ~= "skip" then
|
||||
anyFaces = true
|
||||
local base = merged.count
|
||||
local cl: { number } = cs
|
||||
local p = 0
|
||||
local nf = if fs then #fs else #cl // 3
|
||||
for f = 1, nf do
|
||||
local s = if fs then fs[f] else 3
|
||||
if triangulate then
|
||||
for k = 2, s - 1 do
|
||||
table.insert(sizes, 3)
|
||||
local a, b, c = cl[p + 1], cl[p + k], cl[p + k + 1]
|
||||
if flip then
|
||||
b, c = c, b
|
||||
end
|
||||
table.insert(corners, base + a)
|
||||
table.insert(corners, base + b)
|
||||
table.insert(corners, base + c)
|
||||
end
|
||||
else
|
||||
table.insert(sizes, s)
|
||||
if flip then
|
||||
table.insert(corners, base + cl[p + 1])
|
||||
for k = s, 2, -1 do
|
||||
table.insert(corners, base + cl[p + k])
|
||||
end
|
||||
else
|
||||
for k = 1, s do
|
||||
table.insert(corners, base + cl[p + k])
|
||||
end
|
||||
end
|
||||
end
|
||||
p += s
|
||||
end
|
||||
end
|
||||
info.faceCount = #sizes - info.firstFace
|
||||
merged.count += nv
|
||||
table.insert(merged.parts, info)
|
||||
end
|
||||
merged.sizes = if anyFaces then sizes else nil
|
||||
return merged, nil
|
||||
end
|
||||
|
||||
return Flatten
|
||||
@@ -0,0 +1,81 @@
|
||||
--!strict
|
||||
-- codecs/model/Minecraft/Colors: the built-in default colour of Minecraft blocks, for showing block grids as coloured
|
||||
-- voxels. Hand-made for this library (approximate average colours picked by eye; no game assets or wiki tables were
|
||||
-- copied): exact block names, then families by dye colour and wood type; codecs/model/Minecraft resolves stairs /
|
||||
-- slabs / walls / ... to their base block and falls back to keywords. Format: name=rrggbb or name=rrggbbaa.
|
||||
local Colors = {}
|
||||
|
||||
Colors.BLOCKS = [[
|
||||
stone=7d7d7d granite=956756 polished_granite=9a6a59 diorite=bcbcbc polished_diorite=c0c0c2 andesite=888889
|
||||
polished_andesite=848686 grass_block=6d9a3f dirt=866043 coarse_dirt=77553b podzol=5b3f18 rooted_dirt=90674c
|
||||
mud=3c3a3d cobblestone=7a7a7a bedrock=555555 sand=dbcf9f red_sand=be6621 gravel=837f7e suspicious_sand=d6c996
|
||||
suspicious_gravel=817c7b sandstone=d8cb9b chiseled_sandstone=d8ca9b cut_sandstone=d9cd9e smooth_sandstone=dfd5a5
|
||||
red_sandstone=b5621f cut_red_sandstone=bc6620 chiseled_red_sandstone=b7601e smooth_red_sandstone=b5621f
|
||||
sponge=c3c04a wet_sponge=aaab3c glass=c0f5fe50 tinted_glass=2c262ec0 lapis_block=1f438c gold_block=f6d03d
|
||||
iron_block=dcdcdc diamond_block=62ede4 emerald_block=2acb57 redstone_block=af1805 coal_block=101010
|
||||
netherite_block=433e40 copper_block=c06c50 exposed_copper=a17e68 weathered_copper=6c9a6f oxidized_copper=52a284
|
||||
cut_copper=bf6b51 raw_iron_block=a6896b raw_gold_block=dda92e raw_copper_block=9a6a4e amethyst_block=8562b8
|
||||
budding_amethyst=84609f bricks=976253 bookshelf=75603d chiseled_bookshelf=b29159 mossy_cobblestone=6e7660
|
||||
obsidian=0f0a18 crying_obsidian=200a3c tnt=db4130 spawner=24364a chest=a0742d trapped_chest=a0742d
|
||||
ender_chest=2a3b3c crafting_table=81633c furnace=6d6d6d snow=f9fefe snow_block=f9fefe powder_snow=f8fdfd
|
||||
ice=92b8fec8 packed_ice=8db4fa blue_ice=74a7fd frosted_ice=8cb4fac8 clay=a0a6b3 pumpkin=c6761a
|
||||
carved_pumpkin=c27118 jack_o_lantern=d79a32 netherrack=612626 soul_sand=513e32 soul_soil=4b3a2e basalt=505055
|
||||
polished_basalt=636367 smooth_basalt=48484e glowstone=ab8354 magma_block=8e3f1f nether_bricks=2c1518
|
||||
red_nether_bricks=450709 cracked_nether_bricks=281417 chiseled_nether_bricks=2f171c nether_wart_block=720202
|
||||
warped_wart_block=167879 end_stone=dbdea0 end_stone_bricks=dae0a2 purpur_block=a97ea9 purpur_pillar=ab81ab
|
||||
prismarine=63a29a prismarine_bricks=63ab9e dark_prismarine=335b4b sea_lantern=acc7be hay_block=a68b0c
|
||||
terracotta=985e43 quartz_block=ebe5de smooth_quartz=ece6df quartz_bricks=eae5dd quartz_pillar=ebe6e0
|
||||
chiseled_quartz_block=e7e2da smooth_stone=9e9e9e stone_bricks=7a7979 mossy_stone_bricks=737969
|
||||
cracked_stone_bricks=767676 chiseled_stone_bricks=777777 deepslate=505053 cobbled_deepslate=4d4d51
|
||||
polished_deepslate=484849 deepslate_bricks=474747 cracked_deepslate_bricks=414141 deepslate_tiles=373737
|
||||
cracked_deepslate_tiles=343434 chiseled_deepslate=363637 reinforced_deepslate=505350 tuff=6c6d67
|
||||
polished_tuff=626a63 tuff_bricks=626660 calcite=dfe0dc dripstone_block=866b5c pointed_dripstone=816757
|
||||
moss_block=596d2d moss_carpet=596d2d pale_moss_block=6b7069 melon=6f9118 cactus=587f28 sugar_cane=95c165
|
||||
bamboo=5d8f1e bamboo_block=7f9030 stripped_bamboo_block=c0ad50 water=3f76e4b4 bubble_column=3f76e4b4
|
||||
lava=cf5b14 short_grass=5b8a32 grass=5b8a32 tall_grass=5b8a32 fern=586e30 large_fern=586e30 dead_bush=6b4f29
|
||||
vine=3c6e18 glow_lichen=708079 lily_pad=208030 seagrass=307b16 tall_seagrass=307b16 kelp=3b7f22
|
||||
kelp_plant=3b7f22 dried_kelp_block=323b27 red_mushroom_block=c82e2d brown_mushroom_block=957051
|
||||
mushroom_stem=cbc4b9 red_mushroom=d84a3e brown_mushroom=9a7759 slime_block=6fc05bc8 honey_block=fba92fc8
|
||||
honeycomb_block=e5941e bone_block=e1ddc9 shroomlight=f19346 target=e2aa9e respawn_anchor=4b1e86
|
||||
lodestone=939599 blackstone=2a2328 polished_blackstone=35303b polished_blackstone_bricks=302a32
|
||||
cracked_polished_blackstone_bricks=2c2629 chiseled_polished_blackstone=35303b gilded_blackstone=382b26
|
||||
crimson_nylium=831f1f warped_nylium=2b7265 crimson_roots=7e0812 warped_roots=148a7c packed_mud=8e6b50
|
||||
mud_bricks=89684f sculk=0d1e24 sculk_catalyst=2d3a3b sculk_sensor=074654 sculk_shrieker=c6cdab
|
||||
redstone_lamp=5f361e note_block=58392a jukebox=5d4030 beacon=75dcd7 observer=626262 piston=9a8d6c
|
||||
sticky_piston=8b9c66 piston_head=9a8d6c dispenser=7a7a7a dropper=7a7a7a hopper=434343 anvil=444444
|
||||
chipped_anvil=444444 damaged_anvil=444444 cauldron=4a4a4a rail=7d6c4b powered_rail=8a6d3e detector_rail=7b6853
|
||||
activator_rail=74574b ladder=7c5f35 scaffolding=aa8449 lantern=6a5b54 soul_lantern=4a6366 campfire=6e5638
|
||||
soul_campfire=4e5d5d barrel=86643b smoker=5a5853 blast_furnace=6c6b6b cartography_table=685032
|
||||
fletching_table=c5b485 smithing_table=39394a loom=8e7965 stonecutter=7b7672 grindstone=8e8e8e composter=704a26
|
||||
beehive=b8945b bee_nest=c5964b farmland=8f6646 dirt_path=94793f mycelium=6f6365 torch=ffd80060
|
||||
wall_torch=ffd80060 soul_torch=6be1e360 redstone_torch=c0210f60 redstone_wire=9e0b0060 lever=6e6e6e60
|
||||
cobweb=e4e9ea80 iron_bars=8b8d8b90 chain=3a404e90 end_rod=e0d8d0 chorus_plant=5e395e chorus_flower=977a97
|
||||
dragon_egg=0c0910 end_portal_frame=5b7860 enchanting_table=813838 brewing_stand=7a654f flower_pot=7d4536
|
||||
cake=f8dede conduit=9f8b71 lectern=ad8a54 bell=fdd533 decorated_pot=8f4f35 crafter=7a6c64
|
||||
trial_spawner=3b4a55 vault=46545c heavy_core=4c5056 command_block=b5886c chain_command_block=829f8f
|
||||
repeating_command_block=8370b0 structure_block=58475b jigsaw=50455a
|
||||
dandelion=e0c41c poppy=c42b1a blue_orchid=2aa8d0 allium=b878e8 azure_bluet=dfe6d7 red_tulip=c43b1b
|
||||
orange_tulip=e07e1b white_tulip=e0e8db pink_tulip=e8b8d8 oxeye_daisy=e8e8c8 cornflower=4f76d8
|
||||
lily_of_the_valley=e8e8e8 wither_rose=2a2c18 sunflower=f0c71d lilac=b88cb8 rose_bush=b02a1e peony=e8b8e0
|
||||
torchflower=d9b14e pitcher_plant=7a97c8 pink_petals=f0b8d0 spore_blossom=d066a8 azalea=5f7a2c
|
||||
flowering_azalea=7c6b6e sweet_berry_bush=3f6a2f cocoa=8c5428 wheat=a99c30 carrots=4a9a1e potatoes=4c9a2a
|
||||
beetroots=5a8a2a nether_wart=8a1818 crimson_fungus=8a2525 warped_fungus=2a7a6e twisting_vines=148a7c
|
||||
weeping_vines=8a1414 hanging_roots=a17561 big_dripleaf=6b8f34 small_dripleaf=6b8f34 cave_vines=5a6d23
|
||||
frogspawn=66605ca0 sniffer_egg=8a5045 turtle_egg=dcd8b8 sea_pickle=6a7030 mangrove_roots=4b3c27
|
||||
muddy_mangrove_roots=46413a ochre_froglight=f6e8a6 verdant_froglight=dcf0d6 pearlescent_froglight=f1e1ea
|
||||
creaking_heart=5a4a3c resin_block=d9661c resin_bricks=ce5a1a
|
||||
]]
|
||||
|
||||
-- wool-like colour of each dye, then concrete and terracotta (same order as Colors.DYES)
|
||||
Colors.DYES = { "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black" }
|
||||
Colors.WOOL = "e9ecec f07613 bd44b3 3aafd9 f8c527 70b919 ed8dac 3e4447 8e8e86 158991 792aac 35399d 724728 546d1b a12722 141519"
|
||||
Colors.CONCRETE = "cfd5d6 e06100 a9309f 2389c6 f0af15 5ea818 d5658e 36393d 7d7d73 157788 64209c 2c2e8f 603b1f 495b24 8e2020 080a0f"
|
||||
Colors.TERRACOTTA = "d1b2a1 a15325 95576c 716c89 ba8523 677534 a14e4e 392a23 876a61 575b5b 764656 4a3b5b 4d3323 4c532a 8f3d2e 251610"
|
||||
|
||||
-- wood types: planks, bark (log / wood), leaves
|
||||
Colors.WOODS = { "oak", "spruce", "birch", "jungle", "acacia", "dark_oak", "mangrove", "cherry", "pale_oak", "bamboo", "crimson", "warped" }
|
||||
Colors.PLANKS = "a2834f 735531 c0af79 a07351 a85a32 432b14 763631 e3b3ad e4d9d3 c1ad50 653147 2b6963"
|
||||
Colors.BARK = "6d5533 3a2510 d8d7d2 55441a 676157 3e2f17 543a26 371b22 524a46 7f9030 5c1919 3a3a4d"
|
||||
Colors.LEAVES = "4a7a20 3d5d3d 5f8a3c 3f8a1c 4b7a1e 3c6a18 4b8a28 e5adc2 878d76 5d8f1e 831f1f 2b7265"
|
||||
|
||||
return Colors
|
||||
@@ -0,0 +1,108 @@
|
||||
--!strict
|
||||
-- codecs/model/Minecraft/Legacy: numeric block ids of Minecraft before 1.13 (the .schematic format, Anvil chunks with
|
||||
-- Blocks / Data arrays), from the Minecraft wiki "Java Edition data values/Pre-flattening" page (facts, not code):
|
||||
-- the 1.12 name of every id, and how the data value picks a variant for the blocks whose colour or wood depends on it
|
||||
-- (the modern name of that variant: wool 14 -> red_wool, planks 2 -> birch_planks).
|
||||
local Legacy = {}
|
||||
|
||||
local function words(s: string): { string }
|
||||
local out = {}
|
||||
for w in string.gmatch(s, "%S+") do
|
||||
table.insert(out, w)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- ids 0 .. 255 (NAMES[id + 1]), "-" = unused
|
||||
Legacy.NAMES = words([[air stone grass dirt cobblestone planks sapling bedrock flowing_water water flowing_lava
|
||||
lava sand gravel gold_ore iron_ore coal_ore log leaves sponge glass lapis_ore lapis_block dispenser sandstone noteblock
|
||||
bed golden_rail detector_rail sticky_piston web tallgrass deadbush piston piston_head wool piston_extension
|
||||
yellow_flower red_flower brown_mushroom red_mushroom gold_block iron_block double_stone_slab stone_slab brick_block tnt
|
||||
bookshelf mossy_cobblestone obsidian torch fire mob_spawner oak_stairs chest redstone_wire diamond_ore diamond_block
|
||||
crafting_table wheat farmland furnace lit_furnace standing_sign wooden_door ladder rail stone_stairs wall_sign lever
|
||||
stone_pressure_plate iron_door wooden_pressure_plate redstone_ore lit_redstone_ore unlit_redstone_torch redstone_torch
|
||||
stone_button snow_layer ice snow cactus clay reeds jukebox fence pumpkin netherrack soul_sand glowstone portal
|
||||
lit_pumpkin cake unpowered_repeater powered_repeater stained_glass trapdoor monster_egg stonebrick
|
||||
brown_mushroom_block red_mushroom_block iron_bars glass_pane melon_block pumpkin_stem melon_stem vine fence_gate
|
||||
brick_stairs stone_brick_stairs mycelium waterlily nether_brick nether_brick_fence nether_brick_stairs nether_wart
|
||||
enchanting_table brewing_stand cauldron end_portal end_portal_frame end_stone dragon_egg redstone_lamp
|
||||
lit_redstone_lamp double_wooden_slab wooden_slab cocoa sandstone_stairs emerald_ore ender_chest tripwire_hook tripwire
|
||||
emerald_block spruce_stairs birch_stairs jungle_stairs command_block beacon cobblestone_wall flower_pot carrots
|
||||
potatoes wooden_button skull anvil trapped_chest light_weighted_pressure_plate heavy_weighted_pressure_plate
|
||||
unpowered_comparator powered_comparator daylight_detector redstone_block quartz_ore hopper quartz_block quartz_stairs
|
||||
activator_rail dropper stained_hardened_clay stained_glass_pane leaves2 log2 acacia_stairs dark_oak_stairs slime
|
||||
barrier iron_trapdoor prismarine sea_lantern hay_block carpet hardened_clay coal_block packed_ice double_plant
|
||||
standing_banner wall_banner daylight_detector_inverted red_sandstone red_sandstone_stairs double_stone_slab2
|
||||
stone_slab2 spruce_fence_gate birch_fence_gate jungle_fence_gate dark_oak_fence_gate acacia_fence_gate spruce_fence
|
||||
birch_fence jungle_fence dark_oak_fence acacia_fence spruce_door birch_door jungle_door acacia_door dark_oak_door
|
||||
end_rod chorus_plant chorus_flower purpur_block purpur_pillar purpur_stairs purpur_double_slab purpur_slab end_bricks
|
||||
beetroots grass_path end_gateway repeating_command_block chain_command_block frosted_ice magma nether_wart_block
|
||||
red_nether_brick bone_block structure_void observer white_shulker_box orange_shulker_box magenta_shulker_box
|
||||
light_blue_shulker_box yellow_shulker_box lime_shulker_box pink_shulker_box gray_shulker_box silver_shulker_box
|
||||
cyan_shulker_box purple_shulker_box blue_shulker_box brown_shulker_box green_shulker_box red_shulker_box
|
||||
black_shulker_box white_glazed_terracotta orange_glazed_terracotta magenta_glazed_terracotta
|
||||
light_blue_glazed_terracotta yellow_glazed_terracotta lime_glazed_terracotta pink_glazed_terracotta
|
||||
gray_glazed_terracotta silver_glazed_terracotta cyan_glazed_terracotta purple_glazed_terracotta
|
||||
blue_glazed_terracotta brown_glazed_terracotta green_glazed_terracotta red_glazed_terracotta black_glazed_terracotta
|
||||
concrete concrete_powder - - structure_block]])
|
||||
|
||||
-- legacy names whose modern name differs (data value not involved; only one-to-one renames, so the way back is exact:
|
||||
-- lit_furnace, powered_repeater, ... keep their legacy names)
|
||||
Legacy.RENAMED = {
|
||||
grass = "grass_block", brick_block = "bricks", stonebrick = "stone_bricks", hardened_clay = "terracotta",
|
||||
melon_block = "melon", lit_pumpkin = "jack_o_lantern", slime = "slime_block", magma = "magma_block",
|
||||
red_nether_brick = "red_nether_bricks", nether_brick = "nether_bricks", end_bricks = "end_stone_bricks",
|
||||
mob_spawner = "spawner", web = "cobweb", snow_layer = "snow", snow = "snow_block", noteblock = "note_block",
|
||||
quartz_ore = "nether_quartz_ore", reeds = "sugar_cane", waterlily = "lily_pad",
|
||||
tallgrass = "short_grass", grass_path = "dirt_path", double_stone_slab = "smooth_stone",
|
||||
stone_slab = "smooth_stone_slab", deadbush = "dead_bush", yellow_flower = "dandelion",
|
||||
fence = "oak_fence", fence_gate = "oak_fence_gate",
|
||||
wooden_door = "oak_door", trapdoor = "oak_trapdoor", wooden_pressure_plate = "oak_pressure_plate",
|
||||
wooden_button = "oak_button", stone_stairs = "cobblestone_stairs", standing_sign = "oak_sign",
|
||||
wall_sign = "oak_wall_sign", golden_rail = "powered_rail", portal = "nether_portal", piston_extension = "moving_piston",
|
||||
silver_shulker_box = "light_gray_shulker_box", silver_glazed_terracotta = "light_gray_glazed_terracotta",
|
||||
monster_egg = "infested_stone",
|
||||
standing_banner = "white_banner", wall_banner = "white_wall_banner", skull = "skeleton_skull",
|
||||
bed = "red_bed",
|
||||
} :: { [string]: string }
|
||||
|
||||
-- legacy names whose data value selects the variant: the modern names by data value (0-based)
|
||||
local DYED = "white orange magenta light_blue yellow lime pink gray light_gray cyan purple blue brown green red black"
|
||||
local function dyed(suffix: string): { string }
|
||||
local out = {}
|
||||
for i, d in words(DYED) do
|
||||
out[i] = d .. "_" .. suffix
|
||||
end
|
||||
return out
|
||||
end
|
||||
Legacy.VARIANTS = {
|
||||
stone = { "stone", "granite", "polished_granite", "diorite", "polished_diorite", "andesite", "polished_andesite" },
|
||||
dirt = { "dirt", "coarse_dirt", "podzol" },
|
||||
planks = { "oak_planks", "spruce_planks", "birch_planks", "jungle_planks", "acacia_planks", "dark_oak_planks" },
|
||||
wooden_slab = { "oak_slab", "spruce_slab", "birch_slab", "jungle_slab", "acacia_slab", "dark_oak_slab" },
|
||||
sapling = { "oak_sapling", "spruce_sapling", "birch_sapling", "jungle_sapling", "acacia_sapling", "dark_oak_sapling" },
|
||||
sand = { "sand", "red_sand" },
|
||||
log = { "oak_log", "spruce_log", "birch_log", "jungle_log" }, -- data % 4
|
||||
log2 = { "acacia_log", "dark_oak_log" },
|
||||
leaves = { "oak_leaves", "spruce_leaves", "birch_leaves", "jungle_leaves" },
|
||||
leaves2 = { "acacia_leaves", "dark_oak_leaves" },
|
||||
sponge = { "sponge", "wet_sponge" },
|
||||
sandstone = { "sandstone", "chiseled_sandstone", "cut_sandstone" },
|
||||
red_sandstone = { "red_sandstone", "chiseled_red_sandstone", "cut_red_sandstone" },
|
||||
stonebrick = { "stone_bricks", "mossy_stone_bricks", "cracked_stone_bricks", "chiseled_stone_bricks" },
|
||||
quartz_block = { "quartz_block", "chiseled_quartz_block", "quartz_pillar" },
|
||||
prismarine = { "prismarine", "prismarine_bricks", "dark_prismarine" },
|
||||
cobblestone_wall = { "cobblestone_wall", "mossy_cobblestone_wall" },
|
||||
red_flower = { "poppy", "blue_orchid", "allium", "azure_bluet", "red_tulip", "orange_tulip", "white_tulip", "pink_tulip", "oxeye_daisy" },
|
||||
double_plant = { "sunflower", "lilac", "tall_grass", "large_fern", "rose_bush", "peony" },
|
||||
wool = dyed("wool"),
|
||||
carpet = dyed("carpet"),
|
||||
stained_glass = dyed("stained_glass"),
|
||||
stained_glass_pane = dyed("stained_glass_pane"),
|
||||
stained_hardened_clay = dyed("terracotta"),
|
||||
concrete = dyed("concrete"),
|
||||
concrete_powder = dyed("concrete_powder"),
|
||||
} :: { [string]: { string } }
|
||||
Legacy.MASK = { log = 4, log2 = 4, leaves = 4, leaves2 = 4, sapling = 8, wooden_slab = 8, quartz_block = 8, double_plant = 8 } :: { [string]: number }
|
||||
|
||||
return Legacy
|
||||
@@ -0,0 +1,220 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/model/Minecraft/Packed: Minecraft's packed index arrays. New code, from the Minecraft wiki "Chunk format" and
|
||||
-- the Sponge / Litematica schematic specs: long arrays (little-endian int64s as codecs/text/Nbt keeps them) holding
|
||||
-- bits-wide indices either spanning long boundaries (Litematica, chunks before 1.16) or not (chunks since 1.16:
|
||||
-- floor(64 / bits) per long, the rest padding), and the varint byte arrays of Sponge schematics. Indices are written
|
||||
-- to / read from u16 little-endian buffers. Every access is bounds-checked first; never throws.
|
||||
local Packed = {}
|
||||
|
||||
local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
|
||||
local writeu8, writeu16 = buffer.writeu8, buffer.writeu16
|
||||
local extract, band, rshift, lshift, bor = bit32.extract, bit32.band, bit32.rshift, bit32.lshift, bit32.bor
|
||||
|
||||
-- longsNeeded(count, bits, spanning) -> the number of longs a packed array of count indices takes
|
||||
function Packed.longsNeeded(count: number, bits: number, spanning: boolean): number
|
||||
if spanning then
|
||||
return (count * bits + 63) // 64
|
||||
end
|
||||
local per = 64 // bits
|
||||
return (count + per - 1) // per
|
||||
end
|
||||
|
||||
-- unpack(longs, bits, count, spanning, out, max) -> true | false, message: count indices into out (u16 LE, from byte
|
||||
-- 0); an index >= max is an error. bits 1 .. 16.
|
||||
function Packed.unpack(longs: buffer, bits: number, count: number, spanning: boolean, out: buffer, max: number): (boolean, string?)
|
||||
if bits < 1 or bits > 16 then
|
||||
return false, "unsupported: " .. bits .. "-bit packed indices"
|
||||
end
|
||||
local need = Packed.longsNeeded(count, bits, spanning)
|
||||
if buffer.len(longs) < need * 8 then
|
||||
return false, "packed array too short (" .. buffer.len(longs) // 8 .. " longs, need " .. need .. ")"
|
||||
end
|
||||
if buffer.len(out) < count * 2 then
|
||||
return false, "output too small"
|
||||
end
|
||||
-- a copy with 4 bytes of padding, so every 32-bit read stays in range
|
||||
local n = need * 8
|
||||
local src = buffer.create(n + 4)
|
||||
buffer.copy(src, 0, longs, 0, n)
|
||||
if spanning then
|
||||
local p = 0
|
||||
for i = 0, count - 1 do
|
||||
local v = extract(readu32(src, rshift(p, 3)), band(p, 7), bits)
|
||||
if v >= max then
|
||||
return false, "index " .. v .. " past the palette (" .. max .. ")"
|
||||
end
|
||||
writeu16(out, i * 2, v)
|
||||
p += bits
|
||||
end
|
||||
else
|
||||
local per = 64 // bits
|
||||
local i = 0
|
||||
local base = 0
|
||||
while i < count do
|
||||
local p = 0
|
||||
for _ = 1, per do
|
||||
if i >= count then
|
||||
break
|
||||
end
|
||||
local v = extract(readu32(src, base + rshift(p, 3)), band(p, 7), bits)
|
||||
if v >= max then
|
||||
return false, "index " .. v .. " past the palette (" .. max .. ")"
|
||||
end
|
||||
writeu16(out, i * 2, v)
|
||||
i += 1
|
||||
p += bits
|
||||
end
|
||||
base += 8
|
||||
end
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- pack(indices, count, bits, spanning) -> longs buffer (little-endian int64s): the inverse of unpack
|
||||
function Packed.pack(indices: buffer, count: number, bits: number, spanning: boolean): buffer
|
||||
local need = Packed.longsNeeded(count, bits, spanning)
|
||||
local out = buffer.create(need * 8 + 4)
|
||||
local per = 64 // bits
|
||||
for i = 0, count - 1 do
|
||||
local v = readu16(indices, i * 2)
|
||||
local p = if spanning then i * bits else (i // per) * 64 + (i % per) * bits
|
||||
local at = rshift(p, 3)
|
||||
local sh = band(p, 7)
|
||||
-- OR the value in byte by byte (up to 3 bytes for 16 bits at a shift of 7)
|
||||
local x = lshift(v, sh)
|
||||
for k = 0, 2 do
|
||||
local bits8 = band(rshift(x, k * 8), 0xff)
|
||||
if bits8 ~= 0 then
|
||||
writeu8(out, at + k, bor(readu8(out, at + k), bits8))
|
||||
end
|
||||
end
|
||||
end
|
||||
local res = buffer.create(need * 8)
|
||||
buffer.copy(res, 0, out, 0, need * 8)
|
||||
return res
|
||||
end
|
||||
|
||||
-- bitsFor(n, min) -> bits for indices 0 .. n - 1 (at least min)
|
||||
function Packed.bitsFor(n: number, min: number): number
|
||||
local b = min
|
||||
while lshift(1, b) < n and b < 31 do
|
||||
b += 1
|
||||
end
|
||||
return b
|
||||
end
|
||||
|
||||
-- varints(src, offset, length, count, out, max) -> true | false, message: count unsigned LEB128 varints (Sponge
|
||||
-- BlockData) into out (u16 LE)
|
||||
function Packed.varints(src: buffer, offset: number, length: number, count: number, out: buffer, max: number): (boolean, string?)
|
||||
if buffer.len(out) < count * 2 or offset + length > buffer.len(src) then
|
||||
return false, "bad varint array arguments"
|
||||
end
|
||||
local p, e = offset, offset + length
|
||||
for i = 0, count - 1 do
|
||||
local v, sh = 0, 0
|
||||
while true do
|
||||
if p >= e then
|
||||
return false, "truncated: block data ends after " .. i .. " of " .. count .. " entries"
|
||||
end
|
||||
local c = readu8(src, p)
|
||||
p += 1
|
||||
v += band(c, 0x7f) * 2 ^ sh
|
||||
if c < 128 then
|
||||
break
|
||||
end
|
||||
sh += 7
|
||||
if sh > 28 then
|
||||
return false, "varint too long"
|
||||
end
|
||||
end
|
||||
if v >= max then
|
||||
return false, "index " .. v .. " past the palette (" .. max .. ")"
|
||||
end
|
||||
writeu16(out, i * 2, v)
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- toVarints(indices, count) -> buffer: count u16 indices as unsigned LEB128 varints
|
||||
function Packed.toVarints(indices: buffer, count: number): buffer
|
||||
local out = buffer.create(count * 3)
|
||||
local p = 0
|
||||
for i = 0, count - 1 do
|
||||
local v = readu16(indices, i * 2)
|
||||
while v >= 128 do
|
||||
writeu8(out, p, band(v, 0x7f) + 128)
|
||||
p += 1
|
||||
v = rshift(v, 7)
|
||||
end
|
||||
writeu8(out, p, v)
|
||||
p += 1
|
||||
end
|
||||
local res = buffer.create(p)
|
||||
buffer.copy(res, 0, out, 0, p)
|
||||
return res
|
||||
end
|
||||
|
||||
-- nibble(src, offset, i, highFirst) -> the 4-bit value i of a nibble array (Minecraft: low nibble first; WorldEdit's
|
||||
-- AddBlocks: high nibble first)
|
||||
function Packed.nibble(src: buffer, offset: number, i: number, highFirst: boolean): number
|
||||
local b = readu8(src, offset + rshift(i, 1))
|
||||
local odd = band(i, 1) == 1
|
||||
if odd == highFirst then
|
||||
return band(b, 15)
|
||||
end
|
||||
return rshift(b, 4)
|
||||
end
|
||||
|
||||
-- setNibble(dst, offset, i, v, highFirst)
|
||||
function Packed.setNibble(dst: buffer, offset: number, i: number, v: number, highFirst: boolean)
|
||||
local at = offset + rshift(i, 1)
|
||||
local b = readu8(dst, at)
|
||||
local odd = band(i, 1) == 1
|
||||
if odd == highFirst then
|
||||
writeu8(dst, at, bor(band(b, 0xf0), band(v, 15)))
|
||||
else
|
||||
writeu8(dst, at, bor(band(b, 0x0f), lshift(band(v, 15), 4)))
|
||||
end
|
||||
end
|
||||
|
||||
-- fromYzx(src, sx, sy, sz, dst?, ox?, oy?, oz?, dsx?, dsy?) -> dst: u16 cells in Minecraft's order (x fastest, then
|
||||
-- z, then y: schematics, chunk sections) to Types.Voxels order (x, then y, then z), into dst (default a new
|
||||
-- sx * sy * sz grid) at cell offset (ox, oy, oz) of a dsx * dsy * ... grid. The caller checks the ranges.
|
||||
function Packed.fromYzx(src: buffer, sx: number, sy: number, sz: number, dst: buffer?, ox: number?, oy: number?, oz: number?, dsx: number?, dsy: number?): buffer
|
||||
local out = dst or buffer.create(sx * sy * sz * 2)
|
||||
local bx, by, bz = ox or 0, oy or 0, oz or 0
|
||||
local wx, wy = dsx or sx, dsy or sy
|
||||
local i = 0
|
||||
for y = 0, sy - 1 do
|
||||
for z = 0, sz - 1 do
|
||||
local d = (bx + wx * ((by + y) + wy * (bz + z))) * 2
|
||||
for _ = 0, sx - 1 do
|
||||
writeu16(out, d, readu16(src, i))
|
||||
i += 2
|
||||
d += 2
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- toYzx(src, sx, sy, sz) -> buffer: Types.Voxels order to Minecraft's (the inverse of fromYzx)
|
||||
function Packed.toYzx(src: buffer, sx: number, sy: number, sz: number): buffer
|
||||
local out = buffer.create(sx * sy * sz * 2)
|
||||
local i = 0
|
||||
for y = 0, sy - 1 do
|
||||
for z = 0, sz - 1 do
|
||||
local s = (sx * (y + sy * z)) * 2
|
||||
for _ = 0, sx - 1 do
|
||||
writeu16(out, i, readu16(src, s))
|
||||
i += 2
|
||||
s += 2
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return Packed
|
||||
@@ -0,0 +1,587 @@
|
||||
--!strict
|
||||
-- codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code.
|
||||
-- Block states ("minecraft:oak_stairs[facing=east,half=bottom]": parse / format / NBT compound form), the default
|
||||
-- block colour table (codecs/model/Minecraft/Colors, hand-made) with fallbacks by family, the pre-1.13 numeric ids
|
||||
-- (codecs/model/Minecraft/Legacy), packed index arrays (codecs/model/Minecraft/Packed), and the bridge between block
|
||||
-- grids and Types.Voxels: voxels.blocks holds the exact states (u16 indices into a state palette), voxels.data /
|
||||
-- palette their colours; writing a grid without blocks picks the block nearest in colour for each palette colour.
|
||||
--
|
||||
-- local Mc = require("@rosetta/codecs/model/Minecraft")
|
||||
-- local name, props = Mc.parseState("minecraft:oak_log[axis=y]") -- "minecraft:oak_log", { { "axis", "y" } }
|
||||
-- local rgba = Mc.color("minecraft:red_wool") -- { r, g, b, a } | nil for air
|
||||
-- local v = Mc.voxels(sx, sy, sz, states, indices) -- a Types.Voxels with .blocks
|
||||
-- local states, indices = Mc.blocksOf(v) -- back (or chosen by colour)
|
||||
local Types = require("@rosetta/Types")
|
||||
local Nbt = require("@rosetta/codecs/text/Nbt")
|
||||
local Colors = require("@rosetta/codecs/model/Minecraft/Colors")
|
||||
local Legacy = require("@rosetta/codecs/model/Minecraft/Legacy")
|
||||
local Packed = require("@rosetta/codecs/model/Minecraft/Packed")
|
||||
|
||||
local Minecraft = {}
|
||||
|
||||
Minecraft.Packed = Packed
|
||||
Minecraft.Legacy = Legacy
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ block states
|
||||
-- parseState(s) -> name (namespace added when missing), props { { key, value } } in their order
|
||||
function Minecraft.parseState(s: string): (string, { { string } })
|
||||
local name, rest = string.match(s, "^%s*([^%[%s]*)%s*(.*)$")
|
||||
local n = name or ""
|
||||
if n ~= "" and not string.find(n, ":", 1, true) then
|
||||
n = "minecraft:" .. n
|
||||
end
|
||||
local props = {}
|
||||
local body = rest and string.match(rest :: string, "^%[(.*)%]%s*$")
|
||||
if body then
|
||||
for pair in string.gmatch(body, "[^,]+") do
|
||||
local k, v = string.match(pair, "^%s*([^=%s]+)%s*=%s*(.-)%s*$")
|
||||
if k then
|
||||
table.insert(props, { k, v :: string })
|
||||
end
|
||||
end
|
||||
end
|
||||
return n, props
|
||||
end
|
||||
|
||||
-- stateString(name, props?) -> "name[k=v,...]" (props { { k, v } } in order, or a map: keys sorted)
|
||||
function Minecraft.stateString(name: string, props: { any }?): string
|
||||
if not props or next(props) == nil then
|
||||
return name
|
||||
end
|
||||
local parts = {}
|
||||
if props[1] ~= nil then
|
||||
for _, kv in props do
|
||||
table.insert(parts, kv[1] .. "=" .. tostring(kv[2]))
|
||||
end
|
||||
else
|
||||
for _, k in Types.keys(props) do
|
||||
table.insert(parts, tostring(k) .. "=" .. tostring((props :: any)[k]))
|
||||
end
|
||||
end
|
||||
return name .. "[" .. table.concat(parts, ",") .. "]"
|
||||
end
|
||||
|
||||
-- stateFromNbt(compound) -> the state string of a palette entry { Name, Properties? } (litematic, chunk sections)
|
||||
function Minecraft.stateFromNbt(c: any): string?
|
||||
if type(c) ~= "table" or type(c.Name) ~= "string" then
|
||||
return nil
|
||||
end
|
||||
local props = {}
|
||||
if type(c.Properties) == "table" then
|
||||
for _, k in Types.keys(c.Properties) do
|
||||
local v = c.Properties[k]
|
||||
table.insert(props, { k, if type(v) == "string" then v else tostring(Nbt.number(v) or v) })
|
||||
end
|
||||
end
|
||||
return Minecraft.stateString(c.Name, props)
|
||||
end
|
||||
|
||||
-- stateToNbt(state) -> { Name, Properties? } (a Types.object; Properties in the state's order)
|
||||
function Minecraft.stateToNbt(s: string): { [string]: any }
|
||||
local name, props = Minecraft.parseState(s)
|
||||
local c = Types.object({ Name = name }, { "Name" })
|
||||
if #props > 0 then
|
||||
local p, keys = {}, {}
|
||||
for _, kv in props do
|
||||
p[kv[1]] = kv[2]
|
||||
table.insert(keys, kv[1])
|
||||
end
|
||||
Types.set(c, "Properties", Types.object(p, keys))
|
||||
end
|
||||
return c
|
||||
end
|
||||
|
||||
-- baseName(state) -> the name without namespace and properties ("minecraft:oak_log[axis=y]" -> "oak_log")
|
||||
function Minecraft.baseName(s: string): string
|
||||
local name = string.match(s, "^%s*([^%[%s]*)") or ""
|
||||
return string.match(name, ":(.*)$") or name
|
||||
end
|
||||
|
||||
local AIR = { air = true, cave_air = true, void_air = true, structure_void = true, light = true, barrier = true, moving_piston = true }
|
||||
-- isAir(state) -> true for blocks that are not drawn (air, cave_air, void_air, structure_void, light, barrier)
|
||||
function Minecraft.isAir(s: string): boolean
|
||||
return AIR[Minecraft.baseName(s)] == true
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ colours
|
||||
local function hex(h: string): { number }
|
||||
local c = { tonumber(string.sub(h, 1, 2), 16) or 0, tonumber(string.sub(h, 3, 4), 16) or 0, tonumber(string.sub(h, 5, 6), 16) or 0, 255 }
|
||||
if #h >= 8 then
|
||||
c[4] = tonumber(string.sub(h, 7, 8), 16) or 255
|
||||
end
|
||||
return c
|
||||
end
|
||||
local function list(s: string): { { number } }
|
||||
local out = {}
|
||||
for h in string.gmatch(s, "%x+") do
|
||||
table.insert(out, hex(h))
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local EXACT: { [string]: { number } } = {}
|
||||
for name, h in string.gmatch(Colors.BLOCKS, "([%w_]+)=(%x+)") do
|
||||
EXACT[name :: string] = hex(h :: string)
|
||||
end
|
||||
local WOOL, CONCRETE, TERRACOTTA = list(Colors.WOOL), list(Colors.CONCRETE), list(Colors.TERRACOTTA)
|
||||
local PLANKS, BARK, LEAVES = list(Colors.PLANKS), list(Colors.BARK), list(Colors.LEAVES)
|
||||
-- longest prefixes first, so light_blue wins over blue and dark_oak over oak
|
||||
local function byLength(names: { string }): { { any } }
|
||||
local out: { { any } } = {}
|
||||
for i, n in names do
|
||||
table.insert(out, { n, i })
|
||||
end
|
||||
table.sort(out, function(a: { any }, b: { any }): boolean
|
||||
return #(a[1] :: string) > #(b[1] :: string)
|
||||
end)
|
||||
return out
|
||||
end
|
||||
local DYES, WOODS = byLength(Colors.DYES), byLength(Colors.WOODS)
|
||||
local SUFFIXES = {
|
||||
"_wall_hanging_sign", "_hanging_sign", "_wall_sign", "_sign", "_fence_gate", "_fence", "_pressure_plate", "_button",
|
||||
"_trapdoor", "_door", "_stairs", "_slab", "_wall", "_pane", "_carpet", "_wall_banner", "_banner", "_bars",
|
||||
}
|
||||
local PREFIXES = { "waxed_", "potted_", "flowing_", "infested_", "lit_", "unlit_", "unpowered_", "powered_", "chipped_", "damaged_" }
|
||||
local CORAL: { [string]: { number } } = { tube = hex("3157d0"), brain = hex("cf5b9f"), bubble = hex("a118a0"), fire = hex("a6252f"), horn = hex("d8c53e") }
|
||||
local FALLBACK = hex("909090")
|
||||
|
||||
local function mix(c: { number }, w: { number }, t: number): { number }
|
||||
return { math.floor(c[1] + (w[1] - c[1]) * t + 0.5), math.floor(c[2] + (w[2] - c[2]) * t + 0.5), math.floor(c[3] + (w[3] - c[3]) * t + 0.5), c[4] }
|
||||
end
|
||||
|
||||
local resolve: (string, number) -> { number }?
|
||||
|
||||
local function family(n: string): { number }?
|
||||
for _, d in DYES do
|
||||
local pre = d[1] .. "_"
|
||||
if string.sub(n, 1, #pre) == pre then
|
||||
local rest = string.sub(n, #pre + 1)
|
||||
local i = d[2]
|
||||
if rest == "concrete" then
|
||||
return CONCRETE[i]
|
||||
elseif rest == "concrete_powder" then
|
||||
return mix(CONCRETE[i], { 255, 255, 255, 255 }, 0.2)
|
||||
elseif rest == "terracotta" then
|
||||
return TERRACOTTA[i]
|
||||
elseif string.find(rest, "glass", 1, true) then
|
||||
local c = table.clone(WOOL[i])
|
||||
c[4] = 0x80
|
||||
return c
|
||||
end
|
||||
return WOOL[i]
|
||||
end
|
||||
end
|
||||
local stripped = string.match(n, "^stripped_(.*)$")
|
||||
for _, w in WOODS do
|
||||
local pre = w[1] .. "_"
|
||||
local m = stripped or n
|
||||
if string.sub(m, 1, #pre) == pre then
|
||||
local rest = string.sub(m, #pre + 1)
|
||||
local i = w[2]
|
||||
if stripped then
|
||||
return PLANKS[i]
|
||||
elseif rest == "log" or rest == "wood" or rest == "stem" or rest == "hyphae" then
|
||||
return BARK[i]
|
||||
elseif rest == "leaves" or rest == "sapling" or rest == "propagule" then
|
||||
return LEAVES[i]
|
||||
elseif rest == "block" and w[1] == "bamboo" then
|
||||
return EXACT.bamboo_block
|
||||
end
|
||||
return PLANKS[i]
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function keywords(n: string): { number }?
|
||||
if string.find(n, "copper", 1, true) then
|
||||
return if string.find(n, "oxidized", 1, true) then EXACT.oxidized_copper
|
||||
elseif string.find(n, "weathered", 1, true) then EXACT.weathered_copper
|
||||
elseif string.find(n, "exposed", 1, true) then EXACT.exposed_copper
|
||||
else EXACT.copper_block
|
||||
elseif string.find(n, "coral", 1, true) then
|
||||
if string.find(n, "dead", 1, true) then
|
||||
return hex("857e79")
|
||||
end
|
||||
for k, c in CORAL do
|
||||
if string.find(n, k, 1, true) then
|
||||
return c
|
||||
end
|
||||
end
|
||||
elseif string.find(n, "_ore$") then
|
||||
return if string.find(n, "deepslate", 1, true) then EXACT.deepslate
|
||||
elseif string.find(n, "nether", 1, true) then EXACT.netherrack
|
||||
else EXACT.stone
|
||||
end
|
||||
for _, k in { "deepslate", "blackstone", "sandstone", "prismarine", "purpur", "quartz", "glass", "ice", "stone", "brick", "nether", "end", "mushroom", "grass", "candle", "head", "skull", "rail", "sign", "tulip", "orchid" } do
|
||||
if string.find(n, k, 1, true) then
|
||||
local alias = ({ glass = "glass", ice = "ice", stone = "stone", brick = "bricks", nether = "nether_bricks", ["end"] = "end_stone", mushroom = "mushroom_stem", grass = "short_grass", candle = "white_wool", head = "polished_andesite", skull = "bone_block", rail = "rail", sign = "oak_planks", tulip = "red_tulip", orchid = "blue_orchid", deepslate = "deepslate", blackstone = "blackstone", sandstone = "sandstone", prismarine = "prismarine", purpur = "purpur_block", quartz = "quartz_block" } :: any)[k]
|
||||
return EXACT[alias]
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
resolve = function(n: string, depth: number): { number }?
|
||||
if depth > 4 then
|
||||
return nil
|
||||
end
|
||||
local c = EXACT[n]
|
||||
if c then
|
||||
return c
|
||||
end
|
||||
local renamed = Legacy.RENAMED[n]
|
||||
if renamed then
|
||||
return resolve(renamed, depth + 1)
|
||||
end
|
||||
for _, p in PREFIXES do
|
||||
if string.sub(n, 1, #p) == p then
|
||||
return resolve(string.sub(n, #p + 1), depth + 1)
|
||||
end
|
||||
end
|
||||
c = family(n)
|
||||
if c then
|
||||
return c
|
||||
end
|
||||
for _, sfx in SUFFIXES do
|
||||
if #n > #sfx and string.sub(n, -#sfx) == sfx then
|
||||
local base = string.sub(n, 1, #n - #sfx)
|
||||
for _, form in { base, base .. "s", base .. "_block", base .. "_planks" } do
|
||||
local fc = EXACT[form] or family(form)
|
||||
if fc then
|
||||
return fc
|
||||
end
|
||||
end
|
||||
return resolve(base, depth + 1)
|
||||
end
|
||||
end
|
||||
return keywords(n)
|
||||
end
|
||||
|
||||
local cache: { [string]: { number } | false } = {}
|
||||
-- color(state) -> { r, g, b, a } (0..255) | nil for air-like blocks: the default colour table, families, keywords
|
||||
function Minecraft.color(s: string): { number }?
|
||||
local hit = cache[s]
|
||||
if hit ~= nil then
|
||||
return hit or nil
|
||||
end
|
||||
local name, props = Minecraft.parseState(s)
|
||||
local n = string.match(name, ":(.*)$") or name
|
||||
local res: { number }? = nil
|
||||
if not AIR[n] then
|
||||
-- pre-1.13 names whose data value picks the variant
|
||||
local variants = Legacy.VARIANTS[n] or (if n == "double_wooden_slab" then Legacy.VARIANTS.planks else nil)
|
||||
if variants then
|
||||
local data = 0
|
||||
for _, kv in props do
|
||||
if kv[1] == "data" then
|
||||
data = tonumber(kv[2]) or 0
|
||||
end
|
||||
end
|
||||
local v = variants[data % (Legacy.MASK[n] or 16) + 1] or variants[1]
|
||||
res = resolve(v, 0)
|
||||
end
|
||||
res = res or resolve(n, 0) or FALLBACK
|
||||
end
|
||||
cache[s] = res or false
|
||||
return res
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ legacy ids
|
||||
local REVERSE: { [string]: { number } }? = nil
|
||||
local function reverse(): { [string]: { number } }
|
||||
if REVERSE then
|
||||
return REVERSE
|
||||
end
|
||||
local r: { [string]: { number } } = {}
|
||||
local byName: { [string]: number } = {}
|
||||
for i, n in Legacy.NAMES do
|
||||
if n ~= "-" then
|
||||
byName[n] = i - 1
|
||||
end
|
||||
end
|
||||
for legacy, modern in Legacy.RENAMED do
|
||||
r[modern] = { byName[legacy], 0 }
|
||||
end
|
||||
for legacy, variants in Legacy.VARIANTS do
|
||||
for d, v in variants do
|
||||
if r[v] == nil then
|
||||
r[v] = { byName[legacy], d - 1 }
|
||||
end
|
||||
end
|
||||
end
|
||||
for n, id in byName do
|
||||
if r[n] == nil then
|
||||
r[n] = { id, 0 }
|
||||
end
|
||||
end
|
||||
REVERSE = r
|
||||
return r
|
||||
end
|
||||
|
||||
-- legacyState(id, data) -> the state string for a pre-1.13 block (variant names where the data value picks one, the
|
||||
-- rest of the data value kept as [data=N] so legacyId gives it back exactly)
|
||||
function Minecraft.legacyState(id: number, data: number): string
|
||||
local n = Legacy.NAMES[id + 1]
|
||||
if n == nil or n == "-" then
|
||||
return "minecraft:legacy_" .. id .. (if data ~= 0 then "[data=" .. data .. "]" else "")
|
||||
end
|
||||
local variants = Legacy.VARIANTS[n]
|
||||
if variants then
|
||||
local idx = data % (Legacy.MASK[n] or 16)
|
||||
local v = variants[idx + 1]
|
||||
if v then
|
||||
return "minecraft:" .. v .. (if data ~= idx then "[data=" .. data .. "]" else "")
|
||||
end
|
||||
end
|
||||
return "minecraft:" .. (Legacy.RENAMED[n] or n) .. (if data ~= 0 then "[data=" .. data .. "]" else "")
|
||||
end
|
||||
|
||||
-- legacyId(state) -> id, data | nil: the inverse of legacyState (modern names that exist before 1.13 too; their
|
||||
-- properties are not converted to data values)
|
||||
function Minecraft.legacyId(s: string): (number?, number?)
|
||||
local name, props = Minecraft.parseState(s)
|
||||
local n = string.match(name, ":(.*)$") or name
|
||||
local id: number?, data = nil, 0
|
||||
local lid = string.match(n, "^legacy_(%d+)$")
|
||||
if lid then
|
||||
id = tonumber(lid)
|
||||
else
|
||||
local e = reverse()[n]
|
||||
if e then
|
||||
id, data = e[1], e[2]
|
||||
end
|
||||
end
|
||||
if id == nil then
|
||||
return nil, nil
|
||||
end
|
||||
for _, kv in props do
|
||||
if kv[1] == "data" then
|
||||
data = (tonumber(kv[2]) or data) % 16
|
||||
end
|
||||
end
|
||||
return id, data
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ voxels
|
||||
-- voxels(sx, sy, sz, states, indices, opts?) -> Types.Voxels: indices (u16 LE per cell in Voxels order: x fastest,
|
||||
-- then y, then z) into states; data / palette from the block colours (air -> 0; up to 255 colours, more merge into
|
||||
-- the nearest one)
|
||||
function Minecraft.voxels(sx: number, sy: number, sz: number, states: { string }, indices: buffer): Types.Voxels
|
||||
local v = Types.Voxels.new(sx, sy, sz)
|
||||
local lut = buffer.create(#states)
|
||||
local slots: { [string]: number } = {}
|
||||
local used = 0
|
||||
for i, s in states do
|
||||
local c = Minecraft.color(s)
|
||||
local slot = 0
|
||||
if c then
|
||||
local key = string.format("%d,%d,%d,%d", c[1], c[2], c[3], c[4])
|
||||
slot = slots[key]
|
||||
if not slot then
|
||||
if used < 255 then
|
||||
used += 1
|
||||
slot = used
|
||||
v.palette[slot] = { c[1], c[2], c[3], c[4] }
|
||||
else
|
||||
local best, bd = 1, math.huge
|
||||
for k = 1, 255 do
|
||||
local p = v.palette[k]
|
||||
local d = (p[1] - c[1]) ^ 2 + (p[2] - c[2]) ^ 2 + (p[3] - c[3]) ^ 2 + (p[4] - c[4]) ^ 2
|
||||
if d < bd then
|
||||
best, bd = k, d
|
||||
end
|
||||
end
|
||||
slot = best
|
||||
end
|
||||
slots[key] = slot
|
||||
end
|
||||
end
|
||||
buffer.writeu8(lut, i - 1, slot)
|
||||
end
|
||||
local n = sx * sy * sz
|
||||
local data, nstates = v.data, #states
|
||||
for i = 0, n - 1 do
|
||||
local s = buffer.readu16(indices, i * 2)
|
||||
buffer.writeu8(data, i, if s < nstates then buffer.readu8(lut, s) else 0)
|
||||
end
|
||||
v.blocks = { palette = states, data = indices }
|
||||
return v
|
||||
end
|
||||
|
||||
-- the blocks a colour grid is written with: full blocks of distinct colours (and stained glass for translucent ones)
|
||||
local CANDIDATES: { { any } }? = nil
|
||||
local function candidates(): { { any } }
|
||||
if CANDIDATES then
|
||||
return CANDIDATES
|
||||
end
|
||||
local out = {}
|
||||
for _, d in Colors.DYES do
|
||||
for _, kind in { "wool", "concrete", "terracotta" } do
|
||||
local s = "minecraft:" .. d .. "_" .. kind
|
||||
table.insert(out, { s, Minecraft.color(s) })
|
||||
end
|
||||
end
|
||||
for _, w in Colors.WOODS do
|
||||
local s = "minecraft:" .. w .. "_planks"
|
||||
table.insert(out, { s, Minecraft.color(s) })
|
||||
end
|
||||
for _, n in { "stone", "cobblestone", "bricks", "sand", "red_sand", "dirt", "grass_block", "gravel", "deepslate", "sandstone", "quartz_block", "obsidian", "netherrack", "end_stone", "prismarine", "dark_prismarine", "snow_block", "gold_block", "iron_block", "diamond_block", "emerald_block", "lapis_block", "redstone_block", "coal_block", "glowstone", "sponge", "melon", "pumpkin", "hay_block", "bone_block", "clay", "packed_ice", "nether_bricks", "purpur_block", "andesite", "diorite", "granite", "calcite", "tuff", "blackstone", "mud", "moss_block", "amethyst_block", "copper_block", "oxidized_copper" } do
|
||||
local s = "minecraft:" .. n
|
||||
table.insert(out, { s, Minecraft.color(s) })
|
||||
end
|
||||
CANDIDATES = out
|
||||
return out
|
||||
end
|
||||
|
||||
-- nearestBlock(rgba) -> the block state whose default colour is nearest (translucent colours -> stained glass)
|
||||
function Minecraft.nearestBlock(c: { number }): string
|
||||
local a = c[4] or 255
|
||||
if a < 200 then
|
||||
local best, bd = "minecraft:glass", math.huge
|
||||
for i, d in Colors.DYES do
|
||||
local w = WOOL[i]
|
||||
local dist = (w[1] - c[1]) ^ 2 + (w[2] - c[2]) ^ 2 + (w[3] - c[3]) ^ 2
|
||||
if dist < bd then
|
||||
best, bd = "minecraft:" .. d .. "_stained_glass", dist
|
||||
end
|
||||
end
|
||||
return best
|
||||
end
|
||||
local best, bd = "minecraft:stone", math.huge
|
||||
for _, cand in candidates() do
|
||||
local k = cand[2]
|
||||
local dist = (k[1] - c[1]) ^ 2 + (k[2] - c[2]) ^ 2 + (k[3] - c[3]) ^ 2
|
||||
if dist < bd then
|
||||
best, bd = cand[1], dist
|
||||
end
|
||||
end
|
||||
return best
|
||||
end
|
||||
|
||||
-- blocksOf(voxels) -> states, indices (u16 LE per cell): voxels.blocks when present (checked), else a block per
|
||||
-- palette colour (nearestBlock; cell 0 -> "minecraft:air" at index 0) | nil, message
|
||||
function Minecraft.blocksOf(v: Types.Voxels): ({ string }?, any)
|
||||
local n = v.size[1] * v.size[2] * v.size[3]
|
||||
local b = v.blocks
|
||||
if b then
|
||||
if type(b.palette) ~= "table" or type(b.data) ~= "buffer" or buffer.len(b.data) < n * 2 then
|
||||
return nil, "voxels.blocks must hold a palette and a u16 per cell"
|
||||
end
|
||||
if #b.palette == 0 or #b.palette > 65536 then
|
||||
return nil, "voxels.blocks.palette must have 1 .. 65536 states"
|
||||
end
|
||||
return b.palette, b.data
|
||||
end
|
||||
local states = { "minecraft:air" }
|
||||
local slotOf: { [number]: number } = { [0] = 0 }
|
||||
local byState: { [string]: number } = { ["minecraft:air"] = 0 }
|
||||
local out = buffer.create(n * 2)
|
||||
local data = v.data
|
||||
for i = 0, n - 1 do
|
||||
local p = buffer.readu8(data, i)
|
||||
local s = slotOf[p]
|
||||
if s == nil then
|
||||
local col = v.palette[p] or { 128, 128, 128, 255 }
|
||||
local st = Minecraft.nearestBlock(col)
|
||||
s = byState[st]
|
||||
if s == nil then
|
||||
table.insert(states, st)
|
||||
s = #states - 1
|
||||
byState[st] = s
|
||||
end
|
||||
slotOf[p] = s
|
||||
end
|
||||
buffer.writeu16(out, i * 2, s :: number)
|
||||
end
|
||||
return states, out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ block entities
|
||||
-- Block entity records in one shape, { pos = { x, y, z }, id, data } (Sponge v3's), from / to the flat
|
||||
-- { x, y, z, id, ... } of MCEdit, Litematica and chunks, and Sponge v1 / v2's { Pos, Id, ... }.
|
||||
local function int(v: any): number?
|
||||
local n = Nbt.number(v)
|
||||
if n == nil or n ~= n or n % 1 ~= 0 then
|
||||
return nil
|
||||
end
|
||||
return n
|
||||
end
|
||||
local function ints(v: any): { number }?
|
||||
if Nbt.isTag(v) and v.type == "intArray" then
|
||||
return v.value
|
||||
elseif type(v) == "table" and not Nbt.isTag(v) and (v :: any)[1] ~= nil then
|
||||
local out: { number } = {}
|
||||
for i, x in v :: { any } do
|
||||
out[i] = Nbt.number(x) or 0
|
||||
end
|
||||
return out
|
||||
end
|
||||
return nil
|
||||
end
|
||||
Minecraft.int = int -- the integer value of an NBT number | nil
|
||||
Minecraft.ints = ints -- the numbers of an intArray or a list | nil
|
||||
|
||||
local function rest(c: any, skip: { [string]: boolean }): { [string]: any }
|
||||
local out, keys = {}, {}
|
||||
for _, k in Types.keys(c) do
|
||||
if not skip[k] then
|
||||
out[k] = c[k]
|
||||
table.insert(keys, k)
|
||||
end
|
||||
end
|
||||
return Types.object(out, keys)
|
||||
end
|
||||
|
||||
local FLAT_SKIP = { x = true, y = true, z = true, id = true }
|
||||
local POS_SKIP = { Pos = true, Id = true }
|
||||
|
||||
-- blockEntity(c, style) -> the common shape of one record: style "flat" (MCEdit, Litematica), "pos" (Sponge v1 / v2),
|
||||
-- "data" (Sponge v3)
|
||||
function Minecraft.blockEntity(c: any, style: string): any
|
||||
if type(c) ~= "table" or Nbt.isTag(c) then
|
||||
return nil
|
||||
end
|
||||
if style == "flat" then
|
||||
return { pos = { int(c.x) or 0, int(c.y) or 0, int(c.z) or 0 }, id = if type(c.id) == "string" then c.id else nil, data = rest(c, FLAT_SKIP) }
|
||||
end
|
||||
local p = ints(c.Pos) or { 0, 0, 0 }
|
||||
local data = if style == "data" then (if type(c.Data) == "table" then c.Data else Types.object()) else rest(c, POS_SKIP)
|
||||
return { pos = { p[1] or 0, p[2] or 0, p[3] or 0 }, id = if type(c.Id) == "string" then c.Id else nil, data = data }
|
||||
end
|
||||
|
||||
-- flatBlockEntity(be, style) -> the record in a flavour's shape (the inverse of blockEntity)
|
||||
function Minecraft.flatBlockEntity(be: any, style: string): any
|
||||
local o = Types.object()
|
||||
local data = if type(be.data) == "table" then be.data else Types.object()
|
||||
if style == "flat" then
|
||||
Types.set(o, "x", be.pos[1])
|
||||
Types.set(o, "y", be.pos[2])
|
||||
Types.set(o, "z", be.pos[3])
|
||||
if be.id then
|
||||
Types.set(o, "id", be.id)
|
||||
end
|
||||
for _, k in Types.keys(data) do
|
||||
if not FLAT_SKIP[k] then
|
||||
Types.set(o, k, data[k])
|
||||
end
|
||||
end
|
||||
return o
|
||||
end
|
||||
Types.set(o, "Pos", Nbt.intArray({ be.pos[1], be.pos[2], be.pos[3] }))
|
||||
if be.id then
|
||||
Types.set(o, "Id", be.id)
|
||||
end
|
||||
if style == "data" then
|
||||
Types.set(o, "Data", data)
|
||||
else
|
||||
for _, k in Types.keys(data) do
|
||||
if not POS_SKIP[k] then
|
||||
Types.set(o, k, data[k])
|
||||
end
|
||||
end
|
||||
end
|
||||
return o
|
||||
end
|
||||
|
||||
return Minecraft
|
||||
@@ -0,0 +1,248 @@
|
||||
--!strict
|
||||
-- codecs/model/Polygon: 2D polygons with holes to triangles, for formats that store regions as outlines (Doom map
|
||||
-- sectors, ...). Loops are classified by nesting (a loop inside an odd number of other loops is a hole of the
|
||||
-- smallest loop around it), oriented, each hole bridged to its outer loop at a mutually visible vertex, then the
|
||||
-- result is ear-clipped (reflex-vertex test; a polygon that never yields a clean ear clips its least bad corner so
|
||||
-- every input terminates). New in rosetta, after the classic "ear clipping with hole bridging" method
|
||||
-- (D. Eberly, Triangulation by Ear Clipping); no code taken.
|
||||
--
|
||||
-- local tris = Polygon.triangulate({ { 0, 0, 10, 0, 10, 10, 0, 10 }, { 2, 2, 4, 2, 4, 4, 2, 4 } })
|
||||
-- -- tris = { loop, index, loop, index, loop, index, ... }: three corners per triangle, each a (loop, vertex) pair
|
||||
-- -- (1-based), counter-clockwise
|
||||
--
|
||||
-- Never throws; degenerate loops (fewer than 3 points, zero area) are ignored.
|
||||
local Polygon = {}
|
||||
|
||||
type Pt = { x: number, y: number, loop: number, index: number }
|
||||
|
||||
local function area(pts: { Pt }): number
|
||||
local a = 0
|
||||
local n = #pts
|
||||
for i = 1, n do
|
||||
local p, q = pts[i], pts[i % n + 1]
|
||||
a += p.x * q.y - q.x * p.y
|
||||
end
|
||||
return a / 2
|
||||
end
|
||||
|
||||
local function inside(pts: { Pt }, x: number, y: number): boolean
|
||||
local c = false
|
||||
local n = #pts
|
||||
local j = n
|
||||
for i = 1, n do
|
||||
local a, b = pts[i], pts[j]
|
||||
if (a.y > y) ~= (b.y > y) and x < (b.x - a.x) * (y - a.y) / (b.y - a.y) + a.x then
|
||||
c = not c
|
||||
end
|
||||
j = i
|
||||
end
|
||||
return c
|
||||
end
|
||||
|
||||
local function cross(o: Pt, a: Pt, b: Pt): number
|
||||
return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x)
|
||||
end
|
||||
|
||||
-- segments p1-p2 and q1-q2 cross properly (touching at an endpoint does not count)
|
||||
local function crosses(p1: Pt, p2: Pt, q1: Pt, q2: Pt): boolean
|
||||
if (p1.x == q1.x and p1.y == q1.y) or (p1.x == q2.x and p1.y == q2.y) or (p2.x == q1.x and p2.y == q1.y) or (p2.x == q2.x and p2.y == q2.y) then
|
||||
return false
|
||||
end
|
||||
local d1, d2 = cross(q1, q2, p1), cross(q1, q2, p2)
|
||||
local d3, d4 = cross(p1, p2, q1), cross(p1, p2, q2)
|
||||
return ((d1 > 0 and d2 < 0) or (d1 < 0 and d2 > 0)) and ((d3 > 0 and d4 < 0) or (d3 < 0 and d4 > 0))
|
||||
end
|
||||
|
||||
local function visible(m: Pt, v: Pt, rings: { { Pt } }): boolean
|
||||
for _, r in rings do
|
||||
local n = #r
|
||||
for i = 1, n do
|
||||
if crosses(m, v, r[i], r[i % n + 1]) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- splice hole h into ring outer (both oriented: outer counter-clockwise, hole clockwise) at mutually visible
|
||||
-- vertices; others = every ring the bridge must not cross
|
||||
local function bridge(outer: { Pt }, h: { Pt }, others: { { Pt } }): { Pt }
|
||||
local mi = 1
|
||||
for i, p in h do
|
||||
if p.x > h[mi].x then
|
||||
mi = i
|
||||
end
|
||||
end
|
||||
local m = h[mi]
|
||||
local best, bestD = 0, math.huge
|
||||
for pass = 1, 2 do
|
||||
for i, v in outer do
|
||||
if pass == 2 or v.x >= m.x then
|
||||
local d = (v.x - m.x) ^ 2 + (v.y - m.y) ^ 2
|
||||
if d < bestD and visible(m, v, others) then
|
||||
best, bestD = i, d
|
||||
end
|
||||
end
|
||||
end
|
||||
if best > 0 then
|
||||
break
|
||||
end
|
||||
end
|
||||
if best == 0 then
|
||||
best = 1
|
||||
end
|
||||
local out: { Pt } = {}
|
||||
for i = 1, best do
|
||||
table.insert(out, outer[i])
|
||||
end
|
||||
local n = #h
|
||||
for k = 0, n do
|
||||
table.insert(out, h[(mi - 1 + k) % n + 1])
|
||||
end
|
||||
for i = best, #outer do
|
||||
table.insert(out, outer[i])
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function inTri(a: Pt, b: Pt, c: Pt, p: Pt): boolean
|
||||
return cross(a, b, p) >= 0 and cross(b, c, p) >= 0 and cross(c, a, p) >= 0
|
||||
end
|
||||
|
||||
-- ear clipping of one counter-clockwise ring
|
||||
local function clip(ring: { Pt }, out: { number })
|
||||
local pts = table.clone(ring)
|
||||
local guard = #pts * #pts + 16
|
||||
while #pts > 3 and guard > 0 do
|
||||
guard -= 1
|
||||
local n = #pts
|
||||
local found, bestI, bestScore = 0, 1, -math.huge
|
||||
for i = 1, n do
|
||||
local a, b, c = pts[(i - 2) % n + 1], pts[i], pts[i % n + 1]
|
||||
local cr = cross(a, b, c)
|
||||
if cr > 0 then
|
||||
local ok = true
|
||||
for k = 1, n do
|
||||
local p = pts[k]
|
||||
if p ~= a and p ~= b and p ~= c and not (p.x == b.x and p.y == b.y) and not (p.x == a.x and p.y == a.y) and not (p.x == c.x and p.y == c.y) and inTri(a, b, c, p) then
|
||||
ok = false
|
||||
break
|
||||
end
|
||||
end
|
||||
if ok then
|
||||
found = i
|
||||
break
|
||||
end
|
||||
end
|
||||
if cr > bestScore then
|
||||
bestI, bestScore = i, cr
|
||||
end
|
||||
end
|
||||
local i = if found > 0 then found else bestI
|
||||
local a, b, c = pts[(i - 2) % n + 1], pts[i], pts[i % n + 1]
|
||||
if cross(a, b, c) ~= 0 then
|
||||
table.insert(out, a.loop)
|
||||
table.insert(out, a.index)
|
||||
table.insert(out, b.loop)
|
||||
table.insert(out, b.index)
|
||||
table.insert(out, c.loop)
|
||||
table.insert(out, c.index)
|
||||
end
|
||||
table.remove(pts, i)
|
||||
end
|
||||
if #pts == 3 and cross(pts[1], pts[2], pts[3]) > 0 then
|
||||
for k = 1, 3 do
|
||||
table.insert(out, pts[k].loop)
|
||||
table.insert(out, pts[k].index)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- triangulate(loops) -> { loop, index, ... }: loops[i] = { x1, y1, x2, y2, ... } (closed implicitly)
|
||||
function Polygon.triangulate(loops: { { number } }): { number }
|
||||
local rings: { { Pt } } = {}
|
||||
local areas: { number } = {}
|
||||
for li, l in loops do
|
||||
local pts: { Pt } = {}
|
||||
for k = 1, #l - 1, 2 do
|
||||
local x, y = l[k], l[k + 1]
|
||||
if type(x) == "number" and type(y) == "number" and x == x and y == y then
|
||||
table.insert(pts, { x = x, y = y, loop = li, index = (k + 1) // 2 })
|
||||
end
|
||||
end
|
||||
local a = if #pts >= 3 then area(pts) else 0
|
||||
if a ~= 0 then
|
||||
table.insert(rings, pts)
|
||||
table.insert(areas, math.abs(a))
|
||||
if a < 0 then -- counter-clockwise for now; holes are flipped below
|
||||
local r: { Pt } = {}
|
||||
for k = #pts, 1, -1 do
|
||||
table.insert(r, pts[k])
|
||||
end
|
||||
rings[#rings] = r
|
||||
end
|
||||
end
|
||||
end
|
||||
-- nesting: the parent of a ring is the smallest ring containing its first point
|
||||
local n = #rings
|
||||
local depth, parent = table.create(n, 0), table.create(n, 0)
|
||||
for i = 1, n do
|
||||
local p = rings[i][1]
|
||||
for j = 1, n do
|
||||
if j ~= i and areas[j] > areas[i] and inside(rings[j], p.x, p.y) then
|
||||
depth[i] += 1
|
||||
if parent[i] == 0 or areas[j] < areas[parent[i]] then
|
||||
parent[i] = j
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local holes: { [number]: { number } } = {}
|
||||
for i = 1, n do
|
||||
if depth[i] % 2 == 1 and parent[i] > 0 then
|
||||
local list = holes[parent[i]] or {}
|
||||
holes[parent[i]] = list
|
||||
table.insert(list, i)
|
||||
end
|
||||
end
|
||||
local out: { number } = {}
|
||||
for i = 1, n do
|
||||
if depth[i] % 2 == 0 then
|
||||
local ring = rings[i]
|
||||
local hs = holes[i]
|
||||
if hs then
|
||||
table.sort(hs, function(a: number, b: number): boolean
|
||||
local ma, mb = -math.huge, -math.huge
|
||||
for _, p in rings[a] do
|
||||
ma = math.max(ma, p.x)
|
||||
end
|
||||
for _, p in rings[b] do
|
||||
mb = math.max(mb, p.x)
|
||||
end
|
||||
return ma > mb
|
||||
end)
|
||||
local flipped: { { Pt } } = {}
|
||||
for _, h in hs do
|
||||
local r: { Pt } = {}
|
||||
local src = rings[h]
|
||||
for k = #src, 1, -1 do
|
||||
table.insert(r, src[k])
|
||||
end
|
||||
table.insert(flipped, r)
|
||||
end
|
||||
for k, h in flipped do
|
||||
local others: { { Pt } } = { ring }
|
||||
for k2 = k + 1, #flipped do
|
||||
table.insert(others, flipped[k2])
|
||||
end
|
||||
ring = bridge(ring, h, others)
|
||||
end
|
||||
end
|
||||
clip(ring, out)
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return Polygon
|
||||
@@ -0,0 +1,774 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/model/Rbx/Binary: the property columns of the Roblox binary format (rbx-dom docs/binary.md): one PROP chunk
|
||||
-- holds a property's values for every instance of a class, by type id, with the format's array transforms: byte
|
||||
-- interleaving (all first bytes, then all second bytes, ...), big-endian integers, zigzag signed integers, "rotated"
|
||||
-- floats (sign bit moved to bit 0), delta-coded referents, and CFrame rotation ids (codecs/model/Rbx). Never throws.
|
||||
--
|
||||
-- local values, pEnd = Binary.decode(typeId, buf, p, limit, n, ctx) -- n plain values (codecs/model/Rbx forms)
|
||||
-- local err = Binary.encode(typeId, values, n, writer, ctx) -- nil, or a message
|
||||
-- Binary.readRefs(buf, p, limit, n) / Binary.writeRefs(writer, refs) -- referent arrays (INST, PRNT)
|
||||
--
|
||||
-- ctx: { ref = function(referent) -> Instance? (decode), refOf = function(Instance?) -> referent (-1 = none),
|
||||
-- shared = { string } (SSTR entries, 1-based, decode), sharedIndex = function(string) -> 0-based index (encode) }.
|
||||
-- decode returns nil, message on bad data ("truncated", "corrupt: ...", "unknown" for a type id it does not know /
|
||||
-- a layout it cannot read, which the format keeps raw).
|
||||
local Rbx = require("@rosetta/codecs/model/Rbx")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
|
||||
local Binary = {}
|
||||
|
||||
local readu8, readu16, readi16, readu32, readf32, readf64 =
|
||||
buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readf32, buffer.readf64
|
||||
local writeu32, readstring = buffer.writeu32, buffer.readstring
|
||||
local writef32 = buffer.writef32
|
||||
local floor = math.floor
|
||||
|
||||
local scratch = buffer.create(8)
|
||||
local TWO32 = 4294967296
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ transforms
|
||||
-- the rotated float encoding: bits rotated left by one (sign in bit 0)
|
||||
local function unrotate(x: number): number
|
||||
writeu32(scratch, 0, x // 2 + (x % 2) * 2147483648)
|
||||
return readf32(scratch, 0)
|
||||
end
|
||||
local function rotate(v: number): number
|
||||
writef32(scratch, 0, v)
|
||||
local bits = readu32(scratch, 0)
|
||||
return (bits * 2) % TWO32 + bits // 2147483648
|
||||
end
|
||||
local function unzigzag(x: number): number
|
||||
return if x % 2 == 0 then x // 2 else -(x + 1) // 2
|
||||
end
|
||||
local function zigzag32(v: number): number
|
||||
v = floor(v)
|
||||
return (if v >= 0 then v * 2 else -v * 2 - 1) % TWO32
|
||||
end
|
||||
|
||||
-- n big-endian u32 values interleaved at p (4n bytes)
|
||||
local function u32s(b: buffer, p: number, n: number): { number }
|
||||
local out = table.create(n, 0)
|
||||
local n2, n3 = n * 2, n * 3
|
||||
for i = 0, n - 1 do
|
||||
out[i + 1] = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + n2 + i) * 256 + readu8(b, p + n3 + i)
|
||||
end
|
||||
return out
|
||||
end
|
||||
local function i32s(b: buffer, p: number, n: number): { number }
|
||||
local out = u32s(b, p, n)
|
||||
for i = 1, n do
|
||||
out[i] = unzigzag(out[i])
|
||||
end
|
||||
return out
|
||||
end
|
||||
local function f32s(b: buffer, p: number, n: number): { number }
|
||||
local out = u32s(b, p, n)
|
||||
for i = 1, n do
|
||||
out[i] = unrotate(out[i])
|
||||
end
|
||||
return out
|
||||
end
|
||||
-- n zigzag i64 values (8n interleaved bytes), as doubles
|
||||
local function i64s(b: buffer, p: number, n: number): { number }
|
||||
local out = table.create(n, 0)
|
||||
for i = 0, n - 1 do
|
||||
local hi = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + 2 * n + i) * 256 + readu8(b, p + 3 * n + i)
|
||||
local lo = readu8(b, p + 4 * n + i) * 16777216 + readu8(b, p + 5 * n + i) * 65536 + readu8(b, p + 6 * n + i) * 256 + readu8(b, p + 7 * n + i)
|
||||
local half = hi * 2147483648 + lo // 2
|
||||
out[i + 1] = if lo % 2 == 0 then half else -half - 1
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- writers: n values interleaved as big-endian u32 / zigzag i32 / rotated f32 / zigzag i64
|
||||
local function putU32s(w: Bytes.Writer, vals: { number })
|
||||
local n = #vals
|
||||
local p = w:reserve(4 * n)
|
||||
local b = w.buf
|
||||
for i = 0, n - 1 do
|
||||
local v = vals[i + 1] % TWO32
|
||||
buffer.writeu8(b, p + i, v // 16777216)
|
||||
buffer.writeu8(b, p + n + i, (v // 65536) % 256)
|
||||
buffer.writeu8(b, p + 2 * n + i, (v // 256) % 256)
|
||||
buffer.writeu8(b, p + 3 * n + i, v % 256)
|
||||
end
|
||||
w.pos = p + 4 * n
|
||||
end
|
||||
local function putI32s(w: Bytes.Writer, vals: { number })
|
||||
local t = table.create(#vals, 0)
|
||||
for i, v in vals do
|
||||
t[i] = zigzag32(v)
|
||||
end
|
||||
putU32s(w, t)
|
||||
end
|
||||
local function putF32s(w: Bytes.Writer, vals: { number })
|
||||
local t = table.create(#vals, 0)
|
||||
for i, v in vals do
|
||||
t[i] = rotate(v)
|
||||
end
|
||||
putU32s(w, t)
|
||||
end
|
||||
local function putI64s(w: Bytes.Writer, vals: { number })
|
||||
local n = #vals
|
||||
local p = w:reserve(8 * n)
|
||||
local b = w.buf
|
||||
for i = 0, n - 1 do
|
||||
local v = floor(vals[i + 1])
|
||||
local z = if v >= 0 then v * 2 else -v * 2 - 1
|
||||
local hi, lo = (z // TWO32) % TWO32, z % TWO32
|
||||
buffer.writeu8(b, p + i, hi // 16777216)
|
||||
buffer.writeu8(b, p + n + i, (hi // 65536) % 256)
|
||||
buffer.writeu8(b, p + 2 * n + i, (hi // 256) % 256)
|
||||
buffer.writeu8(b, p + 3 * n + i, hi % 256)
|
||||
buffer.writeu8(b, p + 4 * n + i, lo // 16777216)
|
||||
buffer.writeu8(b, p + 5 * n + i, (lo // 65536) % 256)
|
||||
buffer.writeu8(b, p + 6 * n + i, (lo // 256) % 256)
|
||||
buffer.writeu8(b, p + 7 * n + i, lo % 256)
|
||||
end
|
||||
w.pos = p + 8 * n
|
||||
end
|
||||
|
||||
-- referent arrays: zigzag i32, interleaved, each the difference from the previous one
|
||||
function Binary.readRefs(b: buffer, p: number, limit: number, n: number): ({ number }?, number)
|
||||
if n < 0 or p + 4 * n > limit then
|
||||
return nil, p
|
||||
end
|
||||
local out = i32s(b, p, n)
|
||||
local acc = 0
|
||||
for i = 1, n do
|
||||
acc += out[i]
|
||||
out[i] = acc
|
||||
end
|
||||
return out, p + 4 * n
|
||||
end
|
||||
function Binary.writeRefs(w: Bytes.Writer, refs: { number })
|
||||
local d = table.create(#refs, 0)
|
||||
local prev = 0
|
||||
for i, r in refs do
|
||||
d[i] = r - prev
|
||||
prev = r
|
||||
end
|
||||
putI32s(w, d)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
export type Ctx = {
|
||||
ref: ((number) -> any)?,
|
||||
refOf: ((any) -> number)?,
|
||||
shared: { string }?,
|
||||
sharedIndex: ((string) -> number)?,
|
||||
}
|
||||
|
||||
-- a length-prefixed string at p: string, next p (nil when it runs past limit)
|
||||
local function str(b: buffer, p: number, limit: number): (string?, number)
|
||||
if p + 4 > limit then
|
||||
return nil, p
|
||||
end
|
||||
local len = readu32(b, p)
|
||||
if p + 4 + len > limit then
|
||||
return nil, p
|
||||
end
|
||||
return readstring(b, p + 4, len), p + 4 + len
|
||||
end
|
||||
|
||||
local function cframes(b: buffer, p: number, limit: number, n: number): ({ any }?, number)
|
||||
local rots: { { number } } = table.create(n) :: any
|
||||
for i = 1, n do
|
||||
if p >= limit then
|
||||
return nil, p
|
||||
end
|
||||
local id = readu8(b, p)
|
||||
p += 1
|
||||
if id == 0 then
|
||||
if p + 36 > limit then
|
||||
return nil, p
|
||||
end
|
||||
local m = table.create(9, 0)
|
||||
for k = 0, 8 do
|
||||
m[k + 1] = readf32(b, p + 4 * k)
|
||||
end
|
||||
rots[i] = m
|
||||
p += 36
|
||||
else
|
||||
local m = Rbx.ROTATIONS[id]
|
||||
if not m then
|
||||
return nil, -1
|
||||
end
|
||||
rots[i] = m
|
||||
end
|
||||
end
|
||||
if p + 12 * n > limit then
|
||||
return nil, p
|
||||
end
|
||||
local xs, ys, zs = f32s(b, p, n), f32s(b, p + 4 * n, n), f32s(b, p + 8 * n, n)
|
||||
local out = table.create(n)
|
||||
for i = 1, n do
|
||||
local m = rots[i]
|
||||
out[i] = { xs[i], ys[i], zs[i], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9] }
|
||||
end
|
||||
return out, p + 12 * n
|
||||
end
|
||||
|
||||
local FIXED: { [number]: number } = { -- bytes per value of the fixed-size types
|
||||
[0x02] = 1,
|
||||
[0x03] = 4,
|
||||
[0x04] = 4,
|
||||
[0x05] = 8,
|
||||
[0x06] = 8,
|
||||
[0x07] = 16,
|
||||
[0x08] = 24,
|
||||
[0x09] = 1,
|
||||
[0x0A] = 1,
|
||||
[0x0B] = 4,
|
||||
[0x0C] = 12,
|
||||
[0x0D] = 8,
|
||||
[0x0E] = 12,
|
||||
[0x0F] = 4,
|
||||
[0x12] = 4,
|
||||
[0x13] = 4,
|
||||
[0x14] = 6,
|
||||
[0x17] = 8,
|
||||
[0x18] = 16,
|
||||
[0x1A] = 3,
|
||||
[0x1B] = 8,
|
||||
[0x1C] = 4,
|
||||
[0x1F] = 16,
|
||||
[0x21] = 8,
|
||||
}
|
||||
|
||||
-- decode(typeId, b, p, limit, n, ctx) -> n values, the end offset | nil, message
|
||||
function Binary.decode(t: number, b: buffer, p: number, limit: number, n: number, ctx: Ctx): ({ any }?, any)
|
||||
if limit > buffer.len(b) or p < 0 or n < 0 then
|
||||
return nil, "corrupt: bad ranges"
|
||||
end
|
||||
local size = FIXED[t]
|
||||
if size and p + size * n > limit then
|
||||
return nil, "truncated property values"
|
||||
end
|
||||
if t == 0x01 or t == 0x1D then
|
||||
local out = table.create(n, "")
|
||||
for i = 1, n do
|
||||
local s, q = str(b, p, limit)
|
||||
if not s then
|
||||
return nil, "truncated string"
|
||||
end
|
||||
out[i] = s
|
||||
p = q
|
||||
end
|
||||
return out, p
|
||||
elseif t == 0x02 then
|
||||
local out = table.create(n, false)
|
||||
for i = 1, n do
|
||||
out[i] = readu8(b, p + i - 1) ~= 0
|
||||
end
|
||||
return out, p + n
|
||||
elseif t == 0x03 then
|
||||
return i32s(b, p, n), p + 4 * n
|
||||
elseif t == 0x04 then
|
||||
return f32s(b, p, n), p + 4 * n
|
||||
elseif t == 0x05 then
|
||||
local out = table.create(n, 0)
|
||||
for i = 1, n do
|
||||
out[i] = readf64(b, p + 8 * (i - 1))
|
||||
end
|
||||
return out, p + 8 * n
|
||||
elseif t == 0x06 then
|
||||
local s, o = f32s(b, p, n), i32s(b, p + 4 * n, n)
|
||||
local out = table.create(n)
|
||||
for i = 1, n do
|
||||
out[i] = { s[i], o[i] }
|
||||
end
|
||||
return out, p + 8 * n
|
||||
elseif t == 0x07 then
|
||||
local xs, ys, xo, yo = f32s(b, p, n), f32s(b, p + 4 * n, n), i32s(b, p + 8 * n, n), i32s(b, p + 12 * n, n)
|
||||
local out = table.create(n)
|
||||
for i = 1, n do
|
||||
out[i] = { xs[i], xo[i], ys[i], yo[i] }
|
||||
end
|
||||
return out, p + 16 * n
|
||||
elseif t == 0x08 then
|
||||
local out = table.create(n)
|
||||
for i = 1, n do
|
||||
local q = p + 24 * (i - 1)
|
||||
out[i] = { readf32(b, q), readf32(b, q + 4), readf32(b, q + 8), readf32(b, q + 12), readf32(b, q + 16), readf32(b, q + 20) }
|
||||
end
|
||||
return out, p + 24 * n
|
||||
elseif t == 0x09 or t == 0x0A then
|
||||
local out = table.create(n, 0)
|
||||
for i = 1, n do
|
||||
out[i] = readu8(b, p + i - 1)
|
||||
end
|
||||
return out, p + n
|
||||
elseif t == 0x0B or t == 0x12 then
|
||||
return u32s(b, p, n), p + 4 * n
|
||||
elseif t == 0x0C or t == 0x0E or t == 0x0D or t == 0x18 then
|
||||
local k = if t == 0x0D then 2 elseif t == 0x18 then 4 else 3
|
||||
local cols: { { number } } = table.create(k) :: any
|
||||
for c = 1, k do
|
||||
cols[c] = f32s(b, p + 4 * n * (c - 1), n)
|
||||
end
|
||||
local out = table.create(n)
|
||||
for i = 1, n do
|
||||
local v = table.create(k, 0)
|
||||
for c = 1, k do
|
||||
v[c] = cols[c][i]
|
||||
end
|
||||
out[i] = v
|
||||
end
|
||||
return out, p + 4 * k * n
|
||||
elseif t == 0x0F or t == 0x14 then
|
||||
local k = if t == 0x0F then 2 else 3
|
||||
local out = table.create(n)
|
||||
for i = 1, n do
|
||||
local q = p + 2 * k * (i - 1)
|
||||
out[i] = if k == 2 then { readi16(b, q), readi16(b, q + 2) } else { readi16(b, q), readi16(b, q + 2), readi16(b, q + 4) }
|
||||
end
|
||||
return out, p + 2 * k * n
|
||||
elseif t == 0x10 then
|
||||
local out, q = cframes(b, p, limit, n)
|
||||
if not out then
|
||||
return nil, if q == -1 then "corrupt: bad CFrame rotation id" else "truncated CFrame values"
|
||||
end
|
||||
return out, q
|
||||
elseif t == 0x13 then
|
||||
local refs, q = Binary.readRefs(b, p, limit, n)
|
||||
if not refs then
|
||||
return nil, "truncated referents"
|
||||
end
|
||||
local out = table.create(n)
|
||||
local ref = ctx.ref
|
||||
for i = 1, n do
|
||||
out[i] = if ref and refs[i] >= 0 then ref(refs[i]) else nil
|
||||
end
|
||||
return out, q
|
||||
elseif t == 0x15 or t == 0x16 then
|
||||
local k = if t == 0x15 then 3 else 5
|
||||
local out = table.create(n)
|
||||
for i = 1, n do
|
||||
if p + 4 > limit then
|
||||
return nil, "truncated sequence"
|
||||
end
|
||||
local count = readu32(b, p)
|
||||
p += 4
|
||||
if p + count * 4 * k > limit then
|
||||
return nil, "truncated sequence"
|
||||
end
|
||||
local seq = table.create(count)
|
||||
for j = 1, count do
|
||||
local key = table.create(k, 0)
|
||||
for c = 1, k do
|
||||
key[c] = readf32(b, p + 4 * (c - 1))
|
||||
end
|
||||
seq[j] = key
|
||||
p += 4 * k
|
||||
end
|
||||
out[i] = seq
|
||||
end
|
||||
return out, p
|
||||
elseif t == 0x17 then
|
||||
local out = table.create(n)
|
||||
for i = 1, n do
|
||||
out[i] = { readf32(b, p + 8 * (i - 1)), readf32(b, p + 8 * (i - 1) + 4) }
|
||||
end
|
||||
return out, p + 8 * n
|
||||
elseif t == 0x19 then
|
||||
local out = table.create(n)
|
||||
for i = 1, n do
|
||||
if p >= limit then
|
||||
return nil, "truncated physical properties"
|
||||
end
|
||||
local flag = readu8(b, p)
|
||||
p += 1
|
||||
if flag % 2 == 1 then
|
||||
local k = if flag // 2 % 2 == 1 then 6 else 5
|
||||
if p + 4 * k > limit then
|
||||
return nil, "truncated physical properties"
|
||||
end
|
||||
local v = table.create(6, 1) -- acoustic absorption 1 when the file leaves it out
|
||||
for c = 1, k do
|
||||
v[c] = readf32(b, p + 4 * (c - 1))
|
||||
end
|
||||
out[i] = v
|
||||
p += 4 * k
|
||||
elseif flag ~= 0 then
|
||||
return nil, "unknown"
|
||||
end
|
||||
end
|
||||
return out, p
|
||||
elseif t == 0x1A then
|
||||
local out = table.create(n)
|
||||
for i = 1, n do
|
||||
out[i] = { readu8(b, p + i - 1), readu8(b, p + n + i - 1), readu8(b, p + 2 * n + i - 1) }
|
||||
end
|
||||
return out, p + 3 * n
|
||||
elseif t == 0x1B or t == 0x21 then
|
||||
return i64s(b, p, n), p + 8 * n
|
||||
elseif t == 0x1C then
|
||||
local idx = u32s(b, p, n)
|
||||
local shared: { string } = ctx.shared or {}
|
||||
local out: { string } = table.create(n, "")
|
||||
for i = 1, n do
|
||||
local s = shared[idx[i] + 1]
|
||||
if s == nil then
|
||||
return nil, "corrupt: shared string index out of range"
|
||||
end
|
||||
out[i] = s
|
||||
end
|
||||
return out, p + 4 * n
|
||||
elseif t == 0x1E then
|
||||
if p >= limit or readu8(b, p) ~= 0x10 then
|
||||
return nil, "unknown"
|
||||
end
|
||||
local cfs, q = cframes(b, p + 1, limit, n)
|
||||
if not cfs then
|
||||
return nil, if q == -1 then "corrupt: bad CFrame rotation id" else "truncated CFrame values"
|
||||
end
|
||||
if q + 1 + n > limit or readu8(b, q) ~= 0x02 then
|
||||
return nil, "truncated optional CFrame flags"
|
||||
end
|
||||
local out = table.create(n)
|
||||
for i = 1, n do
|
||||
out[i] = if readu8(b, q + i) ~= 0 then cfs[i] else nil
|
||||
end
|
||||
return out, q + 1 + n
|
||||
elseif t == 0x1F then
|
||||
local out = table.create(n, "")
|
||||
local hex = table.create(16, "")
|
||||
for i = 0, n - 1 do
|
||||
local by = table.create(16, 0)
|
||||
for k = 0, 15 do
|
||||
by[k + 1] = readu8(b, p + k * n + i)
|
||||
end
|
||||
-- bytes 8..15: the random part rotated left by one bit (as a 64-bit integer); undo it
|
||||
local carry = by[16] % 2
|
||||
for k = 9, 16 do
|
||||
local v = by[k]
|
||||
by[k] = v // 2 + carry * 128
|
||||
carry = v % 2
|
||||
end
|
||||
for k = 1, 8 do
|
||||
hex[k] = string.format("%02x", by[8 + k])
|
||||
end
|
||||
for k = 1, 8 do
|
||||
hex[8 + k] = string.format("%02x", by[k + 4 - (if k > 4 then 8 else 0)])
|
||||
end
|
||||
out[i + 1] = table.concat(hex)
|
||||
end
|
||||
return out, p + 16 * n
|
||||
elseif t == 0x20 then
|
||||
local out = table.create(n)
|
||||
for i = 1, n do
|
||||
local fam, q = str(b, p, limit)
|
||||
if not fam or q + 3 > limit then
|
||||
return nil, "truncated font"
|
||||
end
|
||||
local weight, style = readu16(b, q), readu8(b, q + 2)
|
||||
local face, q2 = str(b, q + 3, limit)
|
||||
if not face then
|
||||
return nil, "truncated font"
|
||||
end
|
||||
out[i] = { family = fam, weight = weight, style = if style == 1 then "Italic" else "Normal", cachedFaceId = if face ~= "" then face else nil }
|
||||
p = q2
|
||||
end
|
||||
return out, p
|
||||
elseif t == 0x22 then
|
||||
if p + 4 * n > limit then
|
||||
return nil, "truncated content"
|
||||
end
|
||||
local kinds = i32s(b, p, n)
|
||||
p += 4 * n
|
||||
if p + 4 > limit then
|
||||
return nil, "truncated content"
|
||||
end
|
||||
local nu = readu32(b, p)
|
||||
p += 4
|
||||
local uris = table.create(math.min(nu, n))
|
||||
for j = 1, nu do
|
||||
local s, q = str(b, p, limit)
|
||||
if not s then
|
||||
return nil, "truncated content"
|
||||
end
|
||||
uris[j] = s
|
||||
p = q
|
||||
end
|
||||
if p + 4 > limit then
|
||||
return nil, "truncated content"
|
||||
end
|
||||
local no = readu32(b, p)
|
||||
local objs, q = Binary.readRefs(b, p + 4, limit, no)
|
||||
if not objs or q + 4 > limit then
|
||||
return nil, "truncated content"
|
||||
end
|
||||
if readu32(b, q) ~= 0 then
|
||||
return nil, "unknown" -- external objects: kept raw
|
||||
end
|
||||
p = q + 4
|
||||
local out = table.create(n)
|
||||
local iu, io = 1, 1
|
||||
for i = 1, n do
|
||||
local k = kinds[i]
|
||||
if k == 1 then
|
||||
if iu > nu then
|
||||
return nil, "corrupt: content uri count"
|
||||
end
|
||||
out[i] = uris[iu]
|
||||
iu += 1
|
||||
elseif k == 2 then
|
||||
if io > no then
|
||||
return nil, "corrupt: content object count"
|
||||
end
|
||||
local r = objs[io]
|
||||
out[i] = if ctx.ref and r >= 0 then ctx.ref(r) else nil
|
||||
io += 1
|
||||
elseif k ~= 0 then
|
||||
return nil, "unknown"
|
||||
end
|
||||
end
|
||||
return out, p
|
||||
end
|
||||
return nil, "unknown"
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function num(v: any): number
|
||||
return if type(v) == "number" and v == v then v else 0
|
||||
end
|
||||
-- column c of n array values (missing components 0)
|
||||
local function column(vals: { any }, n: number, c: number): { number }
|
||||
local out = table.create(n, 0)
|
||||
for i = 1, n do
|
||||
local v = vals[i]
|
||||
out[i] = if type(v) == "table" then num(v[c]) else 0
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function putString(w: Bytes.Writer, s: string)
|
||||
w:u32le(#s)
|
||||
w:string(s)
|
||||
end
|
||||
|
||||
local function putCFrames(w: Bytes.Writer, vals: { any }, n: number)
|
||||
for i = 1, n do
|
||||
local v = vals[i]
|
||||
local cf = if type(v) == "table" then v else { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 }
|
||||
local id = Rbx.rotationId(cf)
|
||||
w:u8(id)
|
||||
if id == 0 then
|
||||
for k = 4, 12 do
|
||||
w:f32le(num(cf[k]))
|
||||
end
|
||||
end
|
||||
end
|
||||
putF32s(w, column(vals, n, 1))
|
||||
putF32s(w, column(vals, n, 2))
|
||||
putF32s(w, column(vals, n, 3))
|
||||
end
|
||||
|
||||
local function hexByte(s: string, i: number): number
|
||||
return tonumber(string.sub(s, 2 * i - 1, 2 * i), 16) or 0
|
||||
end
|
||||
|
||||
-- encode(typeId, values, n, w, ctx) -> nil | message: values[1 .. n] in the codecs/model/Rbx forms (nil entries are
|
||||
-- the type's none / default)
|
||||
function Binary.encode(t: number, vals: { any }, n: number, w: Bytes.Writer, ctx: Ctx): string?
|
||||
if t == 0x01 or t == 0x1D then
|
||||
for i = 1, n do
|
||||
local v = vals[i]
|
||||
putString(w, if type(v) == "string" then v else "")
|
||||
end
|
||||
elseif t == 0x02 then
|
||||
for i = 1, n do
|
||||
w:u8(if vals[i] then 1 else 0)
|
||||
end
|
||||
elseif t == 0x03 then
|
||||
local c = table.create(n, 0)
|
||||
for i = 1, n do
|
||||
c[i] = num(vals[i])
|
||||
end
|
||||
putI32s(w, c)
|
||||
elseif t == 0x04 then
|
||||
local c = table.create(n, 0)
|
||||
for i = 1, n do
|
||||
c[i] = num(vals[i])
|
||||
end
|
||||
putF32s(w, c)
|
||||
elseif t == 0x05 then
|
||||
for i = 1, n do
|
||||
w:f64le(num(vals[i]))
|
||||
end
|
||||
elseif t == 0x06 then
|
||||
putF32s(w, column(vals, n, 1))
|
||||
putI32s(w, column(vals, n, 2))
|
||||
elseif t == 0x07 then
|
||||
putF32s(w, column(vals, n, 1))
|
||||
putF32s(w, column(vals, n, 3))
|
||||
putI32s(w, column(vals, n, 2))
|
||||
putI32s(w, column(vals, n, 4))
|
||||
elseif t == 0x08 then
|
||||
for i = 1, n do
|
||||
local v = vals[i]
|
||||
for c = 1, 6 do
|
||||
w:f32le(if type(v) == "table" then num(v[c]) else 0)
|
||||
end
|
||||
end
|
||||
elseif t == 0x09 or t == 0x0A then
|
||||
for i = 1, n do
|
||||
w:u8(num(vals[i]) % 256)
|
||||
end
|
||||
elseif t == 0x0B or t == 0x12 then
|
||||
local c = table.create(n, 0)
|
||||
for i = 1, n do
|
||||
c[i] = floor(num(vals[i]))
|
||||
end
|
||||
putU32s(w, c)
|
||||
elseif t == 0x0C or t == 0x0E or t == 0x0D or t == 0x18 then
|
||||
local k = if t == 0x0D then 2 elseif t == 0x18 then 4 else 3
|
||||
for c = 1, k do
|
||||
putF32s(w, column(vals, n, c))
|
||||
end
|
||||
elseif t == 0x0F or t == 0x14 then
|
||||
local k = if t == 0x0F then 2 else 3
|
||||
for i = 1, n do
|
||||
local v = vals[i]
|
||||
for c = 1, k do
|
||||
local x = floor(if type(v) == "table" then num(v[c]) else 0) % 65536
|
||||
w:u16le(x)
|
||||
end
|
||||
end
|
||||
elseif t == 0x10 then
|
||||
putCFrames(w, vals, n)
|
||||
elseif t == 0x13 then
|
||||
local refs = table.create(n, -1)
|
||||
local refOf = ctx.refOf
|
||||
for i = 1, n do
|
||||
refs[i] = if refOf and vals[i] ~= nil then refOf(vals[i]) else -1
|
||||
end
|
||||
Binary.writeRefs(w, refs)
|
||||
elseif t == 0x15 or t == 0x16 then
|
||||
local k = if t == 0x15 then 3 else 5
|
||||
for i = 1, n do
|
||||
local seq = vals[i]
|
||||
if type(seq) ~= "table" then
|
||||
seq = {}
|
||||
end
|
||||
w:u32le(#seq)
|
||||
for _, key in seq do
|
||||
for c = 1, k do
|
||||
w:f32le(if type(key) == "table" then num(key[c]) else 0)
|
||||
end
|
||||
end
|
||||
end
|
||||
elseif t == 0x17 then
|
||||
for i = 1, n do
|
||||
local v = vals[i]
|
||||
w:f32le(if type(v) == "table" then num(v[1]) else 0)
|
||||
w:f32le(if type(v) == "table" then num(v[2]) else 0)
|
||||
end
|
||||
elseif t == 0x19 then
|
||||
for i = 1, n do
|
||||
local v = vals[i]
|
||||
if type(v) ~= "table" then
|
||||
w:u8(0)
|
||||
else
|
||||
local acoustic = v[6] ~= nil and v[6] ~= 1 -- (rbx-dom leaves the default out)
|
||||
w:u8(if acoustic then 3 else 1)
|
||||
for c = 1, if acoustic then 6 else 5 do
|
||||
w:f32le(num(v[c]))
|
||||
end
|
||||
end
|
||||
end
|
||||
elseif t == 0x1A then
|
||||
for c = 1, 3 do
|
||||
for i = 1, n do
|
||||
local v = vals[i]
|
||||
w:u8(math.clamp(floor(if type(v) == "table" then num(v[c]) else 0), 0, 255))
|
||||
end
|
||||
end
|
||||
elseif t == 0x1B or t == 0x21 then
|
||||
local c = table.create(n, 0)
|
||||
for i = 1, n do
|
||||
c[i] = num(vals[i])
|
||||
end
|
||||
putI64s(w, c)
|
||||
elseif t == 0x1C then
|
||||
local idx = table.create(n, 0)
|
||||
local si = ctx.sharedIndex
|
||||
for i = 1, n do
|
||||
local v = vals[i]
|
||||
idx[i] = if si then si(if type(v) == "string" then v else "") else 0
|
||||
end
|
||||
putU32s(w, idx)
|
||||
elseif t == 0x1E then
|
||||
w:u8(0x10)
|
||||
putCFrames(w, vals, n)
|
||||
w:u8(0x02)
|
||||
for i = 1, n do
|
||||
w:u8(if type(vals[i]) == "table" then 1 else 0)
|
||||
end
|
||||
elseif t == 0x1F then
|
||||
local p = w:reserve(16 * n)
|
||||
local b = w.buf
|
||||
for i = 0, n - 1 do
|
||||
local s = vals[i + 1]
|
||||
if type(s) ~= "string" or #s ~= 32 or string.find(s, "[^%x]") then
|
||||
return "a UniqueId is 32 hex digits"
|
||||
end
|
||||
-- index (hex 25..32) and time (17..24) first, then the random part (1..16) rotated left by one bit
|
||||
local by = table.create(16, 0)
|
||||
for k = 1, 4 do
|
||||
by[k] = hexByte(s, 12 + k)
|
||||
by[4 + k] = hexByte(s, 8 + k)
|
||||
end
|
||||
local top = hexByte(s, 1) // 128
|
||||
for k = 1, 8 do
|
||||
local v = hexByte(s, k)
|
||||
local nxt = if k < 8 then hexByte(s, k + 1) // 128 else top
|
||||
by[8 + k] = (v * 2) % 256 + nxt
|
||||
end
|
||||
for k = 0, 15 do
|
||||
buffer.writeu8(b, p + k * n + i, by[k + 1])
|
||||
end
|
||||
end
|
||||
w.pos = p + 16 * n
|
||||
elseif t == 0x20 then
|
||||
for i = 1, n do
|
||||
local v = vals[i]
|
||||
if type(v) ~= "table" then
|
||||
v = Rbx.default("Font")
|
||||
end
|
||||
putString(w, if type(v.family) == "string" then v.family else "")
|
||||
w:u16le(math.clamp(floor(num(v.weight)), 0, 65535))
|
||||
w:u8(if v.style == "Italic" then 1 else 0)
|
||||
putString(w, if type(v.cachedFaceId) == "string" then v.cachedFaceId else "")
|
||||
end
|
||||
elseif t == 0x22 then
|
||||
local kinds, uris, objs = table.create(n, 0), {}, {}
|
||||
local refOf = ctx.refOf
|
||||
for i = 1, n do
|
||||
local v = vals[i]
|
||||
if type(v) == "string" then
|
||||
kinds[i] = 1
|
||||
table.insert(uris, v)
|
||||
elseif type(v) == "table" then
|
||||
kinds[i] = 2
|
||||
table.insert(objs, if refOf then refOf(v) else -1)
|
||||
end
|
||||
end
|
||||
putI32s(w, kinds)
|
||||
w:u32le(#uris)
|
||||
for _, s in uris do
|
||||
putString(w, s)
|
||||
end
|
||||
w:u32le(#objs)
|
||||
Binary.writeRefs(w, objs)
|
||||
w:u32le(0)
|
||||
else
|
||||
return "unknown type id " .. t
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
return Binary
|
||||
@@ -0,0 +1,281 @@
|
||||
--!strict
|
||||
-- codecs/model/Rbx: the Roblox instance tree every Roblox file format maps to (model/rbxm binary rbxm / rbxl,
|
||||
-- model/rbxmx XML rbxmx / rbxlx), the typed property values, the CFrame rotation IDs, and (codecs/model/Rbx/Binary) the
|
||||
-- binary format's property column codecs. Shared here because a format cannot require another one. Written from the
|
||||
-- rbx-dom format notes (docs/binary.md, docs/xml.md) and checked against rbx-dom through rojo / lune. A file library,
|
||||
-- not a Roblox runtime: nothing here creates Instances; a Roblox game reads the tree itself.
|
||||
--
|
||||
-- local tree = Rbx.tree() -- { kind = "rbxtree", roots = {}, place = false, ... }
|
||||
-- local part = Rbx.instance("Part", "Floor") -- { className, name, properties = {}, children = {} }
|
||||
-- Rbx.set(part, "Size", "Vector3", { 64, 1, 64 }) -- properties.Size = { type = "Vector3", value = {...} }
|
||||
-- Rbx.add(tree, part) -- a root; Rbx.add(parentInstance, child) nests
|
||||
-- for inst, depth in Rbx.descendants(tree) do ... end
|
||||
--
|
||||
-- Property values are { type = <name>, value = <v> } with these value forms (arrays follow the Roblox constructor
|
||||
-- argument order, so Vector3.new(table.unpack(v.value)) / CFrame.new(table.unpack(v.value)) rebuild them in Roblox):
|
||||
-- String, BinaryString, ProtectedString, ContentId, Bytecode string (bytes)
|
||||
-- SharedString string (the content; writers deduplicate)
|
||||
-- Bool boolean
|
||||
-- Int32, Int64, Float32, Float64 number (Int64 exact to 2^53)
|
||||
-- Enum, BrickColor, SecurityCapabilities number
|
||||
-- Faces number: bits Right 1, Top 2, Back 4, Left 8, Bottom 16, Front 32
|
||||
-- Axes number: bits X 1, Y 2, Z 4
|
||||
-- UDim { scale, offset } UDim2 { xScale, xOffset, yScale, yOffset } NumberRange { min, max }
|
||||
-- Vector2 / Vector2int16 { x, y } Vector3 / Vector3int16 { x, y, z } Color3 { r, g, b } (0..1)
|
||||
-- Color3uint8 { r, g, b } (0..255) Rect { minX, minY, maxX, maxY } Ray { ox, oy, oz, dx, dy, dz }
|
||||
-- CFrame { x, y, z, r00, r01, r02, r10, r11, r12, r20, r21, r22 } OptionalCFrame: the same, or nil (none)
|
||||
-- NumberSequence { { time, value, envelope } ... } ColorSequence { { time, r, g, b, envelope } ... }
|
||||
-- PhysicalProperties nil (default) | { density, friction, elasticity, frictionWeight, elasticityWeight,
|
||||
-- acousticAbsorption } (decoders fill acousticAbsorption = 1 when the file leaves it out)
|
||||
-- Ref an Instance of the tree, or nil
|
||||
-- UniqueId 32 hex digits: random (16), time (8), index (8)
|
||||
-- Font { family, weight (100..900), style ("Normal" | "Italic"), cachedFaceId? }
|
||||
-- Content nil (none) | string (a URI) | an Instance (object)
|
||||
-- Raw a binary property of a type this library does not know: { typeId, data (the class's whole column),
|
||||
-- index, count }; written back verbatim while the class keeps the same instances in the same order
|
||||
-- XmlRaw an XML property of an unknown type: value = the element (codecs/text/Xml node), written back as it is
|
||||
-- Name is not a property here: it is inst.name. Never throws.
|
||||
|
||||
local Rbx = {}
|
||||
|
||||
export type Value = { type: string, value: any }
|
||||
export type Instance = {
|
||||
className: string,
|
||||
name: string,
|
||||
properties: { [string]: Value },
|
||||
children: { Instance },
|
||||
parent: Instance?, -- nil for roots
|
||||
referent: string?, -- the file's referent (XML "RBX..." id, binary index) when read; writers make their own
|
||||
service: boolean?, -- a service (binary INST object format 1; rbxl roots)
|
||||
}
|
||||
export type Tree = {
|
||||
kind: "rbxtree",
|
||||
roots: { Instance },
|
||||
place: boolean, -- a place (rbxl / rbxlx: the roots are services under the DataModel) or a model
|
||||
metadata: { [string]: string }, -- binary META / XML <Meta> entries (ExplicitAutoJoints, ...)
|
||||
extra: { any }, -- unknown binary chunks { name, data } / unknown top-level XML elements, written back
|
||||
meta: { source: { format: string, [string]: any }?, [string]: any },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ tree
|
||||
function Rbx.tree(place: boolean?): Tree
|
||||
return { kind = "rbxtree", roots = {}, place = place == true, metadata = {}, extra = {}, meta = {} }
|
||||
end
|
||||
|
||||
function Rbx.instance(className: string, name: string?): Instance
|
||||
return { className = className, name = name or className, properties = {}, children = {} }
|
||||
end
|
||||
|
||||
-- add(parent, child) -> child: parent is a Tree (child becomes a root) or an Instance
|
||||
function Rbx.add(parent: any, child: Instance): Instance
|
||||
if parent.kind == "rbxtree" then
|
||||
child.parent = nil
|
||||
table.insert(parent.roots, child)
|
||||
else
|
||||
child.parent = parent
|
||||
table.insert(parent.children, child)
|
||||
end
|
||||
return child
|
||||
end
|
||||
|
||||
-- set(inst, name, type, value): a property (value nil = the type's nil form: Ref none, OptionalCFrame none, ...)
|
||||
function Rbx.set(inst: Instance, name: string, typ: string, value: any)
|
||||
inst.properties[name] = { type = typ, value = value }
|
||||
end
|
||||
|
||||
-- get(inst, name) -> the property's value (not the Value table), nil when absent
|
||||
function Rbx.get(inst: Instance, name: string): any
|
||||
local v = inst.properties[name]
|
||||
return if v then v.value else nil
|
||||
end
|
||||
|
||||
-- descendants(treeOrInstance) -> iterator over (instance, depth) in depth-first order (roots / the instance's children
|
||||
-- at depth 1)
|
||||
function Rbx.descendants(root: any): () -> (Instance?, number?)
|
||||
local stack: { any } = {}
|
||||
local list = if root.kind == "rbxtree" then root.roots else root.children
|
||||
for i = #list, 1, -1 do
|
||||
table.insert(stack, { list[i], 1 })
|
||||
end
|
||||
return function(): (Instance?, number?)
|
||||
local top = table.remove(stack)
|
||||
if not top then
|
||||
return nil, nil
|
||||
end
|
||||
local inst, depth = top[1], top[2]
|
||||
for i = #inst.children, 1, -1 do
|
||||
table.insert(stack, { inst.children[i], depth + 1 })
|
||||
end
|
||||
return inst, depth
|
||||
end
|
||||
end
|
||||
|
||||
-- list(tree) -> every instance, depth first
|
||||
function Rbx.list(tree: any): { Instance }
|
||||
local out = {}
|
||||
for inst in Rbx.descendants(tree) do
|
||||
table.insert(out, inst :: Instance)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- find(treeOrInstance, path) -> the instance at a "/"-separated path of names ("Workspace/Baseplate"), or nil
|
||||
function Rbx.find(root: any, path: string): Instance?
|
||||
local cur: any = root
|
||||
for part in string.gmatch(path, "[^/]+") do
|
||||
local list = if cur.kind == "rbxtree" then cur.roots else cur.children
|
||||
local found = nil
|
||||
for _, c in list do
|
||||
if c.name == part then
|
||||
found = c
|
||||
break
|
||||
end
|
||||
end
|
||||
if not found then
|
||||
return nil
|
||||
end
|
||||
cur = found
|
||||
end
|
||||
return if cur.kind == "rbxtree" then nil else cur
|
||||
end
|
||||
|
||||
-- fullName(inst) -> "Workspace.Model.Part" (names joined up to the root)
|
||||
function Rbx.fullName(inst: Instance): string
|
||||
local parts = {}
|
||||
local cur: Instance? = inst
|
||||
while cur do
|
||||
table.insert(parts, 1, cur.name)
|
||||
cur = cur.parent
|
||||
end
|
||||
return table.concat(parts, ".")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ CFrame rotation ids
|
||||
-- The binary format stores axis-aligned rotations as one byte: id = 6 * n(RightVector) + n(UpVector) + 1, where n is
|
||||
-- the NormalId of a unit axis (+X 0, +Y 1, +Z 2, -X 3, -Y 4, -Z 5) and the third column is their cross product.
|
||||
local AXES = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }, { -1, 0, 0 }, { 0, -1, 0 }, { 0, 0, -1 } }
|
||||
|
||||
-- the rotation of an id as { r00 .. r22 } (row major), or nil for an id that is not a rotation
|
||||
local ROTATIONS: { [number]: { number } } = {}
|
||||
for a = 0, 5 do
|
||||
for b = 0, 5 do
|
||||
if a % 3 ~= b % 3 then
|
||||
local r, u = AXES[a + 1], AXES[b + 1]
|
||||
local k = { r[2] * u[3] - r[3] * u[2], r[3] * u[1] - r[1] * u[3], r[1] * u[2] - r[2] * u[1] }
|
||||
-- columns: right, up, back (= right x up)
|
||||
ROTATIONS[6 * a + b + 1] = { r[1], u[1], k[1] + 0, r[2], u[2], k[2] + 0, r[3], u[3], k[3] + 0 }
|
||||
end
|
||||
end
|
||||
end
|
||||
Rbx.ROTATIONS = ROTATIONS
|
||||
|
||||
local function axisIndex(x: number, y: number, z: number): number?
|
||||
for i, a in AXES do
|
||||
if a[1] == x and a[2] == y and a[3] == z then
|
||||
return i - 1
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- rotationId(cf) -> the id of the CFrame's rotation (cf = { x, y, z, r00 .. r22 }), or 0 when it is not axis aligned
|
||||
function Rbx.rotationId(cf: { number }): number
|
||||
local a = axisIndex(cf[4], cf[7], cf[10])
|
||||
local b = axisIndex(cf[5], cf[8], cf[11])
|
||||
if not a or not b then
|
||||
return 0
|
||||
end
|
||||
local id = 6 * a + b + 1
|
||||
local rot = ROTATIONS[id]
|
||||
if not rot or rot[3] ~= cf[6] or rot[6] ~= cf[9] or rot[9] ~= cf[12] then
|
||||
return 0
|
||||
end
|
||||
return id
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ values
|
||||
-- binary type ids (rbx-dom docs/binary.md) by type name, and back
|
||||
Rbx.TYPE_IDS = table.freeze({
|
||||
String = 0x01,
|
||||
BinaryString = 0x01,
|
||||
ProtectedString = 0x01,
|
||||
ContentId = 0x01,
|
||||
Bool = 0x02,
|
||||
Int32 = 0x03,
|
||||
Float32 = 0x04,
|
||||
Float64 = 0x05,
|
||||
UDim = 0x06,
|
||||
UDim2 = 0x07,
|
||||
Ray = 0x08,
|
||||
Faces = 0x09,
|
||||
Axes = 0x0A,
|
||||
BrickColor = 0x0B,
|
||||
Color3 = 0x0C,
|
||||
Vector2 = 0x0D,
|
||||
Vector3 = 0x0E,
|
||||
Vector2int16 = 0x0F,
|
||||
CFrame = 0x10,
|
||||
Enum = 0x12,
|
||||
Ref = 0x13,
|
||||
Vector3int16 = 0x14,
|
||||
NumberSequence = 0x15,
|
||||
ColorSequence = 0x16,
|
||||
NumberRange = 0x17,
|
||||
Rect = 0x18,
|
||||
PhysicalProperties = 0x19,
|
||||
Color3uint8 = 0x1A,
|
||||
Int64 = 0x1B,
|
||||
SharedString = 0x1C,
|
||||
Bytecode = 0x1D,
|
||||
OptionalCFrame = 0x1E,
|
||||
UniqueId = 0x1F,
|
||||
Font = 0x20,
|
||||
SecurityCapabilities = 0x21,
|
||||
Content = 0x22,
|
||||
} :: { [string]: number })
|
||||
local NAMES: { [number]: string } = {}
|
||||
for name, id in Rbx.TYPE_IDS do
|
||||
if NAMES[id] == nil or name == "String" then
|
||||
NAMES[id] = name
|
||||
end
|
||||
end
|
||||
Rbx.TYPE_NAMES = table.freeze(NAMES)
|
||||
|
||||
-- the value a binary writer uses for an instance without the property (zero / empty / identity; BrickColor 194, the
|
||||
-- Medium stone grey Roblox defaults to; sequences of two keypoints at times 0 and 1)
|
||||
local IDENTITY_CF = { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 }
|
||||
function Rbx.default(typ: string): any
|
||||
if typ == "String" or typ == "BinaryString" or typ == "ProtectedString" or typ == "ContentId" or typ == "Bytecode" or typ == "SharedString" then
|
||||
return ""
|
||||
elseif typ == "Bool" then
|
||||
return false
|
||||
elseif typ == "BrickColor" then
|
||||
return 194
|
||||
elseif typ == "UDim" or typ == "NumberRange" or typ == "Vector2" or typ == "Vector2int16" then
|
||||
return { 0, 0 }
|
||||
elseif typ == "UDim2" or typ == "Rect" then
|
||||
return { 0, 0, 0, 0 }
|
||||
elseif typ == "Vector3" or typ == "Vector3int16" or typ == "Color3" or typ == "Color3uint8" then
|
||||
return { 0, 0, 0 }
|
||||
elseif typ == "Ray" then
|
||||
return { 0, 0, 0, 0, 0, 0 }
|
||||
elseif typ == "CFrame" then
|
||||
return table.clone(IDENTITY_CF)
|
||||
elseif typ == "NumberSequence" then
|
||||
return { { 0, 0, 0 }, { 1, 0, 0 } }
|
||||
elseif typ == "ColorSequence" then
|
||||
return { { 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 0 } }
|
||||
elseif typ == "UniqueId" then
|
||||
return string.rep("0", 32)
|
||||
elseif typ == "Font" then
|
||||
return { family = "rbxasset://fonts/families/SourceSansPro.json", weight = 400, style = "Normal" }
|
||||
elseif typ == "PhysicalProperties" or typ == "Ref" or typ == "OptionalCFrame" or typ == "Content" then
|
||||
return nil
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- STRINGS: the string-valued types (one binary type, several XML tags)
|
||||
Rbx.STRINGS = table.freeze({ String = true, BinaryString = true, ProtectedString = true, ContentId = true, Bytecode = true } :: { [string]: boolean })
|
||||
|
||||
return Rbx
|
||||
@@ -0,0 +1,274 @@
|
||||
--!strict
|
||||
-- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each
|
||||
-- format only parses its file: vertex-animation frames as morph targets plus "weights" animations, joint hierarchies
|
||||
-- as Scene nodes plus a Skin (inverse bind matrices), per-vertex joint influences as JOINTS_0 / WEIGHTS_0, and
|
||||
-- keyframed joint TRS tracks as animation channels. New in rosetta.
|
||||
--
|
||||
-- Rig.morph(prim, frames) -- frames[k] = f32 x3 positions: targets[k] = frame k - base
|
||||
-- Rig.morphAnimation(scene, node, #frames, { { name = "run", first = 41, last = 46, fps = 10 } }, "LINEAR")
|
||||
-- local nodes, skin = Rig.skeleton(scene, joints, "world") -- joints = { { name, parent (0 = root), t, r, s? } }
|
||||
-- prim.attributes.JOINTS_0, prim.attributes.WEIGHTS_0 = Rig.influences(lists) -- lists[v] = { j1, w1, j2, w2, ... }
|
||||
-- Rig.animation(scene, "idle", nodes, times, tracks) -- tracks[j] = { translation = {...}, rotation = {...} }
|
||||
--
|
||||
-- Frames, joints and tracks come from parsed files: the helpers check every count they rely on and never throw.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Mat4 = require("@rosetta/codecs/model/Mat4")
|
||||
|
||||
local Rig = {}
|
||||
|
||||
local Scene = Types.Scene
|
||||
local readf32, writef32, writeu16 = buffer.readf32, buffer.writef32, buffer.writeu16
|
||||
|
||||
export type Joint = {
|
||||
name: string?,
|
||||
parent: number, -- 1-based index into the joint list, 0 for a root (parents come before their children)
|
||||
translation: { number },
|
||||
rotation: { number }, -- quaternion x, y, z, w
|
||||
scale: { number }?,
|
||||
}
|
||||
export type Range = { name: string?, first: number, last: number, fps: number? } -- frames first..last (1-based)
|
||||
export type Track = { translation: { number }?, rotation: { number }?, scale: { number }? } -- flat, one key per time
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ morph targets
|
||||
-- morph(prim, frames, normals?, base?) -> (): prim.targets[k] = { POSITION = frames[k] - base positions } (and NORMAL
|
||||
-- deltas when normals[k] is given), base = prim.attributes.POSITION (and NORMAL). Every frame buffer must hold as
|
||||
-- many f32 x3 as the base; shorter ones are skipped (false is returned).
|
||||
function Rig.morph(prim: Types.Primitive, frames: { buffer }, normals: { buffer }?): boolean
|
||||
local pos = prim.attributes.POSITION
|
||||
if not pos or pos.type ~= "f32" or pos.components ~= 3 then
|
||||
return false
|
||||
end
|
||||
local nrm = prim.attributes.NORMAL
|
||||
local n = pos.count * 3
|
||||
local targets: { { [string]: Types.Accessor } } = {}
|
||||
local ok = true
|
||||
for k, f in frames do
|
||||
if buffer.len(f) < n * 4 then
|
||||
ok = false
|
||||
break
|
||||
end
|
||||
local t: { [string]: Types.Accessor } = {}
|
||||
local d = buffer.create(n * 4)
|
||||
local base = pos.data
|
||||
for i = 0, n - 1 do
|
||||
writef32(d, i * 4, readf32(f, i * 4) - readf32(base, i * 4))
|
||||
end
|
||||
t.POSITION = Scene.accessor(d, "f32", 3, pos.count)
|
||||
local fn = normals and normals[k]
|
||||
if nrm and fn and nrm.type == "f32" and buffer.len(fn) >= n * 4 then
|
||||
local dn = buffer.create(n * 4)
|
||||
for i = 0, n - 1 do
|
||||
writef32(dn, i * 4, readf32(fn, i * 4) - readf32(nrm.data, i * 4))
|
||||
end
|
||||
t.NORMAL = Scene.accessor(dn, "f32", 3, pos.count)
|
||||
end
|
||||
targets[k] = t
|
||||
end
|
||||
if ok then
|
||||
prim.targets = targets
|
||||
end
|
||||
return ok
|
||||
end
|
||||
|
||||
-- morphAnimation(scene, node, targets, ranges, interpolation?) -> (): one animation per range, a "weights" channel on
|
||||
-- scene.nodes[node] whose key k (at (k - first) / fps seconds) sets target k to 1 and the others to 0 (LINEAR
|
||||
-- blends neighbouring frames, as the games do; default "LINEAR"). Ranges out of 1..targets are clamped / skipped.
|
||||
function Rig.morphAnimation(scene: Types.Scene, node: number, targets: number, ranges: { Range }, interpolation: string?)
|
||||
for _, rg in ranges do
|
||||
local first, last = math.max(1, math.floor(rg.first)), math.min(targets, math.floor(rg.last))
|
||||
if last >= first then
|
||||
local keys = last - first + 1
|
||||
local fps = if rg.fps and rg.fps > 0 then rg.fps else 10
|
||||
local times = buffer.create(keys * 4)
|
||||
local weights = buffer.create(keys * targets * 4)
|
||||
for k = 0, keys - 1 do
|
||||
writef32(times, k * 4, k / fps)
|
||||
writef32(weights, (k * targets + first - 1 + k) * 4, 1)
|
||||
end
|
||||
table.insert(scene.animations, {
|
||||
name = rg.name,
|
||||
channels = {
|
||||
{
|
||||
node = node,
|
||||
path = "weights" :: any,
|
||||
input = Scene.accessor(times, "f32", 1, keys),
|
||||
output = Scene.accessor(weights, "f32", 1, keys * targets),
|
||||
interpolation = (if interpolation == "STEP" then "STEP" else "LINEAR") :: any,
|
||||
},
|
||||
},
|
||||
})
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- normals(pos, count, indices) -> f32 x3 buffer: smooth vertex normals (area-weighted face normals, normalised) of a
|
||||
-- triangle list (indices: 0-based, three per triangle; out-of-range triangles are skipped). For formats whose stored
|
||||
-- normals cannot be used (Quake's precomputed normal table is not redistributable here).
|
||||
function Rig.normals(pos: buffer, count: number, indices: { number }): buffer
|
||||
local out = buffer.create(count * 12)
|
||||
local acc = table.create(count * 3, 0)
|
||||
for k = 1, #indices - 2, 3 do
|
||||
local a, b, c = indices[k], indices[k + 1], indices[k + 2]
|
||||
if a >= 0 and b >= 0 and c >= 0 and a < count and b < count and c < count then
|
||||
local ax, ay, az = readf32(pos, a * 12), readf32(pos, a * 12 + 4), readf32(pos, a * 12 + 8)
|
||||
local ux, uy, uz = readf32(pos, b * 12) - ax, readf32(pos, b * 12 + 4) - ay, readf32(pos, b * 12 + 8) - az
|
||||
local vx, vy, vz = readf32(pos, c * 12) - ax, readf32(pos, c * 12 + 4) - ay, readf32(pos, c * 12 + 8) - az
|
||||
local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
|
||||
for _, v in { a, b, c } do
|
||||
acc[v * 3 + 1] += nx
|
||||
acc[v * 3 + 2] += ny
|
||||
acc[v * 3 + 3] += nz
|
||||
end
|
||||
end
|
||||
end
|
||||
for v = 0, count - 1 do
|
||||
local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3]
|
||||
local l = math.sqrt(x * x + y * y + z * z)
|
||||
if l > 0 then
|
||||
x, y, z = x / l, y / l, z / l
|
||||
end
|
||||
writef32(out, v * 12, x)
|
||||
writef32(out, v * 12 + 4, y)
|
||||
writef32(out, v * 12 + 8, z)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ skeletons
|
||||
local function trs(j: Joint): { number }
|
||||
return Mat4.compose(j.translation, j.rotation, j.scale)
|
||||
end
|
||||
|
||||
-- angles(x, y, z) -> quaternion { x, y, z, w } of the Euler angles in radians applied x first, then y, then z
|
||||
-- (R = Rz * Ry * Rx: the Quake / Half-Life "AngleQuaternion" convention of MDL bones and SMD skeletons)
|
||||
function Rig.angles(x: number, y: number, z: number): { number }
|
||||
local sy, cy = math.sin(z / 2), math.cos(z / 2)
|
||||
local sp, cp = math.sin(y / 2), math.cos(y / 2)
|
||||
local sr, cr = math.sin(x / 2), math.cos(x / 2)
|
||||
return { sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy }
|
||||
end
|
||||
|
||||
-- skeleton(scene, joints, space, root?) -> (joint node indices, skin index, world matrices): one node per joint (TRS relative to its
|
||||
-- parent), parented as listed, roots added to scene.roots (or as children of node `root`); a Skin with the inverse
|
||||
-- bind matrices. space "local": joint TRS are relative to the parent (SMD, MDL); "world": in model space (MD5's
|
||||
-- bind pose), converted to local here. A parent index that does not come earlier makes the joint a root.
|
||||
function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "world", root: number?): ({ number }, number, { { number } })
|
||||
local n = #joints
|
||||
local world: { { number } } = {}
|
||||
local nodes: { number } = {}
|
||||
for i, j in joints do
|
||||
local p = if j.parent >= 1 and j.parent < i then j.parent else 0
|
||||
local m = trs(j)
|
||||
local lt, lr, ls = j.translation, j.rotation, j.scale
|
||||
if space == "world" then
|
||||
world[i] = m
|
||||
if p > 0 then
|
||||
local inv = Mat4.inverse(world[p])
|
||||
if inv then
|
||||
local t, r, s = Mat4.decompose(Mat4.mul(inv, m))
|
||||
lt, lr, ls = t, r, s
|
||||
end
|
||||
end
|
||||
else
|
||||
world[i] = if p > 0 then Mat4.mul(world[p], m) else m
|
||||
end
|
||||
local node: Types.Node = { name = j.name, children = {}, translation = table.clone(lt), rotation = table.clone(lr), scale = if ls then table.clone(ls) else nil }
|
||||
table.insert(scene.nodes, node)
|
||||
local idx = #scene.nodes
|
||||
nodes[i] = idx
|
||||
if p > 0 then
|
||||
table.insert(scene.nodes[nodes[p]].children, idx)
|
||||
elseif root and scene.nodes[root] then
|
||||
table.insert(scene.nodes[root].children, idx)
|
||||
else
|
||||
table.insert(scene.roots, idx)
|
||||
end
|
||||
end
|
||||
local ibm = buffer.create(n * 64)
|
||||
for i = 1, n do
|
||||
local inv = Mat4.inverseFull(world[i]) or Mat4.identity()
|
||||
for k = 1, 16 do
|
||||
writef32(ibm, ((i - 1) * 16 + k - 1) * 4, inv[k])
|
||||
end
|
||||
end
|
||||
local acc = Scene.accessor(ibm, "f32", 16, n)
|
||||
acc.matrix = true
|
||||
table.insert(scene.skins, { joints = nodes, inverseBindMatrices = acc, skeleton = if n > 0 then nodes[1] else nil })
|
||||
return nodes, #scene.skins, world
|
||||
end
|
||||
|
||||
-- influences(lists) -> JOINTS_0 (u16 x4), WEIGHTS_0 (f32 x4): lists[v] = { joint, weight, joint, weight, ... } with
|
||||
-- 0-based joint indices (into the skin's joints; a joint listed twice adds up); the four largest weights are kept
|
||||
-- and normalised to sum 1.
|
||||
function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor)
|
||||
local n = #lists
|
||||
local jb, wb = buffer.create(n * 8), buffer.create(n * 16)
|
||||
for v, l in lists do
|
||||
local pairs_: { { number } } = {}
|
||||
local at: { [number]: { number } } = {}
|
||||
for k = 1, #l - 1, 2 do
|
||||
if l[k + 1] > 0 then
|
||||
local same = at[l[k]]
|
||||
if same then
|
||||
same[2] += l[k + 1] -- the same joint twice: one influence
|
||||
else
|
||||
local e = { l[k], l[k + 1] }
|
||||
at[l[k]] = e
|
||||
table.insert(pairs_, e)
|
||||
end
|
||||
end
|
||||
end
|
||||
table.sort(pairs_, function(a: { number }, b: { number }): boolean
|
||||
return a[2] > b[2]
|
||||
end)
|
||||
local sum = 0
|
||||
for k = 1, math.min(4, #pairs_) do
|
||||
sum += pairs_[k][2]
|
||||
end
|
||||
for k = 1, math.min(4, #pairs_) do
|
||||
writeu16(jb, ((v - 1) * 4 + k - 1) * 2, math.clamp(pairs_[k][1], 0, 65535))
|
||||
writef32(wb, ((v - 1) * 4 + k - 1) * 4, pairs_[k][2] / sum)
|
||||
end
|
||||
end
|
||||
return Scene.accessor(jb, "u16", 4, n), Scene.accessor(wb, "f32", 4, n)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ animations
|
||||
local function floats(t: { number }, count: number, comps: number): Types.Accessor?
|
||||
if #t < count * comps then
|
||||
return nil
|
||||
end
|
||||
local b = buffer.create(count * comps * 4)
|
||||
for i = 1, count * comps do
|
||||
writef32(b, (i - 1) * 4, t[i])
|
||||
end
|
||||
return Scene.accessor(b, "f32", comps, count)
|
||||
end
|
||||
|
||||
-- animation(scene, name, nodes, times, tracks, interpolation?) -> the animation index: tracks[j] (j = index into
|
||||
-- nodes) holds flat translation (x3) / rotation (quaternion x4) / scale (x3) keys, one per time (seconds); tracks
|
||||
-- with too few keys are skipped. Default interpolation "LINEAR".
|
||||
function Rig.animation(scene: Types.Scene, name: string?, nodes: { number }, times: { number }, tracks: { [number]: Track }, interpolation: string?): number
|
||||
local count = #times
|
||||
local input = floats(times, count, 1)
|
||||
local channels: { Types.Channel } = {}
|
||||
local interp: any = if interpolation == "STEP" then "STEP" else "LINEAR"
|
||||
if input then
|
||||
for j, tr in tracks do
|
||||
local node = nodes[j]
|
||||
if node then
|
||||
for _, path in { "translation", "rotation", "scale" } do
|
||||
local keys = (tr :: any)[path]
|
||||
local acc = keys and floats(keys, count, if path == "rotation" then 4 else 3)
|
||||
if acc then
|
||||
table.insert(channels, { node = node, path = path :: any, input = input, output = acc, interpolation = interp })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
table.insert(scene.animations, { name = name, channels = channels })
|
||||
return #scene.animations
|
||||
end
|
||||
|
||||
return Rig
|
||||
@@ -0,0 +1,173 @@
|
||||
--!strict
|
||||
-- codecs/model/Sampler: evaluates Scene animation channels at any time (STEP, LINEAR with quaternion slerp for
|
||||
-- rotations, CUBICSPLINE Hermite splines as glTF 2.0 defines them; times before the first / after the last key hold
|
||||
-- the end values), and the node poses of an animation at a time, for writers of formats that store sampled frames
|
||||
-- (IQM, MD5, BVH, ...). New in rosetta.
|
||||
--
|
||||
-- local sample = Sampler.channel(ch) -- nil for an unreadable channel
|
||||
-- local v = sample(0.5) -- { x, y, z } / { x, y, z, w } / the morph weights
|
||||
-- local times = Sampler.times(anim) -- every key time of the animation, sorted, unique
|
||||
-- local pose = Sampler.pose(scene, anim, 0.5) -- pose[node] = { translation?, rotation?, scale?, weights? }
|
||||
--
|
||||
-- Never throws on bad data: unreadable channels are skipped.
|
||||
local Types = require("@rosetta/Types")
|
||||
|
||||
local Sampler = {}
|
||||
|
||||
export type Sample = (t: number) -> { number }
|
||||
export type Pose = { [number]: { [string]: { number } } }
|
||||
|
||||
local function normalize(q: { number }): { number }
|
||||
local l = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4])
|
||||
if l <= 0 then
|
||||
return { 0, 0, 0, 1 }
|
||||
end
|
||||
return { q[1] / l, q[2] / l, q[3] / l, q[4] / l }
|
||||
end
|
||||
|
||||
local function slerp(a: { number }, b: { number }, s: number): { number }
|
||||
local d = a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4]
|
||||
local bx, by, bz, bw = b[1], b[2], b[3], b[4]
|
||||
if d < 0 then
|
||||
d, bx, by, bz, bw = -d, -bx, -by, -bz, -bw
|
||||
end
|
||||
local wa, wb
|
||||
if d > 0.9995 then
|
||||
wa, wb = 1 - s, s
|
||||
else
|
||||
local th = math.acos(math.min(d, 1))
|
||||
local sn = math.sin(th)
|
||||
wa, wb = math.sin((1 - s) * th) / sn, math.sin(s * th) / sn
|
||||
end
|
||||
return normalize({ a[1] * wa + bx * wb, a[2] * wa + by * wb, a[3] * wa + bz * wb, a[4] * wa + bw * wb })
|
||||
end
|
||||
|
||||
-- channel(ch) -> sample(t) | nil
|
||||
function Sampler.channel(ch: Types.Channel): Sample?
|
||||
local inp, out = ch.input, ch.output
|
||||
if type(inp) ~= "table" or type(out) ~= "table" then
|
||||
return nil
|
||||
end
|
||||
local IN, OUT = Types.Scene.reader(inp), Types.Scene.reader(out)
|
||||
local n = inp.count
|
||||
if not IN or not OUT or n < 1 then
|
||||
return nil
|
||||
end
|
||||
local cubic = ch.interpolation == "CUBICSPLINE"
|
||||
local per = if cubic then 3 else 1
|
||||
local comps: number
|
||||
if ch.path == "weights" then
|
||||
comps = (out.count * out.components) // (n * per)
|
||||
else
|
||||
comps = if ch.path == "rotation" then 4 else 3
|
||||
end
|
||||
if comps < 1 or out.count * out.components < n * per * comps then
|
||||
return nil
|
||||
end
|
||||
local times = table.create(n) :: { number }
|
||||
for k = 1, n do
|
||||
times[k] = IN(k - 1, 0)
|
||||
end
|
||||
local oc = out.components
|
||||
-- element e (0-based, of comps values) of the flat output
|
||||
local function get(e: number): { number }
|
||||
local v = table.create(comps) :: { number }
|
||||
for c = 0, comps - 1 do
|
||||
local flat = e * comps + c
|
||||
v[c + 1] = OUT(flat // oc, flat % oc)
|
||||
end
|
||||
return v
|
||||
end
|
||||
local function value(k: number): { number } -- key k (1-based)
|
||||
return get(if cubic then (k - 1) * 3 + 1 else k - 1)
|
||||
end
|
||||
local rot = ch.path == "rotation"
|
||||
local step = ch.interpolation == "STEP"
|
||||
return function(t: number): { number }
|
||||
if t <= times[1] or n == 1 then
|
||||
return if rot then normalize(value(1)) else value(1)
|
||||
end
|
||||
if t >= times[n] then
|
||||
return if rot then normalize(value(n)) else value(n)
|
||||
end
|
||||
local lo, hi = 1, n
|
||||
while hi - lo > 1 do
|
||||
local mid = (lo + hi) // 2
|
||||
if times[mid] <= t then
|
||||
lo = mid
|
||||
else
|
||||
hi = mid
|
||||
end
|
||||
end
|
||||
local dt = times[hi] - times[lo]
|
||||
local s = if dt > 0 then (t - times[lo]) / dt else 0
|
||||
if step then
|
||||
return if rot then normalize(value(lo)) else value(lo)
|
||||
end
|
||||
if cubic then
|
||||
local p0, m0 = value(lo), get((lo - 1) * 3 + 2)
|
||||
local p1, m1 = value(hi), get((hi - 1) * 3)
|
||||
local s2, s3 = s * s, s * s * s
|
||||
local h00, h10, h01, h11 = 2 * s3 - 3 * s2 + 1, s3 - 2 * s2 + s, -2 * s3 + 3 * s2, s3 - s2
|
||||
local v = table.create(comps) :: { number }
|
||||
for c = 1, comps do
|
||||
v[c] = h00 * p0[c] + h10 * dt * m0[c] + h01 * p1[c] + h11 * dt * m1[c]
|
||||
end
|
||||
return if rot then normalize(v) else v
|
||||
end
|
||||
local a, b = value(lo), value(hi)
|
||||
if rot then
|
||||
return slerp(normalize(a), normalize(b), s)
|
||||
end
|
||||
local v = table.create(comps) :: { number }
|
||||
for c = 1, comps do
|
||||
v[c] = a[c] + (b[c] - a[c]) * s
|
||||
end
|
||||
return v
|
||||
end
|
||||
end
|
||||
|
||||
-- times(anim) -> every key time, sorted and unique
|
||||
function Sampler.times(anim: Types.Animation): { number }
|
||||
local seen: { [number]: boolean } = {}
|
||||
local out: { number } = {}
|
||||
for _, ch in anim.channels do
|
||||
local inp = ch.input
|
||||
local IN = type(inp) == "table" and Types.Scene.reader(inp)
|
||||
if IN then
|
||||
for k = 0, inp.count - 1 do
|
||||
local t = IN(k, 0)
|
||||
if not seen[t] and t == t then
|
||||
seen[t] = true
|
||||
table.insert(out, t)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
table.sort(out)
|
||||
return out
|
||||
end
|
||||
|
||||
-- pose(scene, anim, t, samplers?) -> pose[node] = { [path] = values } for the animated nodes. samplers: a cache table
|
||||
-- (reuse it across calls for the same animation)
|
||||
function Sampler.pose(_scene: Types.Scene, anim: Types.Animation, t: number, samplers: { [any]: any }?): Pose
|
||||
local cache: { [any]: any } = samplers or {}
|
||||
local pose: Pose = {}
|
||||
for _, ch in anim.channels do
|
||||
if cache[ch] == nil then
|
||||
cache[ch] = Sampler.channel(ch) or false
|
||||
end
|
||||
local s: Sample? = cache[ch] or nil
|
||||
if s then
|
||||
local p = pose[ch.node]
|
||||
if not p then
|
||||
p = {}
|
||||
pose[ch.node] = p
|
||||
end
|
||||
p[ch.path] = s(t)
|
||||
end
|
||||
end
|
||||
return pose
|
||||
end
|
||||
|
||||
return Sampler
|
||||
@@ -0,0 +1,590 @@
|
||||
--!strict
|
||||
-- codecs/model/Vrml/Build: the VRML97 / X3D node graph (codecs/model/Vrml/Parse, codecs/model/Vrml/Xml) to a Scene.
|
||||
-- Written from the specifications; no third-party code. Grouping nodes (Group, Transform with center / scaleOrientation,
|
||||
-- Anchor, Billboard, Collision, StaticGroup, Switch whichChoice, LOD first level, CAD and HAnim groups, Inline through
|
||||
-- the fetch callback) become nodes; a Transform is one TRS node (translation T + C, rotation R * SR, scale S) and, when
|
||||
-- it has a center or scale orientation, an inner node (rotation SR^-1, translation SR^-1 * -C) holding the children.
|
||||
-- Shapes become meshes (shared by USE), Appearance / Material / PhysicalMaterial / UnlitMaterial / TwoSidedMaterial
|
||||
-- materials (Phong terms in material.extras.vrml; solid FALSE -> doubleSided), ImageTexture / MovieTexture
|
||||
-- (uri, data through fetch, repeatS / repeatT), PixelTexture (texture.image), TextureTransform (KHR transform:
|
||||
-- translation / scale / rotation; the center in extras); Viewpoint / OrthoViewpoint -> cameras, DirectionalLight /
|
||||
-- PointLight / SpotLight -> lights; ROUTEs from a TimeSensor through Position- / OrientationInterpolators to a
|
||||
-- Transform's translation / rotation / scale -> animations (key times x cycleInterval). Other nodes are counted in
|
||||
-- meta.source.skipped. Never throws: bad data returns nil, message.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Mat4 = require("@rosetta/codecs/model/Mat4")
|
||||
local Fields = require("@rosetta/codecs/model/Vrml/Fields")
|
||||
local Geometry = require("@rosetta/codecs/model/Vrml/Geometry")
|
||||
|
||||
local Build = {}
|
||||
|
||||
local S = Types.Scene
|
||||
local nums, num, vec, bool, str, strs, node, nodes = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.str, Fields.strs, Fields.node, Fields.nodes
|
||||
local deg = math.deg
|
||||
|
||||
export type Options = Geometry.Options & {
|
||||
fetch: ((uri: string) -> buffer?)?, -- reads textures and Inline files
|
||||
load: ((data: buffer) -> (any, string?))?, -- an Inline file's bytes -> its graph
|
||||
format: string?, -- meta.source.format
|
||||
maxInline: number?, -- Inline nesting (default 8)
|
||||
}
|
||||
|
||||
local GROUP = { Group = true, Anchor = true, Billboard = true, Collision = true, StaticGroup = true, CADAssembly = true, CADLayer = true, LayerSet = true, Layer = true, HAnimSegment = true, HAnimSite = true, LOD = true, Switch = true }
|
||||
local TRANSFORM = { Transform = true, CADPart = true, HAnimHumanoid = true, HAnimJoint = true }
|
||||
local CHILDREN = { "children", "skeleton", "segments", "sites", "layers" }
|
||||
-- nodes with nothing to show (not counted as skipped)
|
||||
local QUIET = {
|
||||
WorldInfo = true, NavigationInfo = true, Background = true, TextureBackground = true, Fog = true, TimeSensor = true,
|
||||
PositionInterpolator = true, OrientationInterpolator = true, ScalarInterpolator = true, ColorInterpolator = true,
|
||||
CoordinateInterpolator = true, NormalInterpolator = true, TouchSensor = true, ProximitySensor = true,
|
||||
VisibilitySensor = true, PlaneSensor = true, CylinderSensor = true, SphereSensor = true, Script = true, Sound = true,
|
||||
AudioClip = true, MetadataString = true, MetadataFloat = true, MetadataInteger = true, MetadataDouble = true,
|
||||
MetadataSet = true, MetadataBoolean = true, BooleanFilter = true, BooleanToggle = true, BooleanTrigger = true,
|
||||
BooleanSequencer = true, IntegerSequencer = true, IntegerTrigger = true, TimeTrigger = true, KeySensor = true,
|
||||
StringSensor = true, LoadSensor = true,
|
||||
}
|
||||
local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", gif = "image/gif", bmp = "image/bmp", webp = "image/webp", ktx2 = "image/ktx2", dds = "image/vnd-ms.dds", tga = "image/x-tga" }
|
||||
|
||||
local function quat(r: { number }): { number }
|
||||
return Mat4.axisAngle(r[1], r[2], r[3], deg(r[4]))
|
||||
end
|
||||
local function qmul(a: { number }, b: { number }): { number }
|
||||
return {
|
||||
a[4] * b[1] + a[1] * b[4] + a[2] * b[3] - a[3] * b[2],
|
||||
a[4] * b[2] - a[1] * b[3] + a[2] * b[4] + a[3] * b[1],
|
||||
a[4] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[4],
|
||||
a[4] * b[4] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3],
|
||||
}
|
||||
end
|
||||
local function qrot(q: { number }, v: { number }): { number }
|
||||
local m = Mat4.fromQuat(q)
|
||||
local x, y, z = Mat4.point(m, v[1], v[2], v[3])
|
||||
return { x, y, z }
|
||||
end
|
||||
local function isZero(v: { number }): boolean
|
||||
return v[1] == 0 and v[2] == 0 and v[3] == 0
|
||||
end
|
||||
local function isIdentityQ(q: { number }): boolean
|
||||
return q[1] == 0 and q[2] == 0 and q[3] == 0
|
||||
end
|
||||
-- the rotation taking unit vector a onto b
|
||||
local function between(a: { number }, b: { number }): { number }
|
||||
local l = math.sqrt(b[1] * b[1] + b[2] * b[2] + b[3] * b[3])
|
||||
if l < 1e-12 then
|
||||
return { 0, 0, 0, 1 }
|
||||
end
|
||||
local bx, by, bz = b[1] / l, b[2] / l, b[3] / l
|
||||
local d = a[1] * bx + a[2] * by + a[3] * bz
|
||||
if d < -0.999999 then
|
||||
-- opposite: half a turn about any perpendicular axis
|
||||
return if math.abs(a[1]) < 0.9 then { 0, a[3], -a[2], 0 } else { -a[3], 0, a[1], 0 }
|
||||
end
|
||||
local cx, cy, cz = a[2] * bz - a[3] * by, a[3] * bx - a[1] * bz, a[1] * by - a[2] * bx
|
||||
local w = 1 + d
|
||||
local n = math.sqrt(cx * cx + cy * cy + cz * cz + w * w)
|
||||
return { cx / n, cy / n, cz / n, w / n }
|
||||
end
|
||||
|
||||
type Ctx = {
|
||||
scene: Types.Scene,
|
||||
opts: Options,
|
||||
meshes: { [any]: any },
|
||||
materials: { [any]: any },
|
||||
textures: { [any]: number },
|
||||
instances: { [any]: { { node: number, center: { number }, so: { number } } } },
|
||||
skipped: { [string]: number },
|
||||
depth: number,
|
||||
inline: number,
|
||||
failure: string?,
|
||||
}
|
||||
|
||||
local function addNode(ctx: Ctx, n: Types.Node, parent: number?): number
|
||||
local nodes_ = ctx.scene.nodes
|
||||
table.insert(nodes_, n)
|
||||
local i = #nodes_
|
||||
if parent then
|
||||
table.insert(nodes_[parent].children, i)
|
||||
else
|
||||
table.insert(ctx.scene.roots, i)
|
||||
end
|
||||
return i
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ materials
|
||||
local function texture(ctx: Ctx, t: any): number?
|
||||
if not t then
|
||||
return nil
|
||||
end
|
||||
if t.type == "MultiTexture" then
|
||||
return texture(ctx, nodes(t, "texture")[1])
|
||||
end
|
||||
local cached = ctx.textures[t]
|
||||
if cached then
|
||||
return cached
|
||||
end
|
||||
local tex: Types.Texture = { name = t.def }
|
||||
if t.type == "ImageTexture" or t.type == "MovieTexture" then
|
||||
local urls = strs(t, "url")
|
||||
local fetch = ctx.opts.fetch
|
||||
for _, u in urls do
|
||||
local clean = string.match(u, "^([^#?]*)") or u
|
||||
if not tex.uri and not string.find(clean, "^%a[%w+.-]*://") then
|
||||
tex.uri = clean
|
||||
end
|
||||
local data = fetch and fetch(clean)
|
||||
if data then
|
||||
tex.uri, tex.data = clean, data
|
||||
break
|
||||
end
|
||||
end
|
||||
tex.uri = tex.uri or urls[1]
|
||||
local ext = tex.uri and string.match(tex.uri, "%.(%w+)$")
|
||||
tex.mime = if ext then MIME[string.lower(ext)] else nil
|
||||
elseif t.type == "PixelTexture" then
|
||||
-- SFImage: width height components pixels (0xRRGGBBAA style integers, MSB first)
|
||||
local v = nums(t, "image") or {}
|
||||
local w, h, c = math.floor(v[1] or 0), math.floor(v[2] or 0), math.floor(v[3] or 0)
|
||||
if w > 0 and h > 0 and c >= 1 and c <= 4 and w * h <= 2 ^ 24 and #v >= 3 + w * h then
|
||||
local img = Types.Image.new(w, h)
|
||||
for i = 0, w * h - 1 do
|
||||
local px = math.floor(v[4 + i]) % 2 ^ (8 * c)
|
||||
local b = table.create(4, 0)
|
||||
for k = c, 1, -1 do
|
||||
b[k] = px % 256
|
||||
px //= 256
|
||||
end
|
||||
local r, g, bl, a
|
||||
if c <= 2 then
|
||||
r, g, bl, a = b[1], b[1], b[1], if c == 2 then b[2] else 255
|
||||
else
|
||||
r, g, bl, a = b[1], b[2], b[3], if c == 4 then b[4] else 255
|
||||
end
|
||||
-- the image's first row is the bottom one
|
||||
local row = h - 1 - i // w
|
||||
local o = (row * w + i % w) * 4
|
||||
buffer.writeu8(img.pixels, o, r)
|
||||
buffer.writeu8(img.pixels, o + 1, g)
|
||||
buffer.writeu8(img.pixels, o + 2, bl)
|
||||
buffer.writeu8(img.pixels, o + 3, a)
|
||||
end
|
||||
tex.image = img
|
||||
end
|
||||
else
|
||||
ctx.skipped[t.type] = (ctx.skipped[t.type] or 0) + 1
|
||||
return nil
|
||||
end
|
||||
local rs, rt = bool(t, "repeatS", true), bool(t, "repeatT", true)
|
||||
if not rs or not rt then
|
||||
tex.sampler = { wrapS = if rs then "repeat" else "clamp", wrapT = if rt then "repeat" else "clamp" }
|
||||
end
|
||||
table.insert(ctx.scene.textures, tex)
|
||||
ctx.textures[t] = #ctx.scene.textures
|
||||
return #ctx.scene.textures
|
||||
end
|
||||
|
||||
local function textureRef(ctx: Ctx, t: any, xf: any): Types.TextureRef?
|
||||
local i = texture(ctx, t)
|
||||
if not i then
|
||||
return nil
|
||||
end
|
||||
local ref: Types.TextureRef = { texture = i }
|
||||
if xf and xf.type == "TextureTransform" then
|
||||
local tr, sc, rot = vec(xf, "translation", { 0, 0 }), vec(xf, "scale", { 1, 1 }), num(xf, "rotation", 0)
|
||||
if tr[1] ~= 0 or tr[2] ~= 0 or sc[1] ~= 1 or sc[2] ~= 1 or rot ~= 0 then
|
||||
ref.transform = { offset = tr, scale = sc, rotation = rot }
|
||||
end
|
||||
end
|
||||
return ref
|
||||
end
|
||||
|
||||
local function material(ctx: Ctx, app: any, solid: boolean): number?
|
||||
if not app and solid then
|
||||
return nil
|
||||
end
|
||||
local key = app or "default"
|
||||
local cache = ctx.materials[key]
|
||||
if type(cache) ~= "table" then
|
||||
cache = {}
|
||||
ctx.materials[key] = cache
|
||||
end
|
||||
local hit = (cache :: any)[solid]
|
||||
if hit then
|
||||
return hit
|
||||
end
|
||||
local m = S.material(app and app.def)
|
||||
m.metallic = 0
|
||||
local x: { [string]: any } = {}
|
||||
local mat = app and node(app, "material")
|
||||
local tex = app and node(app, "texture")
|
||||
local xf = app and node(app, "textureTransform")
|
||||
if mat and mat.type == "TwoSidedMaterial" then
|
||||
m.doubleSided = true
|
||||
x.twoSided = true
|
||||
end
|
||||
if mat and (mat.type == "Material" or mat.type == "TwoSidedMaterial") then
|
||||
local d, e, sp = vec(mat, "diffuseColor", { 0.8, 0.8, 0.8 }), vec(mat, "emissiveColor", { 0, 0, 0 }), vec(mat, "specularColor", { 0, 0, 0 })
|
||||
local sh, tr, amb = num(mat, "shininess", 0.2), num(mat, "transparency", 0), num(mat, "ambientIntensity", 0.2)
|
||||
m.name = mat.def or m.name
|
||||
m.baseColor = { d[1], d[2], d[3], 1 - tr }
|
||||
m.emissive = e
|
||||
m.roughness = math.clamp(math.sqrt(2 / (math.max(sh, 0) * 128 + 2)), 0, 1)
|
||||
x.diffuseColor, x.emissiveColor, x.specularColor, x.shininess, x.transparency, x.ambientIntensity = d, e, sp, sh, tr, amb
|
||||
if tr > 0 then
|
||||
m.alphaMode = "blend"
|
||||
end
|
||||
-- X3D 4 texture fields
|
||||
local dt = node(mat, "diffuseTexture")
|
||||
if dt then
|
||||
m.baseColorTexture = textureRef(ctx, dt, nil)
|
||||
end
|
||||
local nt = node(mat, "normalTexture")
|
||||
if nt then
|
||||
m.normalTexture = textureRef(ctx, nt, nil)
|
||||
end
|
||||
elseif mat and mat.type == "PhysicalMaterial" then
|
||||
local b, e = vec(mat, "baseColor", { 1, 1, 1 }), vec(mat, "emissiveColor", { 0, 0, 0 })
|
||||
local tr = num(mat, "transparency", 0)
|
||||
m.name = mat.def or m.name
|
||||
m.baseColor = { b[1], b[2], b[3], 1 - tr }
|
||||
m.emissive, m.metallic, m.roughness = e, num(mat, "metallic", 1), num(mat, "roughness", 1)
|
||||
if tr > 0 then
|
||||
m.alphaMode = "blend"
|
||||
end
|
||||
local slots: { [string]: string } = { baseTexture = "baseColorTexture", metallicRoughnessTexture = "metallicRoughnessTexture", normalTexture = "normalTexture", occlusionTexture = "occlusionTexture", emissiveTexture = "emissiveTexture" }
|
||||
for field, slot in slots do
|
||||
local t = node(mat, field)
|
||||
if t then
|
||||
(m :: any)[slot] = textureRef(ctx, t, nil)
|
||||
end
|
||||
end
|
||||
elseif mat and mat.type == "UnlitMaterial" then
|
||||
local e = vec(mat, "emissiveColor", { 1, 1, 1 })
|
||||
m.name = mat.def or m.name
|
||||
m.baseColor = { e[1], e[2], e[3], 1 - num(mat, "transparency", 0) }
|
||||
m.extensions = { KHR_materials_unlit = {} }
|
||||
else
|
||||
-- no material: unlit white (the specifications' default)
|
||||
m.extensions = { KHR_materials_unlit = {} }
|
||||
end
|
||||
if tex and not m.baseColorTexture then
|
||||
m.baseColorTexture = textureRef(ctx, tex, xf)
|
||||
if m.baseColorTexture and xf then
|
||||
x.textureCenter = vec(xf, "center", { 0, 0 })
|
||||
end
|
||||
end
|
||||
if not solid then
|
||||
m.doubleSided = true
|
||||
end
|
||||
m.extras = { vrml = x }
|
||||
table.insert(ctx.scene.materials, m)
|
||||
local idx = #ctx.scene.materials
|
||||
;(cache :: any)[solid] = idx
|
||||
return idx
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ nodes
|
||||
local walk: (ctx: Ctx, n: any, parent: number?) -> ()
|
||||
|
||||
local function shape(ctx: Ctx, n: any, parent: number?)
|
||||
local geo = node(n, "geometry")
|
||||
if not geo then
|
||||
return
|
||||
end
|
||||
local mi = ctx.meshes[n]
|
||||
if mi == nil then
|
||||
local prim, solidOrErr = Geometry.primitive(geo, ctx.opts)
|
||||
if not prim then
|
||||
if solidOrErr then
|
||||
ctx.failure = ctx.failure or solidOrErr
|
||||
else
|
||||
ctx.skipped[geo.type] = (ctx.skipped[geo.type] or 0) + 1
|
||||
end
|
||||
ctx.meshes[n] = false :: any
|
||||
return
|
||||
end
|
||||
local count = if prim.indices then prim.indices.count else prim.attributes.POSITION.count
|
||||
if count == 0 then
|
||||
-- nothing to draw (no valid faces / points)
|
||||
ctx.meshes[n] = false
|
||||
return
|
||||
end
|
||||
prim.material = material(ctx, node(n, "appearance"), solidOrErr == true)
|
||||
table.insert(ctx.scene.meshes, { name = n.def or geo.def, primitives = { prim } })
|
||||
mi = #ctx.scene.meshes
|
||||
ctx.meshes[n] = mi
|
||||
elseif mi == false then
|
||||
return
|
||||
end
|
||||
addNode(ctx, { name = n.def, children = {}, mesh = mi }, parent)
|
||||
end
|
||||
|
||||
local function viewpoint(ctx: Ctx, n: any, parent: number?)
|
||||
local cam: any
|
||||
if n.type == "OrthoViewpoint" then
|
||||
local f = vec(n, "fieldOfView", { -1, -1, 1, 1 })
|
||||
cam = { type = "orthographic", xmag = (f[3] - f[1]) / 2, ymag = (f[4] - f[2]) / 2, znear = 0.125, zfar = 1e4 }
|
||||
else
|
||||
cam = { type = "perspective", yfov = num(n, "fieldOfView", 0.785398), znear = 0.125 }
|
||||
end
|
||||
cam.name = n.def or str(n, "description")
|
||||
table.insert(ctx.scene.cameras, cam)
|
||||
local o = vec(n, "orientation", { 0, 0, 1, 0 })
|
||||
local nd: Types.Node = { name = cam.name, children = {}, camera = #ctx.scene.cameras, translation = vec(n, "position", { 0, 0, 10 }) }
|
||||
if o[4] ~= 0 then
|
||||
nd.rotation = quat(o)
|
||||
end
|
||||
addNode(ctx, nd, parent)
|
||||
end
|
||||
|
||||
local function light(ctx: Ctx, n: any, parent: number?)
|
||||
local t = n.type
|
||||
local l: Types.Light = { name = n.def, type = "point", color = vec(n, "color", { 1, 1, 1 }), intensity = num(n, "intensity", 1) }
|
||||
local nd: Types.Node = { name = n.def, children = {} }
|
||||
local x: { [string]: any } = { ambientIntensity = num(n, "ambientIntensity", 0), on = bool(n, "on", true), global = bool(n, "global", t == "DirectionalLight") }
|
||||
if t == "DirectionalLight" then
|
||||
l.type = "directional"
|
||||
nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 }))
|
||||
else
|
||||
nd.translation = vec(n, "location", { 0, 0, 0 })
|
||||
l.range = num(n, "radius", 100)
|
||||
x.attenuation = vec(n, "attenuation", { 1, 0, 0 })
|
||||
if t == "SpotLight" then
|
||||
l.type = "spot"
|
||||
nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 }))
|
||||
local cut = num(n, "cutOffAngle", 0.785398)
|
||||
l.outerCone = cut
|
||||
l.innerCone = math.min(num(n, "beamWidth", 1.570796), cut)
|
||||
end
|
||||
end
|
||||
;(l :: any).extras = { vrml = x }
|
||||
table.insert(ctx.scene.lights, l)
|
||||
nd.light = #ctx.scene.lights
|
||||
addNode(ctx, nd, parent)
|
||||
end
|
||||
|
||||
local function children(ctx: Ctx, n: any, parent: number?)
|
||||
if n.type == "Switch" then
|
||||
local which = math.floor(num(n, "whichChoice", -1))
|
||||
local list = nodes(n, "choice")
|
||||
if #list == 0 then
|
||||
list = nodes(n, "children")
|
||||
end
|
||||
local c = list[which + 1]
|
||||
if which >= 0 and c then
|
||||
walk(ctx, c, parent)
|
||||
end
|
||||
return
|
||||
elseif n.type == "LOD" then
|
||||
local list = nodes(n, "level")
|
||||
if #list == 0 then
|
||||
list = nodes(n, "children")
|
||||
end
|
||||
if list[1] then
|
||||
walk(ctx, list[1], parent)
|
||||
end
|
||||
return
|
||||
end
|
||||
for _, f in CHILDREN do
|
||||
for _, c in nodes(n, f) do
|
||||
walk(ctx, c, parent)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function transform(ctx: Ctx, n: any, parent: number?)
|
||||
local t, c = vec(n, "translation", { 0, 0, 0 }), vec(n, "center", { 0, 0, 0 })
|
||||
local r, s, so = vec(n, "rotation", { 0, 0, 1, 0 }), vec(n, "scale", { 1, 1, 1 }), vec(n, "scaleOrientation", { 0, 0, 1, 0 })
|
||||
local qr, qs = quat(r), quat(so)
|
||||
local outer: Types.Node = { name = n.def, children = {} }
|
||||
local tt = { t[1] + c[1], t[2] + c[2], t[3] + c[3] }
|
||||
if not isZero(tt) then
|
||||
outer.translation = tt
|
||||
end
|
||||
local q = if isIdentityQ(qs) then qr else qmul(qr, qs)
|
||||
if not isIdentityQ(q) then
|
||||
outer.rotation = q
|
||||
end
|
||||
if s[1] ~= 1 or s[2] ~= 1 or s[3] ~= 1 then
|
||||
outer.scale = s
|
||||
end
|
||||
local oi = addNode(ctx, outer, parent)
|
||||
local list = ctx.instances[n]
|
||||
if not list then
|
||||
list = {}
|
||||
ctx.instances[n] = list
|
||||
end
|
||||
table.insert(list, { node = oi, center = c, so = qs })
|
||||
local holder = oi
|
||||
if not isZero(c) or not isIdentityQ(qs) then
|
||||
local inv = { -qs[1], -qs[2], -qs[3], qs[4] }
|
||||
local inner: Types.Node = { children = {}, translation = qrot(inv, { -c[1], -c[2], -c[3] }) }
|
||||
if not isIdentityQ(inv) then
|
||||
inner.rotation = inv
|
||||
end
|
||||
holder = addNode(ctx, inner, oi)
|
||||
end
|
||||
children(ctx, n, holder)
|
||||
end
|
||||
|
||||
local function inline(ctx: Ctx, n: any, parent: number?)
|
||||
local fetch, load = ctx.opts.fetch, ctx.opts.load
|
||||
if not fetch or not load or ctx.inline >= (ctx.opts.maxInline or 8) or not bool(n, "load", true) then
|
||||
ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1
|
||||
return
|
||||
end
|
||||
for _, u in strs(n, "url") do
|
||||
local data = fetch(string.match(u, "^([^#?]*)") or u)
|
||||
if data then
|
||||
local g = load(data)
|
||||
if g then
|
||||
local holder = addNode(ctx, { name = n.def, children = {} }, parent)
|
||||
ctx.inline += 1
|
||||
for _, root in g.roots do
|
||||
walk(ctx, root, holder)
|
||||
end
|
||||
ctx.inline -= 1
|
||||
return
|
||||
end
|
||||
end
|
||||
end
|
||||
ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1
|
||||
end
|
||||
|
||||
function walk(ctx: Ctx, n: any, parent: number?)
|
||||
if ctx.failure or type(n) ~= "table" then
|
||||
return
|
||||
end
|
||||
ctx.depth += 1
|
||||
if ctx.depth > 200 then
|
||||
ctx.failure = "limit: scene nested deeper than 200"
|
||||
return
|
||||
end
|
||||
local t = n.type
|
||||
if TRANSFORM[t] then
|
||||
transform(ctx, n, parent)
|
||||
elseif GROUP[t] then
|
||||
local holder = parent
|
||||
if n.def or parent == nil then
|
||||
holder = addNode(ctx, { name = n.def, children = {} }, parent)
|
||||
end
|
||||
children(ctx, n, holder)
|
||||
elseif t == "Shape" then
|
||||
shape(ctx, n, parent)
|
||||
elseif t == "CADFace" then
|
||||
for _, s in nodes(n, "shape") do
|
||||
walk(ctx, s, parent)
|
||||
end
|
||||
elseif t == "Viewpoint" or t == "OrthoViewpoint" then
|
||||
viewpoint(ctx, n, parent)
|
||||
elseif t == "DirectionalLight" or t == "PointLight" or t == "SpotLight" then
|
||||
light(ctx, n, parent)
|
||||
elseif t == "Inline" then
|
||||
inline(ctx, n, parent)
|
||||
elseif t == "WorldInfo" then
|
||||
local src = ctx.scene.meta.source :: any
|
||||
src.title = str(n, "title")
|
||||
local info = strs(n, "info")
|
||||
src.info = if #info > 0 then info else nil
|
||||
elseif not QUIET[t] then
|
||||
ctx.skipped[t] = (ctx.skipped[t] or 0) + 1
|
||||
end
|
||||
ctx.depth -= 1
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ animation
|
||||
local TARGET = { set_translation = "translation", translation = "translation", set_rotation = "rotation", rotation = "rotation", set_scale = "scale", scale = "scale" }
|
||||
|
||||
local function animations(ctx: Ctx, routes: { any })
|
||||
-- interpolator -> its TimeSensor
|
||||
local timer: { [any]: any } = {}
|
||||
for _, r in routes do
|
||||
if (r.toField == "set_fraction" or r.toField == "fraction") and r.from.type == "TimeSensor" then
|
||||
timer[r.to] = r.from
|
||||
end
|
||||
end
|
||||
local anims: { [any]: Types.Animation } = {}
|
||||
local order: { any } = {}
|
||||
for _, r in routes do
|
||||
local path = TARGET[r.toField]
|
||||
local it = r.from
|
||||
local inst = ctx.instances[r.to]
|
||||
if not (path and inst and (it.type == "PositionInterpolator" or it.type == "OrientationInterpolator")) then
|
||||
continue
|
||||
end
|
||||
if (path == "rotation") ~= (it.type == "OrientationInterpolator") then
|
||||
continue
|
||||
end
|
||||
local key: { number }, kv: { number } = nums(it, "key") or {}, nums(it, "keyValue") or {}
|
||||
local comps = if path == "rotation" then 4 else 3
|
||||
local n = math.min(#key, #kv // comps)
|
||||
if n == 0 then
|
||||
continue
|
||||
end
|
||||
local ts = timer[it]
|
||||
local cycle = if ts then num(ts, "cycleInterval", 1) else 1
|
||||
local input = S.accessor(nil, "f32", 1, n)
|
||||
for i = 0, n - 1 do
|
||||
buffer.writef32(input.data, i * 4, key[i + 1] * cycle)
|
||||
end
|
||||
local id = ts or "routes"
|
||||
local anim = anims[id]
|
||||
if not anim then
|
||||
anim = { name = if ts then ts.def else nil, channels = {} }
|
||||
anims[id] = anim
|
||||
table.insert(order, id)
|
||||
end
|
||||
for _, at in inst do
|
||||
local out = S.accessor(nil, "f32", if path == "rotation" then 4 else 3, n)
|
||||
local prev: { number }? = nil
|
||||
for i = 0, n - 1 do
|
||||
local v: { number }
|
||||
if path == "rotation" then
|
||||
v = quat({ kv[i * 4 + 1], kv[i * 4 + 2], kv[i * 4 + 3], kv[i * 4 + 4] })
|
||||
if not isIdentityQ(at.so) then
|
||||
v = qmul(v, at.so)
|
||||
end
|
||||
if prev and prev[1] * v[1] + prev[2] * v[2] + prev[3] * v[3] + prev[4] * v[4] < 0 then
|
||||
v = { -v[1], -v[2], -v[3], -v[4] }
|
||||
end
|
||||
prev = v
|
||||
elseif path == "translation" then
|
||||
v = { kv[i * 3 + 1] + at.center[1], kv[i * 3 + 2] + at.center[2], kv[i * 3 + 3] + at.center[3] }
|
||||
else
|
||||
v = { kv[i * 3 + 1], kv[i * 3 + 2], kv[i * 3 + 3] }
|
||||
end
|
||||
for c = 1, #v do
|
||||
buffer.writef32(out.data, (i * #v + c - 1) * 4, v[c])
|
||||
end
|
||||
end
|
||||
table.insert(anim.channels, { node = at.node, path = path :: any, input = input, output = out, interpolation = "LINEAR" :: any })
|
||||
end
|
||||
end
|
||||
for _, id in order do
|
||||
table.insert(ctx.scene.animations, anims[id])
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ scene
|
||||
function Build.scene(graph: any, opts: Options): (Types.Scene?, string?)
|
||||
local scene = S.new()
|
||||
scene.meta.up = "y"
|
||||
local units = graph.units or {}
|
||||
scene.meta.unit = if units.length and units.length.factor > 0 then units.length.factor else 1
|
||||
local h = graph.header or {}
|
||||
local skipped: { [string]: number } = {}
|
||||
scene.meta.source = {
|
||||
format = opts.format or "vrml", version = h.version, encoding = h.encoding, profile = h.profile, x3d = h.x3d,
|
||||
xml = h.xml, meta = graph.meta, components = graph.components, skipped = skipped,
|
||||
}
|
||||
local ctx: Ctx = { scene = scene, opts = opts, meshes = {}, materials = {}, textures = {}, instances = {}, skipped = skipped, depth = 0, inline = 0, failure = nil }
|
||||
for _, n in graph.roots do
|
||||
walk(ctx, n, nil)
|
||||
end
|
||||
if ctx.failure then
|
||||
return nil, ctx.failure
|
||||
end
|
||||
animations(ctx, graph.routes or {})
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Build
|
||||
@@ -0,0 +1,168 @@
|
||||
--!strict
|
||||
-- codecs/model/Vrml/Fields: typed reads of node fields for codecs/model/Vrml/Build and Geometry. A classic-encoding
|
||||
-- value is a flat array (numbers, strings, booleans, nodes); an X3D XML value is the raw attribute string, parsed here
|
||||
-- on first use (numbers split on blanks / commas, MFString as quoted strings or one unquoted string, booleans
|
||||
-- true / false). Never throws.
|
||||
local Fields = {}
|
||||
|
||||
local gmatch, find, sub, byte = string.gmatch, string.find, string.sub, string.byte
|
||||
|
||||
-- quoted strings of an MFString attribute ("a" "b \"c\""), or the text itself when it is not quoted
|
||||
local function mfString(s: string): { string }
|
||||
local out = {}
|
||||
local p = find(s, "[^%s,]")
|
||||
if not p or byte(s, p) ~= 34 then
|
||||
return if p then { (string.match(s, "^%s*(.-)%s*$") :: string) } else {}
|
||||
end
|
||||
local n = #s
|
||||
while p and p <= n do
|
||||
if byte(s, p) ~= 34 then
|
||||
break
|
||||
end
|
||||
local q = p + 1
|
||||
local parts = {}
|
||||
while true do
|
||||
local e = find(s, '["\\]', q)
|
||||
if not e then
|
||||
table.insert(parts, sub(s, q))
|
||||
table.insert(out, table.concat(parts))
|
||||
return out
|
||||
end
|
||||
table.insert(parts, sub(s, q, e - 1))
|
||||
if byte(s, e) == 92 then
|
||||
table.insert(parts, sub(s, e + 1, e + 1))
|
||||
q = e + 2
|
||||
else
|
||||
p = e + 1
|
||||
break
|
||||
end
|
||||
end
|
||||
table.insert(out, table.concat(parts))
|
||||
p = find(s, "[^%s,]", p)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- nums(node, name) -> the numbers of a field (booleans as 1 / 0), or nil when absent
|
||||
function Fields.nums(node: any, name: string): { number }?
|
||||
local v = node.fields[name]
|
||||
if v == nil then
|
||||
return nil
|
||||
end
|
||||
if type(v) == "string" then
|
||||
local out = {}
|
||||
for w in gmatch(v, "[^%s,]+") do
|
||||
local x = tonumber(w)
|
||||
if x then
|
||||
table.insert(out, x)
|
||||
elseif w == "true" or w == "TRUE" then
|
||||
table.insert(out, 1)
|
||||
elseif w == "false" or w == "FALSE" then
|
||||
table.insert(out, 0)
|
||||
end
|
||||
end
|
||||
node.fields[name] = out
|
||||
return out
|
||||
end
|
||||
if type(v) ~= "table" then
|
||||
return nil
|
||||
end
|
||||
local ok = true
|
||||
for _, x in v do
|
||||
if type(x) ~= "number" then
|
||||
ok = false
|
||||
break
|
||||
end
|
||||
end
|
||||
if ok then
|
||||
return v
|
||||
end
|
||||
local out = {}
|
||||
for _, x in v do
|
||||
if type(x) == "number" then
|
||||
table.insert(out, x)
|
||||
elseif type(x) == "boolean" then
|
||||
table.insert(out, if x then 1 else 0)
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function Fields.num(node: any, name: string, default: number): number
|
||||
local v = Fields.nums(node, name)
|
||||
return if v and type(v[1]) == "number" then v[1] else default
|
||||
end
|
||||
|
||||
-- vec(node, name, default) -> the first #default numbers of a field (the default when the field is shorter)
|
||||
function Fields.vec(node: any, name: string, default: { number }): { number }
|
||||
local v = Fields.nums(node, name)
|
||||
if not v or #v < #default then
|
||||
return default
|
||||
end
|
||||
local out: { number } = {}
|
||||
for i = 1, #default do
|
||||
out[i] = v[i]
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function Fields.bool(node: any, name: string, default: boolean): boolean
|
||||
local v = node.fields[name]
|
||||
if type(v) == "string" then
|
||||
local w = string.lower(string.match(v, "^%s*(%S*)") :: string)
|
||||
return if w == "true" then true elseif w == "false" then false else default
|
||||
end
|
||||
if type(v) == "table" and type(v[1]) == "boolean" then
|
||||
return v[1]
|
||||
end
|
||||
return default
|
||||
end
|
||||
|
||||
function Fields.strs(node: any, name: string): { string }
|
||||
local v = node.fields[name]
|
||||
if type(v) == "string" then
|
||||
local out = mfString(v)
|
||||
node.fields[name] = out
|
||||
return out
|
||||
end
|
||||
local out = {}
|
||||
if type(v) == "table" then
|
||||
for _, x in v do
|
||||
if type(x) == "string" then
|
||||
table.insert(out, x)
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function Fields.str(node: any, name: string, default: string?): string?
|
||||
local v = node.fields[name]
|
||||
if type(v) == "string" then
|
||||
return v
|
||||
end
|
||||
if type(v) == "table" and type(v[1]) == "string" then
|
||||
return v[1]
|
||||
end
|
||||
return default
|
||||
end
|
||||
|
||||
-- nodes(node, name) -> the nodes of an SFNode / MFNode field
|
||||
function Fields.nodes(node: any, name: string): { any }
|
||||
local v = node.fields[name]
|
||||
local out = {}
|
||||
if type(v) == "table" then
|
||||
for _, x in v do
|
||||
if type(x) == "table" and type(x.type) == "string" then
|
||||
table.insert(out, x)
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function Fields.node(node: any, name: string): any
|
||||
return Fields.nodes(node, name)[1]
|
||||
end
|
||||
|
||||
return Fields
|
||||
@@ -0,0 +1,770 @@
|
||||
--!strict
|
||||
-- codecs/model/Vrml/Geometry: VRML97 / X3D geometry nodes to Scene primitives. Written from the specifications; no
|
||||
-- third-party code. IndexedFaceSet (coord / normal / color / texCoord with their own indices, per-vertex or per-face
|
||||
-- normals and colours, ccw, convex polygons fan-triangulated or kept as "polygons"), the X3D triangle / quad sets
|
||||
-- (IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, TriangleFanSet, IndexedTriangleStripSet,
|
||||
-- TriangleStripSet, IndexedQuadSet, QuadSet), ElevationGrid, Extrusion (spine-aligned cross sections, scale,
|
||||
-- orientation, caps), IndexedLineSet / LineSet ("lines"), PointSet ("points"), and the primitives Box, Sphere, Cone,
|
||||
-- Cylinder tessellated with normals and the specification's texture mapping. Texture coordinates get t flipped to
|
||||
-- glTF's top-left origin unless flipV = false. Never throws: returns nil, message for bad data.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Fields = require("@rosetta/codecs/model/Vrml/Fields")
|
||||
|
||||
local Geometry = {}
|
||||
|
||||
local S = Types.Scene
|
||||
local nums, num, vec, bool, node = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.node
|
||||
local sqrt, sin, cos, pi = math.sqrt, math.sin, math.cos, math.pi
|
||||
|
||||
export type Options = { flipV: boolean?, triangulate: boolean?, segments: number?, maxVertices: number? }
|
||||
|
||||
local function f32(list: { number }, comps: number, count: number): Types.Accessor
|
||||
local a = S.accessor(nil, "f32", comps, count)
|
||||
local d = a.data
|
||||
for i = 1, math.min(#list, comps * count) do
|
||||
buffer.writef32(d, (i - 1) * 4, list[i])
|
||||
end
|
||||
return a
|
||||
end
|
||||
|
||||
local function u32(list: { number }): Types.Accessor
|
||||
local a = S.accessor(nil, "u32", 1, #list)
|
||||
for i, v in list do
|
||||
buffer.writeu32(a.data, (i - 1) * 4, v)
|
||||
end
|
||||
return a
|
||||
end
|
||||
|
||||
-- the colour node's values and component count (Color: 3, ColorRGBA: 4)
|
||||
local function colors(n: any): ({ number }?, number)
|
||||
local c = node(n, "color")
|
||||
if not c then
|
||||
return nil, 3
|
||||
end
|
||||
local comps = if c.type == "ColorRGBA" then 4 else 3
|
||||
return nums(c, "color") or {}, comps
|
||||
end
|
||||
|
||||
local function points(n: any, field: string, sub: string): { number }?
|
||||
local c = node(n, field)
|
||||
return if c then nums(c, sub) or {} else nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ polygon meshes
|
||||
-- Mesh input: faces as corner lists of coordinate indices (0-based) plus, per attribute, a per-corner index list (nil:
|
||||
-- the coordinate index) or per-face indices.
|
||||
type PolyIn = {
|
||||
P: { number }, -- coordinates, 3 per point
|
||||
corners: { number }, -- coordinate index per corner, face after face
|
||||
sizes: { number }, -- corners per face
|
||||
N: { number }?, nIdx: { number }?, nFace: boolean?, -- normals; per-corner or per-face indices (nil: identity)
|
||||
C: { number }?, cComps: number?, cIdx: { number }?, cFace: boolean?,
|
||||
T: { number }?, tIdx: { number }?,
|
||||
ccw: boolean,
|
||||
}
|
||||
|
||||
local function polyMesh(m: PolyIn, o: Options, maxV: number): (any, string?)
|
||||
local P, corners, sizes = m.P, m.corners, m.sizes
|
||||
local np = #P // 3
|
||||
local N, C, T = m.N, m.C, m.T
|
||||
local cc = m.cComps or 3
|
||||
-- the attribute index of corner k (1-based) in face f (1-based)
|
||||
local function idx(list: { number }?, perFace: boolean?, f: number, k: number, c: number): number
|
||||
if perFace then
|
||||
return if list and #list > 0 then (list[f] or 0) else f - 1
|
||||
end
|
||||
return if list and #list > 0 then (list[k] or c) else c
|
||||
end
|
||||
local simple = (N == nil or (not m.nFace and (m.nIdx == nil or #m.nIdx == 0))) and (C == nil or (not m.cFace and (m.cIdx == nil or #m.cIdx == 0))) and (T == nil or m.tIdx == nil or #m.tIdx == 0)
|
||||
local vkey: { [string]: number } = {}
|
||||
local vsrc: { { number } } = {} -- per output vertex: coord, normal, colour, texcoord indices
|
||||
local out: { number } = {}
|
||||
local outSizes: { number } = {}
|
||||
local k = 0
|
||||
for f, size in sizes do
|
||||
local face: { number } = {}
|
||||
local valid = size >= 3
|
||||
for q = 1, size do
|
||||
k += 1
|
||||
local c = corners[k]
|
||||
if c == nil or c < 0 or c >= np then
|
||||
valid = false
|
||||
end
|
||||
face[q] = k
|
||||
end
|
||||
if valid then
|
||||
local verts: { number } = {}
|
||||
for q, kk in face do
|
||||
local c = corners[kk]
|
||||
if simple then
|
||||
verts[q] = c
|
||||
else
|
||||
local ni = if N then idx(m.nIdx, m.nFace, f, kk, c) else -1
|
||||
local ci = if C then idx(m.cIdx, m.cFace, f, kk, c) else -1
|
||||
local ti = if T then idx(m.tIdx, false, f, kk, c) else -1
|
||||
local key = c .. ":" .. ni .. ":" .. ci .. ":" .. ti
|
||||
local v = vkey[key]
|
||||
if not v then
|
||||
v = #vsrc
|
||||
vsrc[v + 1] = { c, ni, ci, ti }
|
||||
vkey[key] = v
|
||||
if v >= maxV then
|
||||
return nil, "limit: more than " .. maxV .. " vertices"
|
||||
end
|
||||
end
|
||||
verts[q] = v
|
||||
end
|
||||
end
|
||||
if not m.ccw then
|
||||
for a = 2, (size + 1) // 2 do
|
||||
verts[a], verts[size + 2 - a] = verts[size + 2 - a], verts[a]
|
||||
end
|
||||
end
|
||||
if o.triangulate == false then
|
||||
table.insert(outSizes, size)
|
||||
for _, v in verts do
|
||||
table.insert(out, v)
|
||||
end
|
||||
else
|
||||
for a = 2, size - 1 do
|
||||
table.insert(out, verts[1])
|
||||
table.insert(out, verts[a])
|
||||
table.insert(out, verts[a + 1])
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local nv = if simple then np else #vsrc
|
||||
if nv > maxV then
|
||||
return nil, "limit: more than " .. maxV .. " vertices"
|
||||
end
|
||||
local flipV = o.flipV ~= false
|
||||
local pos = S.accessor(nil, "f32", 3, nv)
|
||||
local nrm = if N then S.accessor(nil, "f32", 3, nv) else nil
|
||||
local col = if C then S.accessor(nil, "f32", cc, nv) else nil
|
||||
local tex = if T then S.accessor(nil, "f32", 2, nv) else nil
|
||||
local wf = buffer.writef32
|
||||
for v = 0, nv - 1 do
|
||||
local s = if simple then nil else vsrc[v + 1]
|
||||
local c = if s then s[1] else v
|
||||
for q = 0, 2 do
|
||||
wf(pos.data, (v * 3 + q) * 4, P[c * 3 + q + 1] or 0)
|
||||
end
|
||||
if nrm and N then
|
||||
local ni = if s then s[2] else v
|
||||
for q = 0, 2 do
|
||||
wf(nrm.data, (v * 3 + q) * 4, N[ni * 3 + q + 1] or 0)
|
||||
end
|
||||
end
|
||||
if col and C then
|
||||
local ci = if s then s[3] else v
|
||||
for q = 0, cc - 1 do
|
||||
wf(col.data, (v * cc + q) * 4, C[ci * cc + q + 1] or 1)
|
||||
end
|
||||
end
|
||||
if tex and T then
|
||||
local ti = if s then s[4] else v
|
||||
local tt = T[ti * 2 + 2] or 0
|
||||
wf(tex.data, v * 8, T[ti * 2 + 1] or 0)
|
||||
wf(tex.data, v * 8 + 4, if flipV then 1 - tt else tt)
|
||||
end
|
||||
end
|
||||
local attrs: { [string]: Types.Accessor } = { POSITION = pos }
|
||||
attrs.NORMAL, attrs.COLOR_0, attrs.TEXCOORD_0 = nrm, col, tex
|
||||
local prim: Types.Primitive = { attributes = attrs, indices = u32(out), mode = "triangles" }
|
||||
if o.triangulate == false then
|
||||
prim.mode = "polygons"
|
||||
prim.faces = u32(outSizes)
|
||||
end
|
||||
return prim
|
||||
end
|
||||
|
||||
-- split a -1 separated index list into corners + sizes
|
||||
local function split(list: { number }): ({ number }, { number })
|
||||
local corners, sizes = {}, {}
|
||||
local run = 0
|
||||
for _, x in list do
|
||||
if x < 0 then
|
||||
if run > 0 then
|
||||
table.insert(sizes, run)
|
||||
end
|
||||
run = 0
|
||||
else
|
||||
table.insert(corners, x)
|
||||
run += 1
|
||||
end
|
||||
end
|
||||
if run > 0 then
|
||||
table.insert(sizes, run)
|
||||
end
|
||||
return corners, sizes
|
||||
end
|
||||
|
||||
-- per-face index lists keep only the entries of faces (the -1 separators of per-corner lists match the corners)
|
||||
local function cornerList(list: { number }?): { number }?
|
||||
if not list or #list == 0 then
|
||||
return nil
|
||||
end
|
||||
local out = {}
|
||||
for _, x in list do
|
||||
if x >= 0 then
|
||||
table.insert(out, x)
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function faceSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?)
|
||||
local P = points(n, "coord", "point") or {}
|
||||
local corners, sizes = split(nums(n, "coordIndex") or {})
|
||||
local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true)
|
||||
local C, cc = colors(n)
|
||||
local tc = node(n, "texCoord")
|
||||
local m: PolyIn = {
|
||||
P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true),
|
||||
N = points(n, "normal", "vector"), nFace = not nPer, nIdx = if nPer then cornerList(nums(n, "normalIndex")) else nums(n, "normalIndex"),
|
||||
C = C, cComps = cc, cFace = not cPer, cIdx = if cPer then cornerList(nums(n, "colorIndex")) else nums(n, "colorIndex"),
|
||||
T = if tc and tc.type ~= "TextureCoordinateGenerator" then (nums(if tc.type == "MultiTextureCoordinate" then (node(tc, "texCoord") or tc) else tc, "point") or {}) else nil,
|
||||
tIdx = cornerList(nums(n, "texCoordIndex")),
|
||||
}
|
||||
return polyMesh(m, o, maxV)
|
||||
end
|
||||
|
||||
-- the X3D triangle / quad sets: faces from index (or vertex order) and fan / strip counts
|
||||
local function triSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?)
|
||||
local t = n.type
|
||||
local P = points(n, "coord", "point") or {}
|
||||
local np = #P // 3
|
||||
local index = nums(n, "index")
|
||||
local seq: { number }
|
||||
if string.sub(t, 1, 7) == "Indexed" then
|
||||
seq = index or {}
|
||||
else
|
||||
seq = {}
|
||||
for i = 0, np - 1 do
|
||||
seq[i + 1] = i
|
||||
end
|
||||
end
|
||||
local corners, sizes = {}, {}
|
||||
local function tri(a: number, b: number, c: number)
|
||||
table.insert(corners, a)
|
||||
table.insert(corners, b)
|
||||
table.insert(corners, c)
|
||||
table.insert(sizes, 3)
|
||||
end
|
||||
-- runs: -1 separated (indexed fans / strips) or fanCount / stripCount (plain fans / strips)
|
||||
local function runs(): { { number } }
|
||||
local out = {}
|
||||
local counts = nums(n, if string.find(t, "Fan", 1, true) then "fanCount" else "stripCount")
|
||||
if string.sub(t, 1, 7) == "Indexed" or not counts then
|
||||
local cur = {}
|
||||
for _, x in seq do
|
||||
if x < 0 then
|
||||
table.insert(out, cur)
|
||||
cur = {}
|
||||
else
|
||||
table.insert(cur, x)
|
||||
end
|
||||
end
|
||||
table.insert(out, cur)
|
||||
else
|
||||
local at = 1
|
||||
for _, c in counts do
|
||||
local cur = {}
|
||||
for q = 0, c - 1 do
|
||||
cur[q + 1] = seq[at + q]
|
||||
end
|
||||
at += c
|
||||
table.insert(out, cur)
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
if t == "IndexedTriangleSet" or t == "TriangleSet" then
|
||||
for i = 1, #seq - 2, 3 do
|
||||
tri(seq[i], seq[i + 1], seq[i + 2])
|
||||
end
|
||||
elseif t == "IndexedQuadSet" or t == "QuadSet" then
|
||||
for i = 1, #seq - 3, 4 do
|
||||
for q = 0, 3 do
|
||||
table.insert(corners, seq[i + q])
|
||||
end
|
||||
table.insert(sizes, 4)
|
||||
end
|
||||
elseif string.find(t, "Fan", 1, true) then
|
||||
for _, r in runs() do
|
||||
for i = 2, #r - 1 do
|
||||
tri(r[1], r[i], r[i + 1])
|
||||
end
|
||||
end
|
||||
else
|
||||
for _, r in runs() do
|
||||
for i = 1, #r - 2 do
|
||||
if i % 2 == 1 then
|
||||
tri(r[i], r[i + 1], r[i + 2])
|
||||
else
|
||||
tri(r[i + 1], r[i], r[i + 2])
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true)
|
||||
local C, cc = colors(n)
|
||||
local tc = node(n, "texCoord")
|
||||
local m: PolyIn = {
|
||||
P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true),
|
||||
N = points(n, "normal", "vector"), nFace = not nPer, C = C, cComps = cc, cFace = not cPer,
|
||||
T = if tc and tc.type == "TextureCoordinate" then nums(tc, "point") or {} else nil,
|
||||
}
|
||||
return polyMesh(m, o, maxV)
|
||||
end
|
||||
|
||||
local function elevationGrid(n: any, o: Options, maxV: number): (Types.Primitive?, string?)
|
||||
local nx, nz = math.floor(num(n, "xDimension", 0)), math.floor(num(n, "zDimension", 0))
|
||||
local dx, dz = num(n, "xSpacing", 1), num(n, "zSpacing", 1)
|
||||
local h: { number } = nums(n, "height") or {}
|
||||
if nx < 2 or nz < 2 then
|
||||
return nil, nil
|
||||
end
|
||||
if nx * nz > maxV then
|
||||
return nil, "limit: elevation grid of " .. nx .. " x " .. nz
|
||||
end
|
||||
local P: { number }, T: { number }, corners: { number }, sizes: { number } = {}, {}, {}, {}
|
||||
for z = 0, nz - 1 do
|
||||
for x = 0, nx - 1 do
|
||||
table.insert(P, x * dx)
|
||||
table.insert(P, h[z * nx + x + 1] or 0)
|
||||
table.insert(P, z * dz)
|
||||
table.insert(T, x / (nx - 1))
|
||||
table.insert(T, z / (nz - 1))
|
||||
end
|
||||
end
|
||||
for z = 0, nz - 2 do
|
||||
for x = 0, nx - 2 do
|
||||
local a = z * nx + x
|
||||
-- counter-clockwise seen from +y: a, a + nx, a + nx + 1, a + 1
|
||||
for _, c in { a, a + nx, a + nx + 1, a + 1 } do
|
||||
table.insert(corners, c)
|
||||
end
|
||||
table.insert(sizes, 4)
|
||||
end
|
||||
end
|
||||
local C, cc = colors(n)
|
||||
local tc = node(n, "texCoord")
|
||||
local m: PolyIn = {
|
||||
P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true),
|
||||
N = points(n, "normal", "vector"), nFace = not bool(n, "normalPerVertex", true), C = C, cComps = cc,
|
||||
cFace = not bool(n, "colorPerVertex", true), T = if tc then nums(tc, "point") or {} else T,
|
||||
}
|
||||
return polyMesh(m, o, maxV)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Extrusion
|
||||
local function cross(a: { number }, b: { number }): { number }
|
||||
return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] }
|
||||
end
|
||||
local function sub3(a: { number }, b: { number }): { number }
|
||||
return { a[1] - b[1], a[2] - b[2], a[3] - b[3] }
|
||||
end
|
||||
local function norm(a: { number }): ({ number }, number)
|
||||
local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3])
|
||||
return if l > 1e-12 then { a[1] / l, a[2] / l, a[3] / l } else { 0, 0, 0 }, l
|
||||
end
|
||||
-- rotate v about the unit axis k by angle a (Rodrigues)
|
||||
local function rotate(v: { number }, k: { number }, a: number): { number }
|
||||
local c, s = cos(a), sin(a)
|
||||
local d = (k[1] * v[1] + k[2] * v[2] + k[3] * v[3]) * (1 - c)
|
||||
local kv = cross(k, v)
|
||||
return { v[1] * c + kv[1] * s + k[1] * d, v[2] * c + kv[2] * s + k[2] * d, v[3] * c + kv[3] * s + k[3] * d }
|
||||
end
|
||||
|
||||
local function extrusion(n: any, o: Options, maxV: number): (Types.Primitive?, string?)
|
||||
local sp = nums(n, "spine") or { 0, 0, 0, 0, 1, 0 }
|
||||
local cs = nums(n, "crossSection") or { 1, 1, 1, -1, -1, -1, -1, 1, 1, 1 }
|
||||
local sc = nums(n, "scale") or { 1, 1 }
|
||||
local ori = nums(n, "orientation") or { 0, 0, 1, 0 }
|
||||
local ns, nc = #sp // 3, #cs // 2
|
||||
if ns < 2 or nc < 2 then
|
||||
return nil, nil
|
||||
end
|
||||
if ns * nc > maxV then
|
||||
return nil, "limit: extrusion of " .. ns .. " x " .. nc
|
||||
end
|
||||
local spine = {}
|
||||
for i = 1, ns do
|
||||
spine[i] = { sp[i * 3 - 2], sp[i * 3 - 1], sp[i * 3] }
|
||||
end
|
||||
local function same(a: { number }, b: { number }): boolean
|
||||
return math.abs(a[1] - b[1]) < 1e-9 and math.abs(a[2] - b[2]) < 1e-9 and math.abs(a[3] - b[3]) < 1e-9
|
||||
end
|
||||
local closedSpine = same(spine[1], spine[ns])
|
||||
local closedCs = math.abs(cs[1] - cs[nc * 2 - 1]) < 1e-9 and math.abs(cs[2] - cs[nc * 2]) < 1e-9
|
||||
-- spine-aligned cross-section planes: Y along the spine, Z from the bend, X = Y x Z
|
||||
local Ys: { { number } }, Zs: { [number]: { number } } = {}, {}
|
||||
for i = 1, ns do
|
||||
local prev = if i > 1 then spine[i - 1] elseif closedSpine then spine[ns - 1] else nil
|
||||
local nxt = if i < ns then spine[i + 1] elseif closedSpine then spine[2] else nil
|
||||
local y = sub3(nxt or spine[i], prev or spine[i])
|
||||
Ys[i] = norm(y)
|
||||
if prev and nxt then
|
||||
local z, l = norm(cross(sub3(nxt, spine[i]), sub3(prev, spine[i])))
|
||||
Zs[i] = if l > 1e-12 then z else nil
|
||||
end
|
||||
end
|
||||
-- missing Z: copy a neighbour's; a straight spine rotates (0, 0, 1) like (0, 1, 0) onto the spine direction
|
||||
local firstZ = nil
|
||||
for i = 1, ns do
|
||||
if Zs[i] then
|
||||
firstZ = Zs[i]
|
||||
break
|
||||
end
|
||||
end
|
||||
for i = 1, ns do
|
||||
if not Ys[i] or (Ys[i][1] == 0 and Ys[i][2] == 0 and Ys[i][3] == 0) then
|
||||
Ys[i] = Ys[i - 1] or { 0, 1, 0 }
|
||||
end
|
||||
end
|
||||
for i = 1, ns do
|
||||
if not Zs[i] then
|
||||
if firstZ then
|
||||
Zs[i] = Zs[i - 1] or firstZ
|
||||
else
|
||||
local y = Ys[i]
|
||||
local axis, l = norm(cross({ 0, 1, 0 }, y))
|
||||
local ang = math.acos(math.clamp(y[2], -1, 1))
|
||||
Zs[i] = if l > 1e-12 then rotate({ 0, 0, 1 }, axis, ang) elseif y[2] < 0 then { 0, 0, -1 } else { 0, 0, 1 }
|
||||
end
|
||||
end
|
||||
if i > 1 and Zs[i][1] * Zs[i - 1][1] + Zs[i][2] * Zs[i - 1][2] + Zs[i][3] * Zs[i - 1][3] < 0 then
|
||||
Zs[i] = { -Zs[i][1], -Zs[i][2], -Zs[i][3] }
|
||||
end
|
||||
end
|
||||
local nr = if closedSpine then ns - 1 else ns
|
||||
local nring = if closedCs then nc - 1 else nc
|
||||
local P = {}
|
||||
for i = 1, nr do
|
||||
local y, z = Ys[i], Zs[i]
|
||||
local x = cross(y, z)
|
||||
local si = if #sc >= i * 2 then i else 1
|
||||
local sx, sz = sc[si * 2 - 1] or 1, sc[si * 2] or 1
|
||||
local oi = if #ori >= i * 4 then i else 1
|
||||
local ax, ang = norm({ ori[oi * 4 - 3] or 0, ori[oi * 4 - 2] or 0, ori[oi * 4 - 1] or 1 }), ori[oi * 4] or 0
|
||||
for j = 1, nring do
|
||||
local v = { cs[j * 2 - 1] * sx, 0, cs[j * 2] * sz }
|
||||
if ang ~= 0 then
|
||||
v = rotate(v, ax, ang)
|
||||
end
|
||||
local s = spine[i]
|
||||
table.insert(P, s[1] + x[1] * v[1] + y[1] * v[2] + z[1] * v[3])
|
||||
table.insert(P, s[2] + x[2] * v[1] + y[2] * v[2] + z[2] * v[3])
|
||||
table.insert(P, s[3] + x[3] * v[1] + y[3] * v[2] + z[3] * v[3])
|
||||
end
|
||||
end
|
||||
local corners, sizes = {}, {}
|
||||
local function at(i: number, j: number): number
|
||||
return ((i - 1) % nr) * nring + (j - 1) % nring
|
||||
end
|
||||
for i = 1, ns - 1 do
|
||||
for j = 1, nc - 1 do
|
||||
for _, c in { at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1) } do
|
||||
table.insert(corners, c)
|
||||
end
|
||||
table.insert(sizes, 4)
|
||||
end
|
||||
end
|
||||
if not closedSpine then
|
||||
if bool(n, "beginCap", true) then
|
||||
for j = 1, nring do
|
||||
table.insert(corners, at(1, j))
|
||||
end
|
||||
table.insert(sizes, nring)
|
||||
end
|
||||
if bool(n, "endCap", true) then
|
||||
for j = nring, 1, -1 do
|
||||
table.insert(corners, at(ns, j))
|
||||
end
|
||||
table.insert(sizes, nring)
|
||||
end
|
||||
end
|
||||
return polyMesh({ P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true) }, o, maxV)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ lines, points
|
||||
local function lines(n: any, maxV: number): (any, string?)
|
||||
local P = points(n, "coord", "point") or {}
|
||||
local np = #P // 3
|
||||
local C, cc = colors(n)
|
||||
local perVertex = bool(n, "colorPerVertex", true)
|
||||
local runs: { { number } } = {}
|
||||
if n.type == "LineSet" then
|
||||
local at = 0
|
||||
for _, c in nums(n, "vertexCount") or {} do
|
||||
local r = {}
|
||||
for q = 0, c - 1 do
|
||||
r[q + 1] = at + q
|
||||
end
|
||||
at += c
|
||||
table.insert(runs, r)
|
||||
end
|
||||
else
|
||||
local corners, sizes = split(nums(n, "coordIndex") or {})
|
||||
local k = 0
|
||||
for _, s in sizes do
|
||||
local r = {}
|
||||
for q = 1, s do
|
||||
r[q] = corners[k + q]
|
||||
end
|
||||
k += s
|
||||
table.insert(runs, r)
|
||||
end
|
||||
end
|
||||
local cIdx = nums(n, "colorIndex") or {}
|
||||
local cList = if perVertex then cornerList(cIdx) else nil
|
||||
local vkey: { [string]: number } = {}
|
||||
local src: { { number } } = {}
|
||||
local out: { number } = {}
|
||||
local k = 0
|
||||
for li, r in runs do
|
||||
local prev: number? = nil
|
||||
for _, c in r do
|
||||
k += 1
|
||||
if c == nil or c < 0 or c >= np then
|
||||
prev = nil
|
||||
continue
|
||||
end
|
||||
local ci = if not C then -1 elseif perVertex then (if cList then cList[k] or c else c) else (cIdx[li] or li - 1)
|
||||
local key = c .. ":" .. ci
|
||||
local v = vkey[key]
|
||||
if not v then
|
||||
v = #src
|
||||
src[v + 1] = { c, ci }
|
||||
vkey[key] = v
|
||||
end
|
||||
if prev then
|
||||
table.insert(out, prev)
|
||||
table.insert(out, v)
|
||||
end
|
||||
prev = v
|
||||
end
|
||||
end
|
||||
if #src > maxV then
|
||||
return nil, "limit: more than " .. maxV .. " vertices"
|
||||
end
|
||||
local pos = S.accessor(nil, "f32", 3, #src)
|
||||
local col = if C then S.accessor(nil, "f32", cc, #src) else nil
|
||||
for v, s in src do
|
||||
for q = 0, 2 do
|
||||
buffer.writef32(pos.data, ((v - 1) * 3 + q) * 4, P[s[1] * 3 + q + 1])
|
||||
end
|
||||
if col and C then
|
||||
for q = 0, cc - 1 do
|
||||
buffer.writef32(col.data, ((v - 1) * cc + q) * 4, C[s[2] * cc + q + 1] or 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
return { attributes = { POSITION = pos, COLOR_0 = col } :: any, indices = u32(out), mode = "lines" }
|
||||
end
|
||||
|
||||
local function pointSet(n: any, maxV: number): (any, string?)
|
||||
local P = points(n, "coord", "point") or {}
|
||||
local np = #P // 3
|
||||
if np > maxV then
|
||||
return nil, "limit: more than " .. maxV .. " points"
|
||||
end
|
||||
local C, cc = colors(n)
|
||||
local attrs: { [string]: Types.Accessor } = { POSITION = f32(P, 3, np) }
|
||||
if C then
|
||||
local col = S.accessor(nil, "f32", cc, np)
|
||||
for i = 0, np * cc - 1 do
|
||||
buffer.writef32(col.data, i * 4, C[i + 1] or 1)
|
||||
end
|
||||
attrs.COLOR_0 = col
|
||||
end
|
||||
return { attributes = attrs, mode = "points" }
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ primitives
|
||||
-- a primitive from flat arrays (positions, normals, uvs with the specification's bottom-left origin, triangles)
|
||||
local function direct(P: { number }, N: { number }, T: { number }, I: { number }, o: Options): Types.Primitive
|
||||
local nv = #P // 3
|
||||
if o.flipV ~= false then
|
||||
for i = 2, #T, 2 do
|
||||
T[i] = 1 - T[i]
|
||||
end
|
||||
end
|
||||
return {
|
||||
attributes = { POSITION = f32(P, 3, nv), NORMAL = f32(N, 3, nv), TEXCOORD_0 = f32(T, 2, nv) },
|
||||
indices = u32(I),
|
||||
mode = "triangles",
|
||||
}
|
||||
end
|
||||
|
||||
local function box(n: any, o: Options): Types.Primitive
|
||||
local s = vec(n, "size", { 2, 2, 2 })
|
||||
local hx, hy, hz = s[1] / 2, s[2] / 2, s[3] / 2
|
||||
local P, N, T, I = {}, {}, {}, {}
|
||||
-- faces: normal, u axis, v axis (the specification's texture orientation)
|
||||
local FACES = {
|
||||
{ { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 0 } }, { { 0, 0, -1 }, { -1, 0, 0 }, { 0, 1, 0 } },
|
||||
{ { 1, 0, 0 }, { 0, 0, -1 }, { 0, 1, 0 } }, { { -1, 0, 0 }, { 0, 0, 1 }, { 0, 1, 0 } },
|
||||
{ { 0, 1, 0 }, { 1, 0, 0 }, { 0, 0, -1 } }, { { 0, -1, 0 }, { 1, 0, 0 }, { 0, 0, 1 } },
|
||||
}
|
||||
for f, face in FACES do
|
||||
local nn, u, v = face[1], face[2], face[3]
|
||||
for _, c in { { -1, -1 }, { 1, -1 }, { 1, 1 }, { -1, 1 } } do
|
||||
for q = 1, 3 do
|
||||
local h = if q == 1 then hx elseif q == 2 then hy else hz
|
||||
table.insert(P, (nn[q] + u[q] * c[1] + v[q] * c[2]) * h)
|
||||
table.insert(N, nn[q])
|
||||
end
|
||||
table.insert(T, (c[1] + 1) / 2)
|
||||
table.insert(T, (c[2] + 1) / 2)
|
||||
end
|
||||
local b = (f - 1) * 4
|
||||
for _, x in { 0, 1, 2, 0, 2, 3 } do
|
||||
table.insert(I, b + x)
|
||||
end
|
||||
end
|
||||
return direct(P, N, T, I, o)
|
||||
end
|
||||
|
||||
-- a ring of segs + 1 vertices (the seam doubled for the texture) at height y, radius r; s starts at the back (-z)
|
||||
-- and runs counter-clockwise seen from +y
|
||||
local function ring(P: { number }, N: { number }?, T: { number }?, segs: number, y: number, r: number, t: number, ny: number?, nr: number?)
|
||||
for i = 0, segs do
|
||||
local a = 2 * pi * i / segs
|
||||
local x, z = -sin(a), -cos(a)
|
||||
table.insert(P, x * r)
|
||||
table.insert(P, y)
|
||||
table.insert(P, z * r)
|
||||
if N then
|
||||
table.insert(N, x * (nr or 1))
|
||||
table.insert(N, ny or 0)
|
||||
table.insert(N, z * (nr or 1))
|
||||
end
|
||||
if T then
|
||||
table.insert(T, i / segs)
|
||||
table.insert(T, t)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- a cap disc at height y facing ny (+1 / -1)
|
||||
local function cap(P: { number }, N: { number }, T: { number }, I: { number }, segs: number, y: number, r: number, ny: number)
|
||||
local b = #P // 3
|
||||
for i = 0, segs - 1 do
|
||||
local a = 2 * pi * i / segs
|
||||
local x, z = -sin(a), -cos(a)
|
||||
table.insert(P, x * r)
|
||||
table.insert(P, y)
|
||||
table.insert(P, z * r)
|
||||
table.insert(N, 0)
|
||||
table.insert(N, ny)
|
||||
table.insert(N, 0)
|
||||
-- the specification maps the cap like a top view: s = x, t = -z (top) or z (bottom)
|
||||
table.insert(T, x / 2 + 0.5)
|
||||
table.insert(T, (if ny > 0 then -z else z) / 2 + 0.5)
|
||||
end
|
||||
for i = 1, segs - 2 do
|
||||
-- the ring runs counter-clockwise seen from +y: in order for the top, reversed for the bottom
|
||||
if ny > 0 then
|
||||
table.insert(I, b)
|
||||
table.insert(I, b + i)
|
||||
table.insert(I, b + i + 1)
|
||||
else
|
||||
table.insert(I, b)
|
||||
table.insert(I, b + i + 1)
|
||||
table.insert(I, b + i)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- quads between two rings of segs + 1 vertices starting at a (lower) and b (upper)
|
||||
local function band(I: { number }, a: number, b: number, segs: number)
|
||||
for i = 0, segs - 1 do
|
||||
table.insert(I, a + i)
|
||||
table.insert(I, a + i + 1)
|
||||
table.insert(I, b + i + 1)
|
||||
table.insert(I, a + i)
|
||||
table.insert(I, b + i + 1)
|
||||
table.insert(I, b + i)
|
||||
end
|
||||
end
|
||||
|
||||
local function sphere(n: any, o: Options, segs: number): Types.Primitive
|
||||
local r = num(n, "radius", 1)
|
||||
local rings = math.max(2, segs // 2)
|
||||
local P, N, T, I = {}, {}, {}, {}
|
||||
for j = 0, rings do
|
||||
local phi = pi * j / rings -- from the bottom
|
||||
local y, rr = -cos(phi), sin(phi)
|
||||
ring(P, N, T, segs, y * r, rr * r, j / rings, y, rr)
|
||||
end
|
||||
for j = 0, rings - 1 do
|
||||
band(I, j * (segs + 1), (j + 1) * (segs + 1), segs)
|
||||
end
|
||||
return direct(P, N, T, I, o)
|
||||
end
|
||||
|
||||
local function cylinder(n: any, o: Options, segs: number, cone: boolean): Types.Primitive
|
||||
local r = num(n, if cone then "bottomRadius" else "radius", 1)
|
||||
local h = num(n, "height", 2)
|
||||
local P, N, T, I = {}, {}, {}, {}
|
||||
if bool(n, "side", true) then
|
||||
-- side normals: a cone's lean outwards by its slope
|
||||
local l = sqrt(r * r + h * h)
|
||||
local ny, nr = if cone and l > 0 then r / l else 0, if cone and l > 0 then h / l else 1
|
||||
ring(P, N, T, segs, -h / 2, r, 0, ny, nr)
|
||||
ring(P, N, T, segs, h / 2, if cone then 0 else r, 1, ny, nr)
|
||||
band(I, 0, segs + 1, segs)
|
||||
end
|
||||
if not cone and bool(n, "top", true) then
|
||||
cap(P, N, T, I, segs, h / 2, r, 1)
|
||||
end
|
||||
if bool(n, "bottom", true) then
|
||||
cap(P, N, T, I, segs, -h / 2, r, -1)
|
||||
end
|
||||
return direct(P, N, T, I, o)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ dispatch
|
||||
-- primitive(geometryNode, opts) -> Primitive | nil, message | nil, nil (a node type without geometry here);
|
||||
-- the second value of a success is the node's solid flag
|
||||
function Geometry.primitive(n: any, o: Options): (Types.Primitive?, any)
|
||||
local t = n.type
|
||||
local maxV = o.maxVertices or 2 ^ 24
|
||||
local segs = math.clamp(math.floor(o.segments or 32), 3, 1024)
|
||||
local solid = bool(n, "solid", true)
|
||||
local prim: Types.Primitive?, err: string? = nil, nil
|
||||
if t == "IndexedFaceSet" then
|
||||
prim, err = faceSet(n, o, maxV)
|
||||
elseif t == "IndexedTriangleSet" or t == "TriangleSet" or t == "IndexedTriangleFanSet" or t == "TriangleFanSet" or t == "IndexedTriangleStripSet" or t == "TriangleStripSet" or t == "IndexedQuadSet" or t == "QuadSet" then
|
||||
prim, err = triSet(n, o, maxV)
|
||||
elseif t == "ElevationGrid" then
|
||||
prim, err = elevationGrid(n, o, maxV)
|
||||
elseif t == "Extrusion" then
|
||||
prim, err = extrusion(n, o, maxV)
|
||||
elseif t == "IndexedLineSet" or t == "LineSet" then
|
||||
prim, err = lines(n, maxV)
|
||||
solid = false
|
||||
elseif t == "PointSet" then
|
||||
prim, err = pointSet(n, maxV)
|
||||
solid = false
|
||||
elseif t == "Box" then
|
||||
prim = box(n, o)
|
||||
elseif t == "Sphere" then
|
||||
prim = sphere(n, o, segs)
|
||||
elseif t == "Cylinder" then
|
||||
prim = cylinder(n, o, segs, false)
|
||||
elseif t == "Cone" then
|
||||
prim = cylinder(n, o, segs, true)
|
||||
else
|
||||
return nil, nil
|
||||
end
|
||||
if not prim then
|
||||
return nil, err
|
||||
end
|
||||
return prim, solid
|
||||
end
|
||||
|
||||
return Geometry
|
||||
@@ -0,0 +1,536 @@
|
||||
--!strict
|
||||
-- codecs/model/Vrml/Parse: the VRML97 (ISO/IEC 14772-1) / X3D classic VRML encoding (ISO/IEC 19776-2) parser, into
|
||||
-- the node graph codecs/model/Vrml/Build reads. Written from the specifications; no third-party code. Field types are
|
||||
-- not known without the node schemas, so a field value is kept as a flat array of what the file wrote (numbers,
|
||||
-- strings, booleans, nodes) and the builder reads it as the type it expects. Handles comments, DEF / USE, PROTO
|
||||
-- (instances are expanded: IS fields take the instance's values or the declared defaults; nested PROTOs, ROUTEs inside
|
||||
-- bodies), EXTERNPROTO (instances stay nodes of that type, without a body), Script / shader interface declarations,
|
||||
-- ROUTE, and the X3D header statements (PROFILE, COMPONENT, META, UNIT, IMPORT, EXPORT). Never throws: errors are
|
||||
-- returned as nil, message ("line N: ...").
|
||||
local Parse = {}
|
||||
|
||||
export type Node = { type: string, def: string?, fields: { [string]: any } }
|
||||
export type Route = { from: Node, fromField: string, to: Node, toField: string }
|
||||
export type Proto = { name: string, fields: { [string]: any }, body: { Node }, routes: { Route }, extern: boolean? }
|
||||
export type Graph = {
|
||||
roots: { Node },
|
||||
routes: { Route },
|
||||
header: { [string]: any }, -- version ("2.0" / "3.3" ...), encoding, x3d (boolean), profile
|
||||
meta: { [string]: string }, -- META / WorldInfo statements
|
||||
components: { string },
|
||||
units: { [string]: { name: string, factor: number } },
|
||||
protos: { [string]: Proto },
|
||||
}
|
||||
-- an IS reference in a PROTO body: fields[name] = { is = "protoField" }
|
||||
export type IsRef = { is: string }
|
||||
|
||||
local find, sub, byte, match, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch
|
||||
|
||||
local ID1 = "^[^%c%s%d\"#',%+%-%.%[\\%]{}][^%c%s\"#',%.%[\\%]{}]*"
|
||||
local MAX_DEPTH = 200
|
||||
local DECL = { field = true, exposedField = true, eventIn = true, eventOut = true, initializeOnly = true, inputOutput = true, inputOnly = true, outputOnly = true }
|
||||
local HAS_VALUE = { field = true, exposedField = true, initializeOnly = true, inputOutput = true }
|
||||
|
||||
-- copy(node, values, defaults, memo) -> a PROTO body node with its IS fields replaced (shared nodes stay shared)
|
||||
local function copy(node: Node, values: { [string]: any }, defaults: { [string]: any }, memo: { [any]: any }): Node
|
||||
local done = memo[node]
|
||||
if done then
|
||||
return done
|
||||
end
|
||||
local out: Node = { type = node.type, def = node.def, fields = {} }
|
||||
memo[node] = out
|
||||
for k, v in node.fields do
|
||||
if type(v) == "table" and type((v :: any).is) == "string" then
|
||||
local name = (v :: any).is
|
||||
local val = values[name]
|
||||
if val == nil then
|
||||
val = defaults[name]
|
||||
end
|
||||
out.fields[k] = val
|
||||
elseif type(v) == "table" then
|
||||
local arr = table.create(#v)
|
||||
for i, x in v do
|
||||
arr[i] = if type(x) == "table" and x.type then copy(x, values, defaults, memo) else x
|
||||
end
|
||||
out.fields[k] = arr
|
||||
else
|
||||
out.fields[k] = v
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- expand(proto, values, def, routes) -> the instance's node (the body's first node), or nil for an EXTERNPROTO
|
||||
function Parse.expand(proto: Proto, values: { [string]: any }, def: string?, routes: { Route }?): Node?
|
||||
if proto.extern or #proto.body == 0 then
|
||||
return nil
|
||||
end
|
||||
local memo = {}
|
||||
local first: Node? = nil
|
||||
for _, n in proto.body do
|
||||
local c = copy(n, values, proto.fields, memo)
|
||||
first = first or c
|
||||
end
|
||||
if routes then
|
||||
for _, r in proto.routes do
|
||||
local from, to = memo[r.from], memo[r.to]
|
||||
if from and to then
|
||||
table.insert(routes, { from = from, fromField = r.fromField, to = to, toField = r.toField })
|
||||
end
|
||||
end
|
||||
end
|
||||
local f = first :: Node
|
||||
if def then
|
||||
-- the instance gets its own copy of the node so its DEF name is its own
|
||||
local out: Node = { type = f.type, def = def, fields = f.fields }
|
||||
return out
|
||||
end
|
||||
return f
|
||||
end
|
||||
|
||||
function Parse.parse(text: string): (Graph?, string?)
|
||||
local n = #text
|
||||
local p = 1
|
||||
local graph: Graph = { roots = {}, routes = {}, header = {}, meta = {}, components = {}, units = {}, protos = {} }
|
||||
local defs: { [string]: Node } = {}
|
||||
local protos: { [string]: Proto } = graph.protos
|
||||
local routes: { Route } = graph.routes
|
||||
local failure: string? = nil
|
||||
local depth = 0
|
||||
|
||||
local function line(at: number): number
|
||||
local l = 1
|
||||
for _ in gmatch(sub(text, 1, at), "\n") do
|
||||
l += 1
|
||||
end
|
||||
return l
|
||||
end
|
||||
local function fail(msg: string)
|
||||
if not failure then
|
||||
failure = "line " .. line(p) .. ": " .. msg
|
||||
end
|
||||
end
|
||||
|
||||
-- header line: #VRML V2.0 utf8 / #X3D V3.3 utf8
|
||||
local v, enc = match(text, "^#VRML V(%S+) (%S+)")
|
||||
if v then
|
||||
graph.header.version, graph.header.encoding = v, enc
|
||||
if v ~= "2.0" then
|
||||
return nil, "unsupported: VRML " .. v .. " (only VRML97 / X3D)"
|
||||
end
|
||||
else
|
||||
v, enc = match(text, "^#X3D V(%S+) (%S+)")
|
||||
if v then
|
||||
graph.header.version, graph.header.encoding, graph.header.x3d = v, enc, true
|
||||
end
|
||||
end
|
||||
|
||||
-- the lexer: skip blanks, commas and comments; returns the next token kind and value
|
||||
-- kinds: "num", "str", "id", "{", "}", "[", "]", ".", "eof"
|
||||
local function skip()
|
||||
while true do
|
||||
local q = find(text, "[^%s,]", p)
|
||||
if not q then
|
||||
p = n + 1
|
||||
return
|
||||
end
|
||||
p = q
|
||||
if byte(text, p) == 35 then -- '#'
|
||||
local e = find(text, "[\r\n]", p)
|
||||
p = if e then e else n + 1
|
||||
else
|
||||
return
|
||||
end
|
||||
end
|
||||
end
|
||||
local function token(): (string, any)
|
||||
skip()
|
||||
if p > n then
|
||||
return "eof", nil
|
||||
end
|
||||
local c = byte(text, p)
|
||||
if c == 123 or c == 125 or c == 91 or c == 93 then -- { } [ ]
|
||||
p += 1
|
||||
return string.char(c), nil
|
||||
elseif c == 34 then -- a string: \" and \\ escapes
|
||||
local q = p + 1
|
||||
local parts = {}
|
||||
while true do
|
||||
local e = find(text, '["\\]', q)
|
||||
if not e then
|
||||
fail("unterminated string")
|
||||
p = n + 1
|
||||
return "eof", nil
|
||||
end
|
||||
table.insert(parts, sub(text, q, e - 1))
|
||||
if byte(text, e) == 92 then
|
||||
table.insert(parts, sub(text, e + 1, e + 1))
|
||||
q = e + 2
|
||||
else
|
||||
p = e + 1
|
||||
return "str", table.concat(parts)
|
||||
end
|
||||
end
|
||||
end
|
||||
if (c >= 48 and c <= 57) or c == 43 or c == 45 or c == 46 then
|
||||
local s, e = find(text, "^[+-]?0[xX]%x+", p)
|
||||
if not s then
|
||||
s, e = find(text, "^[+-]?%d*%.?%d*[eE][+-]?%d+", p)
|
||||
end
|
||||
if not s then
|
||||
s, e = find(text, "^[+-]?%d*%.?%d*", p)
|
||||
end
|
||||
local num = tonumber(sub(text, p, e))
|
||||
if num then
|
||||
p = (e :: number) + 1
|
||||
return "num", num
|
||||
end
|
||||
if c == 46 then
|
||||
p += 1
|
||||
return ".", nil
|
||||
end
|
||||
-- +inf / -nan style words: read the word
|
||||
local _, we = find(text, "^[^%s,%[%]{}#\"]+", p)
|
||||
local w = sub(text, p, we)
|
||||
p = (we :: number) + 1
|
||||
local wl = string.lower(w)
|
||||
local val = if find(wl, "inf", 1, true) then (if c == 45 then -math.huge else math.huge) elseif find(wl, "nan", 1, true) then 0 else nil
|
||||
if val == nil then
|
||||
fail("bad number " .. w)
|
||||
return "eof", nil
|
||||
end
|
||||
return "num", val
|
||||
end
|
||||
local s, e = find(text, ID1, p)
|
||||
if s then
|
||||
p = (e :: number) + 1
|
||||
return "id", sub(text, s, e)
|
||||
end
|
||||
fail("unexpected character " .. sub(text, p, p))
|
||||
p = n + 1
|
||||
return "eof", nil
|
||||
end
|
||||
local function peek(): (string, any)
|
||||
local save = p
|
||||
local k, val = token()
|
||||
p = save
|
||||
return k, val
|
||||
end
|
||||
|
||||
local parseNode: (first: string) -> (Node?, boolean)
|
||||
local parseProto: (extern: boolean) -> ()
|
||||
local parseRoute: () -> ()
|
||||
|
||||
-- a field value (after its name): an array of numbers / strings / booleans / nodes
|
||||
local function value(): any
|
||||
local k, val = token()
|
||||
if k == "[" then
|
||||
local out = {}
|
||||
-- fast path: a bracket of plain numbers (big coordinate arrays)
|
||||
local close = find(text, "]", p, true)
|
||||
if close then
|
||||
local seg = sub(text, p, close - 1)
|
||||
if not find(seg, "[{}\"#]") then
|
||||
local ok = true
|
||||
for w in gmatch(seg, "[^%s,]+") do
|
||||
local x = tonumber(w)
|
||||
if x then
|
||||
table.insert(out, x)
|
||||
elseif w == "TRUE" or w == "FALSE" then
|
||||
table.insert(out, w == "TRUE")
|
||||
else
|
||||
ok = false
|
||||
break
|
||||
end
|
||||
end
|
||||
if ok then
|
||||
p = close + 1
|
||||
return out
|
||||
end
|
||||
table.clear(out)
|
||||
end
|
||||
end
|
||||
while not failure do
|
||||
k, val = token()
|
||||
if k == "]" then
|
||||
return out
|
||||
elseif k == "num" or k == "str" then
|
||||
table.insert(out, val)
|
||||
elseif k == "id" and (val == "TRUE" or val == "FALSE") then
|
||||
table.insert(out, val == "TRUE")
|
||||
elseif k == "id" and val == "NULL" then
|
||||
continue
|
||||
elseif k == "id" then
|
||||
local node = parseNode(val)
|
||||
if node then
|
||||
table.insert(out, node)
|
||||
end
|
||||
else
|
||||
fail("unexpected " .. k .. " in a [ ] value")
|
||||
return out
|
||||
end
|
||||
end
|
||||
return out
|
||||
elseif k == "num" then
|
||||
local out = { val }
|
||||
while true do
|
||||
local save = p
|
||||
local k2, v2 = token()
|
||||
if k2 ~= "num" then
|
||||
p = save
|
||||
break
|
||||
end
|
||||
table.insert(out, v2)
|
||||
end
|
||||
return out
|
||||
elseif k == "str" then
|
||||
return { val }
|
||||
elseif k == "id" then
|
||||
if val == "TRUE" or val == "FALSE" then
|
||||
return { val == "TRUE" }
|
||||
elseif val == "NULL" then
|
||||
return {}
|
||||
end
|
||||
local node = parseNode(val)
|
||||
return if node then { node } else {}
|
||||
end
|
||||
fail("missing field value")
|
||||
return {}
|
||||
end
|
||||
|
||||
-- the fields of a node body, up to its "}"
|
||||
local function body(node: Node)
|
||||
while not failure do
|
||||
local k, name = token()
|
||||
if k == "}" then
|
||||
return
|
||||
elseif k ~= "id" then
|
||||
fail("expected a field name in " .. node.type .. ", got " .. k)
|
||||
return
|
||||
end
|
||||
if name == "ROUTE" then
|
||||
parseRoute()
|
||||
elseif name == "PROTO" or name == "EXTERNPROTO" then
|
||||
parseProto(name == "EXTERNPROTO")
|
||||
elseif DECL[name] then
|
||||
-- Script / shader interface: <access> <type> <name> [<value> | IS <name>]
|
||||
local _, _t = token()
|
||||
local fk, fname = token()
|
||||
if fk ~= "id" then
|
||||
fail("bad interface declaration in " .. node.type)
|
||||
return
|
||||
end
|
||||
local pk, pv = peek()
|
||||
if pk == "id" and pv == "IS" then
|
||||
token()
|
||||
local _, ref = token()
|
||||
node.fields[fname] = { is = ref }
|
||||
elseif HAS_VALUE[name] then
|
||||
node.fields[fname] = value()
|
||||
end
|
||||
else
|
||||
local pk, pv = peek()
|
||||
if pk == "id" and pv == "IS" then
|
||||
token()
|
||||
local _, ref = token()
|
||||
node.fields[name] = { is = ref }
|
||||
else
|
||||
node.fields[name] = value()
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- a node statement starting with the id `first` (DEF name Type { }, USE name, Type { })
|
||||
function parseNode(first: string): (Node?, boolean)
|
||||
if first == "USE" then
|
||||
local k, name = token()
|
||||
if k ~= "id" then
|
||||
fail("USE without a name")
|
||||
return nil, false
|
||||
end
|
||||
local node = defs[name]
|
||||
if not node then
|
||||
fail("USE of an undefined name " .. tostring(name))
|
||||
end
|
||||
return node, true
|
||||
end
|
||||
local def: string? = nil
|
||||
local typ = first
|
||||
if first == "DEF" then
|
||||
local k, name = token()
|
||||
local k2, t2 = token()
|
||||
if k ~= "id" or k2 ~= "id" then
|
||||
fail("bad DEF")
|
||||
return nil, false
|
||||
end
|
||||
def, typ = name, t2
|
||||
end
|
||||
local k = token()
|
||||
if k ~= "{" then
|
||||
fail("expected { after " .. typ)
|
||||
return nil, false
|
||||
end
|
||||
depth += 1
|
||||
if depth > MAX_DEPTH then
|
||||
fail("limit: nodes nested deeper than " .. MAX_DEPTH)
|
||||
return nil, false
|
||||
end
|
||||
local node: Node = { type = typ, def = def, fields = {} }
|
||||
body(node)
|
||||
depth -= 1
|
||||
local proto = protos[typ]
|
||||
if proto and not proto.extern then
|
||||
local inst = Parse.expand(proto, node.fields, def, routes)
|
||||
if inst then
|
||||
node = inst
|
||||
end
|
||||
elseif proto then
|
||||
(node :: any).extern = true
|
||||
end
|
||||
if def then
|
||||
defs[def] = node
|
||||
end
|
||||
return node, false
|
||||
end
|
||||
|
||||
-- ROUTE from.field TO to.field
|
||||
function parseRoute()
|
||||
local function path(): (string?, string?)
|
||||
local k1, a = token()
|
||||
local k2 = token()
|
||||
local k3, b = token()
|
||||
if k1 ~= "id" or k2 ~= "." or k3 ~= "id" then
|
||||
return nil, nil
|
||||
end
|
||||
return a, b
|
||||
end
|
||||
local a, af = path()
|
||||
local k, to = token()
|
||||
local b, bf = path()
|
||||
if not (a and af and b and bf) or k ~= "id" or to ~= "TO" then
|
||||
fail("bad ROUTE")
|
||||
return
|
||||
end
|
||||
local from, dst = defs[a :: string], defs[b :: string]
|
||||
if from and dst then
|
||||
table.insert(routes, { from = from, fromField = af :: string, to = dst, toField = bf :: string })
|
||||
end
|
||||
end
|
||||
|
||||
-- PROTO name [ interface ] { body } / EXTERNPROTO name [ interface ] url
|
||||
function parseProto(extern: boolean)
|
||||
local k, name = token()
|
||||
if k ~= "id" or token() ~= "[" then
|
||||
fail("bad PROTO")
|
||||
return
|
||||
end
|
||||
local proto: Proto = { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil }
|
||||
while not failure do
|
||||
local k2, access = token()
|
||||
if k2 == "]" then
|
||||
break
|
||||
elseif k2 ~= "id" or not DECL[access] then
|
||||
fail("bad PROTO interface")
|
||||
return
|
||||
end
|
||||
local _, _t = token()
|
||||
local fk, fname = token()
|
||||
if fk ~= "id" then
|
||||
fail("bad PROTO interface")
|
||||
return
|
||||
end
|
||||
if HAS_VALUE[access] and not extern then
|
||||
proto.fields[fname] = value()
|
||||
end
|
||||
end
|
||||
if extern then
|
||||
value() -- the url list
|
||||
protos[name] = proto
|
||||
return
|
||||
end
|
||||
if token() ~= "{" then
|
||||
fail("PROTO " .. tostring(name) .. " without a body")
|
||||
return
|
||||
end
|
||||
-- the body has its own DEF names and its own routes
|
||||
local outerDefs, outerRoutes = defs, routes
|
||||
defs, routes = {}, proto.routes
|
||||
while not failure do
|
||||
local k3, w = token()
|
||||
if k3 == "}" then
|
||||
break
|
||||
elseif k3 ~= "id" then
|
||||
fail("bad PROTO body")
|
||||
break
|
||||
elseif w == "ROUTE" then
|
||||
parseRoute()
|
||||
elseif w == "PROTO" or w == "EXTERNPROTO" then
|
||||
parseProto(w == "EXTERNPROTO")
|
||||
else
|
||||
local node = parseNode(w)
|
||||
if node then
|
||||
table.insert(proto.body, node)
|
||||
end
|
||||
end
|
||||
end
|
||||
defs, routes = outerDefs, outerRoutes
|
||||
protos[name] = proto
|
||||
end
|
||||
|
||||
-- statements
|
||||
while not failure do
|
||||
local k, w = token()
|
||||
if k == "eof" then
|
||||
break
|
||||
elseif k ~= "id" then
|
||||
fail("unexpected " .. k)
|
||||
break
|
||||
end
|
||||
if w == "ROUTE" then
|
||||
parseRoute()
|
||||
elseif w == "PROTO" or w == "EXTERNPROTO" then
|
||||
parseProto(w == "EXTERNPROTO")
|
||||
elseif w == "PROFILE" then
|
||||
local _, prof = token()
|
||||
graph.header.profile = prof
|
||||
elseif w == "COMPONENT" then
|
||||
local _, comp = token() -- name:level is one id
|
||||
table.insert(graph.components, tostring(comp))
|
||||
elseif w == "META" then
|
||||
local _, key = token()
|
||||
local _, val = token()
|
||||
graph.meta[tostring(key)] = tostring(val)
|
||||
elseif w == "UNIT" then
|
||||
local _, cat = token()
|
||||
local _, uname = token()
|
||||
local _, factor = token()
|
||||
if type(cat) == "string" and type(factor) == "number" then
|
||||
graph.units[cat] = { name = tostring(uname), factor = factor }
|
||||
end
|
||||
elseif w == "IMPORT" or w == "EXPORT" then
|
||||
-- IMPORT inline.name AS name / EXPORT name AS name: no effect on the scene
|
||||
local _, _a = token()
|
||||
if peek() == "." then
|
||||
token()
|
||||
token()
|
||||
end
|
||||
local pk, pv = peek()
|
||||
if pk == "id" and pv == "AS" then
|
||||
token()
|
||||
token()
|
||||
end
|
||||
else
|
||||
local node = parseNode(w)
|
||||
if node then
|
||||
table.insert(graph.roots, node)
|
||||
end
|
||||
end
|
||||
end
|
||||
if failure then
|
||||
return nil, failure
|
||||
end
|
||||
return graph, nil
|
||||
end
|
||||
|
||||
return Parse
|
||||
@@ -0,0 +1,750 @@
|
||||
--!strict
|
||||
-- codecs/model/Vrml/Write: a Scene to VRML97 (`#VRML V2.0 utf8`), X3D classic (`#X3D V3.3 utf8`) or X3D XML text,
|
||||
-- for model/vrml and model/x3d. New code. Every node becomes a DEF'd Transform (a matrix is decomposed into TRS;
|
||||
-- shear is lost), each primitive a Shape: triangles / polygons / strips / fans -> IndexedFaceSet (coord, normal,
|
||||
-- texCoord with t flipped back unless flipV = false, color; per-vertex, ccw, solid = not doubleSided), lines ->
|
||||
-- IndexedLineSet, points -> PointSet; a mesh used twice is written once and USE'd. Materials -> Appearance / Material
|
||||
-- (diffuse = baseColor, transparency = 1 - alpha, emissive, shininess from roughness, the Phong terms of
|
||||
-- material.extras.vrml when present) with an ImageTexture (the texture bytes go into opts.files named after the uri or
|
||||
-- opts.name, else url = texture.uri). Cameras -> Viewpoint (X3D: OrthoViewpoint for orthographic ones), lights ->
|
||||
-- Directional / Point / SpotLight, animations (translation / rotation / scale channels) -> a TimeSensor and
|
||||
-- Position / OrientationInterpolators with ROUTEs (cubic splines keep their values, weights channels are dropped).
|
||||
-- Never throws: returns nil, message.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Mat4 = require("@rosetta/codecs/model/Mat4")
|
||||
local Flatten = require("@rosetta/codecs/model/MeshFlatten")
|
||||
local Xml = require("@rosetta/codecs/text/Xml")
|
||||
|
||||
local Write = {}
|
||||
|
||||
export type Options = { encoding: ("vrml97" | "x3dv" | "xml")?, files: { [string]: any }?, name: string?, flipV: boolean? }
|
||||
|
||||
-- a written node: fields in order, each { name, kind, value }; kinds: "sf" / "mf" (numbers; mf groups `per` numbers
|
||||
-- per line), "bool", "str", "mstr" (MFString), "node", "nodes"
|
||||
type WNode = { type: string, def: string?, use: string?, fields: { { any } } }
|
||||
|
||||
local format, concat = string.format, table.concat
|
||||
|
||||
local function fmt(v: number): string
|
||||
if v ~= v then
|
||||
return "0"
|
||||
elseif v == math.huge then
|
||||
return "1e38"
|
||||
elseif v == -math.huge then
|
||||
return "-1e38"
|
||||
elseif v == math.floor(v) and math.abs(v) < 2 ^ 53 then
|
||||
return format("%d", v)
|
||||
end
|
||||
return format("%.9g", v)
|
||||
end
|
||||
|
||||
local function W(t: string, def: string?): WNode
|
||||
return { type = t, def = def, fields = {} }
|
||||
end
|
||||
local function F(n: WNode, name: string, kind: string, value: any, per: number?)
|
||||
table.insert(n.fields, { name, kind, value, per })
|
||||
end
|
||||
|
||||
-- names: valid, unique DEF names
|
||||
local function namer(): (string?, string) -> string
|
||||
local used: { [string]: boolean } = {}
|
||||
return function(name: string?, fallback: string): string
|
||||
local s = string.gsub(name or "", "[^%w_]", "_")
|
||||
if s == "" or string.find(s, "^%d") then
|
||||
s = fallback .. (if s ~= "" then "_" .. s else "")
|
||||
end
|
||||
local base, k = s, 1
|
||||
while used[s] do
|
||||
k += 1
|
||||
s = base .. "_" .. k
|
||||
end
|
||||
used[s] = true
|
||||
return s
|
||||
end
|
||||
end
|
||||
|
||||
-- axis-angle of a quaternion (x, y, z, w)
|
||||
local function axisAngle(q: { number }): { number }
|
||||
local x, y, z, w = q[1], q[2], q[3], q[4]
|
||||
local l = math.sqrt(x * x + y * y + z * z + w * w)
|
||||
if l > 0 then
|
||||
x, y, z, w = x / l, y / l, z / l, w / l
|
||||
end
|
||||
local s = math.sqrt(math.max(0, 1 - w * w))
|
||||
if s < 1e-9 then
|
||||
return { 0, 0, 1, 0 }
|
||||
end
|
||||
return { x / s, y / s, z / s, 2 * math.acos(math.clamp(w, -1, 1)) }
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ geometry
|
||||
local function values(acc: any): { number }?
|
||||
return (Flatten.numbers(acc))
|
||||
end
|
||||
|
||||
local function faceSet(prim: any, doubleSided: boolean, o: Options, x3d: boolean): (WNode?, string?)
|
||||
local tmp = { kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } }
|
||||
local keep = function(n: string): boolean
|
||||
return n == "NORMAL" or n == "TEXCOORD_0" or n == "COLOR_0"
|
||||
end
|
||||
local m, err = Flatten.merge(tmp, keep, { triangulate = false })
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
if not m.sizes or #m.sizes == 0 then
|
||||
return nil, nil
|
||||
end
|
||||
local g = W("IndexedFaceSet")
|
||||
local coord = W("Coordinate")
|
||||
F(coord, "point", "mf", m.attrs.POSITION.values, 3)
|
||||
F(g, "coord", "node", coord)
|
||||
local idx = {}
|
||||
local p = 0
|
||||
for _, s in m.sizes do
|
||||
for k = 1, s do
|
||||
table.insert(idx, m.corners[p + k])
|
||||
end
|
||||
table.insert(idx, -1)
|
||||
p += s
|
||||
end
|
||||
F(g, "coordIndex", "mf", idx, 0)
|
||||
local nrm = m.attrs.NORMAL
|
||||
if nrm then
|
||||
local nn = W("Normal")
|
||||
F(nn, "vector", "mf", nrm.values, 3)
|
||||
F(g, "normal", "node", nn)
|
||||
end
|
||||
local tc = m.attrs.TEXCOORD_0
|
||||
if tc then
|
||||
local t = W("TextureCoordinate")
|
||||
local vals, c = {}, tc.components
|
||||
for i = 0, m.count - 1 do
|
||||
local s, tt = tc.values[i * c + 1], tc.values[i * c + 2]
|
||||
table.insert(vals, s)
|
||||
table.insert(vals, if o.flipV ~= false then 1 - tt else tt)
|
||||
end
|
||||
F(t, "point", "mf", vals, 2)
|
||||
F(g, "texCoord", "node", t)
|
||||
end
|
||||
local col = m.attrs.COLOR_0
|
||||
if col then
|
||||
local c = col.components
|
||||
local rgba = c >= 4 and x3d
|
||||
local cn = W(if rgba then "ColorRGBA" else "Color")
|
||||
local vals = {}
|
||||
local scale = if col.raw then (if col.type == "unorm8" then 255 elseif col.type == "unorm16" then 65535 else 1) else 1
|
||||
for i = 0, m.count - 1 do
|
||||
for k = 1, if rgba then 4 else 3 do
|
||||
table.insert(vals, (col.values[i * c + k] or 1) / scale)
|
||||
end
|
||||
end
|
||||
F(cn, "color", "mf", vals, if rgba then 4 else 3)
|
||||
F(g, "color", "node", cn)
|
||||
end
|
||||
F(g, "solid", "bool", not doubleSided)
|
||||
return g, nil
|
||||
end
|
||||
|
||||
-- Coordinate from POSITION, Color / ColorRGBA from COLOR_0 (lines and points)
|
||||
local function coordNode(prim: any): (WNode?, number)
|
||||
local pos = values(prim.attributes.POSITION)
|
||||
if not pos then
|
||||
return nil, 0
|
||||
end
|
||||
local nv, pc = prim.attributes.POSITION.count, prim.attributes.POSITION.components
|
||||
local p3 = {}
|
||||
for i = 0, nv - 1 do
|
||||
for k = 1, 3 do
|
||||
table.insert(p3, pos[i * pc + k] or 0)
|
||||
end
|
||||
end
|
||||
local coord = W("Coordinate")
|
||||
F(coord, "point", "mf", p3, 3)
|
||||
return coord, nv
|
||||
end
|
||||
local function colorNode(prim: any, nv: number, x3d: boolean): WNode?
|
||||
local acc = prim.attributes.COLOR_0
|
||||
local col = acc and values(acc)
|
||||
if not col then
|
||||
return nil
|
||||
end
|
||||
local c = acc.components
|
||||
local rgba = c >= 4 and x3d
|
||||
local vals = {}
|
||||
for i = 0, nv - 1 do
|
||||
for k = 1, if rgba then 4 else 3 do
|
||||
table.insert(vals, col[i * c + k] or 1)
|
||||
end
|
||||
end
|
||||
local cn = W(if rgba then "ColorRGBA" else "Color")
|
||||
F(cn, "color", "mf", vals, if rgba then 4 else 3)
|
||||
return cn
|
||||
end
|
||||
|
||||
local function lineSet(prim: any, x3d: boolean): (WNode?, string?)
|
||||
local coord, nv = coordNode(prim)
|
||||
if not coord then
|
||||
return nil, "lines without POSITION"
|
||||
end
|
||||
local ind: { number }
|
||||
if prim.indices then
|
||||
ind = values(prim.indices) or {}
|
||||
else
|
||||
ind = {}
|
||||
for i = 0, nv - 1 do
|
||||
ind[i + 1] = i
|
||||
end
|
||||
end
|
||||
local idx = {}
|
||||
local mode = prim.mode
|
||||
if mode == "lines" then
|
||||
for i = 1, #ind - 1, 2 do
|
||||
table.insert(idx, ind[i])
|
||||
table.insert(idx, ind[i + 1])
|
||||
table.insert(idx, -1)
|
||||
end
|
||||
else
|
||||
for _, v in ind do
|
||||
table.insert(idx, v)
|
||||
end
|
||||
if mode == "line_loop" and #ind > 0 then
|
||||
table.insert(idx, ind[1])
|
||||
end
|
||||
table.insert(idx, -1)
|
||||
end
|
||||
for _, v in idx do
|
||||
if v >= nv then
|
||||
return nil, "line index out of range"
|
||||
end
|
||||
end
|
||||
local g = W("IndexedLineSet")
|
||||
F(g, "coord", "node", coord)
|
||||
local cn = colorNode(prim, nv, x3d)
|
||||
if cn then
|
||||
F(g, "color", "node", cn)
|
||||
end
|
||||
F(g, "coordIndex", "mf", idx, 0)
|
||||
return g, nil
|
||||
end
|
||||
|
||||
local function pointSet(prim: any, x3d: boolean): (WNode?, string?)
|
||||
local coord, nv = coordNode(prim)
|
||||
if not coord then
|
||||
return nil, "points without POSITION"
|
||||
end
|
||||
local g = W("PointSet")
|
||||
F(g, "coord", "node", coord)
|
||||
local cn = colorNode(prim, nv, x3d)
|
||||
if cn then
|
||||
F(g, "color", "node", cn)
|
||||
end
|
||||
return g, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ materials
|
||||
local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2" }
|
||||
|
||||
local function textureUrl(scene: any, i: number, o: Options, written: { [number]: string }): string?
|
||||
if written[i] then
|
||||
return written[i]
|
||||
end
|
||||
local tex = scene.textures[i]
|
||||
if not tex then
|
||||
return nil
|
||||
end
|
||||
local url = tex.uri
|
||||
if tex.data and type(o.files) == "table" then
|
||||
local base = string.match(o.name or "model", "([^/\\]+)$") or "model"
|
||||
base = string.gsub(base, "%.[^.]*$", "")
|
||||
local ext = EXT[tex.mime or ""] or (url and string.match(url, "%.(%w+)$")) or "png"
|
||||
local file = if url and not string.find(url, "^data:") and not string.find(url, "[/\\]") then url else format("%s_%d.%s", base, i, ext)
|
||||
o.files[file] = tex.data
|
||||
url = file
|
||||
end
|
||||
if url then
|
||||
written[i] = url
|
||||
end
|
||||
return url
|
||||
end
|
||||
|
||||
local function appearance(scene: any, mi: number, o: Options, written: { [number]: string }): WNode
|
||||
local m = scene.materials[mi]
|
||||
local app = W("Appearance")
|
||||
local mat = W("Material")
|
||||
local x = m.extras and m.extras.vrml or {}
|
||||
local c = m.baseColor or { 1, 1, 1, 1 }
|
||||
F(mat, "diffuseColor", "sf", { c[1], c[2], c[3] })
|
||||
local e = m.emissive or { 0, 0, 0 }
|
||||
if e[1] ~= 0 or e[2] ~= 0 or e[3] ~= 0 then
|
||||
F(mat, "emissiveColor", "sf", { e[1], e[2], e[3] })
|
||||
end
|
||||
if type(x.specularColor) == "table" then
|
||||
F(mat, "specularColor", "sf", x.specularColor)
|
||||
end
|
||||
local sh = x.shininess
|
||||
if type(sh) ~= "number" then
|
||||
local r = math.max(m.roughness or 1, 1e-3)
|
||||
sh = math.clamp((2 / (r * r) - 2) / 128, 0, 1)
|
||||
end
|
||||
F(mat, "shininess", "sf", { sh })
|
||||
if type(x.ambientIntensity) == "number" then
|
||||
F(mat, "ambientIntensity", "sf", { x.ambientIntensity })
|
||||
end
|
||||
if (c[4] or 1) < 1 then
|
||||
F(mat, "transparency", "sf", { 1 - c[4] })
|
||||
end
|
||||
F(app, "material", "node", mat)
|
||||
local ref = m.baseColorTexture
|
||||
if ref and type(ref.texture) == "number" then
|
||||
local url = textureUrl(scene, ref.texture, o, written)
|
||||
local img = scene.textures[ref.texture] and scene.textures[ref.texture].image
|
||||
if url or (img and img.format == "rgba8" and img.width * img.height <= 2 ^ 20) then
|
||||
local it
|
||||
if url then
|
||||
it = W("ImageTexture")
|
||||
F(it, "url", "mstr", { url })
|
||||
else
|
||||
-- a decoded image only: PixelTexture (SFImage: width height 4, then 0xRRGGBBAA from the bottom row up)
|
||||
it = W("PixelTexture")
|
||||
local w, h = img.width, img.height
|
||||
local v = { w, h, 4 }
|
||||
for row = h - 1, 0, -1 do
|
||||
for x = 0, w - 1 do
|
||||
table.insert(v, buffer.readu32(img.pixels, (row * w + x) * 4))
|
||||
end
|
||||
end
|
||||
-- the pixels are little-endian RGBA bytes: swap to 0xRRGGBBAA
|
||||
for i = 4, #v do
|
||||
local p = v[i]
|
||||
v[i] = (p % 256) * 16777216 + (p // 256 % 256) * 65536 + (p // 65536 % 256) * 256 + p // 16777216
|
||||
end
|
||||
F(it, "image", "sf", v)
|
||||
end
|
||||
local s = scene.textures[ref.texture].sampler
|
||||
if s and s.wrapS == "clamp" then
|
||||
F(it, "repeatS", "bool", false)
|
||||
end
|
||||
if s and s.wrapT == "clamp" then
|
||||
F(it, "repeatT", "bool", false)
|
||||
end
|
||||
F(app, "texture", "node", it)
|
||||
local tf = ref.transform
|
||||
if tf then
|
||||
local tt = W("TextureTransform")
|
||||
if tf.offset then
|
||||
F(tt, "translation", "sf", tf.offset)
|
||||
end
|
||||
if tf.scale then
|
||||
F(tt, "scale", "sf", tf.scale)
|
||||
end
|
||||
if tf.rotation then
|
||||
F(tt, "rotation", "sf", { tf.rotation })
|
||||
end
|
||||
F(app, "textureTransform", "node", tt)
|
||||
end
|
||||
end
|
||||
end
|
||||
return app
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ the tree
|
||||
function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, string?)
|
||||
local x3d = o.encoding == "x3dv" or o.encoding == "xml"
|
||||
local name = namer()
|
||||
local nodeDef: { [number]: string } = {}
|
||||
local meshShapes: { [number]: { WNode } } = {}
|
||||
local appDef: { [any]: string } = {}
|
||||
local written: { [number]: string } = {}
|
||||
local failure: string? = nil
|
||||
|
||||
local function shapes(mi: number): { WNode }
|
||||
local done = meshShapes[mi]
|
||||
if done then
|
||||
-- USE the shapes written before
|
||||
local out = {}
|
||||
for _, s in done do
|
||||
table.insert(out, { type = "Shape", use = s.def, fields = {} })
|
||||
end
|
||||
return out
|
||||
end
|
||||
local mesh = scene.meshes[mi]
|
||||
local out = {}
|
||||
for pi, prim in (if mesh then mesh.primitives else {}) :: { any } do
|
||||
local mode = prim.mode or "triangles"
|
||||
local mat = if type(prim.material) == "number" then scene.materials[prim.material] else nil
|
||||
local geo, err
|
||||
if mode == "lines" or mode == "line_strip" or mode == "line_loop" then
|
||||
geo, err = lineSet(prim, x3d)
|
||||
elseif mode == "points" then
|
||||
geo, err = pointSet(prim, x3d)
|
||||
else
|
||||
geo, err = faceSet(prim, mat ~= nil and mat.doubleSided == true, o, x3d)
|
||||
end
|
||||
if err then
|
||||
failure = failure or err
|
||||
end
|
||||
if geo then
|
||||
local sh = W("Shape", name((mesh.name or "mesh") .. (if #mesh.primitives > 1 then "_" .. pi else ""), "Shape"))
|
||||
if mat then
|
||||
local key = prim.material
|
||||
if appDef[key] then
|
||||
F(sh, "appearance", "node", { type = "Appearance", use = appDef[key], fields = {} })
|
||||
else
|
||||
local app = appearance(scene, prim.material, o, written)
|
||||
app.def = name(mat.name, "Material")
|
||||
appDef[key] = app.def
|
||||
F(sh, "appearance", "node", app)
|
||||
end
|
||||
end
|
||||
F(sh, "geometry", "node", geo)
|
||||
table.insert(out, sh)
|
||||
end
|
||||
end
|
||||
meshShapes[mi] = out
|
||||
return out
|
||||
end
|
||||
|
||||
local visiting: { [number]: boolean } = {}
|
||||
local function transform(ni: number): WNode?
|
||||
local n = scene.nodes[ni]
|
||||
if type(n) ~= "table" or visiting[ni] then
|
||||
return nil
|
||||
end
|
||||
visiting[ni] = true
|
||||
local def = name(n.name, "Node")
|
||||
nodeDef[ni] = def
|
||||
local t = W("Transform", def)
|
||||
local tr, rot, sc = n.translation, n.rotation, n.scale
|
||||
if n.matrix then
|
||||
tr, rot, sc = Mat4.decompose(n.matrix)
|
||||
end
|
||||
if tr and (tr[1] ~= 0 or tr[2] ~= 0 or tr[3] ~= 0) then
|
||||
F(t, "translation", "sf", { tr[1], tr[2], tr[3] })
|
||||
end
|
||||
if rot then
|
||||
local aa = axisAngle(rot)
|
||||
if aa[4] ~= 0 then
|
||||
F(t, "rotation", "sf", aa)
|
||||
end
|
||||
end
|
||||
if sc and (sc[1] ~= 1 or sc[2] ~= 1 or sc[3] ~= 1) then
|
||||
F(t, "scale", "sf", { sc[1], sc[2], sc[3] })
|
||||
end
|
||||
local kids: { WNode } = {}
|
||||
if type(n.mesh) == "number" then
|
||||
for _, s in shapes(n.mesh) do
|
||||
table.insert(kids, s)
|
||||
end
|
||||
end
|
||||
local cam = if type(n.camera) == "number" then scene.cameras[n.camera] else nil
|
||||
if cam then
|
||||
local v
|
||||
if cam.type == "orthographic" and x3d then
|
||||
v = W("OrthoViewpoint")
|
||||
local xm, ym = cam.xmag or 1, cam.ymag or 1
|
||||
F(v, "fieldOfView", "sf", { -xm, -ym, xm, ym })
|
||||
else
|
||||
v = W("Viewpoint")
|
||||
F(v, "fieldOfView", "sf", { cam.yfov or 0.785398 })
|
||||
end
|
||||
F(v, "position", "sf", { 0, 0, 0 })
|
||||
if cam.name then
|
||||
F(v, "description", "str", cam.name)
|
||||
end
|
||||
table.insert(kids, v)
|
||||
end
|
||||
local l = if type(n.light) == "number" then scene.lights[n.light] else nil
|
||||
if l then
|
||||
local typ = if l.type == "directional" then "DirectionalLight" elseif l.type == "spot" then "SpotLight" else "PointLight"
|
||||
local ln = W(typ)
|
||||
local c = l.color or { 1, 1, 1 }
|
||||
F(ln, "color", "sf", { c[1], c[2], c[3] })
|
||||
F(ln, "intensity", "sf", { math.clamp(l.intensity or 1, 0, 1) })
|
||||
if typ ~= "PointLight" then
|
||||
F(ln, "direction", "sf", { 0, 0, -1 })
|
||||
end
|
||||
if typ ~= "DirectionalLight" then
|
||||
F(ln, "location", "sf", { 0, 0, 0 })
|
||||
F(ln, "radius", "sf", { l.range or 100 })
|
||||
end
|
||||
if typ == "SpotLight" then
|
||||
F(ln, "cutOffAngle", "sf", { l.outerCone or 0.785398 })
|
||||
F(ln, "beamWidth", "sf", { l.innerCone or 0 })
|
||||
end
|
||||
table.insert(kids, ln)
|
||||
end
|
||||
for _, c in n.children or {} do
|
||||
local ct = transform(c)
|
||||
if ct then
|
||||
table.insert(kids, ct)
|
||||
end
|
||||
end
|
||||
if #kids > 0 then
|
||||
F(t, "children", "nodes", kids)
|
||||
end
|
||||
visiting[ni] = nil
|
||||
return t
|
||||
end
|
||||
|
||||
local roots: { WNode } = {}
|
||||
local list = scene.roots
|
||||
if type(list) ~= "table" or #list == 0 then
|
||||
-- no roots: every node without a parent
|
||||
local child = {}
|
||||
for _, n in scene.nodes do
|
||||
for _, c in n.children or {} do
|
||||
child[c] = true
|
||||
end
|
||||
end
|
||||
list = {}
|
||||
for i = 1, #scene.nodes do
|
||||
if not child[i] then
|
||||
table.insert(list, i)
|
||||
end
|
||||
end
|
||||
end
|
||||
for _, ri in list do
|
||||
local t = transform(ri)
|
||||
if t then
|
||||
table.insert(roots, t)
|
||||
end
|
||||
end
|
||||
if #scene.nodes == 0 then
|
||||
for mi = 1, #scene.meshes do
|
||||
for _, s in shapes(mi) do
|
||||
table.insert(roots, s)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- animations: a TimeSensor per animation, an interpolator per channel
|
||||
local routes: { { string } } = {}
|
||||
for ai, anim in scene.animations or {} do
|
||||
local tmax = 0
|
||||
local chans = {}
|
||||
for _, ch in anim.channels or {} do
|
||||
local target = nodeDef[ch.node]
|
||||
if target and (ch.path == "translation" or ch.path == "rotation" or ch.path == "scale") then
|
||||
local input, output = values(ch.input), values(ch.output)
|
||||
if input and output and #input > 0 then
|
||||
tmax = math.max(tmax, input[#input])
|
||||
table.insert(chans, { ch, target, input, output })
|
||||
end
|
||||
end
|
||||
end
|
||||
if #chans > 0 then
|
||||
local cycle = if tmax > 0 then tmax else 1
|
||||
local ts = W("TimeSensor", name(anim.name, "Animation" .. ai))
|
||||
F(ts, "cycleInterval", "sf", { cycle })
|
||||
F(ts, "loop", "bool", true)
|
||||
table.insert(roots, ts)
|
||||
for k, c in chans do
|
||||
local ch, target, input, output = c[1], c[2], c[3], c[4]
|
||||
local rot = ch.path == "rotation"
|
||||
local it = W(if rot then "OrientationInterpolator" else "PositionInterpolator", name(ts.def .. "_" .. k, "Interpolator"))
|
||||
local keys = {}
|
||||
for i, tv in input do
|
||||
keys[i] = tv / cycle
|
||||
end
|
||||
local comps = if rot then 4 else 3
|
||||
local stride = #output // #input
|
||||
-- CUBICSPLINE stores in-tangent, value, out-tangent per key
|
||||
local off = if ch.interpolation == "CUBICSPLINE" and stride == comps * 3 then comps else 0
|
||||
local kv = {}
|
||||
for i = 0, #input - 1 do
|
||||
local v = {}
|
||||
for q = 1, comps do
|
||||
v[q] = output[i * stride + off + q] or 0
|
||||
end
|
||||
if rot then
|
||||
v = axisAngle(v)
|
||||
end
|
||||
for _, x in v do
|
||||
table.insert(kv, x)
|
||||
end
|
||||
end
|
||||
F(it, "key", "mf", keys, 0)
|
||||
F(it, "keyValue", "mf", kv, comps)
|
||||
table.insert(roots, it)
|
||||
table.insert(routes, { ts.def :: string, "fraction_changed", it.def :: string, "set_fraction" })
|
||||
table.insert(routes, { it.def :: string, "value_changed", target, "set_" .. ch.path })
|
||||
end
|
||||
end
|
||||
end
|
||||
if failure then
|
||||
return nil, nil, failure
|
||||
end
|
||||
return roots, routes, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ serializers
|
||||
local function numbers(vals: { number }, per: number?, indent: string): string
|
||||
local out = table.create(#vals)
|
||||
for i, v in vals do
|
||||
out[i] = fmt(v)
|
||||
end
|
||||
if per == 0 then
|
||||
-- index lists: one face per line
|
||||
local lines, cur = {}, {}
|
||||
for i, v in vals do
|
||||
table.insert(cur, out[i])
|
||||
if v == -1 then
|
||||
table.insert(lines, concat(cur, " "))
|
||||
cur = {}
|
||||
end
|
||||
end
|
||||
if #cur > 0 then
|
||||
table.insert(lines, concat(cur, " "))
|
||||
end
|
||||
return concat(lines, "\n" .. indent)
|
||||
end
|
||||
if per and per > 0 then
|
||||
local lines = {}
|
||||
for i = 1, #out, per do
|
||||
table.insert(lines, concat(out, " ", i, math.min(i + per - 1, #out)))
|
||||
end
|
||||
return concat(lines, ",\n" .. indent)
|
||||
end
|
||||
return concat(out, " ")
|
||||
end
|
||||
|
||||
local function quote(s: string): string
|
||||
return '"' .. string.gsub(s, '(["\\])', "\\%1") .. '"'
|
||||
end
|
||||
|
||||
local function classic(roots: { WNode }, routes: { { string } }, x3d: boolean): string
|
||||
local out = {}
|
||||
if x3d then
|
||||
table.insert(out, "#X3D V3.3 utf8\nPROFILE Interchange\n# written by rosetta\n")
|
||||
else
|
||||
table.insert(out, "#VRML V2.0 utf8\n# written by rosetta\n")
|
||||
end
|
||||
local function emit(n: WNode, ind: string): string
|
||||
if n.use then
|
||||
return "USE " .. n.use
|
||||
end
|
||||
local parts = { (if n.def then "DEF " .. n.def .. " " else "") .. n.type .. " {" }
|
||||
local ind2 = ind .. " "
|
||||
for _, f in n.fields do
|
||||
local fname, kind, v, per = f[1], f[2], f[3], f[4]
|
||||
local s
|
||||
if kind == "sf" then
|
||||
s = numbers(v, nil, ind2)
|
||||
elseif kind == "mf" then
|
||||
s = "[\n" .. ind2 .. " " .. numbers(v, per, ind2 .. " ") .. "\n" .. ind2 .. "]"
|
||||
elseif kind == "bool" then
|
||||
s = if v then "TRUE" else "FALSE"
|
||||
elseif kind == "str" then
|
||||
s = quote(v)
|
||||
elseif kind == "mstr" then
|
||||
local q = {}
|
||||
for i, x in v do
|
||||
q[i] = quote(x)
|
||||
end
|
||||
s = "[ " .. concat(q, " ") .. " ]"
|
||||
elseif kind == "node" then
|
||||
s = emit(v, ind2)
|
||||
else
|
||||
local q = {}
|
||||
for i, x in v do
|
||||
q[i] = ind2 .. " " .. emit(x, ind2 .. " ")
|
||||
end
|
||||
s = "[\n" .. concat(q, "\n") .. "\n" .. ind2 .. "]"
|
||||
end
|
||||
table.insert(parts, ind2 .. fname .. " " .. s)
|
||||
end
|
||||
table.insert(parts, ind .. "}")
|
||||
return concat(parts, "\n")
|
||||
end
|
||||
for _, r in roots do
|
||||
table.insert(out, emit(r, ""))
|
||||
end
|
||||
for _, r in routes do
|
||||
table.insert(out, format("ROUTE %s.%s TO %s.%s", r[1], r[2], r[3], r[4]))
|
||||
end
|
||||
return concat(out, "\n") .. "\n"
|
||||
end
|
||||
|
||||
-- the containerField a child element needs when it is not its type's default
|
||||
local DEFAULT = { Appearance = "appearance", Material = "material", ImageTexture = "texture", TextureTransform = "textureTransform", Coordinate = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", TextureCoordinate = "texCoord", IndexedFaceSet = "geometry", IndexedLineSet = "geometry", PointSet = "geometry" }
|
||||
|
||||
local function xml(roots: { WNode }, routes: { { string } }): (string?, string?)
|
||||
local function element(n: WNode, field: string): any
|
||||
local attrs = Types.object()
|
||||
local kids = {}
|
||||
if (DEFAULT[n.type] or "children") ~= field then
|
||||
Types.set(attrs, "containerField", field)
|
||||
end
|
||||
if n.use then
|
||||
Types.set(attrs, "USE", n.use)
|
||||
return Xml.element(n.type, attrs :: any)
|
||||
end
|
||||
if n.def then
|
||||
Types.set(attrs, "DEF", n.def)
|
||||
end
|
||||
for _, f in n.fields do
|
||||
local fname, kind, v, per = f[1], f[2], f[3], f[4]
|
||||
if kind == "sf" then
|
||||
Types.set(attrs, fname, numbers(v, nil, ""))
|
||||
elseif kind == "mf" then
|
||||
local s = numbers(v, per, "")
|
||||
Types.set(attrs, fname, (string.gsub(s, "\n", " ")))
|
||||
elseif kind == "bool" then
|
||||
Types.set(attrs, fname, if v then "true" else "false")
|
||||
elseif kind == "str" then
|
||||
Types.set(attrs, fname, v)
|
||||
elseif kind == "mstr" then
|
||||
local q = {}
|
||||
for i, x in v do
|
||||
q[i] = quote(x)
|
||||
end
|
||||
Types.set(attrs, fname, concat(q, " "))
|
||||
elseif kind == "node" then
|
||||
table.insert(kids, element(v, fname))
|
||||
else
|
||||
for _, x in v do
|
||||
table.insert(kids, element(x, fname))
|
||||
end
|
||||
end
|
||||
end
|
||||
return Xml.element(n.type, attrs :: any, kids)
|
||||
end
|
||||
local sceneKids = {}
|
||||
for _, r in roots do
|
||||
table.insert(sceneKids, element(r, "children"))
|
||||
end
|
||||
for _, r in routes do
|
||||
local a = Types.object()
|
||||
Types.set(a, "fromNode", r[1])
|
||||
Types.set(a, "fromField", r[2])
|
||||
Types.set(a, "toNode", r[3])
|
||||
Types.set(a, "toField", r[4])
|
||||
table.insert(sceneKids, Xml.element("ROUTE", a :: any))
|
||||
end
|
||||
local ra = Types.object()
|
||||
Types.set(ra, "profile", "Interchange")
|
||||
Types.set(ra, "version", "3.3")
|
||||
local meta = Types.object()
|
||||
Types.set(meta, "name", "generator")
|
||||
Types.set(meta, "content", "rosetta")
|
||||
local root = Xml.element("X3D", ra :: any, { Xml.element("head", nil, { Xml.element("meta", meta :: any) }), Xml.element("Scene", nil, sceneKids) })
|
||||
local s, err = Xml.encode(Xml.document(root, { version = "1.0", encoding = "UTF-8" }), { indent = 2 })
|
||||
if not s then
|
||||
return nil, if err then err.message else "xml"
|
||||
end
|
||||
return s, nil
|
||||
end
|
||||
|
||||
-- text(scene, opts) -> the file text
|
||||
function Write.text(scene: any, o: Options): (string?, string?)
|
||||
local roots, routes, err = Write.graph(scene, o)
|
||||
if not roots or not routes then
|
||||
return nil, err
|
||||
end
|
||||
if o.encoding == "xml" then
|
||||
return xml(roots, routes)
|
||||
end
|
||||
return classic(roots, routes, o.encoding == "x3dv"), nil
|
||||
end
|
||||
|
||||
return Write
|
||||
@@ -0,0 +1,238 @@
|
||||
--!strict
|
||||
-- codecs/model/Vrml/Xml: the X3D XML encoding (ISO/IEC 19776-1) to the node graph of codecs/model/Vrml/Parse, so one
|
||||
-- builder serves .wrl, .x3dv and .x3d. Written from the specification; no third-party code. Elements are nodes;
|
||||
-- attributes stay raw strings (the builder parses them as the type it expects); child nodes go into their
|
||||
-- containerField (or the default field of their type: geometry, appearance, material, coord, ...); DEF / USE; ROUTE;
|
||||
-- ProtoDeclare (ProtoInterface fields with value attributes or child nodes, ProtoBody, IS / connect) and
|
||||
-- ProtoInstance (fieldValue) are expanded through Parse.expand; ExternProtoDeclare instances stay plain nodes; head /
|
||||
-- meta, UNIT, component and the profile go into the graph header. Never throws.
|
||||
local Xml = require("@rosetta/codecs/text/Xml")
|
||||
local Parse = require("@rosetta/codecs/model/Vrml/Parse")
|
||||
|
||||
local VXml = {}
|
||||
|
||||
local GEOMETRY = {
|
||||
"Box", "Sphere", "Cone", "Cylinder", "IndexedFaceSet", "IndexedLineSet", "LineSet", "PointSet", "ElevationGrid",
|
||||
"Extrusion", "Text", "IndexedTriangleSet", "TriangleSet", "IndexedTriangleFanSet", "TriangleFanSet",
|
||||
"IndexedTriangleStripSet", "TriangleStripSet", "IndexedQuadSet", "QuadSet", "Arc2D", "ArcClose2D", "Circle2D",
|
||||
"Disk2D", "Polyline2D", "Polypoint2D", "Rectangle2D", "TriangleSet2D", "GeoElevationGrid", "NurbsPatchSurface",
|
||||
}
|
||||
local CONTAINER: { [string]: string } = {
|
||||
Appearance = "appearance", Material = "material", PhysicalMaterial = "material", TwoSidedMaterial = "material",
|
||||
UnlitMaterial = "material", ImageTexture = "texture", PixelTexture = "texture", MovieTexture = "texture",
|
||||
MultiTexture = "texture", ImageCubeMapTexture = "texture", TextureTransform = "textureTransform",
|
||||
Coordinate = "coord", CoordinateDouble = "coord", Normal = "normal", Color = "color", ColorRGBA = "color",
|
||||
TextureCoordinate = "texCoord", MultiTextureCoordinate = "texCoord", TextureCoordinateGenerator = "texCoord",
|
||||
FontStyle = "fontStyle", TextureProperties = "textureProperties", FillProperties = "fillProperties",
|
||||
LineProperties = "lineProperties",
|
||||
}
|
||||
for _, g in GEOMETRY do
|
||||
CONTAINER[g] = "geometry"
|
||||
end
|
||||
|
||||
local function container(el: Xml.Node, typ: string): string
|
||||
local c = el.attrs.containerField
|
||||
if type(c) == "string" and c ~= "" then
|
||||
return c
|
||||
end
|
||||
if string.sub(typ, 1, 8) == "Metadata" then
|
||||
return "metadata"
|
||||
end
|
||||
return CONTAINER[typ] or "children"
|
||||
end
|
||||
|
||||
function VXml.graph(doc: Xml.Node): (Parse.Graph?, string?)
|
||||
local root = doc.root or doc
|
||||
if type(root) ~= "table" or Xml.localName(root.name) ~= "X3D" then
|
||||
return nil, "no <X3D> root element"
|
||||
end
|
||||
local graph: Parse.Graph = { roots = {}, routes = {}, header = { x3d = true, xml = true }, meta = {}, components = {}, units = {}, protos = {} }
|
||||
graph.header.version, graph.header.profile = root.attrs.version, root.attrs.profile
|
||||
local defs: { [string]: Parse.Node } = {}
|
||||
local protos = graph.protos
|
||||
local routes = graph.routes
|
||||
local depth = 0
|
||||
local failure: string? = nil
|
||||
|
||||
local convert: (el: Xml.Node) -> Parse.Node?
|
||||
local function route(el: Xml.Node)
|
||||
local a = el.attrs
|
||||
local from, to = defs[a.fromNode or ""], defs[a.toNode or ""]
|
||||
local ff, tf = a.fromField, a.toField
|
||||
if from and to and type(ff) == "string" and type(tf) == "string" then
|
||||
table.insert(routes, { from = from, fromField = ff, to = to, toField = tf })
|
||||
end
|
||||
end
|
||||
local declare: (el: Xml.Node, extern: boolean) -> ()
|
||||
|
||||
-- the child elements of a node into its fields
|
||||
local function children(el: Xml.Node, node: Parse.Node)
|
||||
for _, ch in el.children do
|
||||
if type(ch) ~= "table" or string.sub(ch.name, 1, 1) == "#" then
|
||||
continue
|
||||
end
|
||||
local name = Xml.localName(ch.name)
|
||||
if name == "ROUTE" then
|
||||
route(ch)
|
||||
elseif name == "IS" then
|
||||
for _, c in Xml.children(ch, "connect") do
|
||||
local nf, pf = c.attrs.nodeField, c.attrs.protoField
|
||||
if nf and pf then
|
||||
node.fields[nf] = { is = pf }
|
||||
end
|
||||
end
|
||||
elseif name == "ProtoDeclare" or name == "ExternProtoDeclare" then
|
||||
declare(ch, name == "ExternProtoDeclare")
|
||||
elseif name == "field" or name == "fieldValue" then
|
||||
continue -- Script / shader interfaces
|
||||
else
|
||||
local c = convert(ch)
|
||||
if c then
|
||||
local f = container(ch, if name == "ProtoInstance" then "" else name)
|
||||
local list = node.fields[f]
|
||||
if type(list) ~= "table" or (list :: any).is then
|
||||
list = {}
|
||||
node.fields[f] = list
|
||||
end
|
||||
table.insert(list, c)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- a field value of ProtoInterface / fieldValue: the value attribute, or the child nodes
|
||||
local function fieldValue(el: Xml.Node): any
|
||||
if el.attrs.value ~= nil then
|
||||
return el.attrs.value
|
||||
end
|
||||
local list = {}
|
||||
for _, ch in el.children do
|
||||
if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then
|
||||
local c = convert(ch)
|
||||
if c then
|
||||
table.insert(list, c)
|
||||
end
|
||||
end
|
||||
end
|
||||
return list
|
||||
end
|
||||
|
||||
function declare(el: Xml.Node, extern: boolean)
|
||||
local name = el.attrs.name
|
||||
if not name then
|
||||
return
|
||||
end
|
||||
local proto: Parse.Proto = { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil }
|
||||
local iface = if extern then el else Xml.child(el, "ProtoInterface")
|
||||
if iface then
|
||||
for _, f in Xml.children(iface, "field") do
|
||||
if f.attrs.name then
|
||||
proto.fields[f.attrs.name] = fieldValue(f)
|
||||
end
|
||||
end
|
||||
end
|
||||
local bodyEl = Xml.child(el, "ProtoBody")
|
||||
if bodyEl and not extern then
|
||||
local outerDefs, outerRoutes = defs, routes
|
||||
defs, routes = {}, proto.routes
|
||||
for _, ch in bodyEl.children do
|
||||
if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then
|
||||
local nm = Xml.localName(ch.name)
|
||||
if nm == "ROUTE" then
|
||||
route(ch)
|
||||
elseif nm == "ProtoDeclare" or nm == "ExternProtoDeclare" then
|
||||
declare(ch, nm == "ExternProtoDeclare")
|
||||
else
|
||||
local c = convert(ch)
|
||||
if c then
|
||||
table.insert(proto.body, c)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
defs, routes = outerDefs, outerRoutes
|
||||
end
|
||||
protos[name] = proto
|
||||
end
|
||||
|
||||
function convert(el: Xml.Node): Parse.Node?
|
||||
local a = el.attrs
|
||||
if a.USE then
|
||||
return defs[a.USE]
|
||||
end
|
||||
depth += 1
|
||||
if depth > 200 then
|
||||
failure = failure or "limit: nodes nested deeper than 200"
|
||||
depth -= 1
|
||||
return nil
|
||||
end
|
||||
local typ = Xml.localName(el.name)
|
||||
local node: any
|
||||
if typ == "ProtoInstance" then
|
||||
local proto = protos[a.name or ""]
|
||||
local values = {}
|
||||
for _, fv in Xml.children(el, "fieldValue") do
|
||||
if fv.attrs.name then
|
||||
values[fv.attrs.name] = fieldValue(fv)
|
||||
end
|
||||
end
|
||||
local inst = proto and Parse.expand(proto, values, a.DEF, routes)
|
||||
node = inst or { type = a.name or "ProtoInstance", def = a.DEF, fields = values }
|
||||
else
|
||||
node = { type = typ, def = a.DEF, fields = {} }
|
||||
for k, v in a do
|
||||
if k ~= "DEF" and k ~= "USE" and k ~= "containerField" and k ~= "class" and not string.find(k, ":", 1, true) then
|
||||
node.fields[k] = v
|
||||
end
|
||||
end
|
||||
children(el, node)
|
||||
end
|
||||
depth -= 1
|
||||
if a.DEF then
|
||||
defs[a.DEF] = node
|
||||
end
|
||||
return node
|
||||
end
|
||||
|
||||
for _, ch in root.children do
|
||||
if type(ch) ~= "table" then
|
||||
continue
|
||||
end
|
||||
local name = Xml.localName(ch.name)
|
||||
if name == "head" then
|
||||
for _, h in ch.children do
|
||||
if type(h) == "table" then
|
||||
local hn = Xml.localName(h.name)
|
||||
if hn == "meta" and h.attrs.name then
|
||||
graph.meta[h.attrs.name] = h.attrs.content or ""
|
||||
elseif hn == "component" and h.attrs.name then
|
||||
table.insert(graph.components, h.attrs.name .. ":" .. (h.attrs.level or "1"))
|
||||
elseif hn == "unit" and h.attrs.category then
|
||||
graph.units[h.attrs.category] = { name = h.attrs.name or "", factor = tonumber(h.attrs.conversionFactor) or 1 }
|
||||
end
|
||||
end
|
||||
end
|
||||
elseif name == "Scene" then
|
||||
local scene: Parse.Node = { type = "Scene", fields = {} }
|
||||
children(ch, scene)
|
||||
local list = scene.fields.children
|
||||
if type(list) == "table" then
|
||||
graph.roots = list
|
||||
end
|
||||
for f, v in scene.fields do
|
||||
-- a top-level node with another containerField still shows
|
||||
if f ~= "children" and type(v) == "table" then
|
||||
for _, x in v do
|
||||
table.insert(graph.roots, x)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if failure then
|
||||
return nil, failure
|
||||
end
|
||||
return graph, nil
|
||||
end
|
||||
|
||||
return VXml
|
||||
@@ -0,0 +1,160 @@
|
||||
--!strict
|
||||
-- codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML,
|
||||
-- .x3dv classic): one parser for the classic encoding (codecs/model/Vrml/Parse), one for the XML encoding
|
||||
-- (codecs/model/Vrml/Xml over codecs/text/Xml), both into the same node graph, and one builder from the graph to a
|
||||
-- Scene (codecs/model/Vrml/Build, codecs/model/Vrml/Geometry). Gzipped files (.wrz / .x3dz / .x3dvz) are inflated
|
||||
-- first. New code, written from ISO/IEC 14772-1 (VRML97), ISO/IEC 19775-1 (X3D) and its encodings 19776-1 / -2.
|
||||
--
|
||||
-- local graph, err = Vrml.graph(bytes) -- classic or XML, by content
|
||||
-- local scene, err2 = Vrml.decode(bytes, { format = "vrml", files = { ["tex.png"] = png } })
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Deflate = require("@rosetta/codecs/compress/Deflate")
|
||||
local XmlCodec = require("@rosetta/codecs/text/Xml")
|
||||
local Parse = require("@rosetta/codecs/model/Vrml/Parse")
|
||||
local VXml = require("@rosetta/codecs/model/Vrml/Xml")
|
||||
local Build = require("@rosetta/codecs/model/Vrml/Build")
|
||||
local Write = require("@rosetta/codecs/model/Vrml/Write")
|
||||
|
||||
local Vrml = {}
|
||||
|
||||
export type Graph = Parse.Graph
|
||||
export type Node = Parse.Node
|
||||
export type Options = Build.Options & {
|
||||
files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string)
|
||||
resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths)
|
||||
maxBytes: number?, -- the inflated size of a gzipped file (default 2^28)
|
||||
}
|
||||
|
||||
-- the bytes as text: gzip inflated, UTF-8 BOM dropped
|
||||
local function text(data: buffer | string, maxBytes: number?): (string?, Err.Err?)
|
||||
local b = if type(data) == "string" then buffer.fromstring(data) else data
|
||||
if buffer.len(b) >= 2 and buffer.readu8(b, 0) == 0x1F and buffer.readu8(b, 1) == 0x8B then
|
||||
local out, err = Deflate.gunzip(b)
|
||||
if not out then
|
||||
return nil, err
|
||||
end
|
||||
if buffer.len(out) > (maxBytes or 2 ^ 28) then
|
||||
return nil, Err.new(Err.LIMIT, "inflated file over maxBytes")
|
||||
end
|
||||
b = out
|
||||
end
|
||||
local s = buffer.tostring(b)
|
||||
if string.sub(s, 1, 3) == "\239\187\191" then
|
||||
s = string.sub(s, 4)
|
||||
end
|
||||
return s, nil
|
||||
end
|
||||
|
||||
local function code(msg: string): string
|
||||
if string.find(msg, "unsupported", 1, true) then
|
||||
return Err.UNSUPPORTED
|
||||
elseif string.find(msg, "limit", 1, true) then
|
||||
return Err.LIMIT
|
||||
elseif string.find(msg, "unterminated", 1, true) then
|
||||
return Err.TRUNCATED
|
||||
end
|
||||
return Err.CORRUPT
|
||||
end
|
||||
|
||||
-- parse(text) -> the graph of a classic-encoding file (VRML97 / .x3dv)
|
||||
function Vrml.parse(s: string): (Graph?, Err.Err?)
|
||||
local g, msg = Parse.parse(s)
|
||||
if not g then
|
||||
return nil, Err.new(code(msg or "parse error"), msg or "parse error")
|
||||
end
|
||||
return g, nil
|
||||
end
|
||||
|
||||
-- parseXml(text | XML document) -> the graph of an X3D XML file
|
||||
function Vrml.parseXml(src: any): (Graph?, Err.Err?)
|
||||
local doc = src
|
||||
if type(src) == "string" then
|
||||
local d, err = XmlCodec.decode(src)
|
||||
if not d and err and err.code == Err.TRUNCATED and not string.find(src, "</X3D>", 1, true) then
|
||||
-- VTK's X3D exporter leaves the root element open
|
||||
d = XmlCodec.decode(src .. "\n</X3D>\n")
|
||||
end
|
||||
if not d then
|
||||
return nil, err
|
||||
end
|
||||
doc = d
|
||||
end
|
||||
local g, msg = VXml.graph(doc)
|
||||
if not g then
|
||||
return nil, Err.new(code(msg or "bad X3D"), msg or "bad X3D")
|
||||
end
|
||||
return g, nil
|
||||
end
|
||||
|
||||
-- graph(bytes, opts?) -> the graph of either encoding (XML when the text starts with "<"); binary X3D is UNSUPPORTED
|
||||
function Vrml.graph(data: buffer | string, opts: Options?): (Graph?, Err.Err?)
|
||||
local s, err = text(data, opts and opts.maxBytes)
|
||||
if not s then
|
||||
return nil, err
|
||||
end
|
||||
local head = string.match(s, "^%s*(.?)")
|
||||
if head == "<" then
|
||||
return Vrml.parseXml(s)
|
||||
end
|
||||
if string.sub(s, 1, 4) == "\224\0\0\1" or string.sub(s, 1, 4) == "$EXI" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "binary X3D (Fast Infoset / EXI encoding)")
|
||||
end
|
||||
return Vrml.parse(s)
|
||||
end
|
||||
|
||||
-- fetcher(opts) -> fetch(uri) -> buffer?: opts.files (uri or base name) / opts.resolve
|
||||
function Vrml.fetcher(opts: Options?): (uri: string) -> buffer?
|
||||
return function(uri: string): buffer?
|
||||
if not opts then
|
||||
return nil
|
||||
end
|
||||
local v: any = nil
|
||||
if type(opts.files) == "table" then
|
||||
v = opts.files[uri] or opts.files[string.match(uri, "([^/\\]+)$") or uri]
|
||||
end
|
||||
if v == nil and type(opts.resolve) == "function" then
|
||||
local ok, res = pcall(opts.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
|
||||
|
||||
-- build(graph, opts?) -> Scene
|
||||
function Vrml.build(graph: Graph, opts: Options?): (Types.Scene?, Err.Err?)
|
||||
local o: any = table.clone(opts or {})
|
||||
o.fetch = o.fetch or Vrml.fetcher(opts)
|
||||
o.load = o.load or function(data: buffer): (any, string?)
|
||||
local g, err = Vrml.graph(data, opts)
|
||||
return g, if err then err.message else nil
|
||||
end
|
||||
local scene, msg = Build.scene(graph, o)
|
||||
if not scene then
|
||||
return nil, Err.new(code(msg or "build failed"), msg or "build failed")
|
||||
end
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
-- decode(bytes, opts?) -> Scene: graph + build
|
||||
function Vrml.decode(data: buffer | string, opts: Options?): (Types.Scene?, Err.Err?)
|
||||
local g, err = Vrml.graph(data, opts)
|
||||
if not g then
|
||||
return nil, err
|
||||
end
|
||||
return Vrml.build(g, opts)
|
||||
end
|
||||
|
||||
-- encode(scene, opts?) -> text: opts.encoding "vrml97" (default) / "x3dv" / "xml"; texture bytes go into opts.files
|
||||
function Vrml.encode(scene: Types.Scene, opts: Write.Options?): (string?, Err.Err?)
|
||||
if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "table" or type(scene.meshes) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "needs a Scene")
|
||||
end
|
||||
local s, msg = Write.text(scene, opts or {})
|
||||
if not s then
|
||||
return nil, Err.new(Err.ARG, msg or "the scene could not be written")
|
||||
end
|
||||
return s, nil
|
||||
end
|
||||
|
||||
return Vrml
|
||||
Reference in new issue
Block a user