ws-3d2/3mf: model/3mf read / write (core, materials extension: base / colour / texture2d groups, composite, multiproperties; components, production p:path parts, units, metadata); tests against lib3mf 2.5 (its test suite), assimp, trimesh, our output read back by all three; bench lines
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
75c677074a
commit
e87102202e
10 files changed
+1805
No files matched your search
@@ -451,6 +451,14 @@ do
|
||||
bench("ply binary decode (" .. buffer.len(ply) // 1000 .. " KB)", 5, buffer.len(ply), function()
|
||||
Ply.decode(Bytes.reader(ply))
|
||||
end)
|
||||
local ThreeMf = require("@formats/model/3mf")
|
||||
local tmf = assert(ThreeMf.encode(scene))
|
||||
bench("3mf decode (" .. buffer.len(tmf) // 1000 .. " KB zipped)", 2, buffer.len(tmf), function()
|
||||
ThreeMf.decode(Bytes.reader(tmf))
|
||||
end)
|
||||
bench("3mf encode", 2, buffer.len(tmf), function()
|
||||
ThreeMf.encode(scene)
|
||||
end)
|
||||
local V = 128
|
||||
local grid = Types.Voxels.new(V, V, V)
|
||||
for z = 0, V - 1 do
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
# 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/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)])
|
||||
@@ -0,0 +1,28 @@
|
||||
-- tools/fixtures/_3mf_encode: run by tools/fixtures/3mf.py (luau CLI, repo root): decodes every 3MF case that lib3mf
|
||||
-- reads with our reader and encodes it with our writer, printing "rt_<case>.3mf\t<hex>" lines for the reference tools
|
||||
-- (lib3mf, assimp, trimesh) to read back.
|
||||
local ThreeMf = require("@formats/model/3mf")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/3mf_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
|
||||
if not c.lib3mf.failed then
|
||||
local scene = ThreeMf.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
if scene then
|
||||
local out = assert(ThreeMf.encode(scene))
|
||||
print(string.format("rt_%d.3mf\t%s", i, hex(buffer.tostring(out))))
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,115 @@
|
||||
# 3MF reference values through lib3mf's Python binding (ctypes over lib3mf.so; both from nixpkgs), run by 3mf.py as
|
||||
# `python3 -I _3mf_reference.py <bindings dir> <lib3mf.so without .so> < paths.json` -> JSON list, one entry per file:
|
||||
# { unit, items, meshObjects = [ [vertices, triangles] ... sorted ], triangles, area, min, max (world space, every
|
||||
# build item through its components), baseGroups, colorGroups, textures, texGroups } or { failed = message }
|
||||
import json, math, sys
|
||||
|
||||
sys.path.insert(0, sys.argv[1])
|
||||
import Lib3MF # noqa: E402
|
||||
|
||||
W = Lib3MF.Wrapper(sys.argv[2])
|
||||
UNITS = {0: "micron", 1: "millimeter", 2: "centimeter", 3: "inch", 4: "foot", 5: "meter"}
|
||||
|
||||
|
||||
def mat(t):
|
||||
f = t.Fields
|
||||
return [[f[r][c] for c in range(3)] for r in range(4)]
|
||||
|
||||
|
||||
def mul(a, b): # row-vector 4x3 affine: p * a * b
|
||||
out = []
|
||||
for r in range(4):
|
||||
row = []
|
||||
for c in range(3):
|
||||
s = sum(a[r][k] * b[k][c] for k in range(3))
|
||||
if r == 3:
|
||||
s += b[3][c]
|
||||
row.append(s)
|
||||
out.append(row)
|
||||
return out
|
||||
|
||||
|
||||
IDENT = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0]]
|
||||
|
||||
|
||||
def count(it):
|
||||
n = 0
|
||||
while it.MoveNext():
|
||||
n += 1
|
||||
return n
|
||||
|
||||
|
||||
def info(path):
|
||||
model = W.CreateModel()
|
||||
reader = model.QueryReader("3mf")
|
||||
reader.SetStrictModeActive(False)
|
||||
reader.ReadFromFile(path)
|
||||
res = {"unit": UNITS.get(model.GetUnit().value if hasattr(model.GetUnit(), "value") else model.GetUnit(), "?")}
|
||||
meshes = []
|
||||
it = model.GetMeshObjects()
|
||||
while it.MoveNext():
|
||||
m = it.GetCurrentMeshObject()
|
||||
meshes.append([m.GetVertexCount(), m.GetTriangleCount()])
|
||||
res["meshObjects"] = sorted(meshes)
|
||||
tot = {"tri": 0, "area": 0.0, "min": [math.inf] * 3, "max": [-math.inf] * 3}
|
||||
|
||||
def place(rid, M, depth):
|
||||
if depth > 32:
|
||||
return
|
||||
try:
|
||||
mo = model.GetMeshObjectByID(rid)
|
||||
except Exception:
|
||||
mo = None
|
||||
if mo is not None:
|
||||
verts = mo.GetVertices()
|
||||
tris = mo.GetTriangleIndices()
|
||||
P = []
|
||||
for v in verts:
|
||||
x, y, z = v.Coordinates[0], v.Coordinates[1], v.Coordinates[2]
|
||||
P.append([x * M[0][c] + y * M[1][c] + z * M[2][c] + M[3][c] for c in range(3)])
|
||||
for p in P:
|
||||
for c in range(3):
|
||||
tot["min"][c] = min(tot["min"][c], p[c])
|
||||
tot["max"][c] = max(tot["max"][c], p[c])
|
||||
for t in tris:
|
||||
a, b, c = (P[i] for i in t.Indices)
|
||||
e1 = [b[k] - a[k] for k in range(3)]
|
||||
e2 = [c[k] - a[k] for k in range(3)]
|
||||
cx = e1[1] * e2[2] - e1[2] * e2[1]
|
||||
cy = e1[2] * e2[0] - e1[0] * e2[2]
|
||||
cz = e1[0] * e2[1] - e1[1] * e2[0]
|
||||
tot["area"] += math.sqrt(cx * cx + cy * cy + cz * cz) / 2
|
||||
tot["tri"] += 1
|
||||
return
|
||||
co = model.GetComponentsObjectByID(rid)
|
||||
for i in range(co.GetComponentCount()):
|
||||
comp = co.GetComponent(i)
|
||||
T = mat(comp.GetTransform()) if comp.HasTransform() else IDENT
|
||||
place(comp.GetObjectResourceID(), mul(T, M), depth + 1)
|
||||
|
||||
items = model.GetBuildItems()
|
||||
n = 0
|
||||
while items.MoveNext():
|
||||
bi = items.GetCurrent()
|
||||
n += 1
|
||||
T = mat(bi.GetObjectTransform()) if bi.HasObjectTransform() else IDENT
|
||||
place(bi.GetObjectResourceID(), T, 0)
|
||||
res["items"] = n
|
||||
res["triangles"] = tot["tri"]
|
||||
res["area"] = tot["area"]
|
||||
if tot["tri"]:
|
||||
res["min"], res["max"] = tot["min"], tot["max"]
|
||||
res["baseGroups"] = count(model.GetBaseMaterialGroups())
|
||||
res["colorGroups"] = count(model.GetColorGroups())
|
||||
res["textures"] = count(model.GetTexture2Ds())
|
||||
res["texGroups"] = count(model.GetTexture2DGroups())
|
||||
return res
|
||||
|
||||
|
||||
out = []
|
||||
for p in json.loads(sys.stdin.read()):
|
||||
try:
|
||||
out.append(info(p))
|
||||
except Exception as e: # noqa: BLE001
|
||||
out.append({"failed": str(e)[:200]})
|
||||
print(json.dumps(out))
|
||||
Reference in new issue
Block a user