ws-3d: model/obj (OBJ + MTL read/write: objects/groups -> nodes, per-material primitives, n-gons fan-triangulated or kept as polygons, vertex colours, lines/points, PBR MTL extension, texture maps with options, files through opts.files/resolve); tests vs assimp + trimesh, and assimp/trimesh reading our output
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
58f6b32541
commit
c3bbae0271
6 files changed
+1641
No files matched your search
@@ -0,0 +1,61 @@
|
||||
# Shared helpers for the model fixture generators (obj.py, gltf.py): reference tools through nix.
|
||||
# assimp_info(ctx, paths) -> [ { 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):
|
||||
out = []
|
||||
for p in paths:
|
||||
txt = ctx.nix("assimp", ["assimp", "info", p]).decode("utf-8", "replace")
|
||||
|
||||
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()):
|
||||
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 []}
|
||||
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,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)])
|
||||
Reference in new issue
Block a user