Draco primitives decode on load (attributes as their accessors declare them, u32 indices), written back uncompressed without the extension; meshopt stays UNSUPPORTED. Tests: transcoded Khronos samples (two quantizations), Draco's and assimp's Draco glTF files, each Draco primitive byte for byte against libdraco, against the uncompressed sources, round trips. Draco bench line; scene.md section.
133 lines
6.3 KiB
Python
133 lines
6.3 KiB
Python
# glTF + Draco fixtures (tools/fixtures.py): KHR_draco_mesh_compression files. The Khronos samples of
|
|
# tests/fixtures/gltf compressed by draco_transcoder 1.5.7 (nix) at its default and at a finer quantization, Draco's
|
|
# own glTF test files (Box_Draco.glb, BoxMetaDraco) and assimp's 2CylinderEngine (robot.glb: 12 MB, left out), read from the
|
|
# nixpkgs sources and never committed. Reference values: every Draco primitive's buffer view decoded by libdraco
|
|
# (tools/fixtures/_draco_dump.cc, compiled against nixpkgs#draco): points, faces, the index and per-attribute CRCs.
|
|
# tests/gen/gltf_draco.luau { { name, data, files = { uri -> bytes }, original? = { data, files } (the uncompressed
|
|
# source), prims = { { mesh, prim, points, faces, indices, attrs = { [name] = { uniqueId,
|
|
# dataType, crc } } } } } }
|
|
import json, os, struct, subprocess, tempfile, zlib
|
|
|
|
INPUTS = ["tests/fixtures/gltf", "tools/fixtures/_draco_dump.cc"]
|
|
|
|
|
|
def store_path(attr):
|
|
out = subprocess.run(["nix", "build", "nixpkgs#" + attr, "--no-link", "--print-out-paths"], capture_output=True, check=True)
|
|
return out.stdout.decode().strip().split("\n")[-1]
|
|
|
|
|
|
def load(path):
|
|
# -> (doc, bin, files): the JSON, the GLB binary chunk, the sibling files a .gltf refers to
|
|
raw = open(path, "rb").read()
|
|
files, binchunk = {}, None
|
|
if raw[:4] == b"glTF":
|
|
off = 12
|
|
doc = None
|
|
while off + 8 <= len(raw):
|
|
n, kind = struct.unpack_from("<II", raw, off)
|
|
chunk = raw[off + 8:off + 8 + n]
|
|
if kind == 0x4E4F534A:
|
|
doc = json.loads(chunk)
|
|
elif kind == 0x004E4942:
|
|
binchunk = chunk
|
|
off += 8 + n
|
|
else:
|
|
doc = json.loads(raw)
|
|
d = os.path.dirname(path)
|
|
for b in doc.get("buffers", []) + doc.get("images", []):
|
|
uri = b.get("uri")
|
|
if uri and not uri.startswith("data:") and os.path.exists(os.path.join(d, uri)):
|
|
files[uri] = open(os.path.join(d, uri), "rb").read()
|
|
return doc, binchunk, files
|
|
|
|
|
|
def buffer_bytes(doc, binchunk, files, i):
|
|
b = doc["buffers"][i]
|
|
uri = b.get("uri")
|
|
if uri is None:
|
|
return binchunk
|
|
if uri.startswith("data:"):
|
|
import base64
|
|
return base64.b64decode(uri.split(",", 1)[1])
|
|
return files[uri]
|
|
|
|
|
|
def references(doc, binchunk, files, dump, tmp):
|
|
prims = []
|
|
for mi, m in enumerate(doc.get("meshes", [])):
|
|
for pi, p in enumerate(m.get("primitives", [])):
|
|
ext = p.get("extensions", {}).get("KHR_draco_mesh_compression")
|
|
if not ext:
|
|
continue
|
|
v = doc["bufferViews"][ext["bufferView"]]
|
|
data = buffer_bytes(doc, binchunk, files, v["buffer"])
|
|
off = v.get("byteOffset", 0)
|
|
drc = data[off:off + v["byteLength"]]
|
|
path = os.path.join(tmp, "p.drc")
|
|
open(path, "wb").write(drc)
|
|
lines = subprocess.run([dump, path], capture_output=True).stdout.decode().split("\n")
|
|
entry = {"mesh": mi + 1, "prim": pi + 1, "attrs": {}}
|
|
by_id = {}
|
|
for line in lines:
|
|
parts = line.split(" ")
|
|
if parts[0] == "POINTS":
|
|
entry["points"] = int(parts[1])
|
|
elif parts[0] == "FACES":
|
|
entry["faces"] = int(parts[1])
|
|
entry["indices"] = zlib.crc32(bytes.fromhex(parts[2] if len(parts) > 2 else ""))
|
|
elif parts[0] == "ATTR":
|
|
by_id[int(parts[5])] = {"dataType": int(parts[2]), "crc": zlib.crc32(bytes.fromhex(parts[6] if len(parts) > 6 else ""))}
|
|
for name, uid in ext.get("attributes", {}).items():
|
|
if uid in by_id:
|
|
a = dict(by_id[uid])
|
|
a["uniqueId"] = uid
|
|
entry["attrs"][name] = a
|
|
prims.append(entry)
|
|
return prims
|
|
|
|
|
|
def generate(ctx):
|
|
draco = store_path("draco")
|
|
dsrc = store_path("draco.src")
|
|
asrc = store_path("assimp.src")
|
|
tmp = tempfile.mkdtemp(prefix="formats-gltfdraco-")
|
|
dump = os.path.join(tmp, "dump")
|
|
ctx.nix("gcc", ["g++", "-O1", "-std=c++17", "-I" + os.path.join(draco, "include"), os.path.join(ctx.root, "tools", "fixtures", "_draco_dump.cc"),
|
|
"-L" + os.path.join(draco, "lib"), "-l:libdraco.a", "-o", dump])
|
|
transcoder = os.path.join(draco, "bin", "draco_transcoder")
|
|
sources = [] # (name, path, original path?)
|
|
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
|
|
for model in sorted(os.listdir(gl)):
|
|
d0 = os.path.join(gl, model)
|
|
for variant in sorted(os.listdir(d0)):
|
|
d = os.path.join(d0, variant)
|
|
if not os.path.isdir(d) or "Quantized" in variant:
|
|
continue
|
|
mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")]
|
|
if not mains:
|
|
continue
|
|
src = os.path.join(d, mains[0])
|
|
for q, args in (("default", []), ("fine", ["-qp", "16", "-qt", "14", "-qn", "12", "-qc", "10", "-qw", "12", "-qtg", "10"])):
|
|
out = os.path.join(tmp, "%s_%s.glb" % (model, q))
|
|
r = subprocess.run([transcoder, "-i", src, "-o", out] + args, capture_output=True)
|
|
if r.returncode == 0 and os.path.exists(out):
|
|
sources.append(("transcoded/%s/%s" % (model, q), out, src))
|
|
break
|
|
for name, rel in (("draco/Box_Draco.glb", os.path.join(dsrc, "testdata", "Box", "glTF_Binary", "Box_Draco.glb")),
|
|
("draco/BoxMetaDraco.gltf", os.path.join(dsrc, "testdata", "BoxMetaDraco", "glTF", "BoxMetaDraco.gltf")),
|
|
("assimp/2CylinderEngine.gltf", os.path.join(asrc, "test", "models", "glTF2", "draco", "2CylinderEngine.gltf"))):
|
|
if os.path.exists(rel):
|
|
sources.append((name, rel, None))
|
|
cases = []
|
|
for name, path, orig in sources:
|
|
doc, binchunk, files = load(path)
|
|
prims = references(doc, binchunk, files, dump, tmp)
|
|
if not prims:
|
|
continue
|
|
case = {"name": name, "data": open(path, "rb").read(), "files": files, "prims": prims}
|
|
if orig:
|
|
_, _, ofiles = load(orig)
|
|
case["original"] = {"data": open(orig, "rb").read(), "files": ofiles}
|
|
cases.append(case)
|
|
ctx.emit("gltf_draco", cases)
|