merge ws/3d3-c (model/pmx, model/vrml, model/x3d, codecs/model/Vrml); README model list

This commit is contained in:
4DBug committed 2026-10-31 15:29:37 -05:00
commit 94783a86d1
29 files changed
+6735 -6

No files matched your search

+13
View File
@@ -919,6 +919,19 @@ do
bench("3mf encode", 2, buffer.len(tmf), function()
ThreeMf.encode(scene)
end)
local Wrl = require("@formats/model/vrml")
local X3d = require("@formats/model/x3d")
local wrl = assert(Wrl.encode(scene))
bench("vrml decode (" .. buffer.len(wrl) // 1000 .. " KB)", 2, buffer.len(wrl), function()
Wrl.decode(Bytes.reader(wrl))
end)
bench("vrml encode", 2, buffer.len(wrl), function()
Wrl.encode(scene)
end)
local x3d = assert(X3d.encode(scene))
bench("x3d xml decode (" .. buffer.len(x3d) // 1000 .. " KB)", 2, buffer.len(x3d), function()
X3d.decode(Bytes.reader(x3d))
end)
local V = 128
local grid = Types.Voxels.new(V, V, V)
for z = 0, V - 1 do
+265
View File
@@ -0,0 +1,265 @@
# A small PMX 2.0 / 2.1 (and PMD 1.0) writer for tools/fixtures/pmx.py: synthetic MikuMikuDance models that use every
# vertex deform type (BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF), both text encodings, every index size, additional UVs,
# several materials (texture / sphere / toon references), a bone chain with IK / inherit / fixed-axis / local-axis
# bones, every morph type, display frames, rigid bodies and joints. Written from the PMX 2.0 / 2.1 specification notes
# (PmxEditor's "PMX仕様") and the PMD layout; no third-party code.
import math, struct
def f32s(*v):
return struct.pack("<%df" % len(v), *v)
class Pmx:
def __init__(self, version=2.0, utf8=False, sizes=(2, 1, 1, 2, 1, 1), uva=0):
self.version, self.utf8, self.uva = version, utf8, uva
self.vsize, self.tsize, self.msize, self.bsize, self.morsize, self.rsize = sizes
def text(self, s):
b = s.encode("utf-8") if self.utf8 else s.encode("utf-16-le")
return struct.pack("<i", len(b)) + b
def idx(self, v, size, vertex=False):
if vertex:
return struct.pack({1: "<B", 2: "<H", 4: "<i"}[size], v)
return struct.pack({1: "<b", 2: "<h", 4: "<i"}[size], v)
def build(self, m):
out = bytearray(b"PMX ")
out += struct.pack("<f", self.version)
out += bytes([8, 1 if self.utf8 else 0, self.uva, self.vsize, self.tsize, self.msize, self.bsize, self.morsize, self.rsize])
for s in (m["name"], m["nameEn"], m["comment"], m["commentEn"]):
out += self.text(s)
B = lambda i: self.idx(i, self.bsize)
out += struct.pack("<i", len(m["vertices"]))
for v in m["vertices"]:
out += f32s(*v["pos"], *v["normal"], *v["uv"])
for k in range(self.uva):
out += f32s(*v["uva"][k])
kind = v["deform"]
out += bytes([kind])
b, w = v["bones"], v["weights"]
if kind == 0:
out += B(b[0])
elif kind == 1:
out += B(b[0]) + B(b[1]) + f32s(w[0])
elif kind in (2, 4):
out += B(b[0]) + B(b[1]) + B(b[2]) + B(b[3]) + f32s(*w[:4])
else:
out += B(b[0]) + B(b[1]) + f32s(w[0]) + f32s(*v["sdef"][0], *v["sdef"][1], *v["sdef"][2])
out += f32s(v["edge"])
out += struct.pack("<i", len(m["indices"]))
for i in m["indices"]:
out += self.idx(i, self.vsize, True)
out += struct.pack("<i", len(m["textures"]))
for t in m["textures"]:
out += self.text(t)
out += struct.pack("<i", len(m["materials"]))
T = lambda i: self.idx(i, self.tsize)
for mat in m["materials"]:
out += self.text(mat["name"]) + self.text(mat["nameEn"])
out += f32s(*mat["diffuse"], *mat["specular"], mat["power"], *mat["ambient"])
out += bytes([mat["flags"]]) + f32s(*mat["edgeColor"], mat["edgeSize"])
out += T(mat["texture"]) + T(mat["sphere"]) + bytes([mat["sphereMode"], 1 if mat["toonShared"] is not None else 0])
out += bytes([mat["toonShared"]]) if mat["toonShared"] is not None else T(mat["toon"])
out += self.text(mat["memo"]) + struct.pack("<i", mat["count"])
out += struct.pack("<i", len(m["bones"]))
for bn in m["bones"]:
fl = bn["flags"]
out += self.text(bn["name"]) + self.text(bn["nameEn"]) + f32s(*bn["pos"]) + B(bn["parent"]) + struct.pack("<iH", bn["layer"], fl)
out += B(bn["tail"]) if fl & 1 else f32s(*bn["tail"])
if fl & 0x300:
out += B(bn["inherit"][0]) + f32s(bn["inherit"][1])
if fl & 0x400:
out += f32s(*bn["axis"])
if fl & 0x800:
out += f32s(*bn["localX"], *bn["localZ"])
if fl & 0x2000:
out += struct.pack("<i", bn["key"])
if fl & 0x20:
ik = bn["ik"]
out += B(ik["target"]) + struct.pack("<if", ik["loops"], ik["limit"]) + struct.pack("<i", len(ik["links"]))
for ln in ik["links"]:
out += B(ln["bone"]) + bytes([1 if ln.get("min") else 0])
if ln.get("min"):
out += f32s(*ln["min"], *ln["max"])
out += struct.pack("<i", len(m["morphs"]))
V = lambda i: self.idx(i, self.vsize, True)
Mo = lambda i: self.idx(i, self.morsize)
for mo in m["morphs"]:
out += self.text(mo["name"]) + self.text(mo["nameEn"]) + bytes([mo["panel"], mo["type"]]) + struct.pack("<i", len(mo["offsets"]))
for o in mo["offsets"]:
t = mo["type"]
if t in (0, 9):
out += Mo(o[0]) + f32s(o[1])
elif t == 1:
out += V(o[0]) + f32s(*o[1])
elif t == 2:
out += B(o[0]) + f32s(*o[1], *o[2])
elif 3 <= t <= 7:
out += V(o[0]) + f32s(*o[1])
elif t == 8:
out += self.idx(o[0], self.msize) + bytes([o[1]]) + f32s(*o[2])
elif t == 10:
out += self.idx(o[0], self.rsize) + bytes([o[1]]) + f32s(*o[2], *o[3])
out += struct.pack("<i", len(m["frames"]))
for fr in m["frames"]:
out += self.text(fr["name"]) + self.text(fr["nameEn"]) + bytes([fr["special"]]) + struct.pack("<i", len(fr["items"]))
for kind, i in fr["items"]:
out += bytes([kind]) + (B(i) if kind == 0 else Mo(i))
out += struct.pack("<i", len(m["rigid"]))
for rb in m["rigid"]:
out += self.text(rb["name"]) + self.text(rb["nameEn"]) + B(rb["bone"]) + struct.pack("<BHB", rb["group"], rb["mask"], rb["shape"])
out += f32s(*rb["size"], *rb["pos"], *rb["rot"], rb["mass"], 0.5, 0.5, 0.0, 0.5) + bytes([rb["mode"]])
out += struct.pack("<i", len(m["joints"]))
R = lambda i: self.idx(i, self.rsize)
for jn in m["joints"]:
out += self.text(jn["name"]) + self.text(jn["nameEn"]) + bytes([0]) + R(jn["a"]) + R(jn["b"])
out += f32s(*jn["pos"], 0, 0, 0, -1, -1, -1, 1, 1, 1, -0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0, 0, 0, 0, 0, 0)
if self.version >= 2.1:
out += struct.pack("<i", 0) # no soft bodies
return bytes(out)
def tube(rings=6, seg=8, nbones=4, nmat=3, version=2.0, uva=0, seed=1, deform=None, name="tube", flips=False):
"""a tube along +y: rings of seg vertices, weighted to a bone chain, faces split over nmat materials"""
import random
rnd = random.Random(seed)
kinds = deform or ([0, 1, 2, 3] + ([4] if version >= 2.1 else []))
verts = []
for r in range(rings):
y = r * 2.0
for s in range(seg):
a = 2 * math.pi * s / seg
x, z = math.cos(a) * 1.5, math.sin(a) * 1.5 + 0.25 * r
b0 = min(nbones - 1, r * nbones // rings)
b1 = min(nbones - 1, b0 + 1)
k = kinds[(r * seg + s) % len(kinds)]
w = rnd.random()
if k == 0:
bones, weights = [b0], [1.0]
elif k in (1, 3):
bones, weights = [b0, b1], [w]
else:
ws = [rnd.random() + 0.1 for _ in range(4)]
bones, weights = [b0, b1, max(0, b0 - 1), -1 if k == 2 else nbones - 1], [x / sum(ws) * 0.9 for x in ws]
verts.append({
"pos": (x, y, z), "normal": (math.cos(a), 0.0, math.sin(a)), "uv": (s / seg, r / (rings - 1)),
"uva": [(rnd.random(), rnd.random(), rnd.random(), rnd.random()) for _ in range(uva)],
"deform": k, "bones": bones, "weights": weights, "edge": 1.0,
"sdef": ((0.0, y, 0.0), (0.0, y - 1, 0.0), (0.0, y + 1, 0.0)),
})
faces = []
for r in range(rings - 1):
for s in range(seg):
a, b = r * seg + s, r * seg + (s + 1) % seg
c, d = a + seg, b + seg
faces += [a, c, b, b, c, d]
ntri = len(faces) // 3
counts, left = [], ntri
for k in range(nmat):
n = left if k == nmat - 1 else max(1, ntri // nmat)
counts.append(n * 3)
left -= n
mats = []
for k in range(nmat):
mats.append({
"name": "材質%d" % k, "nameEn": "mat%d" % k, "diffuse": (0.8, 0.2 + 0.2 * k, 0.1, 1.0 if k != 1 else 0.5),
"specular": (0.1, 0.1, 0.1), "power": 5.0 + 10 * k, "ambient": (0.4, 0.1, 0.05), "flags": [0x01 | 0x10, 0x04 | 0x08, 0x02][k % 3],
"edgeColor": (0, 0, 0, 1), "edgeSize": 1.0, "texture": 0 if k == 0 else -1, "sphere": 1 if k == 0 else -1,
"sphereMode": 1 if k == 0 else 0, "toonShared": 3 if k != 2 else None, "toon": 2, "memo": "memo %d" % k, "count": counts[k],
})
bones = []
for i in range(nbones):
fl = 0x1A | (1 if i < nbones - 1 else 0)
b = {"name": "骨%d" % i, "nameEn": "bone%d" % i, "pos": (0.0, i * (rings - 1) * 2.0 / max(1, nbones - 1), 0.25 * i), "parent": i - 1,
"layer": 0, "flags": fl, "tail": i + 1 if i < nbones - 1 else (0.0, 1.0, 0.0)}
if i == 1:
b["flags"] |= 0x100
b["inherit"] = (0, 0.5)
if i == 2:
b["flags"] |= 0x400 | 0x800
b["axis"] = (0.0, 1.0, 0.0)
b["localX"], b["localZ"] = (1.0, 0.0, 0.0), (0.0, 0.0, 1.0)
bones.append(b)
# an IK bone at the end targeting the last chain bone
bones.append({"name": "IK", "nameEn": "leg IK", "pos": (2.0, 0.0, 0.0), "parent": -1, "layer": 1, "flags": 0x1E | 0x20, "tail": (0.0, 0.0, 1.0),
"ik": {"target": nbones - 1, "loops": 40, "limit": 2.0, "links": [{"bone": nbones - 2, "min": (-3.14, 0, 0), "max": (-0.01, 0, 0)}, {"bone": max(0, nbones - 3)}]}})
morphs = [
{"name": "上", "nameEn": "up", "panel": 1, "type": 1, "offsets": [(i, (0.0, 0.5, -0.25)) for i in range(0, len(verts), 3)]},
{"name": "広", "nameEn": "wide", "panel": 2, "type": 1, "offsets": [(i, (0.3, 0.0, 0.1)) for i in range(1, len(verts), 2)]},
{"name": "uv", "nameEn": "uv", "panel": 3, "type": 3, "offsets": [(0, (0.1, 0.2, 0, 0))]},
{"name": "骨", "nameEn": "bonem", "panel": 4, "type": 2, "offsets": [(1, (0, 1, 0), (0, 0, 0, 1))]},
{"name": "材", "nameEn": "matm", "panel": 4, "type": 8, "offsets": [(-1, 0, (1,) * 28)]},
{"name": "群", "nameEn": "group", "panel": 4, "type": 0, "offsets": [(0, 0.5), (1, 1.0)]},
]
if uva:
morphs.append({"name": "uva", "nameEn": "uva1", "panel": 3, "type": 4, "offsets": [(2, (0.5, 0.5, 0.5, 0.5))]})
if version >= 2.1 and flips: # assimp 6 rejects these morph types
morphs.append({"name": "flip", "nameEn": "flip", "panel": 4, "type": 9, "offsets": [(0, 1.0)]})
morphs.append({"name": "imp", "nameEn": "impulse", "panel": 4, "type": 10, "offsets": [(0, 1, (0, 1, 0), (0, 0, 0))]})
frames = [{"name": "Root", "nameEn": "Root", "special": 1, "items": [(0, 0)]},
{"name": "表情", "nameEn": "Exp", "special": 1, "items": [(1, 0), (1, 1)]}]
rigid = [{"name": "rb%d" % i, "nameEn": "rb%d" % i, "bone": i, "group": i, "mask": 0xFFFF, "shape": i % 3, "size": (1, 2, 3),
"pos": (0, i, 0), "rot": (0, 0, 0), "mass": 1.0, "mode": i % 3} for i in range(2)]
joints = [{"name": "j0", "nameEn": "j0", "a": 0, "b": 1, "pos": (0, 1, 0)}]
return {"name": name, "nameEn": name + " en", "comment": "コメント", "commentEn": "comment", "vertices": verts, "indices": faces,
"textures": ["tex\\body.png", "s.sph", "toon.bmp"], "materials": mats, "bones": bones, "morphs": morphs,
"frames": frames, "rigid": rigid, "joints": joints}
def pmd(m):
"""the same model as PMD 1.0 (BDEF2-style weights only, ASCII names, toon list, English names)"""
def name(s, n):
b = s.encode("ascii", "replace")[: n - 1]
return b + b"\0" * (n - len(b))
out = bytearray(b"Pmd") + struct.pack("<f", 1.0) + name(m["nameEn"], 20) + name(m["commentEn"], 256)
out += struct.pack("<I", len(m["vertices"]))
for v in m["vertices"]:
b = v["bones"] + [v["bones"][0]]
w = v["weights"][0] if v["deform"] != 0 else 1.0
out += f32s(*v["pos"], *v["normal"], *v["uv"]) + struct.pack("<HHBB", max(0, b[0]), max(0, b[1]), int(round(w * 100)), 0)
out += struct.pack("<I", len(m["indices"])) + struct.pack("<%dH" % len(m["indices"]), *m["indices"])
out += struct.pack("<I", len(m["materials"]))
for mat in m["materials"]:
tex = m["textures"][mat["texture"]].replace("\\", "/") if mat["texture"] >= 0 else ""
if mat["sphere"] >= 0:
tex += "*" + m["textures"][mat["sphere"]]
out += f32s(*mat["diffuse"], mat["power"], *mat["specular"], *mat["ambient"])
out += struct.pack("<BBI", mat["toonShared"] if mat["toonShared"] is not None else 255, 1 if mat["flags"] & 0x10 else 0, mat["count"]) + name(tex, 20)
bones = m["bones"]
out += struct.pack("<H", len(bones))
for i, bn in enumerate(bones):
tail = bn["tail"] if bn["flags"] & 1 else 0
out += name(bn["nameEn"], 20) + struct.pack("<hhBh", bn["parent"], tail, 2 if bn["flags"] & 0x20 else 0, 0) + f32s(*bn["pos"])
iks = [(i, bn["ik"]) for i, bn in enumerate(bones) if bn["flags"] & 0x20]
out += struct.pack("<H", len(iks))
for i, ik in iks:
out += struct.pack("<HHBHf", i, ik["target"], len(ik["links"]), ik["loops"], ik["limit"] / 4) + struct.pack("<%dH" % len(ik["links"]), *[ln["bone"] for ln in ik["links"]])
# skins: base (every vertex any morph moves, absolute positions) then the vertex morphs relative to the base list
vm = [mo for mo in m["morphs"] if mo["type"] == 1]
base = sorted({o[0] for mo in vm for o in mo["offsets"]})
pos = {v: k for k, v in enumerate(base)}
out += struct.pack("<H", 1 + len(vm) if vm else 0)
if vm:
out += name("base", 20) + struct.pack("<IB", len(base), 0)
for v in base:
out += struct.pack("<I", v) + f32s(*m["vertices"][v]["pos"])
for mo in vm:
out += name(mo["nameEn"], 20) + struct.pack("<IB", len(mo["offsets"]), mo["panel"])
for v, d in mo["offsets"]:
out += struct.pack("<I", pos[v]) + f32s(*d)
out += struct.pack("<B", 0) # skin display list
out += struct.pack("<B", 1) + name("Root", 50) # bone display groups
out += struct.pack("<I", 1) + struct.pack("<HB", 0, 1)
# English names
out += bytes([1]) + name(m["nameEn"], 20) + name(m["commentEn"], 256)
for bn in bones:
out += name(bn["nameEn"], 20)
for mo in vm:
out += name(mo["nameEn"], 20)
out += name("Root", 50)
for k in range(10):
out += name("toon%02d.bmp" % (k + 1), 100)
out += struct.pack("<I", 0) + struct.pack("<I", 0) # rigid bodies, joints
return bytes(out)
+54
View File
@@ -0,0 +1,54 @@
-- tools/fixtures/_vrml_encode: run by tools/fixtures/vrml.py and x3d.py (luau CLI, repo root): decodes every VRML /
-- X3D case and glTF sample with our readers and writes it back with our writers, printing "<file>\t<hex>" lines for
-- VTK (.wrl) and assimp (.x3d) to read back. Files: case_<i>.wrl, gltf_<i>.wrl, xcase_<i>.x3d, xgltf_<i>.x3d.
local Vrml = require("@formats/model/vrml")
local X3d = require("@formats/model/x3d")
local Gltf = require("@formats/model/gltf")
local Bytes = require("@formats/core/Bytes")
local Cases = require("@tests/gen/vrml_cases")
local GltfCases = require("@tests/gen/vrml_gltf")
local ok, X3dCases = pcall(require, "@tests/gen/x3d_cases")
local HEX = {}
for i = 0, 255 do
HEX[i] = string.format("%02x", i)
end
local function hex(b: buffer): string
local out = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
out[i + 1] = HEX[buffer.readu8(b, i)]
end
return table.concat(out)
end
local function both(scene: any, wrl: string, x3d: string)
local a = Vrml.encode(scene)
if a then
print(wrl .. "\t" .. hex(a))
end
local b = X3d.encode(scene)
if b then
print(x3d .. "\t" .. hex(b))
end
end
for i, c in Cases do
local scene = Vrml.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false })
if scene then
both(scene, string.format("case_%d.wrl", i), string.format("wcase_%d.x3d", i))
end
end
for i, c in GltfCases do
local scene = Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files })
if scene then
both(scene, string.format("gltf_%d.wrl", i), string.format("xgltf_%d.x3d", i))
end
end
if ok and type(X3dCases) == "table" then
for i, c in X3dCases do
local scene = X3d.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false })
if scene then
both(scene, string.format("xcase_%d.wrl", i), string.format("xcase_%d.x3d", i))
end
end
end
+241
View File
@@ -0,0 +1,241 @@
# Shared helpers for tools/fixtures/vrml.py and x3d.py: VTK (nixpkgs python3 vtk) as the VRML97 reference reader and
# as a writer of more .wrl / .x3d inputs, assimp's X3D reader for .x3d, and the hand-written feature files.
# vtk_read(ctx, paths) -> [ { actors, polys, lines, verts, points, min, max } | { failed } ] (vtkVRMLImporter)
# vtk_export(ctx, outdir, gltf_paths) -> [ (name, wrl path, x3d path) ] (vtkVRMLExporter / vtkX3DExporter scenes)
# FEATURES: { name: VRML97 text } covering PROTO, DEF / USE, Switch, LOD, primitives, per-face colours, separate
# indices, ElevationGrid, Extrusion, ROUTE animation, lights, viewpoints, Inline, PixelTexture
import json
VTK_READ = r"""
import json, os, sys, vtk
vtk.vtkObject.GlobalWarningDisplayOff()
def read(p):
imp = vtk.vtkVRMLImporter(); imp.SetFileName(p)
rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); imp.SetRenderWindow(rw)
imp.Update()
acts = imp.GetRenderer().GetActors(); acts.InitTraversal()
out = {"actors": 0, "polys": 0, "lines": 0, "verts": 0, "points": 0}
lo, hi = [1e30] * 3, [-1e30] * 3
for i in range(acts.GetNumberOfItems()):
a = acts.GetNextActor()
m = a.GetMapper()
if not m:
continue
m.Update()
d = m.GetInput()
if d is None or d.GetNumberOfPoints() == 0:
continue
out["actors"] += 1
out["polys"] += d.GetNumberOfPolys() + d.GetNumberOfStrips()
out["lines"] += d.GetNumberOfLines()
out["verts"] += d.GetNumberOfVerts()
out["points"] += d.GetNumberOfPoints()
# tight world bounds: every point through the actor's matrix (GetBounds boxes the local bounds)
mat = a.GetMatrix()
pts = d.GetPoints()
for j in range(d.GetNumberOfPoints()):
p = pts.GetPoint(j)
w = mat.MultiplyPoint((p[0], p[1], p[2], 1.0))
for k in range(3):
lo[k] = min(lo[k], w[k]); hi[k] = max(hi[k], w[k])
if out["actors"]:
out["min"], out["max"] = lo, hi
return out
# one child process per file: vtkVRMLImporter crashes on some valid files
res = []
for p in json.loads(sys.stdin.read()):
r, w = os.pipe()
pid = os.fork()
if pid == 0:
os.close(r)
try:
data = json.dumps(read(p))
except Exception:
data = json.dumps({"failed": True})
os.write(w, data.encode())
os._exit(0)
os.close(w)
chunks = []
while True:
b = os.read(r, 65536)
if not b:
break
chunks.append(b)
os.close(r)
_, status = os.waitpid(pid, 0)
try:
res.append(json.loads(b"".join(chunks).decode()) if status == 0 else {"failed": True, "crashed": True})
except ValueError:
res.append({"failed": True})
print("RESULT " + json.dumps(res))
"""
VTK_EXPORT = r"""
import json, os, sys, vtk
vtk.vtkObject.GlobalWarningDisplayOff()
args = json.loads(sys.stdin.read())
out, gltfs = args["out"], args["gltf"]
made = []
def export(ren, name):
rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); rw.AddRenderer(ren)
ren.ResetCamera()
w = vtk.vtkVRMLExporter(); w.SetRenderWindow(rw); w.SetFileName(os.path.join(out, name + ".wrl")); w.Write()
x = vtk.vtkX3DExporter(); x.SetRenderWindow(rw); x.SetFileName(os.path.join(out, name + ".x3d")); x.SetBinary(0); x.Write()
made.append(name)
def actor(src, pos=(0, 0, 0), scale=(1, 1, 1), rot=(0, 0, 0), color=None, scalars=False):
m = vtk.vtkPolyDataMapper(); m.SetInputConnection(src.GetOutputPort())
if not scalars:
m.ScalarVisibilityOff()
a = vtk.vtkActor(); a.SetMapper(m); a.SetPosition(*pos); a.SetScale(*scale)
a.RotateX(rot[0]); a.RotateY(rot[1]); a.RotateZ(rot[2])
if color:
a.GetProperty().SetColor(*color)
return a
# 1. primitives as polygon meshes, transformed, coloured, one with point scalars
ren = vtk.vtkRenderer()
s = vtk.vtkSphereSource(); s.SetThetaResolution(16); s.SetPhiResolution(8)
ren.AddActor(actor(s, (1, 2, 3), (2, 2, 2), (30, 0, 0), (0.9, 0.2, 0.1)))
c = vtk.vtkConeSource(); c.SetResolution(12)
ren.AddActor(actor(c, (-3, 0, 1), (1, 3, 1), (0, 45, 10), (0.2, 0.8, 0.3)))
cube = vtk.vtkCubeSource(); cube.SetXLength(2); cube.SetYLength(1); cube.SetZLength(0.5)
ren.AddActor(actor(cube, (0, -2, 0), (1, 1, 1), (0, 0, 20), (0.3, 0.3, 0.9)))
keep = [vtk.vtkSphereSource(), vtk.vtkSphereSource(), vtk.vtkCubeSource()]
el = vtk.vtkElevationFilter(); el.SetInputConnection(keep[0].GetOutputPort()); el.SetLowPoint(0, -0.5, 0); el.SetHighPoint(0, 0.5, 0)
ren.AddActor(actor(el, (4, 4, 0), scalars=True))
light = vtk.vtkLight(); light.SetPosition(5, 5, 5); light.SetFocalPoint(0, 0, 0); light.SetColor(1, 0.9, 0.8)
ren.AddLight(light)
export(ren, "vtk_shapes")
# 2. lines and points
ren = vtk.vtkRenderer()
ls = vtk.vtkLineSource(); ls.SetPoint1(0, 0, 0); ls.SetPoint2(3, 1, 2); ls.SetResolution(5)
ren.AddActor(actor(ls, (1, 0, 0), color=(1, 1, 0)))
pts = vtk.vtkPointSource(); pts.SetNumberOfPoints(40); pts.SetRadius(2); pts.SetCenter(0, 5, 0)
ren.AddActor(actor(pts))
ren.AddActor(actor(keep[2], (0, 0, -4)))
export(ren, "vtk_lines_points")
# 3. a textured plane (PixelTexture) and a strip mesh
ren = vtk.vtkRenderer()
pl = vtk.vtkPlaneSource(); pl.SetResolution(3, 2)
img = vtk.vtkImageCanvasSource2D(); img.SetScalarTypeToUnsignedChar(); img.SetNumberOfScalarComponents(3); img.SetExtent(0, 7, 0, 3, 0, 0)
img.SetDrawColor(200, 30, 30); img.FillBox(0, 7, 0, 3); img.SetDrawColor(20, 30, 200); img.FillBox(0, 3, 0, 1); img.Update()
tex = vtk.vtkTexture(); tex.SetInputConnection(img.GetOutputPort())
a = actor(pl, (0, 0, 1), (4, 2, 1)); a.SetTexture(tex)
ren.AddActor(a)
strip = vtk.vtkStripper(); strip.SetInputConnection(keep[1].GetOutputPort())
ren.AddActor(actor(strip, (0, 3, 0)))
export(ren, "vtk_texture_strips")
# 4. glTF sample models through VTK's glTF importer
for g in gltfs:
try:
imp = vtk.vtkGLTFImporter(); imp.SetFileName(g)
rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); imp.SetRenderWindow(rw); imp.Update()
name = "vtk_gltf_" + os.path.splitext(os.path.basename(g))[0]
export(imp.GetRenderer(), name)
except Exception:
pass
print("RESULT " + json.dumps(made))
"""
def vtk_xform_ok(data):
"""False when vtkVRMLImporter's transforms are wrong for the file: it ignores center and scaleOrientation"""
import re
return not re.search(rb"\b(center|scaleOrientation)\s+[-+\d.]", data)
def _run(ctx, code, arg):
out = ctx.python(["vtk"], code, input=json.dumps(arg).encode()).decode("utf-8", "replace")
for line in out.split("\n"):
if line.startswith("RESULT "):
return json.loads(line[7:])
raise RuntimeError("vtk script printed no result")
def vtk_read(ctx, paths):
return _run(ctx, VTK_READ, paths) if paths else []
def vtk_export(ctx, outdir, gltfs):
return _run(ctx, VTK_EXPORT, {"out": outdir, "gltf": gltfs})
FEATURES = {
"feat_proto_use.wrl": """#VRML V2.0 utf8
PROTO Brick [ field SFVec3f size 1 1 1 field SFColor col 1 0 0 exposedField SFVec3f where 0 0 0 ] {
Transform { translation IS where children Shape {
appearance Appearance { material Material { diffuseColor IS col } }
geometry Box { size IS size } } }
}
DEF A Brick { size 2 1 1 col 0 1 0 where 0 0 0 }
Brick { where 3 0 0 }
Transform { translation 0 3 0 children [ DEF S Shape { geometry IndexedFaceSet {
coord DEF C Coordinate { point [ 0 0 0, 1 0 0, 1 1 0, 0 1 0 ] } coordIndex [ 0 1 2 3 -1 ] } } ] }
Transform { translation 0 5 0 rotation 0 0 1 1.5708 children USE S }
""",
"feat_indices.wrl": """#VRML V2.0 utf8
# separate normal / colour / texture indices, per-face colours, ccw FALSE, solid FALSE
Shape {
appearance Appearance { material Material { diffuseColor 0.5 0.5 0.5 transparency 0.25 shininess 0.5 specularColor 1 1 1 } }
geometry IndexedFaceSet {
solid FALSE ccw FALSE
coord Coordinate { point [ 0 0 0, 2 0 0, 2 2 0, 0 2 0, 0 0 2, 2 0 2 ] }
coordIndex [ 0 1 2 3 -1, 0 4 5 1 -1 ]
normal Normal { vector [ 0 0 1, 0 -1 0 ] }
normalPerVertex FALSE normalIndex [ 0 1 ]
color Color { color [ 1 0 0, 0 0 1 ] }
colorPerVertex FALSE
texCoord TextureCoordinate { point [ 0 0, 1 0, 1 1, 0 1 ] }
texCoordIndex [ 0 1 2 3 -1, 3 2 1 0 -1 ]
}
}
Shape { geometry IndexedFaceSet {
coord Coordinate { point [ 5 0 0, 6 0 0, 6 1 0, 5 1 0 ] }
coordIndex [ 0 1 2 -1 0 2 3 ]
color Color { color [ 1 0 0, 0 1 0, 0 0 1, 1 1 1 ] } colorIndex [ 3 2 1 -1 0 1 2 -1 ] } }
""",
"feat_primitives.wrl": """#VRML V2.0 utf8
Transform { translation -4 0 0 children Shape { geometry Box { size 1 2 3 } } }
Transform { translation 0 0 0 children Shape { geometry Sphere { radius 1.5 } } }
Transform { translation 4 0 0 children Shape { geometry Cone { bottomRadius 1 height 3 } } }
Transform { translation 8 0 0 scale 2 1 1 children Shape { geometry Cylinder { radius 0.5 height 4 } } }
""",
"feat_grid_extrusion.wrl": """#VRML V2.0 utf8
Shape { geometry ElevationGrid { xDimension 4 zDimension 3 xSpacing 1 zSpacing 2
height [ 0 1 0 1, 1 2 1 0, 0 0 1 3 ] } }
Transform { translation 6 0 0 children Shape { geometry Extrusion {
crossSection [ 1 1, 1 -1, -1 -1, -1 1, 1 1 ] spine [ 0 0 0, 0 1 0, 1 2 0, 2 2 0 ] scale [ 1 1, 0.5 0.5, 0.5 0.5, 1 1 ] } } }
""",
"feat_scene.wrl": """#VRML V2.0 utf8
WorldInfo { title "feature scene" info [ "made for formats-luau" ] }
DEF Cam Viewpoint { position 0 1 8 orientation 0 1 0 0.3 fieldOfView 0.9 description "front" }
DEF Sun DirectionalLight { direction 0 -1 -1 intensity 0.8 color 1 1 0.9 }
DEF Bulb PointLight { location 1 2 3 radius 10 }
DEF Spot SpotLight { location 0 5 0 direction 0 -1 0 cutOffAngle 0.6 beamWidth 0.4 }
DEF Sw Switch { whichChoice 1 choice [
Shape { geometry Box { } }
Transform { translation 0 2 0 children Shape { geometry Sphere { radius 0.5 } } } ] }
LOD { range [ 10 ] level [ Shape { geometry Box { size 0.5 0.5 0.5 } } Shape { geometry Sphere { } } ] }
DEF Mover Transform { center 1 0 0 scaleOrientation 0 0 1 0.5 scale 1 2 1 children [
Shape { geometry IndexedLineSet { coord Coordinate { point [ 0 0 0, 1 0 0, 1 1 0 ] } coordIndex [ 0 1 2 -1 ] color Color { color [ 1 0 0, 0 1 0, 0 0 1 ] } } }
Shape { geometry PointSet { coord Coordinate { point [ 0 0 1, 1 0 1 ] } } } ] }
DEF Clock TimeSensor { cycleInterval 4 loop TRUE }
DEF Path PositionInterpolator { key [ 0 0.5 1 ] keyValue [ 0 0 0, 0 2 0, 0 0 0 ] }
DEF Turn OrientationInterpolator { key [ 0 1 ] keyValue [ 0 1 0 0, 0 1 0 3.14 ] }
ROUTE Clock.fraction_changed TO Path.set_fraction
ROUTE Clock.fraction_changed TO Turn.set_fraction
ROUTE Path.value_changed TO Mover.set_translation
ROUTE Turn.value_changed TO Mover.set_rotation
Shape { appearance Appearance { texture PixelTexture { image 2 2 3 0xFF0000 0x00FF00 0x0000FF 0xFFFFFF } } geometry Box { } }
Inline { url [ "part.wrl" ] }
""",
}
# the Inline target of feat_scene.wrl
INLINE = {"part.wrl": "#VRML V2.0 utf8\nTransform { translation 0 -3 0 children Shape { geometry Box { size 4 0.2 4 } } }\n"}
+77
View File
@@ -0,0 +1,77 @@
# PMX / PMD fixtures (tools/fixtures.py): assimp's MMD test model (test/models-nonbsd/MMD/Alicia_blade.pmx, read from
# the nixpkgs assimp source, never committed) and synthetic models from tools/fixtures/_pmx_writer.py (PMX 2.0 / 2.1,
# UTF-16 / UTF-8, index sizes 1 / 2 / 4, additional UVs, every deform and morph type), with assimp's counts
# (`assimp info -r`: meshes, faces, vertices, materials, bones) and world bounds (assimp's PreTransformVertices
# export), plus the generator's own facts (vertex / bone / morph counts, sample vertices). The same synthetic models as
# PMD 1.0 (no reference reads PMD: the test compares them with the PMX decode).
# tests/gen/pmx_cases.luau { name, data, files = { name -> bytes }, assimp, expect? }
# tests/gen/pmx_pmd.luau { name, data, pmx (the case index of the same model) }
import importlib.util, os, struct, zlib
INPUTS = ["tools/fixtures/_pmx_writer.py", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py"]
def load(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def tiny_png():
raw = b"".join(b"\0" + bytes([200, 40, 40]) * 2 for _ in range(2))
def chunk(t, d):
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 2, 2, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
def generate(ctx):
M = load(ctx, "_model_ref")
Fbx = load(ctx, "fbx")
W = load(ctx, "_pmx_writer")
tmp = M.tempdir()
cases, pmds = [], []
src = os.path.join(Fbx.assimp_src(ctx), "test", "models-nonbsd", "MMD", "Alicia_blade.pmx")
if os.path.exists(src):
cases.append({"name": "assimp/Alicia_blade.pmx", "path": src, "files": {}})
variants = [
("small_utf16_i1.pmx", dict(version=2.0, utf8=False, sizes=(1, 1, 1, 1, 1, 1), uva=0), dict(rings=4, seg=6, nbones=3, nmat=2)),
("utf8_i2_uva2.pmx", dict(version=2.0, utf8=True, sizes=(2, 2, 2, 2, 2, 2), uva=2), dict(rings=12, seg=16, nbones=5, nmat=3)),
("v21_utf16_i4_uva4.pmx", dict(version=2.1, utf8=False, sizes=(4, 4, 4, 4, 4, 4), uva=4), dict(rings=30, seg=20, nbones=8, nmat=3)),
("v21_utf8_mixed.pmx", dict(version=2.1, utf8=True, sizes=(2, 1, 1, 2, 1, 1), uva=1), dict(rings=8, seg=10, nbones=4, nmat=3, deform=[4, 3, 1], flips=True)),
]
png = tiny_png()
for fname, wopts, topts in variants:
uva = wopts["uva"]
model = W.tube(version=wopts["version"], uva=uva, seed=len(cases), name=fname[:-4], **topts)
data = W.Pmx(**wopts).build(model)
path = os.path.join(tmp, fname)
with open(path, "wb") as f:
f.write(data)
vs = model["vertices"]
samples = []
for i in (0, 1, 2, 3, len(vs) - 1):
v = vs[i]
samples.append({"index": i, "pos": list(v["pos"]), "uv": list(v["uv"]), "deform": v["deform"], "bones": v["bones"], "weights": v["weights"]})
types = {}
for mo in model["morphs"]:
types[str(mo["type"])] = types.get(str(mo["type"]), 0) + 1
expect = {"vertices": len(vs), "bones": len(model["bones"]), "morphs": len(model["morphs"]), "morphTypes": types,
"textures": len(model["textures"]), "uva": uva, "samples": samples, "name": model["name"], "version": wopts["version"],
"rigid": len(model["rigid"]), "joints": len(model["joints"]), "frames": len(model["frames"])}
cases.append({"name": "gen/" + fname, "path": path, "files": {"tex/body.png": png}, "expect": expect})
if wopts["version"] == 2.0 and wopts["sizes"][0] <= 2:
pmds.append({"name": "gen/" + fname[:-4] + ".pmd", "data": W.pmd(model), "pmx": len(cases)})
infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True)
for c, a in zip(cases, infos):
a.update(Fbx.assimp_extra(ctx, c["path"]))
a.pop("min", None)
a.pop("max", None)
a.update(Fbx.ptv_bounds(ctx, c["path"], tmp))
if a.get("failed") and c.get("expect", {}).get("morphTypes", {}).get("9"):
a = {"skip": True} # flip / impulse morphs: assimp's MMD reader stops there
c["assimp"] = a
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("pmx_cases", cases)
ctx.emit("pmx_pmd", pmds)
+99
View File
@@ -0,0 +1,99 @@
# VRML97 fixtures (tools/fixtures.py): assimp's WRL test models (test/models/WRL, read from the nixpkgs assimp source,
# never committed; assimp itself is built without its VRML reader), scenes and glTF sample models written by VTK's
# vtkVRMLExporter, and the hand-written feature files of tools/fixtures/_vrml_ref.py, with VTK's vtkVRMLImporter as
# the reference (polygons, lines, world bounds). Then our encoder's output (tools/fixtures/_vrml_encode.luau) read back
# by VTK.
# tests/gen/vrml_cases.luau { name, data, files = { name -> bytes }, vtk, primitives (bool: tessellated shapes) }
# tests/gen/vrml_gltf.luau glTF sample models for the writer round trips: { name, data, files }
# tests/gen/vrml_xcheck.luau { name, case?, gltf?, vtk }
import importlib.util, os, re
INPUTS = ["src/Formats/codecs/model/Vrml", "src/Formats/model/vrml", "tests/fixtures/gltf", "tools/fixtures/_vrml_ref.py",
"tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", "tools/fixtures/_vrml_encode.luau"]
GLTF = ["Box", "BoxTextured", "BoxVertexColors", "Cameras", "MeshPrimitiveModes", "SimpleMeshes", "AnimatedTriangle", "InterpolationTest",
"NegativeScaleTest", "TextureCoordinateTest", "MultiUVTest"]
def load(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def primitives(data):
return bool(re.search(rb"\b(Box|Sphere|Cone|Cylinder|Extrusion|ElevationGrid|Text)\s*\{|<(Box|Sphere|Cone|Cylinder|Extrusion|ElevationGrid|Text)\b", data))
def gltf_picks(ctx):
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
picks = []
for model in GLTF:
d0 = os.path.join(gl, model)
if not os.path.isdir(d0):
continue
for variant in ("glTF", "glTF-Embedded", "glTF-Binary"):
d = os.path.join(d0, variant)
if not os.path.isdir(d):
continue
mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")]
if mains:
picks.append({"name": model + "/" + variant, "path": os.path.join(d, mains[0]), "data": open(os.path.join(d, mains[0]), "rb").read(),
"files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}})
break
return picks
def generate(ctx):
M = load(ctx, "_model_ref")
Fbx = load(ctx, "fbx")
R = load(ctx, "_vrml_ref")
tmp = M.tempdir()
cases = []
src = os.path.join(Fbx.assimp_src(ctx), "test", "models", "WRL")
for f in sorted(os.listdir(src)):
if f.lower().endswith(".wrl"):
files = {}
if f == "HelloWorld.wrl":
files["earth-topo.png"] = open(os.path.join(src, "earth-topo.png"), "rb").read()
cases.append({"name": "assimp/" + f, "path": os.path.join(src, f), "files": files})
picks = gltf_picks(ctx)
for name in R.vtk_export(ctx, tmp, [p["path"] for p in picks if p["path"].endswith((".gltf", ".glb"))]):
cases.append({"name": "vtk/" + name + ".wrl", "path": os.path.join(tmp, name + ".wrl"), "files": {}})
for name, text in sorted(R.FEATURES.items()):
p = os.path.join(tmp, name)
with open(p, "w") as f:
f.write(text)
cases.append({"name": "feature/" + name, "path": p, "files": dict(R.INLINE)})
for name, text in R.INLINE.items():
with open(os.path.join(tmp, name), "w") as f:
f.write(text)
refs = R.vtk_read(ctx, [c["path"] for c in cases])
for c, v in zip(cases, refs):
c["data"] = open(c["path"], "rb").read()
c["vtk"] = v
c["primitives"] = primitives(c["data"])
c["vtkTransforms"] = R.vtk_xform_ok(c["data"])
del c["path"]
ctx.emit("vrml_cases", cases)
for p in picks:
del p["path"]
ctx.emit("vrml_gltf", picks)
# VTK reads our output
ours = M.luau_encode(ctx, "tools/fixtures/_vrml_encode.luau")
xtmp = M.tempdir()
names = sorted(n for n in ours if n.endswith(".wrl"))
for name, data in ours.items():
with open(os.path.join(xtmp, name), "wb") as f:
f.write(data)
refs = R.vtk_read(ctx, [os.path.join(xtmp, n) for n in names])
out = []
for n, v in zip(names, refs):
e = {"name": n, "vtk": v, "vtkTransforms": R.vtk_xform_ok(ours[n])}
m = re.match(r"(case|gltf)_(\d+)\.wrl$", n)
if m:
e[m.group(1)] = int(m.group(2))
out.append(e)
ctx.emit("vrml_xcheck", out)
+135
View File
@@ -0,0 +1,135 @@
# X3D fixtures (tools/fixtures.py): assimp's X3D / X3DV / X3DB test models (test/models/X3D*, read from the nixpkgs
# assimp source, never committed), scenes and glTF sample models written by VTK's vtkX3DExporter, glTF sample models
# written by assimp's X3D exporter, and hand-written feature files (below), with assimp's X3D reader as the reference
# (`assimp info -r`: meshes, faces, materials; world bounds from its PreTransformVertices export). Then our encoder's
# X3D output (tools/fixtures/_vrml_encode.luau) read back by assimp.
# tests/gen/x3d_cases.luau { name, data, files = { name -> bytes }, assimp, primitives (bool) }
# tests/gen/x3d_xcheck.luau { name, case? / gltf? / wcase?, assimp }
import importlib.util, os, re, subprocess
INPUTS = ["src/Formats/codecs/model/Vrml", "src/Formats/model/x3d", "src/Formats/model/vrml", "tests/fixtures/gltf",
"tools/fixtures/_vrml_ref.py", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", "tools/fixtures/vrml.py",
"tools/fixtures/_vrml_encode.luau"]
FEATURES = {
"feat_sets.x3d": """<?xml version="1.0" encoding="UTF-8"?>
<X3D profile="Interchange" version="3.3"><Scene>
<Transform translation="0 0 0"><Shape><Appearance><Material diffuseColor="1 0 0"/></Appearance>
<IndexedTriangleSet index="0 1 2 0 2 3" solid="false"><Coordinate point="0 0 0 1 0 0 1 1 0 0 1 0"/>
<ColorRGBA color="1 0 0 1 0 1 0 1 0 0 1 0.5 1 1 1 1"/></IndexedTriangleSet></Shape></Transform>
<Transform translation="2 0 0"><Shape><TriangleFanSet fanCount="5"><Coordinate point="0 0 0 1 0 0 1 1 0 0 1 0 -1 1 0"/></TriangleFanSet></Shape></Transform>
<Transform translation="4 0 0"><Shape><IndexedTriangleStripSet index="0 1 2 3 -1 4 5 6"><Coordinate point="0 0 0 1 0 0 0 1 0 1 1 0 0 2 0 1 2 0 0 3 0"/></IndexedTriangleStripSet></Shape></Transform>
<Transform translation="6 0 0"><Shape><IndexedQuadSet index="0 1 2 3"><Coordinate point="0 0 0 1 0 0 1 1 0 0 1 0"/></IndexedQuadSet></Shape></Transform>
<Transform translation="8 0 0"><Shape><TriangleSet><Coordinate point="0 0 0 1 0 0 0 1 0 0 0 1 1 0 1 0 1 1"/></TriangleSet></Shape></Transform>
<Transform translation="0 3 0"><Shape><LineSet vertexCount="3 2"><Coordinate point="0 0 0 1 0 0 1 1 0 2 2 2 3 3 3"/></LineSet></Shape></Transform>
</Scene></X3D>
""",
"feat_proto.x3d": """<?xml version="1.0" encoding="UTF-8"?>
<X3D profile="Immersive" version="3.3"><head><meta name="title" content="protos"/><unit category="length" name="centimetre" conversionFactor="0.01"/></head>
<Scene>
<ProtoDeclare name="Post"><ProtoInterface>
<field name="height" type="SFFloat" accessType="initializeOnly" value="2"/>
<field name="where" type="SFVec3f" accessType="inputOutput" value="0 0 0"/>
<field name="look" type="SFNode" accessType="inputOutput"><Appearance><Material diffuseColor="0 0 1"/></Appearance></field>
</ProtoInterface>
<ProtoBody><Transform><IS><connect nodeField="translation" protoField="where"/></IS>
<Shape><IS><connect nodeField="appearance" protoField="look"/></IS>
<Cylinder radius="0.1"><IS><connect nodeField="height" protoField="height"/></IS></Cylinder></Shape></Transform></ProtoBody>
</ProtoDeclare>
<ProtoInstance name="Post" DEF="P1"><fieldValue name="where" value="1 0 0"/></ProtoInstance>
<ProtoInstance name="Post"><fieldValue name="where" value="-1 0 0"/><fieldValue name="height" value="4"/></ProtoInstance>
<Transform DEF="Spin"><Shape><Appearance><PhysicalMaterial baseColor="0.5 0.5 0.5" metallic="0.25" roughness="0.75"/></Appearance>
<Box size="1 1 1"/></Shape></Transform>
<TimeSensor DEF="Clock" cycleInterval="2" loop="true"/>
<OrientationInterpolator DEF="Rot" key="0 0.5 1" keyValue="0 1 0 0 0 1 0 3.14159 0 1 0 6.28318"/>
<ROUTE fromNode="Clock" fromField="fraction_changed" toNode="Rot" toField="set_fraction"/>
<ROUTE fromNode="Rot" fromField="value_changed" toNode="Spin" toField="set_rotation"/>
<OrthoViewpoint fieldOfView="-2 -1 2 1" position="0 0 5"/>
<Shape><Appearance><UnlitMaterial emissiveColor="0 1 0"/></Appearance><PointSet><Coordinate point="0 5 0 1 5 0"/><Color color="1 0 0 0 1 0"/></PointSet></Shape>
</Scene></X3D>
""",
"feat_classic.x3dv": """#X3D V3.3 utf8
PROFILE Interchange
COMPONENT Geometry2D:1
META "title" "classic"
UNIT length millimetre 0.001
DEF Root Transform { translation 1 2 3 children [
Shape { appearance Appearance { material Material { diffuseColor 0 1 0 } }
geometry IndexedFaceSet { coord Coordinate { point [ 0 0 0 1 0 0 1 1 0 0 1 0 ] } coordIndex [ 0 1 2 3 -1 ]
color ColorRGBA { color [ 1 0 0 1, 0 1 0 1, 0 0 1 1, 1 1 1 0.5 ] } } }
Shape { geometry IndexedTriangleSet { index [ 0 1 2 ] coord Coordinate { point [ 0 0 1 1 0 1 0 1 1 ] } } }
] }
""",
}
def load(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def reference(ctx, M, Fbx, path, tmp):
a = M.assimp_info(ctx, [path], raw=True)[0]
if not a.get("failed"):
a.pop("min", None)
a.pop("max", None)
a.update(Fbx.assimp_extra(ctx, path))
a.update(Fbx.ptv_bounds(ctx, path, tmp))
return a
def generate(ctx):
M = load(ctx, "_model_ref")
Fbx = load(ctx, "fbx")
R = load(ctx, "_vrml_ref")
V = load(ctx, "vrml")
tmp = M.tempdir()
cases = []
root = os.path.join(Fbx.assimp_src(ctx), "test", "models")
for sub in ("X3D", "X3DV", "X3DB"):
d = os.path.join(root, sub)
for f in sorted(os.listdir(d)):
if f.lower().endswith((".x3d", ".x3dv", ".x3db")):
files = {}
if f.startswith("HelloWorld"):
files["earth-topo.png"] = open(os.path.join(d, "earth-topo.png"), "rb").read()
cases.append({"name": "assimp/%s/%s" % (sub, f), "path": os.path.join(d, f), "files": files})
picks = V.gltf_picks(ctx)
for name in R.vtk_export(ctx, tmp, [p["path"] for p in picks]):
cases.append({"name": "vtk/" + name + ".x3d", "path": os.path.join(tmp, name + ".x3d"), "files": {}})
for p in picks:
out = os.path.join(tmp, "assimp_" + p["name"].split("/")[0] + ".x3d")
try:
ctx.nix("assimp", ["assimp", "export", p["path"], out, "-fx3d"])
except subprocess.CalledProcessError:
continue
cases.append({"name": "assimp-export/" + os.path.basename(out), "path": out, "files": dict(p["files"])})
for name, text in sorted(FEATURES.items()):
path = os.path.join(tmp, name)
with open(path, "w") as f:
f.write(text)
cases.append({"name": "feature/" + name, "path": path, "files": {}})
for c in cases:
c["data"] = open(c["path"], "rb").read()
c["primitives"] = V.primitives(c["data"])
c["assimp"] = reference(ctx, M, Fbx, c["path"], tmp) if c["path"].endswith(".x3d") else {"skip": True}
del c["path"]
ctx.emit("x3d_cases", cases)
# assimp reads our X3D output
ours = M.luau_encode(ctx, "tools/fixtures/_vrml_encode.luau")
xtmp = M.tempdir()
out = []
for name in sorted(n for n in ours if n.endswith(".x3d")):
path = os.path.join(xtmp, name)
with open(path, "wb") as f:
# assimp 6 cannot read quoted MFString urls (url='"a.png"', which the X3D encoding requires)
f.write(re.sub(rb'url="&quot;([^&"]*)&quot;"', rb'url="\1"', ours[name]))
e = {"name": name, "assimp": reference(ctx, M, Fbx, path, xtmp)}
m = re.match(r"(xcase|xgltf|wcase)_(\d+)\.x3d$", name)
if m:
e[m.group(1)] = int(m.group(2))
out.append(e)
ctx.emit("x3d_xcheck", out)