# 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: rosetta 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)