merge ws/3d: obj stl ply off vox gltf/glb, ops/MeshOps, codecs Base64/MeshFlatten, api sibling files + texture encoding
This commit is contained in:
commit
91eba2bc24
145 files changed
+16413
-17
No files matched your search
@@ -389,3 +389,85 @@ do
|
||||
Hdr.encode(f)
|
||||
end)
|
||||
end
|
||||
do
|
||||
-- 3D (ws-3d): a 400 x 400 grid mesh (160k vertices, 318k triangles) through our own writers, then the readers; a
|
||||
-- 128^3 noise voxel grid through VOX and greedy meshing
|
||||
local Types = require("@formats/Types")
|
||||
local MeshOps = require("@formats/ops/MeshOps")
|
||||
local Gltf = require("@formats/model/gltf")
|
||||
local Obj = require("@formats/model/obj")
|
||||
local Stl = require("@formats/model/stl")
|
||||
local Ply = require("@formats/model/ply")
|
||||
local Vox = require("@formats/model/vox")
|
||||
local N = 400
|
||||
local pos = Types.Scene.accessor(nil, "f32", 3, N * N)
|
||||
local uv = Types.Scene.accessor(nil, "f32", 2, N * N)
|
||||
for y = 0, N - 1 do
|
||||
for x = 0, N - 1 do
|
||||
local i = y * N + x
|
||||
buffer.writef32(pos.data, i * 12, x / N)
|
||||
buffer.writef32(pos.data, i * 12 + 4, math.sin(x * 0.1) * math.cos(y * 0.1) * 0.05)
|
||||
buffer.writef32(pos.data, i * 12 + 8, y / N)
|
||||
buffer.writef32(uv.data, i * 8, x / N)
|
||||
buffer.writef32(uv.data, i * 8 + 4, y / N)
|
||||
end
|
||||
end
|
||||
local ind = Types.Scene.accessor(nil, "u32", 1, (N - 1) * (N - 1) * 6)
|
||||
local k = 0
|
||||
for y = 0, N - 2 do
|
||||
for x = 0, N - 2 do
|
||||
local a = y * N + x
|
||||
for _, v in { a, a + N, a + 1, a + 1, a + N, a + N + 1 } do
|
||||
buffer.writeu32(ind.data, k * 4, v)
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
local prim = { attributes = { POSITION = pos, TEXCOORD_0 = uv }, indices = ind, mode = "triangles" } :: any
|
||||
MeshOps.computeNormals(prim)
|
||||
local scene = Types.Scene.fromPrimitive(prim, "grid")
|
||||
bench("meshops computeNormals 318k tris", 3, buffer.len(pos.data), function()
|
||||
MeshOps.computeNormals(prim)
|
||||
end)
|
||||
local glb = assert(Gltf.encode(scene, { binary = true }))
|
||||
bench("gltf glb decode (" .. buffer.len(glb) // 1000 .. " KB)", 5, buffer.len(glb), function()
|
||||
Gltf.decode(Bytes.reader(glb))
|
||||
end)
|
||||
bench("gltf glb encode", 3, buffer.len(glb), function()
|
||||
Gltf.encode(scene, { binary = true })
|
||||
end)
|
||||
local obj = assert(Obj.encode(scene))
|
||||
bench("obj decode (" .. buffer.len(obj) // 1000 .. " KB)", 2, buffer.len(obj), function()
|
||||
Obj.decode(Bytes.reader(obj))
|
||||
end)
|
||||
bench("obj encode", 2, buffer.len(obj), function()
|
||||
Obj.encode(scene)
|
||||
end)
|
||||
local stl = assert(Stl.encode(scene))
|
||||
bench("stl binary decode (" .. buffer.len(stl) // 1000 .. " KB)", 5, buffer.len(stl), function()
|
||||
Stl.decode(Bytes.reader(stl))
|
||||
end)
|
||||
local ply = assert(Ply.encode(scene))
|
||||
bench("ply binary decode (" .. buffer.len(ply) // 1000 .. " KB)", 5, buffer.len(ply), function()
|
||||
Ply.decode(Bytes.reader(ply))
|
||||
end)
|
||||
local V = 128
|
||||
local grid = Types.Voxels.new(V, V, V)
|
||||
for z = 0, V - 1 do
|
||||
for y = 0, V - 1 do
|
||||
for x = 0, V - 1 do
|
||||
local h = (math.sin(x * 0.11) + math.cos(y * 0.07) + 2) * V / 8 + z * 0
|
||||
if z < h then
|
||||
Types.Voxels.set(grid, x, y, z, 1 + (x // 8 + y // 8) % 6)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local vox = assert(Vox.encode(grid))
|
||||
bench("vox decode (" .. buffer.len(vox) // 1000 .. " KB)", 5, buffer.len(vox), function()
|
||||
Vox.decode(Bytes.reader(vox))
|
||||
end)
|
||||
bench("greedy mesh 128^3 (MB of cells)", 3, V * V * V, function()
|
||||
MeshOps.voxelsToPrimitive(grid)
|
||||
end)
|
||||
end
|
||||
@@ -0,0 +1,34 @@
|
||||
-- tools/fixtures/_gltf_encode: run by tools/fixtures/gltf.py (luau CLI, repo root): decodes every glTF case with our
|
||||
-- reader and encodes it with our writer as .glb and as .gltf with an external .bin and image files, printing
|
||||
-- "<file>\t<hex>" lines for the reference tools (assimp, trimesh) to read back. Files: rt_<case>.glb, rt_<case>.gltf.
|
||||
local Gltf = require("@formats/model/gltf")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/gltf_cases")
|
||||
|
||||
local HEX = {}
|
||||
for i = 0, 255 do
|
||||
HEX[i] = string.format("%02x", i)
|
||||
end
|
||||
local function hex(s: string): string
|
||||
local out = table.create(#s)
|
||||
for i = 1, #s do
|
||||
out[i] = HEX[string.byte(s, i)]
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
for i, c in Cases do
|
||||
local scene, err = Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files })
|
||||
if scene then
|
||||
local glb = assert(Gltf.encode(scene, { binary = true }))
|
||||
print(string.format("rt_%d.glb\t%s", i, hex(buffer.tostring(glb))))
|
||||
local files = {}
|
||||
local gltf = assert(Gltf.encode(scene, { external = true, files = files, name = "rt_" .. i .. ".gltf" }))
|
||||
print(string.format("rt_%d.gltf\t%s", i, hex(buffer.tostring(gltf))))
|
||||
for name, data in files do
|
||||
print(name .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data)))
|
||||
end
|
||||
else
|
||||
print("skipped " .. c.name .. ": " .. tostring(err))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,69 @@
|
||||
# Shared helpers for the model fixture generators (obj.py, gltf.py): reference tools through nix.
|
||||
# assimp_info(ctx, paths, raw?) -> [ { meshes, materials, vertices, faces, nodes, min, max, perMesh = [ { vertices, faces } ] } ]
|
||||
# trimesh_metrics(ctx, paths) -> [ { area, faces, bounds, volume? } ] (trimesh, process=False, every geometry merged)
|
||||
# luau_encode(ctx, script) -> { name: bytes }: runs a Luau script (repo-relative, .luaurc aliases) that prints
|
||||
# "<name>\t<hex>" lines: how a generator gets our encoder's output for the reference tools to read back.
|
||||
import json, os, re, subprocess, tempfile, shutil
|
||||
|
||||
FLOAT = r"(-?[\d.]+(?:e[-+]?\d+)?|-?nan|-?inf)"
|
||||
|
||||
|
||||
def assimp_info(ctx, paths, raw=False):
|
||||
# raw: `assimp info -r` (no post-processing: no joined vertices, no merged identical meshes)
|
||||
out = []
|
||||
for p in paths:
|
||||
try:
|
||||
txt = ctx.nix("assimp", ["assimp", "info", p] + (["-r"] if raw else [])).decode("utf-8", "replace")
|
||||
except subprocess.CalledProcessError:
|
||||
out.append({"failed": True})
|
||||
continue
|
||||
|
||||
def num(label):
|
||||
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
|
||||
return int(m.group(1)) if m else -1
|
||||
|
||||
def point(label):
|
||||
m = re.search(label + r"\s+\(" + FLOAT + " " + FLOAT + " " + FLOAT + r"\)", txt)
|
||||
return [float(m.group(i)) for i in (1, 2, 3)] if m else []
|
||||
|
||||
per = [{"vertices": int(a), "faces": int(c)} for a, b, c in re.findall(r"^\s+\d+ \(.*?\): \[(\d+) / (\d+) / (\d+) \|", txt, re.M)]
|
||||
out.append({
|
||||
"meshes": num("Meshes"), "materials": num("Materials"), "vertices": num("Vertices"), "faces": num("Faces"),
|
||||
"nodes": num("Nodes"), "min": point("Minimum point"), "max": point("Maximum point"), "perMesh": per,
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
TRIMESH = r"""
|
||||
import json, sys, trimesh, numpy as np
|
||||
res = []
|
||||
for p in json.loads(sys.stdin.read()):
|
||||
try:
|
||||
m = trimesh.load(p, force="mesh", process=False)
|
||||
d = {"area": float(m.area), "faces": int(len(m.faces)), "bounds": [float(v) for v in np.asarray(m.bounds).ravel()] if len(m.faces) else []}
|
||||
except Exception as e:
|
||||
d = {"failed": True}
|
||||
res.append(d)
|
||||
print(json.dumps(res))
|
||||
"""
|
||||
|
||||
|
||||
def trimesh_metrics(ctx, paths):
|
||||
out = ctx.python(["trimesh", "numpy", "networkx", "lxml", "pillow"], TRIMESH, input=json.dumps(paths).encode())
|
||||
return json.loads(out)
|
||||
|
||||
|
||||
def luau_encode(ctx, script):
|
||||
exe = shutil.which("luau")
|
||||
cmd = [exe, script] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script]
|
||||
res = subprocess.run(cmd, cwd=ctx.root, capture_output=True, check=True)
|
||||
files = {}
|
||||
for line in res.stdout.decode().split("\n"):
|
||||
if "\t" in line:
|
||||
name, hexdata = line.split("\t", 1)
|
||||
files[name] = bytes.fromhex(hexdata.strip())
|
||||
return files
|
||||
|
||||
|
||||
def tempdir():
|
||||
return tempfile.mkdtemp(prefix="formats-model-")
|
||||
@@ -0,0 +1,32 @@
|
||||
-- tools/fixtures/_obj_encode: run by tools/fixtures/obj.py (luau CLI, repo root): decodes every OBJ case with our
|
||||
-- reader, encodes it again with our writer and prints "<file>\t<hex>" lines (the OBJ, its .mtl, textures) for the
|
||||
-- reference tools (assimp, trimesh) to read back.
|
||||
local Obj = require("@formats/model/obj")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/obj_cases")
|
||||
|
||||
local HEX = {}
|
||||
for i = 0, 255 do
|
||||
HEX[i] = string.format("%02x", i)
|
||||
end
|
||||
local function hex(s: string): string
|
||||
local out = table.create(#s)
|
||||
for i = 1, #s do
|
||||
out[i] = HEX[string.byte(s, i)]
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
for _, c in Cases do
|
||||
local scene, err = Obj.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files })
|
||||
if not scene then
|
||||
error(c.name .. ": " .. tostring(err))
|
||||
end
|
||||
local name = "rt_" .. c.name
|
||||
local files = {}
|
||||
local out = assert(Obj.encode(scene, { name = name, files = files }))
|
||||
print(name .. "\t" .. hex(buffer.tostring(out)))
|
||||
for fname, data in files do
|
||||
print(fname .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data)))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,56 @@
|
||||
-- tools/fixtures/_off_encode.luau: run by tools/fixtures/off.py under the luau CLI (no file I/O): encodes the scenes of
|
||||
-- tests/gen/off_scenes with each listed option set ("default" = {}, "plain" = no colours / normals / texcoords) and
|
||||
-- prints "<scene>/<encoding> <hex>" lines, which the fixture step hands to trimesh, assimp and its own reader.
|
||||
local Off = require("@formats/model/off")
|
||||
local Types = require("@formats/Types")
|
||||
local Scenes = require("@tests/gen/off_scenes")
|
||||
|
||||
local function build(spec: any): Types.Scene
|
||||
local scene = Types.Scene.new()
|
||||
for i, m in spec.meshes do
|
||||
local prims = {}
|
||||
for _, p in m.prims do
|
||||
local attrs = {}
|
||||
for name, a in p.attrs do
|
||||
attrs[name] = Types.Scene.accessor(buffer.fromstring(a[3]), a[1], a[2], p.count)
|
||||
end
|
||||
local prim: any = { attributes = attrs, mode = p.mode }
|
||||
if p.indices then
|
||||
prim.indices = Types.Scene.accessor(buffer.fromstring(p.indices), "u32", 1, #p.indices // 4)
|
||||
end
|
||||
if p.faces then
|
||||
prim.faces = Types.Scene.accessor(buffer.fromstring(p.faces), "u32", 1, #p.faces // 4)
|
||||
end
|
||||
if p.faceColors then
|
||||
prim.extras = { faceColors = Types.Scene.accessor(buffer.fromstring(p.faceColors), "unorm8", 4, #p.faceColors // 4) }
|
||||
end
|
||||
table.insert(prims, prim)
|
||||
end
|
||||
scene.meshes[i] = { primitives = prims }
|
||||
end
|
||||
for i, n in spec.nodes do
|
||||
scene.nodes[i] = { mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix }
|
||||
end
|
||||
scene.roots = spec.roots
|
||||
return scene
|
||||
end
|
||||
|
||||
local function hex(b: buffer): string
|
||||
local out = table.create(buffer.len(b))
|
||||
for i = 0, buffer.len(b) - 1 do
|
||||
out[i + 1] = string.format("%02x", buffer.readu8(b, i))
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
local OPTS: { [string]: any } = { default = {}, plain = { colors = false, normals = false, texcoords = false } }
|
||||
for _, spec in Scenes do
|
||||
local scene = build(spec)
|
||||
for e in spec.encodings do
|
||||
local b, err = Off.encode(scene, OPTS[e])
|
||||
if not b then
|
||||
error(spec.name .. "/" .. e .. ": " .. tostring(err))
|
||||
end
|
||||
print(spec.name .. "/" .. e .. " " .. hex(b))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,32 @@
|
||||
# OFF reference values (run by tools/fixtures/off.py through ctx.python(["trimesh", "numpy"], ...), python -I).
|
||||
# stdin: JSON {"dir": tmp, "make": [name], "read": [name]}
|
||||
# stdout: JSON {name (only the files trimesh reads): {"vertices": n, "pos_crc": crc of the f32 vertices, "faces": [[...]] or None (n-gons over 4)}}
|
||||
# make: OFF files written by trimesh (an icosphere, a capsule)
|
||||
# read: every file read with trimesh.exchange.off.load_off (positions; faces when all are triangles / quads, the
|
||||
# only polygons trimesh keeps as they are)
|
||||
import json, os, sys, zlib
|
||||
import numpy as np
|
||||
import trimesh
|
||||
from trimesh.exchange import off as toff
|
||||
|
||||
req = json.load(sys.stdin)
|
||||
d = req["dir"]
|
||||
out = {}
|
||||
for name in req["make"]:
|
||||
m = trimesh.creation.icosphere(subdivisions=2, radius=3.0) if "ico" in name else trimesh.creation.capsule(height=2.0, radius=0.5)
|
||||
with open(os.path.join(d, name), "w") as f:
|
||||
f.write(toff.export_off(m, digits=9))
|
||||
for name in req["read"]:
|
||||
try:
|
||||
with open(os.path.join(d, name), "rb") as f:
|
||||
r = toff.load_off(f)
|
||||
except Exception: # noqa: BLE001 - trimesh fails on polygons of more than 4 vertices: no reference then
|
||||
continue
|
||||
v = np.asarray(r["vertices"], dtype=np.float64).reshape(-1, 3)
|
||||
res = {"vertices": len(v), "pos_crc": zlib.crc32(v.astype("<f4").tobytes())}
|
||||
faces = r.get("faces")
|
||||
res["tris"] = int(len(faces)) if faces is not None and len(np.shape(faces)) == 2 and np.shape(faces)[1] == 3 else -1
|
||||
if res["tris"] >= 0:
|
||||
res["faces"] = [[int(x) for x in f] for f in np.asarray(faces)]
|
||||
out[name] = res
|
||||
json.dump(out, sys.stdout)
|
||||
@@ -0,0 +1,52 @@
|
||||
-- tools/fixtures/_ply_encode.luau: run by tools/fixtures/ply.py under the luau CLI (no file I/O): encodes the scenes of
|
||||
-- tests/gen/ply_scenes in the three encodings and prints "<scene>/<encoding> <hex>" lines, which the fixture step
|
||||
-- hands to plyfile and assimp.
|
||||
local Ply = require("@formats/model/ply")
|
||||
local Types = require("@formats/Types")
|
||||
local Scenes = require("@tests/gen/ply_scenes")
|
||||
|
||||
local function build(spec: any): Types.Scene
|
||||
local scene = Types.Scene.new()
|
||||
for i, m in spec.meshes do
|
||||
local prims = {}
|
||||
for _, p in m.prims do
|
||||
local attrs = {}
|
||||
for name, a in p.attrs do
|
||||
attrs[name] = Types.Scene.accessor(buffer.fromstring(a[3]), a[1], a[2], p.count)
|
||||
end
|
||||
local prim: any = { attributes = attrs, mode = p.mode }
|
||||
if p.indices then
|
||||
prim.indices = Types.Scene.accessor(buffer.fromstring(p.indices), "u32", 1, #p.indices // 4)
|
||||
end
|
||||
if p.faces then
|
||||
prim.faces = Types.Scene.accessor(buffer.fromstring(p.faces), "u32", 1, #p.faces // 4)
|
||||
end
|
||||
table.insert(prims, prim)
|
||||
end
|
||||
scene.meshes[i] = { primitives = prims }
|
||||
end
|
||||
for i, n in spec.nodes do
|
||||
scene.nodes[i] = { mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix }
|
||||
end
|
||||
scene.roots = spec.roots
|
||||
return scene
|
||||
end
|
||||
|
||||
local function hex(b: buffer): string
|
||||
local out = table.create(buffer.len(b))
|
||||
for i = 0, buffer.len(b) - 1 do
|
||||
out[i + 1] = string.format("%02x", buffer.readu8(b, i))
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
for _, spec in Scenes do
|
||||
local scene = build(spec)
|
||||
for _, e in { "ascii", "binary_little_endian", "binary_big_endian" } do
|
||||
local b, err = Ply.encode(scene, { format = e })
|
||||
if not b then
|
||||
error(spec.name .. "/" .. e .. ": " .. tostring(err))
|
||||
end
|
||||
print(spec.name .. "/" .. e .. " " .. hex(b))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,307 @@
|
||||
# PLY reference values (run by tools/fixtures/ply.py through ctx.python(["plyfile", "numpy"], ...), python -I).
|
||||
# stdin: JSON {"dir": tmp, "make": [name], "ref": [name], "ours": [{name, file, scene}]}
|
||||
# stdout: JSON {"ref": {name: {...}}, "ours": {name: [ok, detail]}}
|
||||
# make: PLY files written by plyfile (every encoding, every property type, odd orders, lists, extra elements)
|
||||
# ref: every file read with plyfile, mapped to the library's Scene conventions here (independently of the Luau
|
||||
# code): CRC-32 of each attribute's packed little-endian bytes, the triangulated / polygon indices, face
|
||||
# properties, raw elements, comments
|
||||
# ours: our encoder's output read back by plyfile and compared property by property with the scene it came from
|
||||
import json, os, sys, zlib
|
||||
import numpy as np
|
||||
from plyfile import PlyData, PlyElement
|
||||
|
||||
req = json.load(sys.stdin)
|
||||
d = req["dir"]
|
||||
out = {"ref": {}, "ours": {}}
|
||||
|
||||
|
||||
def path(n):
|
||||
return os.path.join(d, n)
|
||||
|
||||
|
||||
def crc(a):
|
||||
return zlib.crc32(np.ascontiguousarray(a).tobytes())
|
||||
|
||||
|
||||
def le(a):
|
||||
a = np.asarray(a)
|
||||
return a.astype(a.dtype.newbyteorder("<"))
|
||||
|
||||
|
||||
def sphere(rng, n):
|
||||
"""a UV sphere with n x n quads (poles as triangle fans): vertices, quads and triangles"""
|
||||
vs = [(0.0, 0.0, 1.0)]
|
||||
for i in range(1, n):
|
||||
th = np.pi * i / n
|
||||
for j in range(n):
|
||||
ph = 2 * np.pi * j / n
|
||||
vs.append((np.sin(th) * np.cos(ph), np.sin(th) * np.sin(ph), np.cos(th)))
|
||||
vs.append((0.0, 0.0, -1.0))
|
||||
faces = []
|
||||
for j in range(n):
|
||||
faces.append([0, 1 + j, 1 + (j + 1) % n])
|
||||
for i in range(n - 2):
|
||||
for j in range(n):
|
||||
a = 1 + i * n + j
|
||||
b = 1 + i * n + (j + 1) % n
|
||||
faces.append([a, a + n, b + n, b])
|
||||
last = len(vs) - 1
|
||||
for j in range(n):
|
||||
a = 1 + (n - 2) * n
|
||||
faces.append([last, a + (j + 1) % n, a + j])
|
||||
return np.array(vs) * (1 + 0.05 * rng.random((len(vs), 1))), faces
|
||||
|
||||
|
||||
def faces_el(faces, ct="u1", it="i4", name="vertex_indices", extra=()):
|
||||
dt = [(name, "O")] + [(n, t) for n, t, _ in extra]
|
||||
a = np.empty(len(faces), dtype=dt)
|
||||
a[name] = [np.array(f, dtype=it) for f in faces]
|
||||
for n, t, vals in extra:
|
||||
a[n] = vals
|
||||
return PlyElement.describe(a, "face", len_types={name: ct}, val_types={name: it[1:] if it[0] in "<>" else it})
|
||||
|
||||
|
||||
def make(name):
|
||||
seed = sum(map(ord, name))
|
||||
rng = np.random.default_rng(seed)
|
||||
comments, obj_info = [], []
|
||||
if name == "cube-le.ply":
|
||||
v = np.array([(x, y, z) for x in (0, 1) for y in (0, 1) for z in (0, 1)], dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")])
|
||||
quads = [[0, 1, 3, 2], [4, 6, 7, 5], [0, 4, 5, 1], [2, 3, 7, 6], [0, 2, 6, 4], [1, 5, 7, 3]]
|
||||
tris = [t for q in quads for t in ([q[0], q[1], q[2]], [q[0], q[2], q[3]])]
|
||||
els = [PlyElement.describe(v, "vertex"), faces_el(tris)]
|
||||
text, byte_order = False, "<"
|
||||
elif name == "colors-be.ply":
|
||||
pos, faces = sphere(rng, 12)
|
||||
n = len(pos)
|
||||
v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("nx", "f4"), ("ny", "f4"), ("nz", "f4"), ("red", "u1"),
|
||||
("green", "u1"), ("blue", "u1"), ("alpha", "u1"), ("quality", "f4"), ("flags", "u2")])
|
||||
v["x"], v["y"], v["z"] = pos.T
|
||||
nn = pos / np.linalg.norm(pos, axis=1)[:, None]
|
||||
v["nx"], v["ny"], v["nz"] = nn.T
|
||||
for c in ("red", "green", "blue", "alpha"):
|
||||
v[c] = rng.integers(0, 256, n)
|
||||
v["quality"] = rng.random(n)
|
||||
v["flags"] = rng.integers(0, 65536, n)
|
||||
els = [PlyElement.describe(v, "vertex"), faces_el(faces, "u1", "u4")]
|
||||
comments = ["made by plyfile", "big endian, quads and triangles"]
|
||||
text, byte_order = False, ">"
|
||||
elif name == "ascii-mixed.ply":
|
||||
n = 40
|
||||
v = np.empty(n, dtype=[("red", "u1"), ("z", "f8"), ("y", "f8"), ("x", "f8"), ("s", "f4"), ("t", "f4"), ("intensity", "i1"), ("id", "i4")])
|
||||
v["red"] = rng.integers(0, 256, n)
|
||||
for c in ("x", "y", "z"):
|
||||
v[c] = rng.random(n) * 20 - 10
|
||||
v["s"], v["t"] = rng.random(n), rng.random(n)
|
||||
v["intensity"] = rng.integers(-128, 128, n)
|
||||
v["id"] = rng.integers(-2 ** 31, 2 ** 31, n)
|
||||
faces = [list(rng.choice(n, size=int(rng.integers(3, 7)), replace=False)) for _ in range(25)]
|
||||
f = faces_el(faces, "u1", "i4", "vertex_index", extra=[("material", "u1", rng.integers(0, 4, 25)), ("weight", "f4", rng.random(25))])
|
||||
e = np.empty(10, dtype=[("vertex1", "i4"), ("vertex2", "i4"), ("crease", "u1")])
|
||||
e["vertex1"], e["vertex2"], e["crease"] = rng.integers(0, n, 10), rng.integers(0, n, 10), rng.integers(0, 256, 10)
|
||||
m = np.empty(3, dtype=[("params", "O"), ("index", "i2")])
|
||||
m["params"] = [np.array(rng.random(k), dtype="f4") for k in (2, 0, 5)]
|
||||
m["index"] = [-1, 0, 7]
|
||||
els = [PlyElement.describe(v, "vertex"), f, PlyElement.describe(e, "edge"),
|
||||
PlyElement.describe(m, "material", len_types={"params": "u1"}, val_types={"params": "f4"})]
|
||||
comments = ["ascii with odd property order", ""]
|
||||
obj_info = ["num_cols 5", "num_rows 8"]
|
||||
text, byte_order = True, "="
|
||||
elif name == "points-le.ply":
|
||||
n = 500
|
||||
v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("red", "u1"), ("green", "u1"), ("blue", "u1")])
|
||||
for c in ("x", "y", "z"):
|
||||
v[c] = rng.random(n) * 100
|
||||
for c in ("red", "green", "blue"):
|
||||
v[c] = rng.integers(0, 256, n)
|
||||
els = [PlyElement.describe(v, "vertex")]
|
||||
text, byte_order = False, "<"
|
||||
elif name == "points-ascii-float.ply":
|
||||
n = 60
|
||||
v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("red", "f4"), ("green", "f4"), ("blue", "f4"), ("u", "f4"), ("v", "f4")])
|
||||
for c in v.dtype.names:
|
||||
v[c] = rng.random(n)
|
||||
els = [PlyElement.describe(v, "vertex")]
|
||||
text, byte_order = True, "="
|
||||
elif name == "types-be.ply":
|
||||
n = 400
|
||||
types = [("a", "i1"), ("b", "u1"), ("c", "i2"), ("d", "u2"), ("e", "i4"), ("f", "u4"), ("g", "f4"), ("h", "f8")]
|
||||
v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")] + types)
|
||||
v["x"], v["y"] = np.cos(np.arange(n) * 2 * np.pi / n), np.sin(np.arange(n) * 2 * np.pi / n)
|
||||
v["z"] = 0
|
||||
for nm, t in types:
|
||||
info = np.iinfo(t) if t[0] in "iu" else None
|
||||
v[nm] = rng.integers(info.min, info.max, n, endpoint=True, dtype=t) if info else rng.standard_normal(n) * 1e3
|
||||
faces = [list(range(n - 1, 99, -1)), list(range(0, 100))] # a 300-gon (ushort count) and a 100-gon
|
||||
els = [PlyElement.describe(v, "vertex"), faces_el(faces, "u2", "i4")]
|
||||
text, byte_order = False, ">"
|
||||
elif name == "big-le.ply":
|
||||
pos, faces = sphere(rng, 180)
|
||||
tris = [t for q in faces for t in (([q[0], q[1], q[2]], [q[0], q[2], q[3]]) if len(q) == 4 else ([q[0], q[1], q[2]],))]
|
||||
v = np.empty(len(pos), dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")])
|
||||
v["x"], v["y"], v["z"] = pos.T
|
||||
els = [PlyElement.describe(v, "vertex"), faces_el(tris, "u1", "i4")]
|
||||
text, byte_order = False, "<"
|
||||
elif name == "tristrips.ply":
|
||||
v = np.array([(i, i % 2, 0) for i in range(8)], dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")])
|
||||
s = np.empty(1, dtype=[("vertex_indices", "O")])
|
||||
s["vertex_indices"] = [np.array([0, 1, 2, 3, 4, -1, 4, 5, 6, 7], dtype="i4")]
|
||||
els = [PlyElement.describe(v, "vertex"), PlyElement.describe(s, "tristrips", len_types={"vertex_indices": "i4"}, val_types={"vertex_indices": "i4"})]
|
||||
text, byte_order = False, "<"
|
||||
else:
|
||||
raise ValueError(name)
|
||||
PlyData(els, text=text, byte_order=byte_order, comments=comments, obj_info=obj_info).write(path(name))
|
||||
|
||||
|
||||
for name in req["make"]:
|
||||
make(name)
|
||||
|
||||
ACC = {"i1": "i8", "u1": "u8", "i2": "i16", "u2": "u16", "i4": "i32", "u4": "u32", "f4": "f32", "f8": "f64"}
|
||||
PAIRS = [("u", "v"), ("s", "t"), ("texture_u", "texture_v"), ("texture_s", "texture_t")]
|
||||
|
||||
|
||||
def kind(a):
|
||||
return np.dtype(a.dtype).str[1:]
|
||||
|
||||
|
||||
def index_list(f):
|
||||
for n in ("vertex_indices", "vertex_index"):
|
||||
if n in f.data.dtype.names and f.properties[[p.name for p in f.properties].index(n)].__class__.__name__ == "PlyListProperty":
|
||||
return n
|
||||
return None
|
||||
|
||||
|
||||
def reference(name):
|
||||
ply = PlyData.read(path(name))
|
||||
v = ply["vertex"].data
|
||||
names = v.dtype.names
|
||||
taken = set()
|
||||
attrs = {}
|
||||
|
||||
def group(attr, cols, acc_type, dt, fill=None):
|
||||
arr = np.stack([v[c].astype(dt) for c in cols] + ([np.full(len(v), fill, dtype=dt)] if fill is not None else []), axis=1)
|
||||
attrs[attr] = {"type": acc_type, "components": arr.shape[1], "crc": crc(le(arr))}
|
||||
taken.update(cols)
|
||||
|
||||
if all(c in names for c in "xyz"):
|
||||
group("POSITION", ["x", "y", "z"], "f32", "<f4")
|
||||
if all(c in names for c in ("nx", "ny", "nz")) and all(kind(v[c])[0] == "f" for c in ("nx", "ny", "nz")):
|
||||
group("NORMAL", ["nx", "ny", "nz"], "f32", "<f4")
|
||||
if all(c in names for c in ("red", "green", "blue")):
|
||||
cols = ["red", "green", "blue"] + (["alpha"] if "alpha" in names else [])
|
||||
ks = {"f" if kind(v[c])[0] == "f" else kind(v[c]) for c in cols}
|
||||
if ks == {"u1"}:
|
||||
group("COLOR_0", cols, "unorm8", "u1", None if "alpha" in names else 255)
|
||||
elif ks == {"u2"}:
|
||||
group("COLOR_0", cols, "unorm16", "<u2", None if "alpha" in names else 65535)
|
||||
elif ks == {"f"}:
|
||||
group("COLOR_0", cols, "f32", "<f4", None if "alpha" in names else 1.0)
|
||||
for a, b in PAIRS:
|
||||
if a in names and b in names and kind(v[a])[0] == "f" and kind(v[b])[0] == "f":
|
||||
group("TEXCOORD_0", [a, b], "f32", "<f4")
|
||||
break
|
||||
for c in names:
|
||||
if c not in taken:
|
||||
attrs["_" + c] = {"type": ACC[kind(v[c])], "components": 1, "crc": crc(le(v[c]))}
|
||||
encoding = "ascii" if ply.text else ("binary_big_endian" if ply.byte_order == ">" else "binary_little_endian")
|
||||
res = {"vertices": len(v), "attrs": attrs, "encoding": encoding,
|
||||
"comments": list(ply.comments), "objInfo": list(ply.obj_info), "order": [e.name for e in ply.elements]}
|
||||
face = None
|
||||
if "face" in ply:
|
||||
f = ply["face"]
|
||||
il = index_list(f)
|
||||
if il:
|
||||
face = f
|
||||
if face is not None and len(face.data):
|
||||
lists = [np.asarray(x, dtype=np.int64) for x in face.data[il]]
|
||||
sizes = [len(x) for x in lists]
|
||||
corners = np.concatenate(lists) if lists else np.zeros(0, dtype=np.int64)
|
||||
res["faces"] = len(lists)
|
||||
res["corners_crc"] = crc(corners.astype("<u4"))
|
||||
res["sizes_crc"] = crc(np.array(sizes, dtype="<u4"))
|
||||
tris, fot = [], []
|
||||
for i, x in enumerate(lists):
|
||||
for k in range(1, len(x) - 1):
|
||||
tris += [x[0], x[k], x[k + 1]]
|
||||
fot.append(i)
|
||||
res["tri_crc"] = crc(np.array(tris, dtype="<u4"))
|
||||
res["tris"] = len(tris) // 3
|
||||
res["fot_crc"] = crc(np.array(fot, dtype="<u4"))
|
||||
res["allTri"] = all(s == 3 for s in sizes)
|
||||
fa = {}
|
||||
for p in face.properties:
|
||||
if p.name == il:
|
||||
continue
|
||||
col = face.data[p.name]
|
||||
if p.__class__.__name__ == "PlyListProperty":
|
||||
items = np.concatenate([np.asarray(x) for x in col]) if len(col) else np.zeros(0)
|
||||
fa[p.name] = {"list": True, "sizes_crc": crc(np.array([len(x) for x in col], dtype="<u4")),
|
||||
"items_crc": crc(le(np.asarray(items, dtype=np.dtype(p.val_dtype))))}
|
||||
else:
|
||||
fa[p.name] = {"type": ACC[kind(col)], "crc": crc(le(col))}
|
||||
res["faceAttributes"] = fa
|
||||
else:
|
||||
res["faces"] = 0
|
||||
els = []
|
||||
for e in ply.elements:
|
||||
if e.name == "vertex" or (face is not None and e is face):
|
||||
continue
|
||||
props = []
|
||||
for p in e.properties:
|
||||
col = e.data[p.name]
|
||||
if p.__class__.__name__ == "PlyListProperty":
|
||||
vd = np.dtype(p.val_dtype)
|
||||
items = np.concatenate([np.asarray(x, dtype=vd) for x in col]) if len(col) else np.zeros(0, dtype=vd)
|
||||
props.append({"name": p.name, "list": True, "sizes_crc": crc(np.array([len(x) for x in col], dtype="<u4")),
|
||||
"values_crc": crc(le(items))})
|
||||
else:
|
||||
props.append({"name": p.name, "crc": crc(le(col))})
|
||||
els.append({"name": e.name, "count": len(e.data), "props": props})
|
||||
res["elements"] = els
|
||||
return res
|
||||
|
||||
|
||||
for name in req["ref"]:
|
||||
out["ref"][name] = reference(name)
|
||||
|
||||
# our encoder's output: every expected vertex property (name, kind, values) and the faces
|
||||
for o in req["ours"]:
|
||||
name = o["name"]
|
||||
try:
|
||||
ply = PlyData.read(path(o["file"]))
|
||||
v = ply["vertex"].data
|
||||
ok, detail = True, "%d vertices" % len(v)
|
||||
want_names = [p["name"] for p in o["props"]]
|
||||
if list(v.dtype.names) != want_names:
|
||||
ok, detail = False, "vertex properties %s, want %s" % (list(v.dtype.names), want_names)
|
||||
else:
|
||||
for p in o["props"]:
|
||||
got = np.asarray(v[p["name"]])
|
||||
want = np.frombuffer(bytes.fromhex(p["values"]), dtype=p["dtype"])
|
||||
if kind(got) != np.dtype(p["dtype"]).str[1:]:
|
||||
ok, detail = False, "%s: type %s, want %s" % (p["name"], kind(got), p["dtype"])
|
||||
break
|
||||
if p.get("tol"):
|
||||
if got.shape != want.shape or float(np.abs(got.astype(np.float64) - want).max(initial=0)) > p["tol"]:
|
||||
ok, detail = False, "%s: values differ" % p["name"]
|
||||
break
|
||||
elif not np.array_equal(got, want):
|
||||
ok, detail = False, "%s: values differ" % p["name"]
|
||||
break
|
||||
if ok:
|
||||
if o.get("faces") is None:
|
||||
if "face" in ply:
|
||||
ok, detail = False, "a point cloud with a face element"
|
||||
else:
|
||||
f = ply["face"].data
|
||||
il = "vertex_indices" if "vertex_indices" in f.dtype.names else "vertex_index"
|
||||
got = [list(map(int, x)) for x in f[il]]
|
||||
if got != o["faces"]:
|
||||
ok, detail = False, "faces differ"
|
||||
else:
|
||||
detail += ", %d faces" % len(got)
|
||||
out["ours"][name] = [ok, detail]
|
||||
except Exception as e: # noqa: BLE001 - a reference failure is a verdict
|
||||
out["ours"][name] = [False, "plyfile: %s" % e]
|
||||
|
||||
json.dump(out, sys.stdout)
|
||||
@@ -0,0 +1,56 @@
|
||||
-- tools/fixtures/_stl_encode.luau: run by tools/fixtures/stl.py under the luau CLI (no file I/O): encodes the scenes of
|
||||
-- tests/gen/stl_scenes with every encoding they list and prints "<scene>/<encoding> <hex>" lines, which the fixture
|
||||
-- step hands to trimesh and assimp.
|
||||
local Stl = require("@formats/model/stl")
|
||||
local Types = require("@formats/Types")
|
||||
local Scenes = require("@tests/gen/stl_scenes")
|
||||
|
||||
local function acc(s: string, t: string, comps: number, count: number): Types.Accessor
|
||||
return Types.Scene.accessor(buffer.fromstring(s), t, comps, count)
|
||||
end
|
||||
|
||||
local function build(spec: any): Types.Scene
|
||||
local scene = Types.Scene.new()
|
||||
for i, m in spec.meshes do
|
||||
local prims = {}
|
||||
for _, p in m.prims do
|
||||
local prim: any = { attributes = { POSITION = acc(p.pos, p.posType or "f32", 3, p.count) }, mode = p.mode }
|
||||
if p.indices then
|
||||
prim.indices = acc(p.indices, "u32", 1, #p.indices // 4)
|
||||
end
|
||||
if p.faces then
|
||||
prim.faces = acc(p.faces, "u32", 1, #p.faces // 4)
|
||||
end
|
||||
if p.color then
|
||||
prim.attributes.COLOR_0 = acc(p.color, "unorm8", 4, p.count)
|
||||
end
|
||||
table.insert(prims, prim)
|
||||
end
|
||||
scene.meshes[i] = { name = m.name, primitives = prims }
|
||||
end
|
||||
for i, n in spec.nodes do
|
||||
scene.nodes[i] = { name = n.name, mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix }
|
||||
end
|
||||
scene.roots = spec.roots
|
||||
return scene
|
||||
end
|
||||
|
||||
local function hex(b: buffer): string
|
||||
local out = table.create(buffer.len(b))
|
||||
for i = 0, buffer.len(b) - 1 do
|
||||
out[i + 1] = string.format("%02x", buffer.readu8(b, i))
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
local OPTS: { [string]: any } = { binary = {}, ascii = { ascii = true }, viscam = { colors = "viscam" }, magics = { colors = "magics" } }
|
||||
for _, spec in Scenes do
|
||||
local scene = build(spec)
|
||||
for _, e in spec.encodings do
|
||||
local b, err = Stl.encode(scene, OPTS[e])
|
||||
if not b then
|
||||
error(spec.name .. "/" .. e .. ": " .. tostring(err))
|
||||
end
|
||||
print(spec.name .. "/" .. e .. " " .. hex(b))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,112 @@
|
||||
# STL reference values (run by tools/fixtures/stl.py through ctx.python(["trimesh", "numpy"], ...), python -I).
|
||||
# stdin: JSON {"dir": tmp, "make": [[name, kind, file_type, seed]], "ref": [name], "ours": [{name, file, ...}]}
|
||||
# stdout: JSON {"ref": {name: {...}}, "ours": {name: [ok, detail]}}
|
||||
# make: meshes made and exported by trimesh itself (binary / ascii STL)
|
||||
# ref: every file read with trimesh.exchange.stl.load_stl (the raw arrays, no processing): facet count, CRC-32 of
|
||||
# the f32 triangle vertices / facet normals (as the file has them), area, bounds, the raw attribute words
|
||||
# ours: our encoder's output read back by trimesh and compared with the expected world-space triangles
|
||||
import json, os, sys, zlib
|
||||
import numpy as np
|
||||
import trimesh
|
||||
from trimesh.exchange import stl as tstl
|
||||
|
||||
req = json.load(sys.stdin)
|
||||
d = req["dir"]
|
||||
out = {"ref": {}, "ours": {}}
|
||||
|
||||
|
||||
def path(n):
|
||||
return os.path.join(d, n)
|
||||
|
||||
|
||||
for name, kind, ftype, seed in req["make"]:
|
||||
rng = np.random.default_rng(seed)
|
||||
if kind == "icosphere":
|
||||
m = trimesh.creation.icosphere(subdivisions=3, radius=2.5)
|
||||
elif kind == "box":
|
||||
m = trimesh.creation.box(extents=(1.5, 2.0, 0.25))
|
||||
elif kind == "capsule":
|
||||
m = trimesh.creation.capsule(height=3.0, radius=0.7)
|
||||
else:
|
||||
tri = (rng.random((1500, 3, 3)) * 200 - 100).astype(np.float32)
|
||||
m = trimesh.Trimesh(vertices=tri.reshape(-1, 3), faces=np.arange(4500).reshape(-1, 3), process=False)
|
||||
data = m.export(file_type=ftype)
|
||||
with open(path(name), "wb") as f:
|
||||
f.write(data.encode() if isinstance(data, str) else data)
|
||||
|
||||
|
||||
def load(name):
|
||||
with open(path(name), "rb") as f:
|
||||
r = tstl.load_stl(f)
|
||||
if "geometry" in r: # several solids
|
||||
parts = list(r["geometry"].values())
|
||||
if not parts:
|
||||
return np.zeros((0, 3)), np.zeros((0, 3), dtype=np.int64), np.zeros((0, 3)), None
|
||||
vs, fs, ns, off = [], [], [], 0
|
||||
for g in parts:
|
||||
vs.append(g["vertices"])
|
||||
fs.append(np.asarray(g["faces"]) + off)
|
||||
ns.append(g["face_normals"])
|
||||
off += len(g["vertices"])
|
||||
# trimesh does not read normals written on the "outer loop" line: no normals then
|
||||
nrm = None if any(x is None for x in ns) else np.concatenate(ns)
|
||||
return np.concatenate(vs), np.concatenate(fs), nrm, None
|
||||
attr = r.get("face_attributes", {}).get("stl")
|
||||
return np.asarray(r["vertices"]), np.asarray(r["faces"]), np.asarray(r["face_normals"]), attr
|
||||
|
||||
|
||||
def crc(a, dt):
|
||||
return zlib.crc32(np.ascontiguousarray(np.asarray(a).astype(dt)).tobytes())
|
||||
|
||||
|
||||
for name in req["ref"]:
|
||||
v, f, n, attr = load(name)
|
||||
tri = v[f].astype(np.float32) # (n, 3, 3)
|
||||
m = trimesh.Trimesh(vertices=v, faces=f, process=False)
|
||||
res = {
|
||||
"facets": int(len(f)),
|
||||
"pos_crc": crc(tri, "<f4"),
|
||||
"area": float(m.area) if len(f) else 0.0,
|
||||
"bounds": [float(x) for x in (m.bounds.reshape(-1) if len(f) else np.zeros(6))],
|
||||
}
|
||||
if n is not None:
|
||||
res["nrm_crc"] = crc(np.repeat(np.asarray(n, dtype=np.float32), 3, axis=0), "<f4")
|
||||
if attr is not None:
|
||||
res["attr"] = [int(x) for x in attr]
|
||||
out["ref"][name] = res
|
||||
|
||||
# our encoder's files
|
||||
for o in req["ours"]:
|
||||
name = o["name"]
|
||||
try:
|
||||
v, f, n, attr = load(o["file"])
|
||||
tri = v[f].astype(np.float32).reshape(-1, 9)
|
||||
want = np.frombuffer(bytes.fromhex(o["expect"]), dtype="<f4").reshape(-1, 9)
|
||||
if tri.shape != want.shape:
|
||||
out["ours"][name] = [False, "facet count %s, want %s" % (tri.shape, want.shape)]
|
||||
continue
|
||||
tol = 0 if o["exact"] else 1e-5 * max(1.0, float(np.abs(want).max()))
|
||||
err = float(np.abs(tri.astype(np.float64) - want.astype(np.float64)).max()) if len(want) else 0.0
|
||||
if err > tol:
|
||||
out["ours"][name] = [False, "positions differ by %g" % err]
|
||||
continue
|
||||
# the stored facet normals: the right-hand rule normal of each triangle
|
||||
t = want.astype(np.float64).reshape(-1, 3, 3)
|
||||
cn = np.cross(t[:, 1] - t[:, 0], t[:, 2] - t[:, 0])
|
||||
ln = np.linalg.norm(cn, axis=1)
|
||||
cn[ln > 0] /= ln[ln > 0, None]
|
||||
nerr = float(np.abs(np.asarray(n, dtype=np.float64) - cn).max()) if len(want) else 0.0
|
||||
if nerr > 1e-4:
|
||||
out["ours"][name] = [False, "facet normals differ by %g" % nerr]
|
||||
continue
|
||||
if "colors" in o:
|
||||
want_words = o["colors"]
|
||||
got = [int(x) for x in attr] if attr is not None else []
|
||||
if got != want_words:
|
||||
out["ours"][name] = [False, "attribute words differ"]
|
||||
continue
|
||||
out["ours"][name] = [True, "%d facets, max error %g" % (len(want), err)]
|
||||
except Exception as e: # noqa: BLE001 - a reference failure is a verdict
|
||||
out["ours"][name] = [False, "trimesh: %s" % e]
|
||||
|
||||
json.dump(out, sys.stdout)
|
||||
@@ -0,0 +1,13 @@
|
||||
# Base64 fixtures (tools/fixtures.py): random byte strings of every length 0..70 plus a few large ones, with Python's
|
||||
# base64 (standard, URL-safe, unpadded) as the reference.
|
||||
# tests/gen/base64_cases.luau { data, std, url, nopad }
|
||||
import base64
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(3)
|
||||
cases = []
|
||||
for n in list(range(71)) + [1000, 4097, 65536]:
|
||||
d = bytes(rng.randrange(256) for _ in range(n))
|
||||
cases.append({"data": d, "std": base64.b64encode(d), "url": base64.urlsafe_b64encode(d), "nopad": base64.b64encode(d).rstrip(b"=")})
|
||||
ctx.emit("base64_cases", cases)
|
||||
@@ -0,0 +1,115 @@
|
||||
# glTF fixtures (tools/fixtures.py): Khronos glTF-Sample-Assets models (tests/fixtures/gltf, licences per model
|
||||
# folder), gltfpack (meshoptimizer) quantized variants (KHR_mesh_quantization, normalized and integer positions,
|
||||
# KHR_texture_transform), and files exported by assimp, with reference values from assimp (`assimp info`: meshes, faces,
|
||||
# bounds, materials, animations, cameras, lights) and trimesh (area, triangles, bounds of the whole scene).
|
||||
# tests/gen/gltf_cases.luau { name, main, data, files = { uri -> bytes }, assimp, trimesh, like? (the original of a
|
||||
# quantized variant: compare against its references with a tolerance) }
|
||||
# tests/gen/gltf_xcheck.luau our encoder's .glb and .gltf for every case (tools/fixtures/_gltf_encode.luau), read back
|
||||
# by assimp and trimesh: { name, case, assimp, trimesh }
|
||||
import importlib.util, json, os, struct
|
||||
|
||||
INPUTS = ["tests/fixtures/gltf", "src/Formats/model/gltf", "src/Formats/codecs/Json", "src/Formats/codecs/Base64",
|
||||
"tools/fixtures/_model_ref.py", "tools/fixtures/_gltf_encode.luau"]
|
||||
|
||||
|
||||
def ref_module(ctx):
|
||||
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def assimp_extra(ctx, path):
|
||||
# cameras / lights / animations counts from assimp info (the shared helper parses meshes / faces / bounds)
|
||||
import re, subprocess
|
||||
try:
|
||||
txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace")
|
||||
except subprocess.CalledProcessError:
|
||||
return {}
|
||||
out = {}
|
||||
for label in ("Animations", "Cameras", "Lights", "Bones"):
|
||||
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
|
||||
if m:
|
||||
out[label.lower()] = int(m.group(1))
|
||||
return out
|
||||
|
||||
|
||||
def ply_torus(R=2.0, r=0.5, a=16, b=8):
|
||||
import math
|
||||
vs, fs = [], []
|
||||
for i in range(a):
|
||||
for j in range(b):
|
||||
u, v = 2 * math.pi * i / a, 2 * math.pi * j / b
|
||||
vs.append(((R + r * math.cos(v)) * math.cos(u), r * math.sin(v), (R + r * math.cos(v)) * math.sin(u)))
|
||||
for i in range(a):
|
||||
for j in range(b):
|
||||
p, q = i * b + j, ((i + 1) % a) * b + j
|
||||
p2, q2 = i * b + (j + 1) % b, ((i + 1) % a) * b + (j + 1) % b
|
||||
fs.append((p, p2, q2))
|
||||
fs.append((p, q2, q))
|
||||
head = "ply\nformat ascii 1.0\nelement vertex %d\nproperty float x\nproperty float y\nproperty float z\nelement face %d\nproperty list uchar int vertex_indices\nend_header\n" % (len(vs), len(fs))
|
||||
return (head + "".join("%r %r %r\n" % v for v in vs) + "".join("3 %d %d %d\n" % f for f in fs)).encode()
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
M = ref_module(ctx)
|
||||
root = os.path.join(ctx.root, "tests", "fixtures", "gltf")
|
||||
cases = []
|
||||
for model in sorted(os.listdir(root)):
|
||||
for variant in sorted(os.listdir(os.path.join(root, model))):
|
||||
d = os.path.join(root, model, variant)
|
||||
if not os.path.isdir(d):
|
||||
continue
|
||||
mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")]
|
||||
if not mains:
|
||||
continue
|
||||
files = {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}
|
||||
cases.append({"name": model + "/" + variant, "main": mains[0], "path": os.path.join(d, mains[0]), "files": files})
|
||||
# gltfpack variants of a few models: default (integer positions + texture transform), -vpn (normalized positions),
|
||||
# -vpf (float positions, quantized normals / uvs)
|
||||
tmp = M.tempdir()
|
||||
for model, variant, main in (("BoxTextured", "glTF", "BoxTextured.gltf"), ("Box", "glTF-Binary", "Box.glb"), ("SimpleSkin", "glTF", "SimpleSkin.gltf"), ("MultiUVTest", "glTF-Binary", "MultiUVTest.glb")):
|
||||
for flag in ("", "-vpn", "-vpf", "-vpi"):
|
||||
out = os.path.join(tmp, "%s_q%s.glb" % (model, flag))
|
||||
args = ["gltfpack", "-i", os.path.join(root, model, variant, main), "-o", out, "-kn", "-km"] + ([flag] if flag else [])
|
||||
ctx.nix("meshoptimizer", args)
|
||||
cases.append({"name": "gltfpack/%s%s" % (model, flag), "main": os.path.basename(out), "path": out, "files": {}, "like": model + "/" + variant})
|
||||
# assimp's glTF exporters
|
||||
ply = os.path.join(tmp, "torus.ply")
|
||||
with open(ply, "wb") as f:
|
||||
f.write(ply_torus())
|
||||
for ext in ("glb", "gltf"):
|
||||
out = os.path.join(tmp, "torus_assimp." + ext)
|
||||
ctx.nix("assimp", ["assimp", "export", ply, out, "-f" + ("glb2" if ext == "glb" else "gltf2")])
|
||||
files = {}
|
||||
for f in os.listdir(tmp):
|
||||
if f.startswith("torus_assimp") and f.endswith(".bin"):
|
||||
files[f] = open(os.path.join(tmp, f), "rb").read()
|
||||
cases.append({"name": "assimp/torus." + ext, "main": os.path.basename(out), "path": out, "files": files})
|
||||
infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True)
|
||||
tms = M.trimesh_metrics(ctx, [c["path"] for c in cases])
|
||||
for c, a, t in zip(cases, infos, tms):
|
||||
a.update(assimp_extra(ctx, c["path"]))
|
||||
c["assimp"] = a
|
||||
c["trimesh"] = t
|
||||
c["data"] = open(c["path"], "rb").read()
|
||||
del c["path"]
|
||||
ctx.emit("gltf_cases", cases)
|
||||
|
||||
# the reference tools read our output
|
||||
ours = M.luau_encode(ctx, "tools/fixtures/_gltf_encode.luau")
|
||||
xtmp = M.tempdir()
|
||||
names = []
|
||||
for name, data in sorted(ours.items()):
|
||||
with open(os.path.join(xtmp, name), "wb") as f:
|
||||
f.write(data)
|
||||
if name.endswith(".glb") or name.endswith(".gltf"):
|
||||
names.append(name)
|
||||
paths = [os.path.join(xtmp, n) for n in names]
|
||||
xi = M.assimp_info(ctx, paths, raw=True)
|
||||
xt = M.trimesh_metrics(ctx, paths)
|
||||
out = []
|
||||
for n, a, t in zip(names, xi, xt):
|
||||
a.update(assimp_extra(ctx, os.path.join(xtmp, n)))
|
||||
out.append({"name": n, "case": int(n.split("_")[1].split(".")[0]), "assimp": a, "trimesh": t})
|
||||
ctx.emit("gltf_xcheck", out)
|
||||
@@ -0,0 +1,257 @@
|
||||
# OBJ fixtures (tools/fixtures.py): OBJ / MTL files written here (materials, textures, objects and groups, n-gons,
|
||||
# negative indices, vertex colours, continuation lines, comments, lines and points, a concave polygon) and files
|
||||
# exported by assimp (from generated PLY meshes), with reference values from assimp (`assimp info`: meshes, materials,
|
||||
# vertices, faces, bounds) and trimesh (area, triangle count, bounds).
|
||||
# tests/gen/obj_cases.luau { name, data, files = { name -> bytes }, assimp = {...}, trimesh = {...}, polygonArea? }
|
||||
# tests/gen/obj_xcheck.luau our encoder's output for every case (tools/fixtures/_obj_encode.luau), read back by assimp
|
||||
# and trimesh: { name, assimp, trimesh, want = the original's values }
|
||||
import importlib.util, math, os, struct
|
||||
|
||||
INPUTS = ["src/Formats/model/obj", "tools/fixtures/_model_ref.py", "tools/fixtures/_obj_encode.luau"]
|
||||
|
||||
|
||||
def ref_module(ctx):
|
||||
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def png_1x1():
|
||||
import zlib
|
||||
def ch(t, d):
|
||||
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
|
||||
return b"\x89PNG\r\n\x1a\n" + ch(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 6, 0, 0, 0)) + ch(b"IDAT", zlib.compress(b"\0\xff\0\0\xff")) + ch(b"IEND", b"")
|
||||
|
||||
|
||||
def fmt(v):
|
||||
return "%.6g" % v
|
||||
|
||||
|
||||
CUBE = """# a cube: one object, two groups, two materials, a textured quad
|
||||
mtllib cube.mtl
|
||||
o Cube
|
||||
v 0 0 0
|
||||
v 1 0 0
|
||||
v 1 1 0
|
||||
v 0 1 0
|
||||
v 0 0 1
|
||||
v 1 0 1
|
||||
v 1 1 1
|
||||
v 0 1 1
|
||||
vt 0 0
|
||||
vt 1 0
|
||||
vt 1 1
|
||||
vt 0 1
|
||||
vn 0 0 1
|
||||
g top
|
||||
usemtl red
|
||||
s 1
|
||||
f 5/1/1 6/2/1 7/3/1 8/4/1
|
||||
g bottom
|
||||
usemtl blue
|
||||
f 1 4 3 2
|
||||
f 1 2 6 5
|
||||
f 2 3 7 6
|
||||
f 3 4 8 7
|
||||
f 4 1 5 8
|
||||
"""
|
||||
|
||||
CUBE_MTL = """# materials
|
||||
newmtl red
|
||||
Ka 0.1 0.1 0.1
|
||||
Kd 1 0 0
|
||||
Ks 0.5 0.5 0.5
|
||||
Ns 50
|
||||
illum 2
|
||||
map_Kd -s 2 2 1 -o 0.5 0 0 textures/tex.png
|
||||
map_Bump -bm 0.5 normal.png
|
||||
newmtl blue
|
||||
Kd 0 0 1
|
||||
d 0.5
|
||||
Pr 0.25
|
||||
Pm 1
|
||||
Ke 0.1 0.2 0.3
|
||||
"""
|
||||
|
||||
|
||||
def sphere(rng, rings, segs, colors=False):
|
||||
vs, fs = [], []
|
||||
for i in range(rings - 1): # no poles: assimp turns degenerate triangles into lines
|
||||
th = math.pi * (i + 1) / rings
|
||||
for j in range(segs):
|
||||
ph = 2 * math.pi * j / segs
|
||||
vs.append((math.sin(th) * math.cos(ph), math.cos(th), math.sin(th) * math.sin(ph)))
|
||||
for i in range(rings - 2):
|
||||
for j in range(segs):
|
||||
a, b = i * segs + j, i * segs + (j + 1) % segs
|
||||
c, d = a + segs, b + segs
|
||||
fs.append((a, c, d, b))
|
||||
return vs, fs
|
||||
|
||||
|
||||
def random_obj(rng):
|
||||
vs, fs = sphere(rng, 6, 9)
|
||||
lines = ["# random sphere: quads, triangles, pentagons, negative indices, vertex colours, continuations"]
|
||||
for v in vs:
|
||||
lines.append("v %s %s %s %s %s %s" % (fmt(v[0]), fmt(v[1]), fmt(v[2]), fmt(rng.random()), fmt(rng.random()), fmt(rng.random())))
|
||||
for k in range(len(vs)):
|
||||
lines.append("vt %s %s" % (fmt(rng.random()), fmt(rng.random())))
|
||||
lines.append("vn 0 1 0")
|
||||
lines.append("vn 1 0 0")
|
||||
lines.append("g sphere")
|
||||
n = len(vs)
|
||||
for i, f in enumerate(fs):
|
||||
if i % 7 == 0:
|
||||
# negative (relative) indices
|
||||
lines.append("f " + " ".join("%d/%d" % (v - n, v - n) for v in f))
|
||||
elif i % 7 == 1:
|
||||
lines.append("f " + " ".join("%d//%d" % (v + 1, 1 + i % 2) for v in f))
|
||||
elif i % 7 == 2:
|
||||
lines.append("f %d/%d/1 %d/%d/2 \\\n %d/%d/1 %d/%d/2" % (f[0] + 1, f[0] + 1, f[1] + 1, f[1] + 1, f[2] + 1, f[2] + 1, f[3] + 1, f[3] + 1))
|
||||
elif i % 7 == 3:
|
||||
lines.append("f %d %d %d" % (f[0] + 1, f[1] + 1, f[2] + 1))
|
||||
lines.append("f %d %d %d" % (f[0] + 1, f[2] + 1, f[3] + 1))
|
||||
else:
|
||||
lines.append("f " + " ".join("%d/%d" % (v + 1, v + 1) for v in f))
|
||||
# a convex pentagon and a hexagon
|
||||
base = len(vs)
|
||||
for k in range(5):
|
||||
lines.append("v %s %s 2" % (fmt(math.cos(2 * math.pi * k / 5)), fmt(math.sin(2 * math.pi * k / 5))))
|
||||
lines.append("g pentagon")
|
||||
lines.append("f " + " ".join(str(base + k + 1) for k in range(5)))
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def concave():
|
||||
# an L-shaped hexagon (area 3) and a U-shaped octagon (area 5) in the xz plane, as n-gons
|
||||
L = [(0, 0), (2, 0), (2, 1), (1, 1), (1, 2), (0, 2)]
|
||||
U = [(3, 0), (6, 0), (6, 2), (5, 2), (5, 1), (4, 1), (4, 2), (3, 2)]
|
||||
lines = ["o shapes"]
|
||||
for x, z in L + U:
|
||||
lines.append("v %d 0 %d" % (x, z))
|
||||
lines.append("f " + " ".join(str(k + 1) for k in range(len(L))))
|
||||
lines.append("f " + " ".join(str(len(L) + k + 1) for k in range(len(U))))
|
||||
area = sum(abs(sum(p[i][0] * p[(i + 1) % len(p)][1] - p[(i + 1) % len(p)][0] * p[i][1] for i in range(len(p)))) / 2 for p in (L, U))
|
||||
return "\n".join(lines) + "\n", area
|
||||
|
||||
|
||||
def lines_points():
|
||||
return """o wire
|
||||
v 0 0 0
|
||||
v 1 0 0
|
||||
v 1 1 0
|
||||
v 0 1 0
|
||||
l 1 2 3 4 1
|
||||
p 1 3
|
||||
f 1 2 3
|
||||
"""
|
||||
|
||||
|
||||
def ply_torus(rng, R=2.0, r=0.5, a=24, b=12):
|
||||
vs, fs = [], []
|
||||
for i in range(a):
|
||||
for j in range(b):
|
||||
u, v = 2 * math.pi * i / a, 2 * math.pi * j / b
|
||||
vs.append(((R + r * math.cos(v)) * math.cos(u), r * math.sin(v), (R + r * math.cos(v)) * math.sin(u)))
|
||||
for i in range(a):
|
||||
for j in range(b):
|
||||
p, q = i * b + j, ((i + 1) % a) * b + j
|
||||
p2, q2 = i * b + (j + 1) % b, ((i + 1) % a) * b + (j + 1) % b
|
||||
fs.append((p, p2, q2, q))
|
||||
head = "ply\nformat ascii 1.0\nelement vertex %d\nproperty float x\nproperty float y\nproperty float z\nelement face %d\nproperty list uchar int vertex_indices\nend_header\n" % (len(vs), len(fs))
|
||||
body = "".join("%r %r %r\n" % v for v in vs) + "".join("4 %d %d %d %d\n" % f for f in fs)
|
||||
return (head + body).encode()
|
||||
|
||||
|
||||
def fan_area(text):
|
||||
# the area of every face fan-triangulated (an exact reference in double precision)
|
||||
text = text.replace("\\\n", " ")
|
||||
V, A = [], 0.0
|
||||
for l in text.split("\n"):
|
||||
w = l.split()
|
||||
if not w:
|
||||
continue
|
||||
if w[0] == "v":
|
||||
V.append([float(x) for x in w[1:4]])
|
||||
elif w[0] == "f":
|
||||
idx = []
|
||||
for c in w[1:]:
|
||||
v = int(c.split("/")[0])
|
||||
idx.append(v - 1 if v > 0 else len(V) + v)
|
||||
for k in range(1, len(idx) - 1):
|
||||
a, b, c = V[idx[0]], V[idx[k]], V[idx[k + 1]]
|
||||
e1 = [b[i] - a[i] for i in range(3)]
|
||||
e2 = [c[i] - a[i] for i in range(3)]
|
||||
x, y, z = e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]
|
||||
A += math.sqrt(x * x + y * y + z * z) / 2
|
||||
return A
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
M = ref_module(ctx)
|
||||
rng = ctx.rng(11)
|
||||
tmp = M.tempdir()
|
||||
cases = []
|
||||
|
||||
def add(name, data, files=None, **extra):
|
||||
path = os.path.join(tmp, name)
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "wb") as f:
|
||||
f.write(data)
|
||||
for fn, fd in (files or {}).items():
|
||||
p = os.path.join(tmp, fn)
|
||||
os.makedirs(os.path.dirname(p), exist_ok=True)
|
||||
with open(p, "wb") as f:
|
||||
f.write(fd)
|
||||
c = {"name": name, "data": data, "files": files or {}, "path": path, "fanArea": fan_area(data.decode())}
|
||||
c.update(extra)
|
||||
cases.append(c)
|
||||
|
||||
png = png_1x1()
|
||||
add("cube.obj", CUBE.encode(), {"cube.mtl": CUBE_MTL.encode(), "textures/tex.png": png, "normal.png": png})
|
||||
# assimp joins mixed-attribute corners differently (136 vertices where the file has 101 distinct v/vt/vn): no
|
||||
# vertex count check for this one
|
||||
# and trimesh gets its area wrong (12.60 for 12.52: mixed index forms?): only the exact fan area here
|
||||
add("random.obj", random_obj(rng).encode(), noVertexCount=True, noTrimesh=True)
|
||||
text, area = concave()
|
||||
add("concave.obj", text.encode(), polygonArea=area)
|
||||
add("wire.obj", lines_points().encode(), noTrimesh=True)
|
||||
# assimp's OBJ exporter, from a PLY torus
|
||||
ply = os.path.join(tmp, "torus.ply")
|
||||
with open(ply, "wb") as f:
|
||||
f.write(ply_torus(rng))
|
||||
out = os.path.join(tmp, "torus_assimp.obj")
|
||||
ctx.nix("assimp", ["assimp", "export", ply, out])
|
||||
files = {}
|
||||
if os.path.exists(out[:-4] + ".mtl"):
|
||||
files["torus_assimp.mtl"] = open(out[:-4] + ".mtl", "rb").read()
|
||||
add("torus_assimp.obj", open(out, "rb").read(), files)
|
||||
|
||||
paths = [c["path"] for c in cases]
|
||||
infos = M.assimp_info(ctx, paths)
|
||||
tm = M.trimesh_metrics(ctx, [c["path"] for c in cases if not c.get("noTrimesh")])
|
||||
k = 0
|
||||
for c, info in zip(cases, infos):
|
||||
c["assimp"] = info
|
||||
if not c.get("noTrimesh"):
|
||||
c["trimesh"] = tm[k]
|
||||
k += 1
|
||||
for c in cases:
|
||||
del c["path"]
|
||||
ctx.emit("obj_cases", cases)
|
||||
|
||||
# the reference tools read our encoder's output (decode -> encode in Luau, then assimp / trimesh)
|
||||
ours = M.luau_encode(ctx, "tools/fixtures/_obj_encode.luau")
|
||||
xtmp = M.tempdir()
|
||||
names = []
|
||||
for name, data in sorted(ours.items()):
|
||||
p = os.path.join(xtmp, name)
|
||||
os.makedirs(os.path.dirname(p), exist_ok=True)
|
||||
with open(p, "wb") as f:
|
||||
f.write(data)
|
||||
if name.endswith(".obj"):
|
||||
names.append(name)
|
||||
xinfos = M.assimp_info(ctx, [os.path.join(xtmp, n) for n in names])
|
||||
xtm = M.trimesh_metrics(ctx, [os.path.join(xtmp, n) for n in names])
|
||||
ctx.emit("obj_xcheck", [{"name": n, "assimp": a, "trimesh": t} for n, a, t in zip(names, xinfos, xtm)])
|
||||
@@ -0,0 +1,343 @@
|
||||
# OFF fixtures (tools/fixtures.py).
|
||||
# tests/gen/off_scenes.luau scenes for the encoder (STCNOFF mesh, polygons under a TRS node, a float-colour point
|
||||
# cloud, polygons with face colours) with the expected file content, computed here
|
||||
# tests/gen/off.luau cases: OFF files written by trimesh and by hand here (COFF with integer / float colours,
|
||||
# RGB / RGBA, NOFF, STOFF, STCNOFF, face colours of both kinds, colormap indices, comments
|
||||
# everywhere, counts on the header line, CRLF and tabs, n-gons, a point cloud), with the
|
||||
# values they were written from (positions cross-checked with trimesh's OFF reader);
|
||||
# `ours`: our encoder's output (luau CLI: tools/fixtures/_off_encode.luau) read back by
|
||||
# trimesh, assimp and a small reader here, as verdicts
|
||||
import json, math, os, shutil, struct, subprocess, tempfile, zlib
|
||||
|
||||
INPUTS = ["src/Formats/model/off", "tools/fixtures/_off_reference.py", "tools/fixtures/_off_encode.luau"]
|
||||
|
||||
|
||||
def f32(x):
|
||||
return struct.unpack("<f", struct.pack("<f", x))[0]
|
||||
|
||||
|
||||
def pack(fmt, vals):
|
||||
return struct.pack("<%d%s" % (len(vals), fmt), *vals)
|
||||
|
||||
|
||||
def crc(b):
|
||||
return zlib.crc32(b)
|
||||
|
||||
|
||||
def fan(faces):
|
||||
tris, fot = [], []
|
||||
for i, f in enumerate(faces):
|
||||
for k in range(1, len(f) - 1):
|
||||
tris += [f[0], f[k], f[k + 1]]
|
||||
fot.append(i)
|
||||
return tris, fot
|
||||
|
||||
|
||||
def random_faces(rng, nv, nf, sizes=(3, 4, 5, 6)):
|
||||
out = []
|
||||
for _ in range(nf):
|
||||
s = rng.choice(sizes)
|
||||
out.append(rng.sample(range(nv), s))
|
||||
return out
|
||||
|
||||
|
||||
def colour_tokens(rng, kind, comps):
|
||||
if kind == "int":
|
||||
vals = [rng.randrange(256) for _ in range(comps)]
|
||||
return [str(v) for v in vals], vals
|
||||
vals = [round(rng.random(), 6) for _ in range(comps)]
|
||||
return ["%.6f" % v for v in vals], vals
|
||||
|
||||
|
||||
def colour_bytes(kind, vals_list, comps_list):
|
||||
"""the expected COLOR_0 / faceColors bytes (unorm8 x4 or f32 x4; missing alpha / colour = full)"""
|
||||
out = b""
|
||||
for vals, comps in zip(vals_list, comps_list):
|
||||
if kind == "int":
|
||||
v = list(vals) + [255] * (4 - len(vals))
|
||||
out += bytes(v)
|
||||
else:
|
||||
v = list(vals) + [1.0] * (4 - len(vals))
|
||||
out += pack("f", v)
|
||||
return out
|
||||
|
||||
|
||||
def make_case(rng, name, nv, faces, normals=False, st=False, vcol=None, fcol=None, style=None):
|
||||
"""an OFF file and the values it holds. vcol / fcol = (kind "int" | "float" | "map", comps)"""
|
||||
style = style or {}
|
||||
kw = ("ST" if st else "") + ("C" if vcol else "") + ("N" if normals else "") + "OFF"
|
||||
nl = "\r\n" if style.get("crlf") else "\n"
|
||||
sep = "\t" if style.get("tabs") else " "
|
||||
lines = []
|
||||
if style.get("comments"):
|
||||
lines.append("# a comment before the keyword")
|
||||
if style.get("inline"):
|
||||
lines.append("%s %d %d 0" % (kw, nv, len(faces)))
|
||||
else:
|
||||
lines.append(kw + (" # keyword" if style.get("comments") else ""))
|
||||
if style.get("comments"):
|
||||
lines += ["", "# counts next"]
|
||||
lines.append("%d %d %d" % (nv, len(faces), 0))
|
||||
pos, nrm, tex, vc_vals, vc_comps = [], [], [], [], []
|
||||
for i in range(nv):
|
||||
p = [f32(rng.uniform(-10, 10)) for _ in range(3)]
|
||||
pos += p
|
||||
toks = [repr(c) for c in p]
|
||||
if normals:
|
||||
v = [rng.uniform(-1, 1) for _ in range(3)]
|
||||
ln = math.sqrt(sum(c * c for c in v))
|
||||
n = [f32(c / ln) for c in v]
|
||||
nrm += n
|
||||
toks += [repr(c) for c in n]
|
||||
if vcol:
|
||||
comps = vcol[1] if vcol[1] != "mixed" else rng.choice((3, 4))
|
||||
ct, cv = colour_tokens(rng, vcol[0], comps)
|
||||
toks += ct
|
||||
vc_vals.append(cv)
|
||||
vc_comps.append(comps)
|
||||
if st:
|
||||
t = [f32(rng.random()) for _ in range(2)]
|
||||
tex += t
|
||||
toks += [repr(c) for c in t]
|
||||
line = sep.join(toks)
|
||||
if style.get("comments") and i % 3 == 0:
|
||||
line += " # vertex %d" % i
|
||||
lines.append(line)
|
||||
if style.get("comments") and i == 1:
|
||||
lines.append("")
|
||||
lines.append(" # an indented comment line")
|
||||
fc_vals, fc_comps, any_fc, colormap = [], [], False, False
|
||||
for i, f in enumerate(faces):
|
||||
toks = [str(len(f))] + [str(x) for x in f]
|
||||
if fcol and not (fcol[1] == "some" and i % 3 == 1):
|
||||
if fcol[0] == "map":
|
||||
toks.append(str(rng.randrange(16)))
|
||||
colormap = True
|
||||
fc_vals.append([])
|
||||
fc_comps.append(0)
|
||||
else:
|
||||
comps = 4 if fcol[1] in (4, "some") else 3
|
||||
ct, cv = colour_tokens(rng, fcol[0], comps)
|
||||
toks += ct
|
||||
fc_vals.append(cv)
|
||||
fc_comps.append(comps)
|
||||
any_fc = True
|
||||
else:
|
||||
fc_vals.append([])
|
||||
fc_comps.append(0)
|
||||
lines.append(sep.join(toks))
|
||||
data = (nl.join(lines) + nl).encode()
|
||||
exp = {"name": name, "data": data, "keyword": kw, "vertices": nv, "faces": len(faces), "pos_crc": crc(pack("f", pos))}
|
||||
if normals:
|
||||
exp["nrm_crc"] = crc(pack("f", nrm))
|
||||
if st:
|
||||
exp["tex_crc"] = crc(pack("f", tex))
|
||||
if vcol:
|
||||
exp["color"] = {"type": "unorm8" if vcol[0] == "int" else "f32", "crc": crc(colour_bytes(vcol[0], vc_vals, vc_comps))}
|
||||
if any_fc:
|
||||
exp["faceColors"] = {"type": "unorm8" if fcol[0] == "int" else "f32", "crc": crc(colour_bytes(fcol[0], fc_vals, fc_comps))}
|
||||
if colormap:
|
||||
exp["colormap"] = True
|
||||
tris, fot = fan(faces)
|
||||
exp["allTri"] = all(len(f) == 3 for f in faces)
|
||||
exp["tris"] = len(tris) // 3
|
||||
exp["tri_crc"] = crc(pack("I", tris))
|
||||
exp["fot_crc"] = crc(pack("I", fot))
|
||||
exp["corners_crc"] = crc(pack("I", [c for f in faces for c in f]))
|
||||
exp["sizes_crc"] = crc(pack("I", [len(f) for f in faces]))
|
||||
return exp
|
||||
|
||||
|
||||
def handmade(rng):
|
||||
cases = []
|
||||
cases.append(make_case(rng, "coff-int.off", 30, random_faces(rng, 30, 20), vcol=("int", 4), fcol=("int", 3), style={"comments": True}))
|
||||
cases.append(make_case(rng, "coff-float-rgb.off", 25, random_faces(rng, 25, 12, (3, 4)), vcol=("float", 3), fcol=("float", 4)))
|
||||
cases.append(make_case(rng, "coff-mixed-alpha.off", 12, random_faces(rng, 12, 6, (3,)), vcol=("int", "mixed")))
|
||||
cases.append(make_case(rng, "noff.off", 20, random_faces(rng, 20, 10, (3,)), normals=True))
|
||||
cases.append(make_case(rng, "stoff.off", 16, random_faces(rng, 16, 9), st=True, style={"tabs": True}))
|
||||
cases.append(make_case(rng, "stcnoff.off", 18, random_faces(rng, 18, 11), normals=True, st=True, vcol=("int", 4), fcol=("int", "some")))
|
||||
cases.append(make_case(rng, "inline-crlf.off", 10, random_faces(rng, 10, 5, (3, 4)), style={"inline": True, "crlf": True}))
|
||||
cases.append(make_case(rng, "colormap.off", 9, random_faces(rng, 9, 4, (3, 4)), fcol=("map", 1)))
|
||||
cases.append(make_case(rng, "points.off", 40, []))
|
||||
cases.append(make_case(rng, "big-ngon.off", 300, [list(range(300)), list(range(0, 300, 7))]))
|
||||
return cases
|
||||
|
||||
|
||||
# --- encoder scenes
|
||||
def mat_trs(node):
|
||||
x, y, z, w = node.get("rotation", [0, 0, 0, 1])
|
||||
sx, sy, sz = node.get("scale", [1, 1, 1])
|
||||
tx, ty, tz = node.get("translation", [0, 0, 0])
|
||||
r = [
|
||||
[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
|
||||
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
|
||||
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
|
||||
]
|
||||
return [[r[i][0] * sx, r[i][1] * sy, r[i][2] * sz, (tx, ty, tz)[i]] for i in range(3)]
|
||||
|
||||
|
||||
def scenes(rng):
|
||||
out = []
|
||||
n = 12
|
||||
pos = [f32(rng.uniform(-5, 5)) for _ in range(n * 3)]
|
||||
nrm = [f32(rng.uniform(-1, 1)) for _ in range(n * 3)]
|
||||
col = [rng.randrange(256) for _ in range(n * 4)]
|
||||
tex = [f32(rng.random()) for _ in range(n * 2)]
|
||||
idx = [rng.randrange(n) for _ in range(30)]
|
||||
faces = [idx[i:i + 3] for i in range(0, 30, 3)]
|
||||
vlines = [pos[i * 3:i * 3 + 3] + nrm[i * 3:i * 3 + 3] + col[i * 4:i * 4 + 4] + tex[i * 2:i * 2 + 2] for i in range(n)]
|
||||
out.append({"name": "mesh", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{
|
||||
"mode": "triangles", "count": n, "indices": pack("I", idx),
|
||||
"attrs": {"POSITION": ["f32", 3, pack("f", pos)], "NORMAL": ["f32", 3, pack("f", nrm)], "COLOR_0": ["unorm8", 4, bytes(col)],
|
||||
"TEXCOORD_0": ["f32", 2, pack("f", tex)]}}]}],
|
||||
"encodings": {"default": {"keyword": "STCNOFF", "vertices": vlines, "faces": faces},
|
||||
"plain": {"keyword": "OFF", "vertices": [v[:3] for v in vlines], "faces": faces}}})
|
||||
pv = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 2, 0, 0, 3, 0.5, 0, 2.5, 1.5, 0.2, 1.5, 1.2, 0.1, 0, 0, 1]
|
||||
q = [rng.uniform(-1, 1) for _ in range(4)]
|
||||
ln = math.sqrt(sum(c * c for c in q))
|
||||
node = {"mesh": 1, "translation": [1, 2, 3], "rotation": [c / ln for c in q], "scale": [2, 0.5, 1.5]}
|
||||
m = mat_trs(node)
|
||||
w = [[m[i][0] * pv[k * 3] + m[i][1] * pv[k * 3 + 1] + m[i][2] * pv[k * 3 + 2] + m[i][3] for i in range(3)] for k in range(9)]
|
||||
pf = [[0, 1, 2, 3], [1, 4, 5, 6, 7, 2], [0, 3, 8]]
|
||||
out.append({"name": "polys", "nodes": [node], "roots": [1], "meshes": [{"prims": [{
|
||||
"mode": "polygons", "count": 9, "indices": pack("I", [c for f in pf for c in f]), "faces": pack("I", [len(f) for f in pf]),
|
||||
"attrs": {"POSITION": ["f32", 3, pack("f", pv)]}}]}],
|
||||
"encodings": {"default": {"keyword": "OFF", "vertices": w, "faces": pf, "tol": 1e-5}}})
|
||||
n = 20
|
||||
pos = [f32(rng.uniform(-50, 50)) for _ in range(n * 3)]
|
||||
col = [f32(rng.random()) for _ in range(n * 4)]
|
||||
out.append({"name": "cloud", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{
|
||||
"mode": "points", "count": n, "attrs": {"POSITION": ["f32", 3, pack("f", pos)], "COLOR_0": ["f32", 4, pack("f", col)]}}]}],
|
||||
"encodings": {"default": {"keyword": "COFF", "vertices": [pos[i * 3:i * 3 + 3] + col[i * 4:i * 4 + 4] for i in range(n)], "faces": []}}})
|
||||
# face colours on planar polygons (assimp triangulates non-planar ones its own way)
|
||||
pf = [[0, 1, 2, 3], [1, 4, 5, 6, 7, 2], [0, 3, 8]]
|
||||
pos = [f32(v) for v in pv]
|
||||
fc = [rng.randrange(256) for _ in range(12)]
|
||||
out.append({"name": "facecolors", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{
|
||||
"mode": "polygons", "count": 9, "indices": pack("I", [c for f in pf for c in f]), "faces": pack("I", [len(f) for f in pf]),
|
||||
"attrs": {"POSITION": ["f32", 3, pack("f", pos)]}, "faceColors": bytes(fc)}]}],
|
||||
"encodings": {"default": {"keyword": "OFF", "vertices": [pos[i * 3:i * 3 + 3] for i in range(9)], "faces": pf,
|
||||
"faceColors": [fc[i * 4:i * 4 + 4] for i in range(3)]}}})
|
||||
return out
|
||||
|
||||
|
||||
def parse_off(text):
|
||||
"""a small OFF reader for checking our output: keyword, vertex rows (numbers), faces, face colour rows"""
|
||||
rows = []
|
||||
for line in text.split("\n"):
|
||||
line = line.split("#", 1)[0].strip()
|
||||
if line:
|
||||
rows.append(line.split())
|
||||
kw = rows[0][0]
|
||||
nv, nf = int(rows[1][0]), int(rows[1][1])
|
||||
verts = [[float(x) for x in r] for r in rows[2:2 + nv]]
|
||||
faces, fcols = [], []
|
||||
for r in rows[2 + nv:2 + nv + nf]:
|
||||
k = int(r[0])
|
||||
faces.append([int(x) for x in r[1:1 + k]])
|
||||
fcols.append([float(x) for x in r[1 + k:]])
|
||||
return kw, verts, faces, fcols, len(rows) == 2 + nv + nf
|
||||
|
||||
|
||||
def check_ours(text, want):
|
||||
kw, verts, faces, fcols, exact_rows = parse_off(text)
|
||||
if kw != want["keyword"]:
|
||||
return False, "keyword %s, want %s" % (kw, want["keyword"])
|
||||
if not exact_rows:
|
||||
return False, "extra or missing rows"
|
||||
if len(verts) != len(want["vertices"]):
|
||||
return False, "vertex count"
|
||||
tol = want.get("tol", 0)
|
||||
for got, exp in zip(verts, want["vertices"]):
|
||||
if len(got) != len(exp):
|
||||
return False, "vertex row length %d, want %d" % (len(got), len(exp))
|
||||
for g, e in zip(got, exp):
|
||||
if (abs(f32(g) - f32(e)) > tol * max(1, abs(e))) if tol else f32(g) != f32(e):
|
||||
return False, "vertex value %r, want %r" % (g, e)
|
||||
if faces != want["faces"]:
|
||||
return False, "faces differ"
|
||||
if "faceColors" in want:
|
||||
if [list(map(int, c)) for c in fcols] != want["faceColors"]:
|
||||
return False, "face colours differ"
|
||||
elif any(fcols):
|
||||
return False, "unexpected face colours"
|
||||
return True, "%d vertices, %d faces" % (len(verts), len(faces))
|
||||
|
||||
|
||||
def luau_cmd():
|
||||
exe = shutil.which("luau")
|
||||
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
|
||||
|
||||
|
||||
def assimp_faces(ctx, path):
|
||||
txt = ctx.nix("assimp", ["assimp", "info", path]).decode(errors="replace")
|
||||
for line in txt.split("\n"):
|
||||
if line.startswith("Faces:"):
|
||||
return int(line.split()[1])
|
||||
return None
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(53)
|
||||
tmp = tempfile.mkdtemp(prefix="formats-off-")
|
||||
try:
|
||||
_generate(ctx, rng, tmp)
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
|
||||
def _generate(ctx, rng, tmp):
|
||||
sc = scenes(rng)
|
||||
ctx.emit("off_scenes", sc)
|
||||
cases = handmade(rng)
|
||||
for c in cases:
|
||||
with open(os.path.join(tmp, c["name"]), "wb") as f:
|
||||
f.write(c["data"])
|
||||
make = ["trimesh-ico.off", "trimesh-capsule.off"]
|
||||
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_off_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode()
|
||||
ours = []
|
||||
byname = {s["name"]: s for s in sc}
|
||||
for line in enc.split("\n"):
|
||||
if not line.strip():
|
||||
continue
|
||||
label, hexdata = line.split(" ", 1)
|
||||
scene_name, encoding = label.split("/")
|
||||
fn = "ours-%s-%s.off" % (scene_name, encoding)
|
||||
data = bytes.fromhex(hexdata.strip())
|
||||
with open(os.path.join(tmp, fn), "wb") as f:
|
||||
f.write(data)
|
||||
ours.append((label, fn, data, byname[scene_name]["encodings"][encoding]))
|
||||
names = [c["name"] for c in cases if c["vertices"] > 0] + make + [o[1] for o in ours]
|
||||
code = open(os.path.join(ctx.root, "tools", "fixtures", "_off_reference.py")).read()
|
||||
try:
|
||||
ref = json.loads(ctx.python(["trimesh", "numpy"], code, input=json.dumps({"dir": tmp, "make": make, "read": names}).encode()))
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise RuntimeError("off reference: " + e.stderr.decode(errors="replace")[-3000:])
|
||||
# trimesh agrees with the values the files were written from
|
||||
for c in cases:
|
||||
r = ref.get(c["name"])
|
||||
if r:
|
||||
assert r["vertices"] == c["vertices"] and r["pos_crc"] == c["pos_crc"], c["name"]
|
||||
for name in make:
|
||||
with open(os.path.join(tmp, name), "rb") as f:
|
||||
data = f.read()
|
||||
r = ref[name]
|
||||
tris = [x for f in r["faces"] for x in f]
|
||||
cases.append({"name": name, "data": data, "keyword": "OFF", "vertices": r["vertices"], "faces": r["tris"], "pos_crc": r["pos_crc"],
|
||||
"allTri": True, "tris": r["tris"], "tri_crc": crc(pack("I", tris)), "corners_crc": crc(pack("I", tris)),
|
||||
"sizes_crc": crc(pack("I", [3] * r["tris"]))})
|
||||
verdicts = []
|
||||
for label, fn, data, want in ours:
|
||||
ok, detail = check_ours(data.decode(), want)
|
||||
r = ref.get(fn)
|
||||
if ok and r and not want.get("tol"):
|
||||
exp = pack("f", [c for v in want["vertices"] for c in v[:3]])
|
||||
if r["pos_crc"] != crc(exp):
|
||||
ok, detail = False, "trimesh reads other positions"
|
||||
if ok and want["faces"]:
|
||||
got = assimp_faces(ctx, os.path.join(tmp, fn))
|
||||
exp_f = sum(len(f) - 2 for f in want["faces"])
|
||||
if got != exp_f:
|
||||
ok, detail = False, "assimp reads %s faces, want %d" % (got, exp_f)
|
||||
verdicts.append({"name": label, "ok": ok, "detail": detail})
|
||||
ctx.emit("off", {"cases": cases, "ours": verdicts})
|
||||
@@ -0,0 +1,192 @@
|
||||
# PLY fixtures (tools/fixtures.py).
|
||||
# tests/gen/ply_scenes.luau scenes for the encoder (an indexed mesh with every attribute kind and custom properties,
|
||||
# polygons under a TRS node, a float-colour point cloud, two meshes merged, a mirrored
|
||||
# polygon) with the expected vertex properties (names, types, values) and faces, computed
|
||||
# here
|
||||
# tests/gen/ply.luau cases: PLY files written by plyfile (ascii / binary LE / BE, every property type, odd
|
||||
# orders, n-gons up to 300 vertices, face properties and lists, edge / material / tristrips
|
||||
# elements, comments, obj_info, point clouds, a 65k-vertex sphere) and by assimp (OFF / OBJ
|
||||
# -> PLY), each with reference values from plyfile mapped to the Scene conventions;
|
||||
# `ours`: our encoder's output (luau CLI: tools/fixtures/_ply_encode.luau) read back by
|
||||
# plyfile and assimp, as verdicts
|
||||
import json, math, os, shutil, struct, subprocess, tempfile
|
||||
|
||||
INPUTS = ["src/Formats/model/ply", "tools/fixtures/_ply_reference.py", "tools/fixtures/_ply_encode.luau"]
|
||||
|
||||
|
||||
def f32(x):
|
||||
return struct.unpack("<f", struct.pack("<f", x))[0]
|
||||
|
||||
|
||||
def pack(fmt, vals):
|
||||
return struct.pack("<%d%s" % (len(vals), fmt), *vals)
|
||||
|
||||
|
||||
def mat_trs(node):
|
||||
x, y, z, w = node.get("rotation", [0, 0, 0, 1])
|
||||
sx, sy, sz = node.get("scale", [1, 1, 1])
|
||||
tx, ty, tz = node.get("translation", [0, 0, 0])
|
||||
r = [
|
||||
[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
|
||||
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
|
||||
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
|
||||
]
|
||||
return [[r[i][0] * sx, r[i][1] * sy, r[i][2] * sz, (tx, ty, tz)[i]] for i in range(3)]
|
||||
|
||||
|
||||
def quat(rng):
|
||||
q = [rng.uniform(-1, 1) for _ in range(4)]
|
||||
ln = math.sqrt(sum(c * c for c in q))
|
||||
return [c / ln for c in q]
|
||||
|
||||
|
||||
def scenes(rng):
|
||||
out = []
|
||||
# an indexed mesh with every attribute kind
|
||||
W, H = 5, 4
|
||||
n = W * H
|
||||
pos = [f32(v) for y in range(H) for x in range(W) for v in (x, y, rng.uniform(-1, 1))]
|
||||
nrm = []
|
||||
for _ in range(n):
|
||||
v = [rng.uniform(-1, 1) for _ in range(3)]
|
||||
ln = math.sqrt(sum(c * c for c in v))
|
||||
nrm += [f32(c / ln) for c in v]
|
||||
col = [rng.randrange(256) for _ in range(n * 4)]
|
||||
tex = [f32(rng.random()) for _ in range(n * 2)]
|
||||
quality = [f32(rng.uniform(0, 10)) for _ in range(n)]
|
||||
label = [rng.randrange(65536) for _ in range(n)]
|
||||
idx = []
|
||||
for y in range(H - 1):
|
||||
for x in range(W - 1):
|
||||
a = y * W + x
|
||||
idx += [a, a + 1, a + W + 1, a, a + W + 1, a + W]
|
||||
out.append({"name": "mesh", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{
|
||||
"mode": "triangles", "count": n, "indices": pack("I", idx),
|
||||
"attrs": {"POSITION": ["f32", 3, pack("f", pos)], "NORMAL": ["f32", 3, pack("f", nrm)], "COLOR_0": ["unorm8", 4, bytes(col)],
|
||||
"TEXCOORD_0": ["f32", 2, pack("f", tex)], "_quality": ["f32", 1, pack("f", quality)], "_label": ["u16", 1, pack("H", label)]}}]}],
|
||||
"props": [("x", "<f4", pos[0::3]), ("y", "<f4", pos[1::3]), ("z", "<f4", pos[2::3]), ("nx", "<f4", nrm[0::3]), ("ny", "<f4", nrm[1::3]),
|
||||
("nz", "<f4", nrm[2::3]), ("red", "u1", col[0::4]), ("green", "u1", col[1::4]), ("blue", "u1", col[2::4]), ("alpha", "u1", col[3::4]),
|
||||
("s", "<f4", tex[0::2]), ("t", "<f4", tex[1::2]), ("label", "<u2", label), ("quality", "<f4", quality)],
|
||||
"faces": [idx[i:i + 3] for i in range(0, len(idx), 3)]})
|
||||
# polygons under a TRS node (positions transformed: compared with a tolerance)
|
||||
pv = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 2, 0, 0, 3, 0.5, 0, 2.5, 1.5, 0.2, 1.5, 1.2, 0.1, 0, 0, 1]
|
||||
node = {"mesh": 1, "translation": [1, 2, 3], "rotation": quat(rng), "scale": [2, 0.5, 1.5]}
|
||||
m = mat_trs(node)
|
||||
w = [[f32(m[i][0] * pv[k * 3] + m[i][1] * pv[k * 3 + 1] + m[i][2] * pv[k * 3 + 2] + m[i][3]) for i in range(3)] for k in range(9)]
|
||||
out.append({"name": "polys", "nodes": [node], "roots": [1], "meshes": [{"prims": [{
|
||||
"mode": "polygons", "count": 9, "indices": pack("I", [0, 1, 2, 3, 1, 4, 5, 6, 7, 2, 0, 3, 8]), "faces": pack("I", [4, 6, 3]),
|
||||
"attrs": {"POSITION": ["f32", 3, pack("f", pv)]}}]}],
|
||||
"props": [("x", "<f4", [p[0] for p in w], 1e-5), ("y", "<f4", [p[1] for p in w], 1e-5), ("z", "<f4", [p[2] for p in w], 1e-5)],
|
||||
"faces": [[0, 1, 2, 3], [1, 4, 5, 6, 7, 2], [0, 3, 8]], "transformed": True})
|
||||
# a point cloud with float colours (alpha all 1: not written)
|
||||
n = 30
|
||||
pos = [f32(rng.uniform(-50, 50)) for _ in range(n * 3)]
|
||||
col = [f32(rng.random()) if k % 4 != 3 else 1.0 for k in range(n * 4)]
|
||||
out.append({"name": "cloud", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{
|
||||
"mode": "points", "count": n, "attrs": {"POSITION": ["f32", 3, pack("f", pos)], "COLOR_0": ["f32", 4, pack("f", col)]}}]}],
|
||||
"props": [("x", "<f4", pos[0::3]), ("y", "<f4", pos[1::3]), ("z", "<f4", pos[2::3]), ("red", "<f4", col[0::4]),
|
||||
("green", "<f4", col[1::4]), ("blue", "<f4", col[2::4])]})
|
||||
# two meshes merged: the second has no colours (filled with opaque white: alpha not written)
|
||||
pa = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0]
|
||||
ca = [10, 20, 30, 255, 40, 50, 60, 255, 70, 80, 90, 255, 100, 110, 120, 255]
|
||||
pb = [5, 5, 5, 6, 5, 5, 6, 6, 5, 5, 6, 5.5]
|
||||
allp = pa + pb
|
||||
allc = ca + [255] * 16
|
||||
out.append({"name": "multi", "nodes": [{"mesh": 1}, {"mesh": 2}], "roots": [1, 2], "meshes": [
|
||||
{"prims": [{"mode": "triangles", "count": 4, "indices": pack("I", [0, 1, 2, 0, 2, 3]),
|
||||
"attrs": {"POSITION": ["f32", 3, pack("f", pa)], "COLOR_0": ["unorm8", 4, bytes(ca)]}}]},
|
||||
{"prims": [{"mode": "polygons", "count": 4, "indices": pack("I", [0, 1, 2, 3]), "faces": pack("I", [4]),
|
||||
"attrs": {"POSITION": ["f32", 3, pack("f", pb)]}}]}],
|
||||
"props": [("x", "<f4", allp[0::3]), ("y", "<f4", allp[1::3]), ("z", "<f4", allp[2::3]), ("red", "u1", allc[0::4]),
|
||||
("green", "u1", allc[1::4]), ("blue", "u1", allc[2::4])],
|
||||
"faces": [[0, 1, 2], [0, 2, 3], [4, 5, 6, 7]]})
|
||||
# a mirrored polygon: the winding reverses (first corner kept)
|
||||
pm = [0, 0, 0, 1, 0, 0, 1.5, 1, 0, 0.5, 1.5, 0, -0.5, 1, 0]
|
||||
out.append({"name": "mirror", "nodes": [{"mesh": 1, "scale": [-1, 1, 1]}], "roots": [1], "meshes": [{"prims": [{
|
||||
"mode": "polygons", "count": 5, "indices": pack("I", [0, 1, 2, 3, 4]), "faces": pack("I", [5]),
|
||||
"attrs": {"POSITION": ["f32", 3, pack("f", pm)]}}]}],
|
||||
"props": [("x", "<f4", [-v for v in pm[0::3]]), ("y", "<f4", pm[1::3]), ("z", "<f4", pm[2::3])],
|
||||
"faces": [[0, 4, 3, 2, 1]], "transformed": True})
|
||||
for sc in out:
|
||||
sc["props"] = [{"name": p[0], "dtype": p[1], "values": struct.pack("<%d%s" % (len(p[2]), {"<f4": "f", "u1": "B", "<u2": "H"}[p[1]]), *p[2]),
|
||||
**({"tol": p[3]} if len(p) > 3 else {})} for p in sc["props"]]
|
||||
if "faces" in sc:
|
||||
sc["faceSizes"] = pack("I", [len(f) for f in sc["faces"]])
|
||||
sc["faceCorners"] = pack("I", [c for f in sc["faces"] for c in f])
|
||||
return out
|
||||
|
||||
|
||||
def luau_cmd():
|
||||
exe = shutil.which("luau")
|
||||
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
|
||||
|
||||
|
||||
def assimp_faces(ctx, path):
|
||||
txt = ctx.nix("assimp", ["assimp", "info", path]).decode(errors="replace")
|
||||
for line in txt.split("\n"):
|
||||
if line.startswith("Faces:"):
|
||||
return int(line.split()[1])
|
||||
return None
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(47)
|
||||
tmp = tempfile.mkdtemp(prefix="formats-ply-")
|
||||
try:
|
||||
_generate(ctx, rng, tmp)
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
|
||||
def _generate(ctx, rng, tmp):
|
||||
sc = scenes(rng)
|
||||
ctx.emit("ply_scenes", sc)
|
||||
make = ["cube-le.ply", "colors-be.ply", "ascii-mixed.ply", "points-le.ply", "points-ascii-float.ply", "types-be.ply", "big-le.ply", "tristrips.ply"]
|
||||
# assimp conversions: OFF -> PLY (ascii), OBJ -> PLY (binary)
|
||||
off = "OFF\n6 3 0\n" + "".join("%r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(6))
|
||||
off += "3 0 1 2\n4 1 3 4 2\n3 4 5 2\n"
|
||||
obj = "".join("v %r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(8))
|
||||
obj += "vn 0 0 1\nf 1//1 2//1 3//1 4//1\nf 5//1 6//1 7//1\nf 1//1 8//1 5//1\n"
|
||||
with open(os.path.join(tmp, "in.off"), "w") as f:
|
||||
f.write(off)
|
||||
with open(os.path.join(tmp, "in.obj"), "w") as f:
|
||||
f.write(obj)
|
||||
ctx.nix("assimp", ["assimp", "export", os.path.join(tmp, "in.off"), os.path.join(tmp, "assimp-off.ply"), "-fply"])
|
||||
ctx.nix("assimp", ["assimp", "export", os.path.join(tmp, "in.obj"), os.path.join(tmp, "assimp-obj-b.ply"), "-fplyb"])
|
||||
refs = make + ["assimp-off.ply", "assimp-obj-b.ply"]
|
||||
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_ply_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode()
|
||||
ours = []
|
||||
byname = {s["name"]: s for s in sc}
|
||||
for line in enc.split("\n"):
|
||||
if not line.strip():
|
||||
continue
|
||||
label, hexdata = line.split(" ", 1)
|
||||
scene_name, encoding = label.split("/")
|
||||
s = byname[scene_name]
|
||||
fn = "ours-%s-%s.ply" % (scene_name, encoding)
|
||||
with open(os.path.join(tmp, fn), "wb") as f:
|
||||
f.write(bytes.fromhex(hexdata.strip()))
|
||||
ours.append({"name": label, "file": fn, "props": [{**p, "values": p["values"].hex()} for p in s["props"]], "faces": s.get("faces")})
|
||||
code = open(os.path.join(ctx.root, "tools", "fixtures", "_ply_reference.py")).read()
|
||||
try:
|
||||
res = json.loads(ctx.python(["plyfile", "numpy"], code, input=json.dumps({"dir": tmp, "make": make, "ref": refs, "ours": ours}).encode()))
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise RuntimeError("ply reference: " + e.stderr.decode(errors="replace")[-3000:])
|
||||
verdicts = []
|
||||
for o in ours:
|
||||
ok, detail = res["ours"][o["name"]]
|
||||
if o["faces"]:
|
||||
want = sum(len(f) - 2 for f in o["faces"])
|
||||
got = assimp_faces(ctx, os.path.join(tmp, o["file"]))
|
||||
if got != want:
|
||||
ok, detail = False, "assimp reads %s faces, want %d" % (got, want)
|
||||
verdicts.append({"name": o["name"], "ok": ok, "detail": detail})
|
||||
cases = []
|
||||
for name in refs:
|
||||
with open(os.path.join(tmp, name), "rb") as f:
|
||||
data = f.read()
|
||||
r = res["ref"][name]
|
||||
c = {"name": name, "data": data}
|
||||
c.update({k: v for k, v in r.items() if v is not None})
|
||||
cases.append(c)
|
||||
ctx.emit("ply", {"cases": cases, "ours": verdicts})
|
||||
@@ -0,0 +1,383 @@
|
||||
# STL fixtures (tools/fixtures.py).
|
||||
# tests/gen/stl_scenes.luau scenes for the encoder (indexed grid with colours, polygons under a TRS node, a node tree
|
||||
# with a matrix, a mirror and u16 positions) with the expected world-space triangle soup
|
||||
# (computed here with numpy) and the expected colour attribute words
|
||||
# tests/gen/stl.luau cases: STL files made by trimesh (binary / ascii), by assimp (obj / ply -> stl / stlb)
|
||||
# and by hand here (binary starting with "solid", VisCAM and Magics colours, raw attribute
|
||||
# words, odd ASCII: case, tabs, CRLF, several solids, quads, no endsolid, trailing bytes,
|
||||
# empty), each with reference values from trimesh's raw STL reader (facets, CRC-32 of the
|
||||
# f32 vertices and normals, area, bounds, attribute words); `ours`: our encoder's output
|
||||
# (run through the luau CLI: tools/fixtures/_stl_encode.luau) read back by trimesh and
|
||||
# assimp, as verdicts
|
||||
import json, math, os, shutil, struct, subprocess, tempfile, zlib
|
||||
|
||||
INPUTS = ["src/Formats/model/stl", "tools/fixtures/_stl_reference.py", "tools/fixtures/_stl_encode.luau"]
|
||||
|
||||
|
||||
def f32(x):
|
||||
return struct.unpack("<f", struct.pack("<f", x))[0]
|
||||
|
||||
|
||||
def binary_stl(header, tris, normals=None, attrs=None, extra=b""):
|
||||
out = bytearray(header.ljust(80, b"\0")[:80])
|
||||
out += struct.pack("<I", len(tris))
|
||||
for i, t in enumerate(tris):
|
||||
n = normals[i] if normals else (0.0, 0.0, 0.0)
|
||||
out += struct.pack("<3f", *n)
|
||||
for v in t:
|
||||
out += struct.pack("<3f", *v)
|
||||
out += struct.pack("<H", attrs[i] if attrs else 0)
|
||||
return bytes(out) + extra
|
||||
|
||||
|
||||
def rand_tris(rng, n, scale=10.0):
|
||||
return [[tuple(f32(rng.uniform(-scale, scale)) for _ in range(3)) for _ in range(3)] for _ in range(n)]
|
||||
|
||||
|
||||
def unit_normal(t):
|
||||
ux, uy, uz = (t[1][k] - t[0][k] for k in range(3))
|
||||
vx, vy, vz = (t[2][k] - t[0][k] for k in range(3))
|
||||
n = (uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx)
|
||||
ln = math.sqrt(sum(c * c for c in n)) or 1.0
|
||||
return tuple(f32(c / ln) for c in n)
|
||||
|
||||
|
||||
def x8(v):
|
||||
return (v * 255 + 15) // 31
|
||||
|
||||
|
||||
def to5(c):
|
||||
return (c * 31 + 127) // 255
|
||||
|
||||
|
||||
def soup_bytes(tris):
|
||||
return b"".join(struct.pack("<3f", *v) for t in tris for v in t)
|
||||
|
||||
|
||||
def crc(b):
|
||||
return zlib.crc32(b)
|
||||
|
||||
|
||||
# --- hand-made files: (name, data, expected) where expected holds what trimesh cannot tell us
|
||||
def handmade(rng):
|
||||
cases = []
|
||||
tris = rand_tris(rng, 12)
|
||||
cases.append(("bin-solid-header.stl", binary_stl(b"solid this is binary all the same", tris, [unit_normal(t) for t in tris]), {}))
|
||||
# VisCAM: bit 15 = valid, red high; some facets invalid
|
||||
tris = rand_tris(rng, 40)
|
||||
words, cols = [], []
|
||||
for i in range(40):
|
||||
r, g, b = rng.randrange(32), rng.randrange(32), rng.randrange(32)
|
||||
if i % 7 == 3:
|
||||
words.append(rng.randrange(0x8000)) # not valid: the default (opaque white)
|
||||
cols.append((255, 255, 255, 255))
|
||||
else:
|
||||
words.append(0x8000 | r << 10 | g << 5 | b)
|
||||
cols.append((x8(r), x8(g), x8(b), 255))
|
||||
cases.append(("viscam.stl", binary_stl(b"VisCAM colours", tris, None, words), {"colors": "viscam", "cols": cols}))
|
||||
# Magics: COLOR= object colour, bit 15 clear = own colour, red low
|
||||
tris = rand_tris(rng, 40)
|
||||
dc = (200, 100, 50, 180)
|
||||
header = b"magics part COLOR=" + bytes(dc) + b",MATERIAL=" + bytes(range(12))
|
||||
words, cols = [], []
|
||||
for i in range(40):
|
||||
r, g, b = rng.randrange(32), rng.randrange(32), rng.randrange(32)
|
||||
if i % 5 == 0:
|
||||
words.append(0x8000 | rng.randrange(0x8000))
|
||||
cols.append(dc)
|
||||
else:
|
||||
words.append(r | g << 5 | b << 10)
|
||||
cols.append((x8(r), x8(g), x8(b), 255))
|
||||
cases.append(("magics.stl", binary_stl(header, tris, None, words), {"colors": "magics", "cols": cols, "defaultColor": list(dc)}))
|
||||
# raw attribute words (no colour convention)
|
||||
tris = rand_tris(rng, 9)
|
||||
words = [rng.randrange(1, 0x8000) for _ in range(9)]
|
||||
cases.append(("attrs.stl", binary_stl(b"attribute words", tris, None, words), {"words": words}))
|
||||
cases.append(("bin-empty.stl", binary_stl(b"empty", []), {}))
|
||||
# ASCII oddities: case, tabs, CRLF, exponents, two solids (one unnamed), blank lines
|
||||
t1, t2 = rand_tris(rng, 3), rand_tris(rng, 2)
|
||||
s = "SOLID first part\r\n"
|
||||
for t in t1:
|
||||
s += "\tFACET NORMAL %.6e %.6e %.6e\r\n\t\tOUTER LOOP\r\n" % unit_normal(t)
|
||||
for v in t:
|
||||
s += "\t\t\tVERTEX %.9g\t%.9e %r\r\n" % (v[0], v[1], v[2])
|
||||
s += "\t\tENDLOOP\r\n\tENDFACET\r\n\r\n"
|
||||
s += "ENDSOLID first part\r\n\nsolid\n"
|
||||
for t in t2:
|
||||
s += "facet normal %r %r %r outer loop\n" % unit_normal(t)
|
||||
s += " ".join("vertex %r %r %r" % v for v in t) + "\nendloop endfacet\n"
|
||||
s += "endsolid\n"
|
||||
normals = [tuple(f32(float("%.6e" % c)) for c in unit_normal(t)) for t in t1] + [unit_normal(t) for t in t2]
|
||||
cases.append(("ascii-odd.stl", s.encode(), {"solids": ["first part", ""], "solidFacets": [3, 2], "normals": normals}))
|
||||
# a quad facet (fan-triangulated: trimesh cannot read it, the expectation is computed here)
|
||||
q = [(0.0, 0.0, 0.0), (2.0, 0.0, 0.0), (2.0, 1.0, 0.0), (0.0, 1.0, 0.5)]
|
||||
s = "solid quad\nfacet normal 0 0 1\nouter loop\n" + "".join("vertex %r %r %r\n" % v for v in q) + "endloop\nendfacet\nendsolid quad\n"
|
||||
qt = [[q[0], q[1], q[2]], [q[0], q[2], q[3]]]
|
||||
cases.append(("ascii-quad.stl", s.encode(), {"self": True, "tris": qt, "normals": [(0.0, 0.0, 1.0)] * 2}))
|
||||
# no final endsolid
|
||||
t3 = rand_tris(rng, 2)
|
||||
s = "solid open\n" + "".join("facet normal 0 0 0\nouter loop\n" + "".join("vertex %r %r %r\n" % v for v in t) + "endloop\nendfacet\n" for t in t3)
|
||||
cases.append(("ascii-noend.stl", s.encode(), {"self": True, "tris": t3, "normals": [(0.0, 0.0, 0.0)] * 2}))
|
||||
# binary with trailing bytes (size != 84 + 50 n: trimesh refuses, we tolerate)
|
||||
t4 = rand_tris(rng, 5)
|
||||
n4 = [unit_normal(t) for t in t4]
|
||||
cases.append(("bin-trailing.stl", binary_stl(b"trailing junk", t4, n4, extra=b"JUNK!!!"), {"self": True, "tris": t4, "normals": n4}))
|
||||
return cases
|
||||
|
||||
|
||||
# --- encoder scenes (also used by tests/model/stl.luau for round trips)
|
||||
def quat(rng):
|
||||
q = [rng.uniform(-1, 1) for _ in range(4)]
|
||||
ln = math.sqrt(sum(c * c for c in q))
|
||||
return [c / ln for c in q]
|
||||
|
||||
|
||||
def mmul(a, b):
|
||||
return [[sum(a[i][k] * b[k][j] for k in range(4)) for j in range(4)] for i in range(4)]
|
||||
|
||||
|
||||
def det3(m):
|
||||
return (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
|
||||
+ m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]))
|
||||
|
||||
|
||||
EYE = [[1.0 if i == j else 0.0 for j in range(4)] for i in range(4)]
|
||||
|
||||
|
||||
def mat_trs(node):
|
||||
"""row-major 4x4 of a node (glTF: column-major matrix, or T * R * S)"""
|
||||
if "matrix" in node:
|
||||
c = node["matrix"]
|
||||
return [[c[j * 4 + i] for j in range(4)] for i in range(4)]
|
||||
x, y, z, w = node.get("rotation", [0, 0, 0, 1])
|
||||
sx, sy, sz = node.get("scale", [1, 1, 1])
|
||||
tx, ty, tz = node.get("translation", [0, 0, 0])
|
||||
r = [
|
||||
[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
|
||||
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
|
||||
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
|
||||
]
|
||||
return [[r[0][0] * sx, r[0][1] * sy, r[0][2] * sz, tx], [r[1][0] * sx, r[1][1] * sy, r[1][2] * sz, ty],
|
||||
[r[2][0] * sx, r[2][1] * sy, r[2][2] * sz, tz], [0.0, 0.0, 0.0, 1.0]]
|
||||
|
||||
|
||||
def unpack(fmt, data):
|
||||
n = len(data) // struct.calcsize("<" + fmt)
|
||||
return list(struct.unpack("<%d%s" % (n, fmt), data))
|
||||
|
||||
|
||||
def expected_soup(sc):
|
||||
"""world-space triangles (fan-triangulated polygons, reversed winding under a mirror) as f32 bytes, and the
|
||||
colour of each facet's first vertex"""
|
||||
out, cols = [], []
|
||||
|
||||
def prim_tris(p):
|
||||
n = p["count"]
|
||||
flat = unpack("H" if p.get("posType") == "u16" else "f", p["pos"])
|
||||
pos = [flat[i * 3:i * 3 + 3] for i in range(n)]
|
||||
idx = unpack("I", p["indices"]) if "indices" in p else list(range(n))
|
||||
if p["mode"] == "polygons":
|
||||
tris, at = [], 0
|
||||
for s in unpack("I", p["faces"]):
|
||||
for k in range(1, s - 1):
|
||||
tris.append((idx[at], idx[at + k], idx[at + k + 1]))
|
||||
at += s
|
||||
else:
|
||||
tris = [tuple(idx[i:i + 3]) for i in range(0, len(idx) - len(idx) % 3, 3)]
|
||||
return pos, tris
|
||||
|
||||
def walk(ni, parent):
|
||||
node = sc["nodes"][ni - 1]
|
||||
has = any(k in node for k in ("matrix", "translation", "rotation", "scale"))
|
||||
m = mmul(parent, mat_trs(node)) if has else parent
|
||||
if "mesh" in node:
|
||||
for p in sc["meshes"][node["mesh"] - 1]["prims"]:
|
||||
pos, tris = prim_tris(p)
|
||||
flip = det3(m) < 0
|
||||
w = [[m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2] + m[i][3] for i in range(3)] for v in pos]
|
||||
col = p.get("color")
|
||||
for a, b, c in tris:
|
||||
if flip:
|
||||
b, c = c, b
|
||||
out.append(w[a] + w[b] + w[c])
|
||||
if col is not None:
|
||||
cols.append(tuple(col[a * 4:a * 4 + 4]))
|
||||
for c in node.get("children", []):
|
||||
walk(c, m)
|
||||
|
||||
for r in sc["roots"]:
|
||||
walk(r, EYE)
|
||||
return b"".join(struct.pack("<9f", *t) for t in out), cols
|
||||
|
||||
|
||||
def pack(fmt, vals):
|
||||
return struct.pack("<%d%s" % (len(vals), fmt), *vals)
|
||||
|
||||
|
||||
def scenes(rng):
|
||||
out = []
|
||||
# grid: indexed, colours on 5-bit steps, no transform
|
||||
W, H = 7, 6
|
||||
pos = [v for y in range(H) for x in range(W) for v in (x * 0.5, y * 0.5, rng.uniform(-1, 1))]
|
||||
idx = []
|
||||
for y in range(H - 1):
|
||||
for x in range(W - 1):
|
||||
a = y * W + x
|
||||
idx += [a, a + 1, a + W + 1, a, a + W + 1, a + W]
|
||||
col = bytes(v for _ in range(W * H) for v in (x8(rng.randrange(32)), x8(rng.randrange(32)), x8(rng.randrange(32)), 255))
|
||||
out.append({"name": "grid", "nodes": [{"mesh": 1, "name": "grid"}], "roots": [1], "meshes": [{"name": "grid", "prims": [
|
||||
{"mode": "triangles", "count": W * H, "pos": pack("f", pos), "indices": pack("I", idx), "color": col}]}],
|
||||
"encodings": ["binary", "ascii", "viscam", "magics"]})
|
||||
# polygons under a TRS node
|
||||
pv = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 2, 0, 0, 3, 0.5, 0, 2.5, 1.5, 0.2, 1.5, 1.2, 0.1, 0, 0, 1]
|
||||
corners = [0, 1, 2, 3, 1, 4, 5, 6, 7, 2, 0, 3, 8]
|
||||
out.append({"name": "polys", "nodes": [{"mesh": 1, "translation": [1, 2, 3], "rotation": quat(rng), "scale": [2, 0.5, 1.5]}], "roots": [1],
|
||||
"meshes": [{"name": "polys", "prims": [{"mode": "polygons", "count": 9, "pos": pack("f", pv),
|
||||
"indices": pack("I", corners), "faces": pack("I", [4, 6, 3])}]}],
|
||||
"encodings": ["binary", "ascii"]})
|
||||
# a node tree: a matrix root, a mirrored child (winding flips), a child without its own transform, u16 positions,
|
||||
# a soup without indices
|
||||
soup = [rng.uniform(-3, 3) for _ in range(45)]
|
||||
u16 = [rng.randrange(0, 100) for _ in range(18)]
|
||||
c, s = math.cos(0.7), math.sin(0.7)
|
||||
m = [c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 5, -2, 0.5, 1] # column-major: rotate about z, translate
|
||||
out.append({"name": "tree", "nodes": [
|
||||
{"mesh": 2, "matrix": m, "children": [2, 3]},
|
||||
{"mesh": 1, "scale": [-1, 1, 1], "translation": [0, 0, 1]},
|
||||
{"mesh": 3, "name": "plain"},
|
||||
], "roots": [1], "meshes": [
|
||||
{"name": "soup", "prims": [{"mode": "triangles", "count": 15, "pos": pack("f", soup)}]},
|
||||
{"name": "u16", "prims": [{"mode": "triangles", "count": 6, "posType": "u16", "pos": pack("H", u16),
|
||||
"indices": pack("I", [0, 1, 2, 2, 3, 4, 4, 5, 0, 1, 3, 5])}]},
|
||||
{"name": "pair", "prims": [{"mode": "triangles", "count": 4, "pos": pack("f", [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0.25]),
|
||||
"indices": pack("I", [0, 1, 2, 0, 2, 3])}]},
|
||||
], "encodings": ["binary", "ascii"]})
|
||||
for sc in out:
|
||||
soup_b, cols = expected_soup(sc)
|
||||
sc["expect"] = soup_b
|
||||
sc["exact"] = sc["name"] == "grid"
|
||||
if cols:
|
||||
sc["viscamWords"] = [0x8000 | to5(r) << 10 | to5(g) << 5 | to5(b) for r, g, b, _ in cols]
|
||||
sc["magicsWords"] = [to5(r) | to5(g) << 5 | to5(b) << 10 for r, g, b, _ in cols]
|
||||
return out
|
||||
|
||||
|
||||
def luau_cmd():
|
||||
exe = shutil.which("luau")
|
||||
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
|
||||
|
||||
|
||||
def assimp_info(ctx, path):
|
||||
txt = ctx.nix("assimp", ["assimp", "info", path]).decode(errors="replace")
|
||||
faces = verts = None
|
||||
for line in txt.split("\n"):
|
||||
if line.startswith("Faces:"):
|
||||
faces = int(line.split()[1])
|
||||
if line.startswith("Vertices:"):
|
||||
verts = int(line.split()[1])
|
||||
return faces, verts
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(31)
|
||||
tmp = tempfile.mkdtemp(prefix="formats-stl-")
|
||||
try:
|
||||
_generate(ctx, rng, tmp)
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
|
||||
def _generate(ctx, rng, tmp):
|
||||
# scenes first: the encoder script reads them
|
||||
sc = scenes(rng)
|
||||
ctx.emit("stl_scenes", sc)
|
||||
files = {}
|
||||
hand = handmade(rng)
|
||||
for name, data, _ in hand:
|
||||
files[name] = data
|
||||
# assimp conversions: an OBJ with quads and a PLY -> ASCII and binary STL
|
||||
obj = "".join("v %r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(12))
|
||||
obj += "f 1 2 3 4\nf 5 6 7\nf 8 9 10 11 12\nf 2 4 6\n"
|
||||
ply = "ply\nformat ascii 1.0\nelement vertex 5\nproperty float x\nproperty float y\nproperty float z\nelement face 3\nproperty list uchar int vertex_indices\nend_header\n"
|
||||
ply += "".join("%r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(5))
|
||||
ply += "3 0 1 2\n4 0 2 3 4\n3 4 3 1\n"
|
||||
with open(os.path.join(tmp, "in.obj"), "w") as f:
|
||||
f.write(obj)
|
||||
with open(os.path.join(tmp, "in.ply"), "w") as f:
|
||||
f.write(ply)
|
||||
for src, dst, fid in (("in.obj", "assimp-obj.stl", "stl"), ("in.obj", "assimp-obj-b.stl", "stlb"), ("in.ply", "assimp-ply-b.stl", "stlb")):
|
||||
ctx.nix("assimp", ["assimp", "export", os.path.join(tmp, src), os.path.join(tmp, dst), "-f" + fid])
|
||||
for name, data in files.items():
|
||||
with open(os.path.join(tmp, name), "wb") as f:
|
||||
f.write(data)
|
||||
make = [["trimesh-icosphere.stl", "icosphere", "stl", 1], ["trimesh-icosphere-ascii.stl", "icosphere", "stl_ascii", 1],
|
||||
["trimesh-box.stl", "box", "stl", 2], ["trimesh-capsule-ascii.stl", "capsule", "stl_ascii", 3],
|
||||
["trimesh-soup.stl", "soup", "stl", 4], ["trimesh-soup-ascii.stl", "soup", "stl_ascii", 5]]
|
||||
refnames = [m[0] for m in make] + ["assimp-obj.stl", "assimp-obj-b.stl", "assimp-ply-b.stl"]
|
||||
refnames += [n for n, _, e in hand if not e.get("self")]
|
||||
# our encoder's output (the luau CLI prints "<scene>/<encoding> <hex>" lines)
|
||||
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_stl_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode()
|
||||
ours = []
|
||||
byname = {s["name"]: s for s in sc}
|
||||
for line in enc.split("\n"):
|
||||
if not line.strip():
|
||||
continue
|
||||
label, hexdata = line.split(" ", 1)
|
||||
scene_name, encoding = label.split("/")
|
||||
s = byname[scene_name]
|
||||
fn = "ours-%s-%s.stl" % (scene_name, encoding)
|
||||
with open(os.path.join(tmp, fn), "wb") as f:
|
||||
f.write(bytes.fromhex(hexdata.strip()))
|
||||
o = {"name": label, "file": fn, "expect": s["expect"].hex(), "exact": s["exact"]}
|
||||
if encoding == "viscam":
|
||||
o["colors"] = s["viscamWords"]
|
||||
elif encoding == "magics":
|
||||
o["colors"] = s["magicsWords"]
|
||||
ours.append(o)
|
||||
code = open(os.path.join(ctx.root, "tools", "fixtures", "_stl_reference.py")).read()
|
||||
try:
|
||||
res = json.loads(ctx.python(["trimesh", "numpy"], code, input=json.dumps({"dir": tmp, "make": make, "ref": refnames, "ours": ours}).encode()))
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise RuntimeError("stl reference: " + e.stderr.decode(errors="replace")[-3000:])
|
||||
verdicts = []
|
||||
for o in ours:
|
||||
ok, detail = res["ours"][o["name"]]
|
||||
# assimp reads it too
|
||||
faces, _ = assimp_info(ctx, os.path.join(tmp, o["file"]))
|
||||
want = len(bytes.fromhex(o["expect"])) // 36
|
||||
if faces != want:
|
||||
ok, detail = False, "assimp reads %s faces, want %d" % (faces, want)
|
||||
verdicts.append({"name": o["name"], "ok": ok, "detail": detail})
|
||||
cases = []
|
||||
for name in refnames:
|
||||
with open(os.path.join(tmp, name), "rb") as f:
|
||||
data = f.read()
|
||||
r = res["ref"][name]
|
||||
c = {"name": name, "data": data, "facets": r["facets"], "pos_crc": r["pos_crc"], "area": r["area"], "bounds": r["bounds"]}
|
||||
extra = next((e for n, _, e in hand if n == name), {})
|
||||
if "nrm_crc" in r:
|
||||
c["nrm_crc"] = r["nrm_crc"]
|
||||
elif "normals" in extra: # the normals written here (%.6e / repr of f32 values, read as f32)
|
||||
c["nrm_crc"] = crc(b"".join(struct.pack("<3f", *n) * 3 for n in extra["normals"]))
|
||||
if "cols" in extra:
|
||||
c["colors"] = extra["colors"]
|
||||
c["col_crc"] = crc(b"".join(bytes(col) * 3 for col in extra["cols"]))
|
||||
# the colour words trimesh read must be the ones written
|
||||
assert r.get("attr") is not None
|
||||
if "defaultColor" in extra:
|
||||
c["defaultColor"] = extra["defaultColor"]
|
||||
if "words" in extra:
|
||||
assert r["attr"] == extra["words"]
|
||||
c["attr_crc"] = crc(struct.pack("<%dH" % len(extra["words"]), *extra["words"]))
|
||||
if "solids" in extra:
|
||||
c["solids"] = extra["solids"]
|
||||
c["solidFacets"] = extra["solidFacets"]
|
||||
c["binary"] = not data.lstrip()[:5].lower() == b"solid" or (len(data) >= 84 and 84 + 50 * struct.unpack("<I", data[80:84])[0] == len(data))
|
||||
cases.append(c)
|
||||
for name, data, e in hand:
|
||||
if e.get("self"):
|
||||
tris = e["tris"]
|
||||
cases.append({"name": name, "data": data, "facets": len(tris), "pos_crc": crc(soup_bytes(tris)),
|
||||
"nrm_crc": crc(b"".join(struct.pack("<3f", *n) * 3 for n in e["normals"])),
|
||||
"binary": not data.startswith(b"solid")})
|
||||
ctx.emit("stl", {"cases": cases, "ours": verdicts})
|
||||
@@ -0,0 +1,292 @@
|
||||
# VOX fixtures (tools/fixtures.py). There is no MagicaVoxel reader in nixpkgs, so the reference is (1) files saved by
|
||||
# MagicaVoxel itself (tests/fixtures/vox: ephtracy/voxel-model samples, version 150, and jpaver/opengametools demo files
|
||||
# with scene graphs, layers, materials, render objects, cameras, notes and META; licences in licenses/), parsed here
|
||||
# by an independent Python reader written from the spec, and (2) synthetic files written here with every chunk type,
|
||||
# rotations (including mirrors), nested groups, animation frames and odd cases.
|
||||
# tests/gen/vox_cases.luau { name, data, version, models = { { size, count, crc (of the dense x-fastest grid),
|
||||
# faces (exposed unit faces: the greedy mesh area) } }, paletteCrc, chunks = { id = n },
|
||||
# nodes = { { name, world (row-major 3x4: R | t) } } for every shape node, names, layers,
|
||||
# materials, notes, cameras, robjs }
|
||||
import os, struct, zlib
|
||||
|
||||
INPUTS = ["tests/fixtures/vox"]
|
||||
|
||||
def default_palette():
|
||||
steps = [0xff, 0xcc, 0x99, 0x66, 0x33, 0]
|
||||
pal = [(r, g, b, 255) for r in steps for g in steps for b in steps][:215]
|
||||
ramp = [0xee, 0xdd, 0xbb, 0xaa, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11]
|
||||
for ch in range(3):
|
||||
for v in ramp:
|
||||
c = [0, 0, 0, 255]
|
||||
c[ch] = v
|
||||
pal.append(tuple(c))
|
||||
pal += [(v, v, v, 255) for v in ramp]
|
||||
return pal
|
||||
|
||||
|
||||
def spec_palette(text):
|
||||
# the default_palette[256] array of the spec text (ABGR words, entry i = palette index i)
|
||||
body = text[text.index("default_palette[256]"):]
|
||||
body = body[body.index("{") + 1:body.index("}")]
|
||||
words = [int(w, 16) for w in body.replace(",", " ").split()]
|
||||
return [(w & 255, (w >> 8) & 255, (w >> 16) & 255, w >> 24) for w in words]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- reader (reference)
|
||||
def rd_dict(d, p):
|
||||
n, = struct.unpack_from("<i", d, p)
|
||||
p += 4
|
||||
out = {}
|
||||
for _ in range(n):
|
||||
kl, = struct.unpack_from("<i", d, p)
|
||||
k = d[p + 4:p + 4 + kl].decode("latin1")
|
||||
p += 4 + kl
|
||||
vl, = struct.unpack_from("<i", d, p)
|
||||
v = d[p + 4:p + 4 + vl].decode("latin1")
|
||||
p += 4 + vl
|
||||
out[k] = v
|
||||
return out, p
|
||||
|
||||
|
||||
def rot(b):
|
||||
i0, i1 = b & 3, (b >> 2) & 3
|
||||
i2 = 3 - i0 - i1
|
||||
R = [[0] * 3 for _ in range(3)]
|
||||
for row, (i, bit) in enumerate(((i0, 4), (i1, 5), (i2, 6))):
|
||||
R[row][i] = -1 if b & (1 << bit) else 1
|
||||
return R
|
||||
|
||||
|
||||
def matmul(A, B): # 3x4 affine (R | t)
|
||||
R = [[sum(A[r][k] * B[k][c] for k in range(3)) for c in range(3)] for r in range(3)]
|
||||
t = [sum(A[r][k] * B[k][3] for k in range(3)) + A[r][3] for r in range(3)]
|
||||
return [R[r] + [t[r]] for r in range(3)]
|
||||
|
||||
|
||||
def parse(d):
|
||||
assert d[:4] == b"VOX "
|
||||
version, = struct.unpack_from("<i", d, 4)
|
||||
assert d[8:12] == b"MAIN"
|
||||
n, m = struct.unpack_from("<ii", d, 12)
|
||||
p = 20 + n
|
||||
end = min(p + m, len(d))
|
||||
models, size, palette = [], None, None
|
||||
graph, counts = {}, {}
|
||||
mats, layers, notes, cams, robjs = {}, [], [], [], []
|
||||
while p + 12 <= end:
|
||||
cid = d[p:p + 4].decode("latin1")
|
||||
n, m = struct.unpack_from("<ii", d, p + 4)
|
||||
c = p + 12
|
||||
counts[cid] = counts.get(cid, 0) + 1
|
||||
if cid == "SIZE":
|
||||
size = struct.unpack_from("<iii", d, c)
|
||||
elif cid == "XYZI":
|
||||
k, = struct.unpack_from("<i", d, c)
|
||||
sx, sy, sz = size
|
||||
grid = bytearray(sx * sy * sz)
|
||||
for i in range(k):
|
||||
x, y, z, ci = d[c + 4 + i * 4:c + 8 + i * 4]
|
||||
if x < sx and y < sy and z < sz and ci:
|
||||
grid[x + sx * (y + sy * z)] = ci
|
||||
models.append((size, grid))
|
||||
elif cid == "RGBA":
|
||||
palette = [tuple(d[c + i * 4:c + i * 4 + 4]) for i in range(255)]
|
||||
elif cid == "MATL":
|
||||
mid, = struct.unpack_from("<i", d, c)
|
||||
mats[mid], _ = rd_dict(d, c + 4)
|
||||
elif cid == "nTRN":
|
||||
nid, = struct.unpack_from("<i", d, c)
|
||||
attrs, q = rd_dict(d, c + 4)
|
||||
child, _, layer, nf = struct.unpack_from("<iiii", d, q)
|
||||
q += 16
|
||||
frames = []
|
||||
for _ in range(nf):
|
||||
f, q = rd_dict(d, q)
|
||||
frames.append(f)
|
||||
graph[nid] = ("T", attrs, child, frames)
|
||||
elif cid == "nGRP":
|
||||
nid, = struct.unpack_from("<i", d, c)
|
||||
attrs, q = rd_dict(d, c + 4)
|
||||
k, = struct.unpack_from("<i", d, q)
|
||||
graph[nid] = ("G", attrs, list(struct.unpack_from("<%di" % k, d, q + 4)))
|
||||
elif cid == "nSHP":
|
||||
nid, = struct.unpack_from("<i", d, c)
|
||||
attrs, q = rd_dict(d, c + 4)
|
||||
k, = struct.unpack_from("<i", d, q)
|
||||
mid, = struct.unpack_from("<i", d, q + 4)
|
||||
graph[nid] = ("S", attrs, mid)
|
||||
elif cid == "LAYR":
|
||||
lid, = struct.unpack_from("<i", d, c)
|
||||
layers.append(rd_dict(d, c + 4)[0])
|
||||
elif cid == "NOTE":
|
||||
k, = struct.unpack_from("<i", d, c)
|
||||
q = c + 4
|
||||
for _ in range(k):
|
||||
l, = struct.unpack_from("<i", d, q)
|
||||
notes.append(d[q + 4:q + 4 + l].decode("latin1"))
|
||||
q += 4 + l
|
||||
elif cid == "rCAM":
|
||||
cams.append(struct.unpack_from("<i", d, c)[0])
|
||||
elif cid == "rOBJ":
|
||||
robjs.append(rd_dict(d, c)[0])
|
||||
p = c + n + m
|
||||
# shape nodes in depth-first order with world transforms
|
||||
shapes = []
|
||||
|
||||
def walk(nid, parent):
|
||||
kind, attrs, child, frames = graph[nid]
|
||||
f = frames[0] if frames else {}
|
||||
R = rot(int(f["_r"])) if "_r" in f else [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
|
||||
t = [int(v) for v in f.get("_t", "0 0 0").split()]
|
||||
world = matmul(parent, [R[r] + [t[r]] for r in range(3)])
|
||||
ch = graph.get(child)
|
||||
if ch and ch[0] == "G":
|
||||
for c2 in ch[2]:
|
||||
walk(c2, world)
|
||||
elif ch and ch[0] == "S":
|
||||
shapes.append({"name": attrs.get("_name", ""), "model": ch[2] + 1, "world": [v for row in world for v in row]})
|
||||
|
||||
if 0 in graph:
|
||||
walk(0, [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])
|
||||
pal = palette or default_palette()
|
||||
out_models = []
|
||||
for (sx, sy, sz), grid in models:
|
||||
faces = 0
|
||||
for z in range(sz):
|
||||
for y in range(sy):
|
||||
for x in range(sx):
|
||||
if grid[x + sx * (y + sy * z)]:
|
||||
for dx, dy, dz in ((1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)):
|
||||
X, Y, Z = x + dx, y + dy, z + dz
|
||||
if not (0 <= X < sx and 0 <= Y < sy and 0 <= Z < sz) or not grid[X + sx * (Y + sy * Z)]:
|
||||
faces += 1
|
||||
out_models.append({"size": [sx, sy, sz], "count": sum(1 for v in grid if v), "crc": zlib.crc32(bytes(grid)), "faces": faces})
|
||||
return {
|
||||
"version": version,
|
||||
"models": out_models,
|
||||
"paletteCrc": zlib.crc32(bytes(v for c in pal for v in c)),
|
||||
"hasPalette": palette is not None,
|
||||
"chunks": counts,
|
||||
"shapes": shapes,
|
||||
"layers": len(layers),
|
||||
"materials": len(mats),
|
||||
"notes": len(notes),
|
||||
"cameras": len(cams),
|
||||
"robjs": len(robjs),
|
||||
"glassMaterials": sum(1 for m in mats.values() if m.get("_type") == "_glass"),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- writer (synthetic files)
|
||||
def s(x):
|
||||
b = x.encode()
|
||||
return struct.pack("<i", len(b)) + b
|
||||
|
||||
|
||||
def dct(d):
|
||||
return struct.pack("<i", len(d)) + b"".join(s(k) + s(v) for k, v in d.items())
|
||||
|
||||
|
||||
def chunk(cid, content, children=b""):
|
||||
return cid.encode() + struct.pack("<ii", len(content), len(children)) + content + children
|
||||
|
||||
|
||||
def vox(chunks, version=200, main_size=None):
|
||||
body = b"".join(chunks)
|
||||
return b"VOX " + struct.pack("<i", version) + b"MAIN" + struct.pack("<ii", 0, main_size if main_size is not None else len(body)) + body
|
||||
|
||||
|
||||
def model(rng, sx, sy, sz, fill=0.4, colors=(1, 255)):
|
||||
vox_list = []
|
||||
for z in range(sz):
|
||||
for y in range(sy):
|
||||
for x in range(sx):
|
||||
if rng.random() < fill:
|
||||
vox_list.append((x, y, z, rng.randrange(*colors)))
|
||||
rng.shuffle(vox_list)
|
||||
return [chunk("SIZE", struct.pack("<iii", sx, sy, sz)), chunk("XYZI", struct.pack("<i", len(vox_list)) + b"".join(bytes(v) for v in vox_list))]
|
||||
|
||||
|
||||
def ntrn(nid, child, attrs=None, frames=None, layer=0):
|
||||
frames = frames or [{}]
|
||||
return chunk("nTRN", struct.pack("<i", nid) + dct(attrs or {}) + struct.pack("<iiii", child, -1, layer, len(frames)) + b"".join(dct(f) for f in frames))
|
||||
|
||||
|
||||
def ngrp(nid, children, attrs=None):
|
||||
return chunk("nGRP", struct.pack("<i", nid) + dct(attrs or {}) + struct.pack("<i", len(children)) + b"".join(struct.pack("<i", c) for c in children))
|
||||
|
||||
|
||||
def nshp(nid, models_):
|
||||
return chunk("nSHP", struct.pack("<i", nid) + dct({}) + struct.pack("<i", len(models_)) + b"".join(struct.pack("<i", m) + dct({"_f": str(i)} if len(models_) > 1 else {}) for i, m in enumerate(models_)))
|
||||
|
||||
|
||||
def rgba(rng):
|
||||
return chunk("RGBA", bytes(rng.randrange(256) for _ in range(1024)))
|
||||
|
||||
|
||||
def synthetic(rng):
|
||||
out = []
|
||||
# 1. a plain v150 model without a palette (the default palette)
|
||||
out.append(("syn-default-palette", vox(model(rng, 7, 5, 3), 150)))
|
||||
# 2. full scene: nested groups, every rotation family, mirrors, hidden, layers, materials, notes, cameras, IMAP, META
|
||||
ch = []
|
||||
for _ in range(4):
|
||||
ch += model(rng, rng.randrange(1, 12), rng.randrange(1, 12), rng.randrange(1, 12))
|
||||
ch += [
|
||||
ntrn(0, 1, layer=-1),
|
||||
ngrp(1, [2, 4, 8]),
|
||||
ntrn(2, 3, {"_name": "a"}, [{"_r": "4", "_t": "1 2 3"}]),
|
||||
nshp(3, [0]),
|
||||
ntrn(4, 5, {"_name": "group", "_hidden": "1"}, [{"_r": "17", "_t": "-5 0 7"}], layer=1), # 90 deg about z
|
||||
ngrp(5, [6, 10]),
|
||||
ntrn(6, 7, {"_name": "b"}, [{"_r": "20", "_t": "0 0 -4"}]), # a mirror (x flipped)
|
||||
nshp(7, [1]),
|
||||
ntrn(8, 9, {"_name": "anim"}, [{"_r": "9", "_t": "3 3 3", "_f": "0"}, {"_r": "4", "_t": "4 4 4", "_f": "5"}]),
|
||||
nshp(9, [2, 3]),
|
||||
ntrn(10, 11, {"_name": "c"}, [{"_r": "98", "_t": "10 -20 30"}]),
|
||||
nshp(11, [3]),
|
||||
chunk("LAYR", struct.pack("<i", 0) + dct({"_name": "zero"}) + struct.pack("<i", -1)),
|
||||
chunk("LAYR", struct.pack("<i", 1) + dct({"_name": "one", "_hidden": "1", "_color": "255 0 0"}) + struct.pack("<i", -1)),
|
||||
rgba(rng),
|
||||
chunk("IMAP", bytes(range(256))),
|
||||
]
|
||||
for mid in (1, 2, 200):
|
||||
ch.append(chunk("MATL", struct.pack("<i", mid) + dct({"_type": ["_diffuse", "_glass", "_emit"][mid % 3], "_rough": "0.25", "_ior": "1.5", "_flux": "2"})))
|
||||
ch.append(chunk("rOBJ", dct({"_type": "_bg", "_color": "0 0 0"})))
|
||||
ch.append(chunk("rCAM", struct.pack("<i", 0) + dct({"_mode": "pers", "_focus": "0 0 0", "_angle": "30 40 0", "_radius": "80", "_frustum": "0.4", "_fov": "45"})))
|
||||
ch.append(chunk("NOTE", struct.pack("<i", 2) + s("first") + s("second")))
|
||||
ch.insert(0, chunk("META", dct({"_anim_range": "0 30"})))
|
||||
ch.append(chunk("ZZZZ", b"unknown payload"))
|
||||
out.append(("syn-scene", vox(ch)))
|
||||
# 3. edge cases: voxels outside the grid, index 0, duplicates, a 1x1x1 model
|
||||
vox_list = [(0, 0, 0, 5), (9, 0, 0, 7), (1, 1, 1, 0), (1, 1, 1, 9), (1, 1, 1, 10)]
|
||||
ch = [chunk("SIZE", struct.pack("<iii", 2, 2, 2)), chunk("XYZI", struct.pack("<i", len(vox_list)) + b"".join(bytes(v) for v in vox_list)), rgba(rng)]
|
||||
out.append(("syn-edge", vox(ch)))
|
||||
out.append(("syn-single", vox([chunk("SIZE", struct.pack("<iii", 1, 1, 1)), chunk("XYZI", struct.pack("<i", 1) + bytes((0, 0, 0, 1)))])))
|
||||
# 4. a full 64^3 block and a 3d checkerboard (worst case for greedy meshing)
|
||||
full = [(x, y, z, 1 + (z % 3)) for z in range(64) for y in range(64) for x in range(64)]
|
||||
out.append(("syn-block64", vox([chunk("SIZE", struct.pack("<iii", 64, 64, 64)), chunk("XYZI", struct.pack("<i", len(full)) + b"".join(bytes(v) for v in full))])))
|
||||
chk = [(x, y, z, 3) for z in range(16) for y in range(16) for x in range(16) if (x + y + z) % 2 == 0]
|
||||
out.append(("syn-checker16", vox([chunk("SIZE", struct.pack("<iii", 16, 16, 16)), chunk("XYZI", struct.pack("<i", len(chk)) + b"".join(bytes(v) for v in chk))])))
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(7)
|
||||
cases = []
|
||||
folder = os.path.join("tests", "fixtures", "vox")
|
||||
for f in sorted(os.listdir(os.path.join(ctx.root, folder))):
|
||||
if f.endswith(".vox"):
|
||||
cases.append((f, ctx.read(os.path.join(folder, f))))
|
||||
cases += synthetic(rng)
|
||||
out = []
|
||||
for name, data in cases:
|
||||
ref = parse(data)
|
||||
ref["name"] = name
|
||||
ref["data"] = data
|
||||
out.append(ref)
|
||||
ctx.emit("vox_cases", out)
|
||||
# the spec's default palette (parsed from the spec text) must equal the formula used by both readers
|
||||
pal = spec_palette(ctx.read(os.path.join(folder, "MagicaVoxel-file-format-vox.txt")).decode())[1:]
|
||||
assert pal == default_palette(), "default palette formula differs from the spec"
|
||||
ctx.emit("vox_default_palette", [list(c) for c in pal])
|
||||
Reference in new issue
Block a user