384 lines
18 KiB
Python
384 lines
18 KiB
Python
# 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})
|