merge ws/3d3-d (model/b3d, model/ldraw)

This commit is contained in:
4DBug committed 2026-10-31 14:30:17 -05:00
commit de2695b87d
14 files changed
+2843 -1

No files matched your search

+204
View File
@@ -0,0 +1,204 @@
# B3D fixtures (tools/fixtures.py): assimp's Blitz3D test models (WusonBlitz, dwarf2, turtle1: read from the nixpkgs
# assimp source, never committed; their textures next to them go into `files`) and B3D files written here (textures
# with transforms and clamp flags, brushes with alpha / FX, vertex colours, two UV sets, nested rotated / scaled nodes,
# pivots, master brushes, bones with weights, KEYS + ANIM), with reference values from assimp: `assimp info -r`
# (meshes, faces, materials, animations, channels, bones) and its PreTransformVertices OBJ export (world bounds,
# triangle area, signed volume: the handedness conversion and winding), plus the counts the generator wrote.
# tests/gen/b3d_cases.luau { name, data, files = { name -> bytes }, assimp = {...}, want? = {...} }
import importlib.util, math, os, re, struct, subprocess
INPUTS = ["tools/fixtures/_model_ref.py"]
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 assimp_src():
out = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True)
return out.stdout.decode().strip().split("\n")[-1]
# ---------------------------------------------------------------------------------------------------- B3D writer
def chunk(tag, *parts):
body = b"".join(parts)
return tag.encode() + struct.pack("<I", len(body)) + body
def cstr(s):
return s.encode() + b"\0"
def f32(*v):
return struct.pack("<%df" % len(v), *v)
def i32(*v):
return struct.pack("<%di" % len(v), *v)
def quat_axis(ax, ay, az, deg):
# Blitz3D order: w, x, y, z
l = math.sqrt(ax * ax + ay * ay + az * az)
h = math.radians(deg) / 2
s = math.sin(h) / l
return (math.cos(h), ax * s, ay * s, az * s)
def node(name, pos=(0, 0, 0), scale=(1, 1, 1), rot=(1, 0, 0, 0), *children):
return chunk("NODE", cstr(name), f32(*pos), f32(*scale), f32(*rot), *children)
def box_mesh(sx, sy, sz, flags=0, sets=1, size=2, brushes=(-1,), master=-1):
# 8 corners, 12 triangles; split between the brushes round-robin by face
verts = []
for i in range(8):
x, y, z = (sx if i & 1 else -sx), (sy if i & 2 else -sy), (sz if i & 4 else -sz)
v = f32(x, y, z)
if flags & 1:
l = math.sqrt(x * x + y * y + z * z)
v += f32(x / l, y / l, z / l)
if flags & 2:
v += f32((i & 1) * 1.0, ((i >> 1) & 1) * 1.0, ((i >> 2) & 1) * 1.0, 1.0)
for s in range(sets):
v += f32(*[(i * 0.1 + s + k * 0.5) for k in range(size)])
verts.append(v)
# Blitz3D front faces are clockwise seen from outside (left-handed, Direct3D culling)
quads = [(0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)]
tris = []
for a, b, c, d in quads:
tris += [(a, b, c), (a, c, d)]
tchunks = []
for k, br in enumerate(brushes):
mine = [t for j, t in enumerate(tris) if j % len(brushes) == k]
tchunks.append(chunk("TRIS", i32(br), b"".join(i32(*t) for t in mine)))
return chunk("MESH", i32(master), chunk("VRTS", i32(flags, sets, size), b"".join(verts)), *tchunks), 8, 12
def textured():
texs = chunk("TEXS", cstr("tex/a.png"), i32(1, 2), f32(0.25, 0.5), f32(2, 3), f32(0.5),
cstr("b.png"), i32(1 | 16 | 32 | 65536, 2), f32(0, 0), f32(1, 1), f32(0))
brus = chunk("BRUS", i32(2),
cstr("red"), f32(1, 0, 0, 1), f32(0.5), i32(1, 0), i32(0, 1),
cstr("glass"), f32(0.2, 0.4, 1, 0.5), f32(0), i32(1, 16 | 1), i32(1, -1))
m1, _, _ = box_mesh(1, 2, 3, flags=3, sets=2, size=2, brushes=(0, 1))
m2, _, _ = box_mesh(0.5, 0.5, 0.5, flags=1, sets=1, size=2, brushes=(-1,), master=1)
child = node("child", (3, 1, -2), (1, 2, 1), quat_axis(0, 1, 1, 50), m2)
root = node("root", (1, 2, 3), (2, 1, 0.5), quat_axis(1, 1, 0, 30), m1, child)
data = chunk("BB3D", i32(1), texs, brus, root)
return data, {"vertices": 16, "triangles": 24, "textures": 2, "materials": 2, "colors": True, "uvSets": 2, "nodes": 2}
def pivots():
m1, _, _ = box_mesh(1, 1, 1, brushes=(-1,))
m2, _, _ = box_mesh(2, 0.5, 1, sets=0, brushes=(-1,))
a = node("a", (5, 0, 0), (1, 1, 1), quat_axis(0, 0, 1, 90), m1)
b = node("b", (0, 0, 5), (-1, 1, 1), quat_axis(0, 1, 0, -45), m2)
pivot = node("pivot", (0, 3, 0), (1, 1, 1), quat_axis(1, 0, 0, 20), a, b)
data = chunk("BB3D", i32(1), node("top", (0, 0, 0), (1, 1, 1), (1, 0, 0, 0), pivot))
return data, {"vertices": 16, "triangles": 24, "textures": 0, "materials": 0, "colors": False, "uvSets": 1, "nodes": 4, "mirrored": True}
def skinned():
# a bar along y: 3 rings of 4 vertices; two bones (nested), each weighting rings; keys on both bones
verts, tris = [], []
for ring in range(3):
for k in range(4):
a = math.radians(90 * k)
verts.append(f32(math.cos(a), ring * 2.0, math.sin(a)))
for ring in range(2):
for k in range(4):
a, b = ring * 4 + k, ring * 4 + (k + 1) % 4
tris += [(a, b + 4, b), (a, a + 4, b + 4)]
mesh = chunk("MESH", i32(-1), chunk("VRTS", i32(0, 0, 0), b"".join(verts)), chunk("TRIS", i32(-1), b"".join(i32(*t) for t in tris)))
w1 = b"".join(i32(v) + f32(1.0 if v < 4 else 0.5) for v in range(8))
w2 = b"".join(i32(v) + f32(0.5 if v < 8 else 1.0) for v in range(4, 12))
keys1 = chunk("KEYS", i32(4), *[i32(f) + f32(*quat_axis(0, 0, 1, f * 10)) for f in (1, 5, 10)])
keys2 = chunk("KEYS", i32(1 | 2), *[i32(f) + f32(0, 2 + f * 0.1, 0) + f32(1, 1 + f * 0.05, 1) for f in (1, 10)])
bone2 = node("bone2", (0, 2, 0), (1, 1, 1), (1, 0, 0, 0), chunk("BONE", w2), keys2)
bone1 = node("bone1", (0, 0, 0), (1, 1, 1), (1, 0, 0, 0), chunk("BONE", w1), keys1, bone2)
root = node("body", (0, 1, 0), (1, 1, 1), quat_axis(0, 1, 0, 15), mesh, bone1, chunk("ANIM", i32(0, 10), f32(25)))
data = chunk("BB3D", i32(1), root)
return data, {"vertices": 12, "triangles": 16, "textures": 0, "materials": 0, "colors": False, "uvSets": 0, "nodes": 3,
"joints": 2, "channels": 3, "fps": 25.0, "frames": 10}
# ---------------------------------------------------------------------------------------------------- references
def info(ctx, path):
try:
txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace")
except subprocess.CalledProcessError:
return {"failed": True}
out = {}
for label in ("Meshes", "Materials", "Faces", "Vertices", "Animations", "Bones", "Animation Channels", "Nodes"):
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
out[label.lower().replace(" ", "_")] = int(m.group(1)) if m else -1
return out
def ptv(ctx, path, tmp):
# world-space triangles from assimp's PreTransformVertices OBJ export: bounds, area, signed volume
out = os.path.join(tmp, "ptv.obj")
ctx.nix("assimp", ["assimp", "export", path, out, "-ptv"])
vs, area, vol = [], 0.0, 0.0
lo, hi = [1e30] * 3, [-1e30] * 3
with open(out) as f:
for line in f:
p = line.split()
if not p:
continue
if p[0] == "v":
v = [float(x) for x in p[1:4]]
vs.append(v)
lo = [min(a, b) for a, b in zip(lo, v)]
hi = [max(a, b) for a, b in zip(hi, v)]
elif p[0] == "f":
idx = [int(x.split("/")[0]) for x in p[1:]]
idx = [i - 1 if i > 0 else len(vs) + i for i in idx]
for k in range(1, len(idx) - 1):
a, b, c = vs[idx[0]], vs[idx[k]], vs[idx[k + 1]]
e1 = [b[j] - a[j] for j in range(3)]
e2 = [c[j] - a[j] for j in range(3)]
cr = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]
area += math.sqrt(sum(x * x for x in cr)) / 2
vol += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6
os.remove(out)
return {"min": lo, "max": hi, "area": area, "volume": vol}
def generate(ctx):
M = ref_module(ctx)
tmp = M.tempdir()
cases = []
src = assimp_src()
for rel in ("models/B3D/WusonBlitz.b3d", "models-nonbsd/B3D/dwarf2.b3d", "models-nonbsd/B3D/turtle1.b3d"):
p = os.path.join(src, "test", rel)
if not os.path.exists(p):
continue
d = os.path.dirname(p)
files = {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d))
if f.lower().endswith((".png", ".jpg")) and os.path.getsize(os.path.join(d, f)) < 300000}
cases.append({"name": "assimp/" + rel, "path": p, "files": files})
for name, fn in (("textured", textured), ("pivots", pivots), ("skinned", skinned)):
data, want = fn()
p = os.path.join(tmp, name + ".b3d")
with open(p, "wb") as f:
f.write(data)
files = {"a.png": M_PNG, "b.png": M_PNG} if name == "textured" else {}
cases.append({"name": "gen/" + name, "path": p, "files": files, "want": want})
for c in cases:
a = info(ctx, c["path"])
if not a.get("failed"):
a.update(ptv(ctx, c["path"], tmp))
c["assimp"] = a
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("b3d_cases", cases)
# a 1x1 PNG (texture data for the generated files)
M_PNG = bytes.fromhex("89504e470d0a1a0a0000000d4948445200000001000000010806000000"
"1f15c4890000000d49444154789c63f8cfc0f01f0005000201a2b3d6bd0000000049454e44ae426082")
+417
View File
@@ -0,0 +1,417 @@
# LDraw fixtures (tools/fixtures.py): hand-written LDraw files (a brick built from primitives that come through
# `files` with library paths, an MPD with embedded sub-files and sub-models, BFC CERTIFY CW / CCW, INVERTNEXT,
# mirrored references, NOCERTIFY / NOCLIP, colour inheritance 16 / 24, direct colours, local !COLOUR definitions,
# optional lines, a missing part) and real parts and the sample models car.ldr / pyramid.ldr from the LDraw parts
# library (complete.zip, CC BY 2.0 / 4.0, the copy nixpkgs' LeoCAD package uses; read from the nix store, never
# committed: each case carries the files it needs). References: an independent expansion written here (world
# triangles after the decoder's root flip, per colour, lines, area, bounds, signed volume of the one-sided faces) and
# LeoCAD's OBJ export (`leocad -obj`: bounds and area of the real models), plus LDConfig.ldr itself for the built-in
# colour table.
# tests/gen/ldraw_cases.luau { name, data, files = { path -> text }, opts?, want = {...}, leocad? = {...} }
# tests/gen/ldraw_config.luau { text = LDConfig.ldr, colours = { { code, rgb, edge, alpha } } }
import math, os, re, subprocess, zipfile
INPUTS = []
def nix_out(attr):
out = subprocess.run(["nix", "build", attr, "--no-link", "--print-out-paths"], capture_output=True, check=True)
return out.stdout.decode().strip().split("\n")[-1]
def library_zip(leocad):
# LeoCAD's wrapper points LEOCAD_LIB at the parts library zip
wrapper = open(os.path.join(leocad, "bin", "leocad"), "rb").read().decode("latin-1")
m = re.search(r"(/nix/store/[^'\" ]*complete\.zip)", wrapper)
return m.group(1) if m else None
# ---------------------------------------------------------------------------------------------------- reference
def norm(name):
return name.strip().replace("\\", "/").lower()
class Ref:
"""an independent LDraw expansion: every triangle in world space (after the root flip y -> -y, z -> -z)"""
PREFIXES = ("", "parts/", "p/", "parts/s/", "models/")
def __init__(self, main, files, colours):
self.files = {norm(k): v for k, v in files.items()}
self.colours = colours # code -> (rgb, edge)
self.mpd = {}
self.missing = set()
self.tris = [] # (colour, ds, (v0, v1, v2))
self.lines = 0
self.optional = 0
text = main
if re.search(r"^\s*0\s+FILE\s", text, re.M):
cur = None
first = None
for line in text.splitlines():
m = re.match(r"^\s*0\s+FILE\s+(.*?)\s*$", line)
if m:
cur = norm(m.group(1))
first = first or cur
self.mpd[cur] = []
continue
if re.match(r"^\s*0\s+NOFILE\b", line):
cur = None
continue
if cur:
self.mpd[cur].append(line)
self.main = "\n".join(self.mpd[first])
else:
self.main = text
org = re.search(r"^\s*0\s+!LDRAW_ORG\s+(\S+)", self.main, re.M)
refs = re.search(r"^\s*1\s", self.main, re.M)
self.main_part = bool(org and "model" not in org.group(1).lower()) or not refs
def lookup(self, name):
n = norm(name)
if n in self.mpd:
return "\n".join(self.mpd[n])
for p in self.PREFIXES:
if p + n in self.files:
return self.files[p + n]
self.missing.add(n)
return None
def colour(self, code, cur):
if code == 16:
return cur
if code == 24:
return self.edge(cur)
return code
def edge(self, c):
if c in self.colours:
e = self.colours[c][1]
return e
return 0x2333333 if c < 0x2000000 else 0x2000000
def walk(self, text, m, colour, inv, certified, depth, model, stack=()):
# model files (the main file, .ldr / .mpd sub-models) do not limit the certification of what they place
if depth > 64:
return
st = {"cw": False, "cert": None, "clip": True, "invert": False}
for raw in text.splitlines():
t = raw.split()
if not t:
continue
if t[0] == "0":
if len(t) >= 3 and t[1] == "!COLOUR":
self.colours.update({k: (v[0], v[1]) for k, v in parse_ldconfig(raw).items()})
if len(t) >= 3 and t[1] == "BFC":
words = [w.upper() for w in t[2:]]
if "NOCERTIFY" in words:
st["cert"] = False
elif "CERTIFY" in words:
st["cert"] = True
if "CW" in words:
st["cw"] = True
if "CCW" in words:
st["cw"] = False
if "NOCLIP" in words:
st["clip"] = False
elif "CLIP" in words:
st["clip"] = True
if "INVERTNEXT" in words:
st["invert"] = True
continue
invert_next = st["invert"]
st["invert"] = False
try:
kind = int(t[0])
code = int(t[1], 0)
cert = certified and st["cert"] is True and st["clip"]
if kind == 1 and len(t) >= 15:
x, y, z, a, b, c, d, e, f, g, h, i = [float(v) for v in t[2:14]]
loc = [[a, b, c, x], [d, e, f, y], [g, h, i, z]]
name = raw.split(None, 14)[14].strip()
if norm(name) in stack:
continue # a file that (indirectly) places itself
sub = self.lookup(name)
if sub is None:
continue
sub_model = norm(name).endswith((".ldr", ".mpd"))
self.walk(sub, mul(m, loc), self.colour(code, colour), inv ^ invert_next,
(True if model else cert), depth + 1, sub_model, stack + (norm(name),))
elif kind in (3, 4) and len(t) >= 2 + 3 * kind:
pts = [apply(m, [float(v) for v in t[2 + 3 * k:5 + 3 * k]]) for k in range(kind)]
if st["cw"] ^ inv ^ (det(m) < 0):
pts = pts[::-1]
col = self.colour(code, colour)
one = cert and not model or (model and st["cert"] is True and st["clip"])
self.tris.append((col, not one, (pts[0], pts[1], pts[2])))
if kind == 4:
self.tris.append((col, not one, (pts[0], pts[2], pts[3])))
elif kind == 2 and len(t) >= 8:
[float(v) for v in t[2:8]]
self.lines += 1
elif kind == 5 and len(t) >= 14:
[float(v) for v in t[2:14]]
self.optional += 1
except ValueError:
pass
def run(self, main_colour=16):
flip = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0]]
self.walk(self.main, flip, main_colour, False, True, 0, not self.main_part)
return self
def summary(self):
per = {}
area, vol = 0.0, 0.0
lo, hi = [1e30] * 3, [-1e30] * 3
for col, ds, (a, b, c) in self.tris:
per[col] = per.get(col, 0) + 1
for p in (a, b, c):
lo = [min(u, v) for u, v in zip(lo, p)]
hi = [max(u, v) for u, v in zip(hi, p)]
area += tri_area(a, b, c)
if not ds:
vol += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6
out = {"triangles": len(self.tris), "lines": self.lines, "optional": self.optional, "area": area, "volume": vol,
"doubleSided": sum(1 for x in self.tris if x[1]),
"colours": [[k, v] for k, v in sorted(per.items())], "missing": sorted(self.missing)}
if self.tris:
out["min"], out["max"] = lo, hi
return out
def mul(m, l):
# 3x4 affine product m * l
r = [[0.0] * 4 for _ in range(3)]
for i in range(3):
for j in range(4):
s = sum(m[i][k] * l[k][j] for k in range(3))
r[i][j] = s + (m[i][3] if j == 3 else 0)
return r
def apply(m, p):
return [m[i][0] * p[0] + m[i][1] * p[1] + m[i][2] * p[2] + m[i][3] for i in range(3)]
def det(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]))
def tri_area(a, b, c):
e1 = [b[i] - a[i] for i in range(3)]
e2 = [c[i] - a[i] for i in range(3)]
x = e1[1] * e2[2] - e1[2] * e2[1]
y = e1[2] * e2[0] - e1[0] * e2[2]
z = e1[0] * e2[1] - e1[1] * e2[0]
return math.sqrt(x * x + y * y + z * z) / 2
def parse_ldconfig(text):
out = {}
for line in text.splitlines():
m = re.match(r"^\s*0\s+!COLOUR\s+(\S+)\s+(.*)$", line)
if not m:
continue
t = m.group(2).split()
kv = {}
for i in range(0, len(t) - 1):
if t[i] in ("CODE", "VALUE", "EDGE", "ALPHA") and t[i] not in kv:
kv[t[i]] = t[i + 1]
code = int(kv["CODE"])
rgb = int(kv["VALUE"][1:], 16)
e = kv["EDGE"]
edge = (0x2000000 | int(e[1:], 16)) if e.startswith("#") else int(e)
out[code] = (rgb, edge, int(kv.get("ALPHA", "255")), m.group(1))
return out
# ---------------------------------------------------------------------------------------------------- hand-written
BOX = """0 a unit box primitive (faces outward, CCW)
0 BFC CERTIFY CCW
4 16 -1 -1 -1 1 -1 -1 1 -1 1 -1 -1 1
4 16 -1 1 -1 -1 1 1 1 1 1 1 1 -1
4 16 -1 -1 -1 -1 -1 1 -1 1 1 -1 1 -1
4 16 1 -1 -1 1 1 -1 1 1 1 1 -1 1
4 16 -1 -1 -1 -1 1 -1 1 1 -1 1 -1 -1
4 16 -1 -1 1 1 -1 1 1 1 1 -1 1 1
2 24 -1 -1 -1 1 -1 -1
2 24 -1 -1 -1 -1 1 -1
5 24 -1 -1 -1 -1 1 -1 1 -1 -1 -1 -1 1
"""
BOX_CW = """0 the same box written clockwise
0 BFC CERTIFY CW
4 16 -1 -1 1 1 -1 1 1 -1 -1 -1 -1 -1
4 16 1 1 -1 1 1 1 -1 1 1 -1 1 -1
4 16 -1 1 -1 -1 1 1 -1 -1 1 -1 -1 -1
4 16 1 -1 1 1 1 1 1 1 -1 1 -1 -1
4 16 1 -1 -1 1 1 -1 -1 1 -1 -1 -1 -1
4 16 -1 1 1 1 1 1 1 -1 1 -1 -1 1
"""
TRI = """0 an uncertified triangle
3 16 0 0 0 1 0 0 0 0 1
"""
# a brick: an outer box, an inner box turned inside out (INVERTNEXT), a mirrored stud box, an uncertified triangle
BRICK = """0 Test Brick 1 x 2
0 Name: testbrick.dat
0 Author: formats-luau
0 !LDRAW_ORG Unofficial_Part
0 BFC CERTIFY CCW
1 16 0 12 0 20 0 0 0 12 0 0 0 10 box.dat
0 BFC INVERTNEXT
1 16 0 14 0 18 0 0 0 10 0 0 0 8 box.dat
1 4 10 -2 0 -6 0 0 0 2 0 0 0 6 s\\stud box.dat
1 16 0 -4 0 1 0 0 0 1 0 0 0 1 48\\cwbox.dat
1 16 0 30 0 5 0 0 0 5 0 0 0 5 tri.dat
"""
PLAIN_LDR = """0 Two bricks
0 Name: two.ldr
1 1 0 0 0 1 0 0 0 1 0 0 0 1 testbrick.dat
1 14 60 -24 0 0 0 1 0 1 0 -1 0 0 testbrick.dat
1 16 -60 0 0 -1 0 0 0 1 0 0 0 1 testbrick.dat
0 STEP
1 0x2FF8000 0 -60 0 1 0 0 0 1 0 0 0 1 testbrick.dat
1 4 0 -90 0 1 0 0 0 1 0 0 0 1 nosuchpart.dat
"""
MPD = """0 FILE main.ldr
0 MPD main
0 Name: main.ldr
0 !COLOUR Test_Purple CODE 1000 VALUE #8000FF EDGE #200040 ALPHA 200
1 16 0 0 0 1 0 0 0 1 0 0 0 1 sub.ldr
1 1000 0 -100 0 1 0 0 0 1 0 0 0 1 sub.ldr
1 2 0 50 50 1 0 0 0 -1 0 0 0 1 Embedded Part.dat
3 24 0 0 0 10 0 0 0 10 0
0 NOFILE
0 FILE sub.ldr
0 a sub-model: two parts and a nested sub-model
1 16 0 0 0 1 0 0 0 1 0 0 0 1 embedded part.dat
1 4 30 0 0 1 0 0 0 1 0 0 0 1 embedded part.dat
1 16 0 0 40 1 0 0 0 1 0 0 0 1 inner.ldr
0 NOFILE
0 FILE inner.ldr
1 0x3FF0000 0 0 0 2 0 0 0 2 0 0 0 2 embedded part.dat
0 FILE Embedded Part.dat
0 !LDRAW_ORG Unofficial_Part
0 BFC CERTIFY CCW
1 16 0 0 0 5 0 0 0 5 0 0 0 5 box.dat
0 BFC NOCLIP
3 24 0 -5 0 5 -5 0 0 -5 5
0 BFC CLIP
4 16 -5 -6 -5 5 -6 -5 5 -6 5 -5 -6 5
"""
BAD_REFS = """0 cycles and bad lines are survived
1 16 0 0 0 1 0 0 0 1 0 0 0 1 loop.dat
1 16 0 0 0 1 0 0 0 1
3 16 0 0 0 1 x 0 0 0 1
4 16 0 0 0 1 0 0 1 1 0 0 1 0
"""
LOOP = "0 a file that calls itself\n3 16 0 0 0 1 0 0 0 1 0\n1 16 0 0 0 1 0 0 0 1 0 0 0 1 loop.dat\n"
LIB = {"parts/box.dat": BOX, "p/s/stud box.dat": BOX, "p/48/cwbox.dat": BOX_CW, "p/tri.dat": TRI,
"parts/testbrick.dat": BRICK, "loop.dat": LOOP}
def hand_cases(colours):
cases = []
def add(name, text, files, opts=None):
ref = Ref(text, files, colours).run()
c = {"name": name, "data": text, "files": files, "want": ref.summary()}
if opts:
c["opts"] = opts
cases.append(c)
add("brick.dat", BRICK, {k: v for k, v in LIB.items() if k != "parts/testbrick.dat"})
add("two.ldr", PLAIN_LDR, dict(LIB))
add("model.mpd", MPD, {"parts/box.dat": BOX})
add("badrefs.ldr", BAD_REFS, {"loop.dat": LOOP})
add("crlf.ldr", PLAIN_LDR.replace("\n", "\r\n"), dict(LIB))
return cases
# ---------------------------------------------------------------------------------------------------- real parts
def closure(z, names, text_of):
"""the library files a set of references needs: { library path -> text }"""
have = {}
index = {}
for n in z.namelist():
if n.startswith("ldraw/") and n.lower().endswith(".dat"):
index[n[6:].lower()] = n
todo = list(names)
while todo:
n = norm(todo.pop())
for p in Ref.PREFIXES:
key = p + n
if key in index:
if key not in have:
t = z.read(index[key]).decode("utf-8", "replace")
have[key] = t
for line in t.splitlines():
parts = line.split(None, 14)
if len(parts) == 15 and parts[0] == "1":
todo.append(parts[14].strip())
break
return have
def leocad_obj(leocad, libzip, path, tmp):
out = os.path.join(tmp, "leocad.obj")
env = dict(os.environ, QT_QPA_PLATFORM="offscreen")
subprocess.run([os.path.join(leocad, "bin", "leocad"), "-l", libzip, path, "-obj", out], env=env, capture_output=True, timeout=300, check=True)
vs, area = [], 0.0
lo, hi = [1e30] * 3, [-1e30] * 3
with open(out) as f:
for line in f:
p = line.split()
if not p:
continue
if p[0] == "v":
v = [float(x) for x in p[1:4]]
vs.append(v)
lo = [min(a, b) for a, b in zip(lo, v)]
hi = [max(a, b) for a, b in zip(hi, v)]
elif p[0] == "f":
idx = [int(x.split("/")[0]) - 1 for x in p[1:]]
for k in range(1, len(idx) - 1):
area += tri_area(vs[idx[0]], vs[idx[k]], vs[idx[k + 1]])
return {"min": lo, "max": hi, "area": area}
def generate(ctx):
import tempfile
tmp = tempfile.mkdtemp(prefix="formats-ldraw-")
leocad = nix_out("nixpkgs#leocad")
libzip = library_zip(leocad)
z = zipfile.ZipFile(libzip)
config = z.read("ldraw/LDConfig.ldr").decode("utf-8")
colours = {k: (v[0], v[1]) for k, v in parse_ldconfig(config).items()}
ctx.emit("ldraw_config", {"text": config, "colours": [[k, v[0], v[1], v[2]] for k, v in sorted(parse_ldconfig(config).items())]})
cases = hand_cases(colours)
# real parts and the library's sample models, with LeoCAD's export
reals = [("3001.dat", None), ("3062b.dat", None), ("4073.dat", None), ("3626c.dat", None), ("car.ldr", "ldraw/models/car.ldr"),
("pyramid.ldr", "ldraw/models/pyramid.ldr")]
for name, member in reals:
if member:
text = z.read(member).decode("utf-8", "replace")
else:
text = "0 one part\n1 4 0 0 0 1 0 0 0 1 0 0 0 1 %s\n" % name
files = closure(z, [l.split(None, 14)[14].strip() for l in text.splitlines() if l.split(None, 14)[:1] == ["1"]], None)
ref = Ref(text, files, colours).run()
c = {"name": "library/" + name, "data": text, "files": files, "want": ref.summary()}
p = os.path.join(tmp, "model.ldr")
with open(p, "w") as f:
f.write(text)
try:
c["leocad"] = leocad_obj(leocad, libzip, p, tmp)
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError):
pass
cases.append(c)
ctx.emit("ldraw_cases", cases)