brokkr.kit.v0: an extrude shape, a PROFILES section along a polyline through core.sweep; wedge and gusset sections

core.SHAPES gains extrude (section, w, h, t, path, up, loop?, at?, rot?). check_kit refuses a section
PROFILES does not have, a path outside 2 to 64 points (3 with loop), and anything that is not an expression
where one belongs; _extrude builds through profile and sweep and re-raises what either refuses under the
shape's name. PROFILES gains wedge (a right trapezoid) and gusset (a right triangle with its tips cut square).
No sweep, profile or circle signature changes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-02 16:10:21 +01:00
commit 19c36b984f
2 changed files with 132 additions and 10 deletions

View file

@ -2,9 +2,10 @@
numpy and the standard library only, no Blender: tests/test_kitbash.py runs this file as it is. A kit is data
(kits/<name>.v0.json beside this file: mechanical, the machine parts, and cutters, the parts brokkr_kitbash.cut
places to cut a mesh, each with its recess floor as a socket). A part is a list of shapes (tube, box, lathe, and a repeat of one of
them, a step apart or turned about an axis) whose numbers may be expressions over the part's params, and a list of
sockets, each a frame on one of the part's flat faces. A lathe profile point may be marked sharp: its ring of edges
places to cut a mesh, each with its recess floor as a socket; and frame, the beams, truss, portal, gusset and wedge
of a chassis). A part is a list of shapes (tube, box, lathe, extrude: a PROFILES section along a polyline through
sweep; and a repeat of one of them, a step apart or turned about an axis) whose numbers may be expressions over the
part's params, and a list of sockets, each a frame on one of the part's flat faces. A lathe profile point may be marked sharp: its ring of edges
is then a crease (Built.sharp). An expression is parsed with ast.parse and walked against a
whitelist; nothing in a kit is ever run as Python.
@ -17,8 +18,9 @@ both kits declare the socket's type with the same match rule. surface_frame is t
met a surface. closure_residual is how far two sockets stand from meeting as a pin,
whatever the roll: what closes a loop the tree of connections cannot state.
The structure under an armor cage is built, not kit parts: PROFILES are the sections (I, C, T, L, box), sweep takes
an outline along a polyline with mitred joints (a longeron, a post), band is the rib beside a section in its plane,
PROFILES are the seven sections (I, C, T, L, box, wedge, gusset) and sweep takes an outline along a polyline with
mitred joints: an extrude shape is the two together, and so is a longeron or a post of the structure under an armor
cage, which is built, not kit parts: band is the rib beside a section in its plane,
offset and clipped so that it follows a crease instead of folding in it (away, the distance to a polyline, is what
clips it), inset is the step that offsets a mesh inward by its own faces (the surface a rib's edge is cut from), crossings
finds where a section line meets a half-plane, resample fills a section's points in, and spans
@ -57,8 +59,10 @@ PLACED = ("at", "rot")
SHAPES = {"tube": (("r0", "r1", "length", "segments"), ("inner0", "inner1", "smooth") + PLACED),
"box": (("size",), PLACED),
"lathe": (("profile", "segments"), ("loop", "smooth") + PLACED),
"extrude": (("section", "w", "h", "t", "path", "up"), ("loop",) + PLACED),
"repeat": (("count", "of"), ("step", "around", "center"))}
SEGMENTS = (3, 128)
PATH = 64 # the most points an extrude's path may list
COPIES = (1, 256)
@ -233,6 +237,21 @@ def _shape(shape: Any, names, where: str, inside_repeat: bool = False) -> dict:
if kind == "box":
made["size"] = _vector(shape["size"], names, f"{where} size")
return made
if kind == "extrude":
section, path = shape["section"], shape["path"]
if not isinstance(section, str) or section not in PROFILES:
raise KitError(f"{where} section: {section!r} is not one of {', '.join(PROFILES)}")
if not isinstance(shape.get("loop", False), bool):
raise KitError(f"{where} loop must be true or false")
made["section"], made["loop"] = section, shape.get("loop", False)
for key in ("w", "h", "t"):
made[key] = parse(shape[key], names, f"{where} {key}")
least = 3 if made["loop"] else 2
if not isinstance(path, list) or not least <= len(path) <= PATH:
raise KitError(f"{where} path must be an array of {least} to {PATH} [x, y, z] points{' (it is a loop)' if made['loop'] else ''}")
made["path"] = [_vector(point, names, f"{where} path[{i}]") for i, point in enumerate(path)]
made["up"] = _vector(shape["up"], names, f"{where} up")
return made
for key in ("loop", "smooth"):
if not isinstance(shape.get(key, False), bool):
raise KitError(f"{where} {key} must be true or false")
@ -550,8 +569,22 @@ def _box(shape: dict, env):
return BOX_SIGNS * size, BOX_FACES.ravel(), np.full(6, 4), np.zeros(6, dtype=bool), NO_SHARP
def _extrude(shape: dict, env):
"""A PROFILES section swept along the path: profile and sweep own the geometry (the outline's x is up cross the
path's tangent, its y is up taken off the tangent, the joints are mitred), and what either refuses is refused
here under the shape's name. Every face is flat."""
size = [shape[key].value(env) for key in ("w", "h", "t")]
path = [[e.value(env) for e in point] for point in shape["path"]]
up = [e.value(env) for e in shape["up"]]
try:
swept = sweep(path, profile(shape["section"], *size), up, shape["loop"])
except KitError as error:
raise KitError(f"{shape['where']}: {error}") from None
return swept.V, swept.faces, swept.counts, swept.smooth, NO_SHARP
def _placed(shape: dict, env):
V, faces, counts, smooth, sharp = {"tube": _tube, "box": _box, "lathe": _lathe}[shape["shape"]](shape, env)
V, faces, counts, smooth, sharp = {"tube": _tube, "box": _box, "lathe": _lathe, "extrude": _extrude}[shape["shape"]](shape, env)
rotation = _rotation([e.value(env) for e in shape["rot"]])
return V @ rotation.T + np.array([e.value(env) for e in shape["at"]]), faces, counts, smooth, sharp
@ -606,6 +639,7 @@ def build(part: dict, params: dict | None = None) -> Built:
# --- structure: sections swept along paths --------------------------------------------------------------------
PROFILES = { # (w, h, t) -> the outline, counter-clockwise in (x across, y along up): flange width, height, wall
# (a wedge's t is its front height and a gusset's the flat that cuts each acute tip square)
"I": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, -h / 2 + t), (t / 2, -h / 2 + t), (t / 2, h / 2 - t), (w / 2, h / 2 - t),
(w / 2, h / 2), (-w / 2, h / 2), (-w / 2, h / 2 - t), (-t / 2, h / 2 - t), (-t / 2, -h / 2 + t), (-w / 2, -h / 2 + t)],
"C": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, -h / 2 + t), (-w / 2 + t, -h / 2 + t), (-w / 2 + t, h / 2 - t), (w / 2, h / 2 - t),
@ -613,6 +647,8 @@ PROFILES = { # (w, h, t) -> the outline, counter-clockwise in (x across, y alon
"T": lambda w, h, t: [(-t / 2, -h / 2), (t / 2, -h / 2), (t / 2, h / 2 - t), (w / 2, h / 2 - t), (w / 2, h / 2), (-w / 2, h / 2), (-w / 2, h / 2 - t), (-t / 2, h / 2 - t)],
"L": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, -h / 2 + t), (-w / 2 + t, -h / 2 + t), (-w / 2 + t, h / 2), (-w / 2, h / 2)],
"box": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, h / 2), (-w / 2, h / 2)],
"wedge": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, -h / 2 + t), (-w / 2, h / 2)],
"gusset": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, -h / 2 + t), (-w / 2 + t, h / 2), (-w / 2, h / 2)],
}
TURN_LIMIT = 150.0 # degrees a swept path may turn at one point: past it a mitre runs 3.9 times the section's width
@ -620,10 +656,12 @@ TURN_LIMIT = 150.0 # degrees a swept path may turn at one point: past it a mitr
def profile(kind: str, w: float, h: float, t: float) -> np.ndarray:
"""PROFILES[kind] at a width, height and wall, as an (M, 2) array. Refuses a kind PROFILES does not have, a size
that is not above 0, and a wall that leaves no section: as wide as the flange, or as thick as the height its
flanges share (two on an I and a C, one on a T and an L). A box has no wall."""
flanges share (two on an I and a C, one on a T and an L). A box has no wall. A wedge is a right trapezoid, base w,
back height h and front height t, under h; a gusset a right triangle on legs w and h whose two acute tips are cut
square by a flat t long, under half the shorter leg."""
if kind not in PROFILES:
raise KitError(f"profile {kind!r} is not one of {', '.join(PROFILES)}")
limit = min(w, h / 2 if kind in ("I", "C") else h)
limit = h if kind == "wedge" else min(w, h) / 2 if kind == "gusset" else min(w, h / 2 if kind in ("I", "C") else h)
if not all(finite(v) and v > 0 for v in (w, h, t)) or (kind != "box" and not t < limit):
raise KitError(f"profile {kind!r} of width {w}, height {h}, wall {t}: every size must be above 0 and the wall under {limit:.6g}")
return np.array(PROFILES[kind](w, h, t), dtype=np.float64)

View file

@ -187,6 +187,7 @@ class CheckKitTests(unittest.TestCase):
"""check-kit-refusals. Mutant M2 (skip the unknown-key check): the 'colour' and 'radius' documents are admitted."""
socket = {"name": "s", "type": "mount", "size": 1, "at": [0, 0, 0], "z": "+z", "y": "+y"}
box = {"shape": "box", "size": [1, 1, 1]}
beam = {"shape": "extrude", "section": "I", "w": 0.06, "h": 0.1, "t": 0.012, "path": [[0, 0, 0], [0, 0, 1]], "up": [0, 1, 0]}
cases = [
({**document(), "schema": "brokkr.kit.v1"}, r"schema must be brokkr\.kit\.v0"),
({**document(), "colour": 1}, r"kit has no key 'colour'"),
@ -209,7 +210,20 @@ class CheckKitTests(unittest.TestCase):
(document(sockets=[{**socket, "z": {}}]), r"part 'p' socket 's': z must be one of"),
(document([{"shape": ["box"], "size": [1, 1, 1]}]), r"part 'p' shape 0: unknown shape \['box'\]"),
(document(sockets=[{**socket, "at": [0, 0, 10 ** 400]}]), r"part 'p' socket 's' at\[2\]: 1000\d+ is not a finite number"),
# extrude-refusals. Mutants E2 (the section checked only at build) and E9 (a 65-point path admitted)
(document([{**beam, "section": "Z"}]), r"part 'p' shape 0 \(extrude\) section: 'Z' is not one of I, C, T, L, box, wedge, gusset"),
(document([{**beam, "section": ["I"]}]), r"part 'p' shape 0 \(extrude\) section: \['I'\] is not one of"),
(document([{**beam, "path": [[0, 0, 0]]}]), r"part 'p' shape 0 \(extrude\) path must be an array of 2 to 64 \[x, y, z\] points$"),
(document([{**beam, "loop": True}]), r"part 'p' shape 0 \(extrude\) path must be an array of 3 to 64 \[x, y, z\] points \(it is a loop\)"),
(document([{**beam, "path": [[0, 0, k] for k in range(65)]}]), r"part 'p' shape 0 \(extrude\) path must be an array of 2 to 64"),
(document([{**beam, "path": [[0, 0, 0], [0, 1]]}]), r"part 'p' shape 0 \(extrude\) path\[1\] must be an array of three"),
(document([{**beam, "up": "+y"}]), r"part 'p' shape 0 \(extrude\) up must be an array of three"),
(document([{**beam, "loop": "yes"}]), r"part 'p' shape 0 \(extrude\) loop must be true or false"),
(document([{**beam, "w": "q"}]), r"part 'p' shape 0 \(extrude\) w: 'q' names 'q'"),
(document([{**beam, "smooth": True}]), r"part 'p' shape 0 \(extrude\) has no key 'smooth'"),
(document([{k: v for k, v in beam.items() if k != "t"}]), r"part 'p' shape 0 \(extrude\) lacks 't'"),
]
self.assertEqual(len(core.check_kit(document([{**beam, "path": [[0, 0, k] for k in range(64)]}]))["parts"]["p"]["shapes"][0]["path"]), 64)
for doc, message in cases:
with self.assertRaisesRegex(core.KitError, message):
core.check_kit(doc)
@ -406,6 +420,70 @@ class ShapeTests(unittest.TestCase):
self.assertEqual(b.shape.tolist(), [0] * 6 + [1] * 18 + [2] * 10)
self.assertEqual((b.shape.dtype, b.shell_count), (np.int32, 5))
BEAM = {"shape": "extrude", "section": "I", "w": 0.06, "h": 0.1, "t": 0.012, "path": [[0, 0, 0], [0, 0, 0.3]], "up": [0, 1, 0]}
def test_an_extrude_is_a_section_swept_along_its_path(self):
"""extrude-holds. Each of the seven sections along a straight path is one closed shell, wound outward, of the
section's area times the length, every face flat, the outline's x on up cross the tangent and its y on up.
Mutant E6 (up ignored, +z always): the path along z is refused, and the one along x stands its height on z
whatever up says."""
w, h, t = 0.06, 0.1, 0.012
self.assertEqual(list(core.PROFILES), ["I", "C", "T", "L", "box", "wedge", "gusset"])
for section in core.PROFILES:
outline = core.profile(section, w, h, t)
x, y = outline.T
area = float(0.5 * np.sum(x * np.roll(y, -1) - np.roll(x, -1) * y))
b = built([{**self.BEAM, "section": section, "w": "a", "path": [[0, 0, 0], [0, 0, "5*a"]]}], [param("a", 0.01, 1, w)])
self.assertTrue(closed_and_oriented(b), section)
self.assertLess(abs(signed_volume(b) - area * 0.3), 1e-12, section)
self.assertEqual((b.shell_count, b.counts.tolist(), bool(b.smooth.any()), b.sharp.shape), (1, [4] * len(outline) + [len(outline)] * 2, False, (0, 2)), section)
self.assertEqual(b.V[:len(outline)].tolist(), [[px, py, 0.0] for px, py in outline.tolist()], section)
self.assertEqual(b.V[len(outline):, 2].tolist(), [0.06 * 5] * len(outline))
extent = lambda up: np.round(np.ptp(built([{**self.BEAM, "path": [[0, 0, 0], [0.3, 0, 0]], "up": up}]).V, axis=0), 12).tolist() # noqa: E731
self.assertEqual((extent([0, 0, 1]), extent([0, 1, 0]), extent([0, 5, 5])), ([0.3, w, h], [0.3, h, w], [0.3, round((w + h) / 2 ** 0.5, 12), round((w + h) / 2 ** 0.5, 12)]))
def test_an_extrude_is_placed_and_repeated_as_every_shape(self):
"""extrude-holds, extrude-in-repeat-and-loop. Mutants E1 (an extrude ignores at and rot: the box section stands
at the origin, unturned), E5 (repeat refuses an extrude) and E7 (loop ignored: the ring is an open path with
two caps, 14 faces and three quarters of the volume)."""
rot, at, size = [30, 40, 50], [1, 2, 3], [0.06, 0.1, 0.3]
lifted = (np.array(at) + core._rotation(rot) @ [0, 0, 0.15]).tolist()
swept = built([{**self.BEAM, "section": "box", "rot": rot, "at": at}])
box = built([{"shape": "box", "size": size, "rot": rot, "at": lifted}])
order = lambda V: V[np.lexsort(np.round(V, 9).T)] # noqa: E731
self.assertLess(float(np.abs(order(swept.V) - order(box.V)).max()), 1e-12)
self.assertLess(abs(signed_volume(swept) - 0.06 * 0.1 * 0.3), 1e-12)
area = 2 * 0.06 * 0.012 + (0.1 - 2 * 0.012) * 0.012
for change, centres in (({"step": [0.5, 0, "a"]}, [[0, 0, 0.15], [0.5, 0, 1.15], [1.0, 0, 2.15]]),
({"around": "+y", "center": [1, 0, 0]}, [[0, 0, 0.15], [1.5 + 0.15 * 0.75 ** 0.5, 0, 0.75 ** 0.5 - 0.075], [1.5 - 0.15 * 0.75 ** 0.5, 0, -0.75 ** 0.5 - 0.075]])):
b = built([{"shape": "box", "size": [1, 1, 1]}, {"shape": "repeat", "count": 3, **change, "of": self.BEAM}], [param("a")])
self.assertEqual((b.shell_count, b.shape.tolist()), (4, [0] * 6 + [1] * 14 * 3))
self.assertTrue(closed_and_oriented(b))
self.assertLess(abs(signed_volume(b) - 1.0 - 3 * area * 0.3), 1e-12)
self.assertTrue(np.allclose(b.V[8:].reshape(3, 24, 3).mean(axis=1), centres, atol=1e-12), change)
ring = built([{**self.BEAM, "section": "box", "w": 0.1, "h": 0.2, "loop": True, "path": [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], "up": [0, 0, 1]}])
self.assertEqual((ring.shell_count, ring.counts.tolist(), len(ring.V)), (1, [4] * 16, 16))
self.assertTrue(closed_and_oriented(ring))
self.assertLess(abs(signed_volume(ring) - 0.1 * 0.2 * 4.0), 1e-12) # mitred: the area times the path's length
def test_what_a_sweep_refuses_an_extrude_refuses_by_name(self):
"""extrude-refusals, at build. Mutant E8 (the where prefix dropped): each message starts at 'path point' or
'profile' and names no kit, part or shape."""
here = r"^kit 't' part 'p' shape 0 \(extrude\): "
for change, message in (
({"path": [[0, 0, 0], [1, 0, 0], [0.015, 0.17, 0]], "up": [0, 0, 1]}, here + r"path point 1: the path turns 170\.2 degrees there, over 150$"),
({"up": [0, 0, 2]}, here + r"path point 0: up \[0\.0, 0\.0, 2\.0\] runs along the path there"),
({"up": [0, 0, 0]}, here + r"path point 0: up \[0\.0, 0\.0, 0\.0\] runs along the path there \(or is zero\)"),
({"w": 0.4, "path": [[0, 0, 0], [1, 0, 0], [1, 0.05, 0]], "up": [0, 0, 1]}, here + r"path point 1: the section folds there"),
({"path": [[0, 0, 0], [0, 0, 0]]}, here + r"path point 0: the segment from it is shorter than 1e-9"),
({"t": "a"}, here + r"profile 'I' of width 0\.06, height 0\.1, wall 0\.05: every size must be above 0 and the wall under 0\.05$"),
({"w": "a-0.05"}, here + r"profile 'I' of width 0\.0, ")):
with self.assertRaisesRegex(core.KitError, message):
built([{**self.BEAM, **change}], [param("a", 0, 1, 0.05)])
with self.assertRaisesRegex(core.KitError, r"^kit 't' part 'p' shape 1 \(repeat\) of \(extrude\): path point 0: up"):
built([{"shape": "box", "size": [1, 1, 1]}, {"shape": "repeat", "count": 2, "step": [1, 0, 0], "of": {**self.BEAM, "up": [0, 0, 1]}}])
self.assertEqual(len(built([{**self.BEAM, "t": "a"}], [param("a", 0, 1, 0.05)], {"a": 0.04}).counts), 14)
def test_sockets_are_right_handed_frames(self):
socket = {"name": "s", "type": "mount", "size": "2*a", "at": ["a", 2, 3], "z": "+x", "y": "+z"}
kit = core.check_kit(document(params=[param("a")], sockets=[socket]))
@ -1178,7 +1256,8 @@ class StructureTests(unittest.TestCase):
def test_the_profiles_are_counter_clockwise_sections(self):
w, h, t = 0.06, 0.1, 0.012
areas = {"I": 2 * w * t + (h - 2 * t) * t, "C": 2 * w * t + (h - 2 * t) * t, "T": w * t + (h - t) * t, "L": w * t + (h - t) * t, "box": w * h}
areas = {"I": 2 * w * t + (h - 2 * t) * t, "C": 2 * w * t + (h - 2 * t) * t, "T": w * t + (h - t) * t, "L": w * t + (h - t) * t, "box": w * h,
"wedge": w * (h + t) / 2, "gusset": 0.003888} # the gusset's five corners by the shoelace: t*h + (w - t)*(h + t)/2
self.assertEqual(sorted(core.PROFILES), sorted(areas))
for kind, area in areas.items():
outline = core.profile(kind, w, h, t)
@ -1187,7 +1266,12 @@ class StructureTests(unittest.TestCase):
self.assertAlmostEqual(float(outline[:, 1].max() - outline[:, 1].min()), h, places=15)
self.assertAlmostEqual(self.area(core.circle(0.5, 16)), 0.5 * 16 * 0.25 * math.sin(2 * math.pi / 16), places=15)
self.assertEqual(core.circle(0.5, 16)[0].tolist(), [0.5, 0.0])
for bad in (("Z", w, h, t), ("I", w, h, h / 2), ("T", w, h, w), ("L", 0.0, h, t), ("C", w, h, float("nan")), ("box", w, h, 0.0)):
# profiles-seven. Mutants E3 (a wedge admits t = h: a box) and E4 (a gusset ignores t: three corners, sharp tips)
self.assertEqual(core.profile("wedge", w, h, t).tolist(), [[-w / 2, -h / 2], [w / 2, -h / 2], [w / 2, -h / 2 + t], [-w / 2, h / 2]])
self.assertEqual(core.profile("gusset", w, h, t).tolist(), [[-w / 2, -h / 2], [w / 2, -h / 2], [w / 2, -h / 2 + t], [-w / 2 + t, h / 2], [-w / 2, h / 2]])
self.assertEqual((len(core.profile("wedge", w, h, 0.99 * h)), len(core.profile("gusset", w, h, 0.49 * w))), (4, 5))
for bad in (("Z", w, h, t), ("I", w, h, h / 2), ("T", w, h, w), ("L", 0.0, h, t), ("C", w, h, float("nan")), ("box", w, h, 0.0),
("wedge", w, h, h), ("gusset", w, h, min(w, h) / 2), ("gusset", h, w, min(w, h) / 2), ("wedge", w, h, 0.0)):
with self.assertRaisesRegex(core.KitError, "profile"):
core.profile(*bad)
for bad in ((0.0, 16), (0.5, 2), (0.5, 129)):