Files
rosetta/tools/fixtures/3mf.py
T
4DBugandClaude Opus 5.5 434a304315 ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4
C2, the hierarchy (tools/move.py, every reference rewritten mechanically):
- codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder;
  codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample
  VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url;
  codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err
  Crc32 Adler32 Base64 Md5 Input Sniff.
- LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md).
- Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes.

C3, generic code out of format folders:
- containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first,
  trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64
  through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it.
- codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position,
  priming and end trimming) that aac, caf and m4a each carried (~70 lines each).
- codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of
  its own (the AND mask / alpha rule stay ICO's).
- codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model),
  Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is
  Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the
  fixtures' bind shapes).
- README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes:
  FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the
  shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks
  decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type
  baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-31 12:25:03 -05:00

112 lines
5.2 KiB
Python

# 3MF fixtures (tools/fixtures.py): the lib3mf test suite and SDK example files (nixpkgs#lib3mf.src, read only, never
# committed: core, materials (base / colour / texture / composite / multiproperties), production parts, metadata,
# units, thumbnails, files lib3mf rejects), assimp's box.3mf (nixpkgs#assimp.src), and files written by assimp's and
# trimesh's 3MF exporters, with reference values from lib3mf 2.5 (tools/fixtures/_3mf_reference.py: world-space
# triangles / area / bounds through build items and components, mesh object sizes, material group counts, unit),
# assimp (`assimp info -r`) and trimesh (area, faces).
# tests/gen/3mf_cases.luau { name, data, lib3mf = {...} | { failed }, assimp, trimesh }
# tests/gen/3mf_xcheck.luau our encoder's output for every case (tools/fixtures/_3mf_encode.luau) read back by
# lib3mf / assimp / trimesh: { name, case, lib3mf, assimp, trimesh }
import importlib.util, json, os, subprocess, sys
INPUTS = ["src/Formats/model/3mf", "src/Formats/codecs/text/Xml", "src/Formats/containers/Zip",
"tools/fixtures/_3mf_reference.py", "tools/fixtures/_3mf_encode.luau", "tools/fixtures/_model_ref.py"]
MAX_SIZE = 500_000
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 store(attr):
out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#" + attr], check=True, capture_output=True)
return out.stdout.decode().strip().split("\n")[-1]
def lib3mf(ctx, paths):
src, lib = store("lib3mf.src"), store("lib3mf")
res = subprocess.run([sys.executable, "-I", os.path.join(ctx.root, "tools", "fixtures", "_3mf_reference.py"),
os.path.join(src, "Autogenerated", "Bindings", "Python"), os.path.join(lib, "lib", "lib3mf")],
input=json.dumps(paths).encode(), capture_output=True, check=True)
return json.loads(res.stdout)
TRIMESH_EXPORT = r"""
import sys, trimesh
m = trimesh.creation.icosphere(subdivisions=2, radius=10.0)
b = trimesh.creation.box(extents=(4, 6, 8))
b.apply_translation((20, 0, 0))
s = trimesh.Scene([m, b])
open(sys.argv[1] if len(sys.argv) > 1 else "/dev/stdout", "wb").write(s.export(file_type="3mf"))
"""
def ply_torus(R=20.0, r=5.0, a=24, b=12):
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 + r * math.cos(v)) * math.sin(u), r * math.sin(v)))
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, q2, p2))
fs.append((p, q, q2))
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)
src = store("lib3mf.src")
files = []
for base in ("Tests/TestFiles", "SDK/Examples/Files"):
for d, _, fs in sorted(os.walk(os.path.join(src, base))):
for f in sorted(fs):
p = os.path.join(d, f)
if f.endswith(".3mf") and os.path.getsize(p) <= MAX_SIZE:
files.append(("lib3mf/" + os.path.relpath(p, os.path.join(src, base)), p))
files.append(("assimp/box.3mf", os.path.join(store("assimp.src"), "test", "models", "3MF", "box.3mf")))
tmp = M.tempdir()
ply = os.path.join(tmp, "torus.ply")
with open(ply, "wb") as f:
f.write(ply_torus())
out = os.path.join(tmp, "torus_assimp.3mf")
ctx.nix(["assimp"], ["assimp", "export", ply, out, "-f3mf"])
files.append(("assimp/torus_export.3mf", out))
tm = ctx.python(["trimesh", "numpy", "networkx", "lxml"], TRIMESH_EXPORT)
out = os.path.join(tmp, "trimesh_export.3mf")
with open(out, "wb") as f:
f.write(tm)
files.append(("trimesh/export.3mf", out))
paths = [p for _, p in files]
refs = lib3mf(ctx, paths)
infos = M.assimp_info(ctx, paths, raw=True)
tms = M.trimesh_metrics(ctx, paths)
cases = []
for (name, p), r, a, t in zip(files, refs, infos, tms):
cases.append({"name": name, "data": open(p, "rb").read(), "lib3mf": r, "assimp": a, "trimesh": t})
ctx.emit("3mf_cases", cases)
# the reference tools read our output
ours = M.luau_encode(ctx, "tools/fixtures/_3mf_encode.luau")
xtmp = M.tempdir()
names = sorted(ours, key=lambda n: int(n.split("_")[1].split(".")[0]))
xp = []
for n in names:
p = os.path.join(xtmp, n)
with open(p, "wb") as f:
f.write(ours[n])
xp.append(p)
xr = lib3mf(ctx, xp)
xi = M.assimp_info(ctx, xp, raw=True)
xt = M.trimesh_metrics(ctx, xp)
ctx.emit("3mf_xcheck", [{"name": n, "case": int(n.split("_")[1].split(".")[0]), "lib3mf": r, "assimp": a, "trimesh": t}
for n, r, a, t in zip(names, xr, xi, xt)])