Merge pull request 'brokkr_kitbash.shell: a faceted, hollow armor shell from a loft of rings with crease runs, rebuilt in place under its cuts (cut kit-faceted-shell)' (#31) from nibu/kit-faceted-shell into main

This commit is contained in:
Eureka 2026-12-02 13:25:51 +00:00
commit 516fb4d1cb
16 changed files with 3283 additions and 1511 deletions

View file

@ -43,6 +43,12 @@ a cutter. The ribs object is a bake of the cage at that call, and kit_ribs on it
nothing reads it to decide geometry, and ribs is its one writer. The one Manifold Boolean in the package is the hole
cut inside ribs, on webs it built as closed shells that do not cross; a target's live Booleans stay Exact.
shell makes the cage that cut and ribs work on: a loft of rings with crease runs (core.sheet) under a Kit Subsurf
and a Kit Solidify. kit_shell on the object is the request, and it owns the cage mesh as kit_params owns a part's:
shell is the one writer of the mesh, its crease attributes and those two modifiers, and calling it again on the
object rewrites the mesh in place, leaving the object, its cutters, ribs, Booleans and material slots. shell
evaluates nothing: Blender's own update after the action evaluates the plate once.
Connections are a tree. A loop (a brace from one branch to another) is closed by a closure: three ID properties
on the closing part, kit_close_socket, kit_close_to (a pointer to the other part) and kit_close_to_socket. close
writes them, only when the two sockets already meet, and writes nothing else; detach clears them. Nothing here
@ -51,6 +57,7 @@ solves a loop: a closure never places a part, and a report says how far its two
bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (5, 3, 0),
"category": "Object", "description": "Parametric machine parts from kits, with socket frames; agent-callable through Brokkr."}
import contextlib
import json
import math
@ -79,6 +86,9 @@ BEVEL_SEGMENTS, BEVEL_ANGLE = 2, math.radians(30.0)
REPORT_LIMIT = 16000 # characters of a result Brokkr copies into a receipt before it truncates
RIBS_LIMIT = 64 # planes in one ribs
LONGERONS_LIMIT = 16 # longerons in one ribs
SHELL = "kit_shell" # on a shell: the request its cage is derived from, as JSON; its presence admits a rebuild, and nothing reads it to decide geometry
SUBSURF, SOLIDIFY = "Kit Subsurf", "Kit Solidify" # a shell's own modifiers, in that order, before any of its Booleans and the Kit Bevel
SHELL_FACES_LIMIT = 262144 # faces of a shell's subdivided surface: cage quads times 4 to the levels
def kit_work(work):
@ -1283,6 +1293,118 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator):
return report
class BROKKR_KITBASH_OT_shell(PolishOperator):
"""Make a faceted, hollow armor shell from a loft of rings: a quad cage with crease runs and a creased rim, under
a Subdivision and a Solidify; on an object that is already a shell, rebuild its cage in place under its cutters,
ribs and Booleans"""
bl_idname = "brokkr_kitbash.shell"
bl_label = "Make A Shell"
object_name: bpy.props.StringProperty(name="Object", description="The shell's name: a new object, or a shell to rebuild")
sheet: bpy.props.StringProperty(name="Sheet", description="A JSON object {rings, closed, mirror, creases, rim, flip}: rings of [x, y, z] points in the shell's own frame")
thickness: bpy.props.FloatProperty(name="Thickness", default=0.05, min=0.0009, max=1.0, description="The wall's thickness")
offset: bpy.props.FloatProperty(name="Offset", default=-1.0, min=-1.0, max=1.0, description="-1: the wall grows inward from the designed surface; 1: outward")
levels: bpy.props.IntProperty(name="Levels", default=3, min=1, max=4, description="Subdivision levels")
bevel: bpy.props.FloatProperty(name="Bevel", default=0.0, min=0.0, max=0.1, description="Width of the Kit Bevel on the plate's edges; 0: none")
count_folds: bpy.props.BoolProperty(name="Count Folds", default=False, description="Evaluate the wall and report how many of its inner faces fold")
# the action table states thickness from 0.001: a float property rounds 0.001 up, so its bound stands just under
@kit_work
def work(self, context):
if not 1 <= len(self.object_name) <= 63:
raise Refused(f"object_name {self.object_name!r} must be 1 to 63 characters; nothing changed.")
obj = bpy.data.objects.get(self.object_name)
if obj is not None:
if obj.type != "MESH" or SHELL not in obj:
raise Refused(f"An object named {obj.name!r} exists and is no shell (it carries no {SHELL}): shell rebuilds only what shell made; nothing changed.")
rigid(obj)
own_mesh(obj, "rebuilding")
if self.count_folds:
unseen = [modifier.name for modifier in obj.modifiers if modifier.name in (SUBSURF, SOLIDIFY) and not modifier.show_viewport]
if unseen:
raise Refused(f"{obj.name!r} has its {' and '.join(unseen)} hidden in viewports, and count_folds reads the wall those two make. "
"Show them, or leave count_folds off; nothing changed.")
with self.wall_alone(obj):
evaluable(context, obj)
try:
document = json.loads(self.sheet)
except ValueError as error:
raise Refused(f"sheet is not JSON ({error}); nothing changed.") from None
built = core.sheet(document)
cage_faces = len(built.counts)
if cage_faces * 4 ** self.levels > SHELL_FACES_LIMIT:
raise Refused(f"sheet: {cage_faces} cage quads at {self.levels} levels subdivide to {cage_faces * 4 ** self.levels} faces, over {SHELL_FACES_LIMIT}. "
"Use fewer levels or a sparser sheet; nothing changed.")
rebuilt = obj is not None
if rebuilt:
mesh = obj.data
mesh.clear_geometry()
else:
mesh = bpy.data.meshes.new(self.object_name)
write_mesh(mesh, built)
ends = np.zeros(2 * len(mesh.edges), dtype=np.int32)
mesh.edges.foreach_get("vertices", ends)
ends = np.sort(ends.reshape(-1, 2), axis=1).astype(np.int64)
order = np.argsort(ends[:, 0] * len(built.V) + ends[:, 1]) # the mesh lists its edges in calc_edges' order, not by vertex pair: each of core.sheet's creases is found by its pair
at = np.searchsorted((ends[:, 0] * len(built.V) + ends[:, 1])[order], built.creases[:, 0] * len(built.V) + built.creases[:, 1])
edge_weights, point_weights = np.zeros(len(mesh.edges), dtype=np.float32), np.zeros(len(built.V), dtype=np.float32)
edge_weights[order[at]] = built.weights
point_weights[built.corners] = built.corner_weights
for name, domain, weights in (("crease_edge", "EDGE", edge_weights), ("crease_vert", "POINT", point_weights)):
(mesh.attributes.get(name) or mesh.attributes.new(name, "FLOAT", domain)).data.foreach_set("value", weights)
if not rebuilt:
obj = bpy.data.objects.new(self.object_name, mesh)
context.scene.collection.objects.link(obj)
smooth = obj.modifiers.get(SUBSURF) or obj.modifiers.new(SUBSURF, "SUBSURF")
smooth.levels = smooth.render_levels = self.levels
smooth.subdivision_type, smooth.boundary_smooth, smooth.use_creases = "CATMULL_CLARK", "PRESERVE_CORNERS", True
wall = obj.modifiers.get(SOLIDIFY) or obj.modifiers.new(SOLIDIFY, "SOLIDIFY")
wall.thickness, wall.offset, wall.use_even_offset, wall.use_rim = self.thickness, self.offset, True, True
sync_bevel(obj, self.bevel)
obj[SHELL] = json.dumps({"sheet": document, "thickness": self.thickness, "offset": self.offset, "levels": self.levels, "bevel": self.bevel})
corners = built.V[built.faces.reshape(-1, 4)]
facing = np.cross(corners[:, 2] - corners[:, 0], corners[:, 3] - corners[:, 1]).sum(axis=0) # twice the quads' vector areas, summed
cancels = np.linalg.norm(facing) <= 1e-9 * np.linalg.norm(np.cross(corners[:, 2] - corners[:, 0], corners[:, 3] - corners[:, 1]), axis=1).sum()
return {"object": obj.name, "rebuilt": rebuilt, "rings": built.rings, "points": built.points, "cageFaces": cage_faces, "creases": len(built.creases),
"folded": self.folded_faces(context, obj, cage_faces * 4 ** self.levels) if self.count_folds else None,
"corners": len(built.corners), "subdividedFaces": cage_faces * 4 ** self.levels,
"facing": None if cancels else [round(float(v), 6) for v in facing / np.linalg.norm(facing)],
"thickness": round(self.thickness, 6), "offset": round(self.offset, 6), "levels": self.levels, "children": sorted(child.name for child in obj.children)}
@staticmethod
@contextlib.contextmanager
def wall_alone(shell):
"""The shell with every modifier but its Kit Subsurf and Kit Solidify hidden, and shown again on the way out: what
an evaluation inside reads is the wall, and no Boolean runs for it."""
hidden = [modifier for modifier in shell.modifiers if modifier.name not in (SUBSURF, SOLIDIFY) and modifier.show_viewport]
for modifier in hidden:
modifier.show_viewport = False
try:
yield
finally:
for modifier in hidden:
modifier.show_viewport = True
@staticmethod
def folded_faces(context, shell, faces: int) -> int:
"""How many inner faces of a shell's wall fold, counted on the wall as Blender evaluates it (wall_alone): Kit
Solidify lists the `faces` subdivided faces of the designed surface, then their inner twins in the same order,
each wound the other way. An inner face folds when the turn at any of its corners runs with its outer twin's
normal instead of against it: the corner has passed over its neighbour. 0 is a wall that nowhere folds."""
with BROKKR_KITBASH_OT_shell.wall_alone(shell):
_, evaluated = evaluable(context, shell)
mesh = evaluated.to_mesh()
try:
points, corners = np.zeros(3 * len(mesh.vertices)), np.zeros(len(mesh.loops), dtype=np.int32)
mesh.vertices.foreach_get("co", points)
mesh.loops.foreach_get("vertex_index", corners)
quads = points.reshape(-1, 3)[corners[:8 * faces].reshape(2, faces, 4)]
outward = np.cross(quads[0, :, 2] - quads[0, :, 0], quads[0, :, 3] - quads[0, :, 1])
turns = np.cross(quads[1] - np.roll(quads[1], 1, axis=1), np.roll(quads[1], -1, axis=1) - quads[1])
return int((np.einsum("fkc,fc->fk", turns, outward) > 0).any(axis=1).sum())
finally:
evaluated.to_mesh_clear()
class BROKKR_KITBASH_OT_describe(PolishOperator):
"""List a kit's parts, or one part: params with type, bounds, default and doc, and sockets in the part's frame
at default params"""
@ -1314,7 +1436,8 @@ class BROKKR_KITBASH_OT_report(PolishOperator):
classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report,
BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_roll, BROKKR_KITBASH_OT_aim, BROKKR_KITBASH_OT_reach,
BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_apply, BROKKR_KITBASH_OT_ribs)
BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_apply, BROKKR_KITBASH_OT_ribs,
BROKKR_KITBASH_OT_shell)
def register():

View file

@ -716,6 +716,69 @@
"doc": "the section's wall"
}
]
},
{
"name": "brokkr_kitbash.shell",
"doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The cage is subdivided (Kit Subsurf, creases kept) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. A thickness the cage cannot hold is not refused: the wall folds over itself beside a tight crease or rim corner, and a cut there is unsound. count_folds evaluates the wall alone (Kit Subsurf and Kit Solidify, no Boolean; 4 ms on a plate of 1600 subdivided faces) and counts the folded inner faces; nothing else in the report reads an evaluated mesh, and no figure of the cage bounds the fold. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings, points, cageFaces, creases, folded (null unless count_folds: then the number of the wall's inner faces that fold over, counted on the evaluated wall; 0 is a wall with no folded face, which an Exact Boolean can still fail on just short of a fold: read nonManifoldEdges after cutting), corners, subdividedFaces, facing, thickness, offset, levels and children.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "object_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "the shell's name: no object's name, or a shell's, which is then rebuilt"
},
{
"name": "sheet",
"type": "string",
"required": true,
"minLength": 2,
"maxLength": 32000,
"doc": "the shell description, a JSON object: rings, closed, mirror, creases, rim, flip"
},
{
"name": "thickness",
"type": "number",
"minimum": 0.001,
"maximum": 1,
"default": 0.05,
"doc": "the wall's thickness"
},
{
"name": "offset",
"type": "number",
"minimum": -1,
"maximum": 1,
"default": -1,
"doc": "-1: the wall grows inward from the designed surface; 1: outward"
},
{
"name": "levels",
"type": "integer",
"minimum": 1,
"maximum": 4,
"default": 3,
"doc": "subdivision levels; cage quads times 4 to the levels may not pass 262144"
},
{
"name": "bevel",
"type": "number",
"minimum": 0,
"maximum": 0.1,
"default": 0,
"doc": "width of the Kit Bevel on the plate's edges; 0: none"
},
{
"name": "count_folds",
"type": "boolean",
"default": false,
"doc": "evaluate the wall (Kit Subsurf and Kit Solidify alone) and report folded, the number of its inner faces that fold over"
}
]
}
]
}

View file

@ -25,6 +25,10 @@ finds where a section line meets a half-plane, resample fills a section's points
says which runs of a section keep their frame where the plate over them is open. brokkr_kitbash.ribs is the bpy
around them.
An armor shell is a loft, not a kit part: sheet turns a shell description (rings of points, crease runs along ring
and column edges, a rim weight, a mirror in x) into a quad cage wound by a stated rule and the creases a subdivision
surface keeps on it. brokkr_kitbash.shell is the bpy around it.
A pin's roll is its one degree of freedom, and it is solved in closed form: roll_terms gives how a point or an axis
of the child moves along a world direction as the roll turns (a cosine, a sine and a constant), aim_roll the roll
that points an axis of the child at a direction, reach_roll the roll that brings a point of the child to a plane.
@ -973,6 +977,163 @@ def spans(flags, lengths, closed: bool, bridge: float, clearance: float) -> list
return kept
# --- shells: a loft of rings and its creases -------------------------------------------------------------------
SHEET_LIMIT = 64 # rings in a sheet, and authored points in a ring
SHEET_AREA = 1e-8 # square metres: a cage quad under this is a collapsed corner
MIRROR_EPS = 1e-6 # metres a mirrored ring's point 0 may stand off x = 0, and any of its points behind it
SHEET_KEYS = ("closed", "mirror", "creases", "rim", "flip")
class Sheet(NamedTuple):
"""A shell's cage, in the shell's frame, metres: the five fields a mesh is written from (every face a quad,
shaded smooth, no sharp edge) and what a subdivision surface creases. creases is an (E, 2) array of vertex index
pairs with weights (E,) in (0, 1]; corners (K,) are vertex indices with corner_weights (K,) in (0, 1]. Vertex
i * points + j is ring i's point j, of rings rings of points points (2C - 1 when mirrored)."""
V: np.ndarray
faces: np.ndarray
counts: np.ndarray
smooth: np.ndarray
sharp: np.ndarray
creases: np.ndarray
weights: np.ndarray
corners: np.ndarray
corner_weights: np.ndarray
rings: int
points: int
def _index(value: Any, where: str, least: int, most: int) -> int:
if isinstance(value, bool) or not isinstance(value, int) or not least <= value <= most:
raise KitError(f"{where} must be a whole number from {least} to {most}, not {value!r}")
return value
def _weight(value: Any, where: str) -> float:
if not finite(value) or not 0.0 <= value <= 1.0:
raise KitError(f"{where} must be a number from 0 to 1, not {value!r}")
return float(value)
def sheet(document: Any) -> Sheet:
"""The cage of a shell description {rings, closed, mirror, creases, rim, flip}.
rings: 2 to 64 rings of 2 to 64 [x, y, z] points, equal counts. Quad (i, j) is P[i][j], P[i][j+1], P[i+1][j+1],
P[i+1][j], so its normal (P[i][j+1] - P[i][j]) x (P[i+1][j] - P[i][j]) faces out: seen from outside, a ring's
points run left to right and the rings run upward. flip reverses every face. closed joins each ring's last
point to its first. mirror: each ring is authored from its point 0 on x = 0 toward +x and becomes its mirrored
points in reverse, then itself (2C - 1 points); a crease names authored indices and lands on both halves.
creases: {ring, from, to, weight} creases ring's edges from point `from` to point `to` (on a closed ring `to`
may be the count: the edge back to point 0); {column, from, to, weight} a column's edges from ring `from` to
ring `to`; {point: [ring, point], weight} one vertex. rim is the weight of every boundary edge no run names.
An edge has one weight: two runs that give it different ones are refused."""
_keys(document, "sheet", ("rings",), SHEET_KEYS)
flags = {}
for key in ("closed", "mirror", "flip"):
flags[key] = document.get(key, False)
if not isinstance(flags[key], bool):
raise KitError(f"sheet.{key} must be true or false, not {flags[key]!r}")
closed, mirror, flip = flags["closed"], flags["mirror"], flags["flip"]
if mirror and closed:
raise KitError("sheet.mirror with sheet.closed: a mirrored ring runs from -x to +x and has two ends; state one of them")
rim = _weight(document.get("rim", 1.0), "sheet.rim")
rings = document["rings"]
if not isinstance(rings, list) or not 2 <= len(rings) <= SHEET_LIMIT:
raise KitError(f"sheet.rings must be 2 to {SHEET_LIMIT} rings, not {len(rings) if isinstance(rings, list) else rings!r}")
for i, ring in enumerate(rings):
if not isinstance(ring, list) or not 2 <= len(ring) <= SHEET_LIMIT:
raise KitError(f"sheet.rings[{i}] must be 2 to {SHEET_LIMIT} points, not {len(ring) if isinstance(ring, list) else ring!r}")
if len(ring) != len(rings[0]):
raise KitError(f"sheet.rings[{i}] has {len(ring)} points and sheet.rings[0] has {len(rings[0])}: a loft's rings have equal counts")
for j, point in enumerate(ring):
if not isinstance(point, list) or len(point) != 3 or not all(finite(v) for v in point):
raise KitError(f"sheet.rings[{i}][{j}] must be three finite numbers [x, y, z]")
P = np.array(rings, dtype=np.float64)
R, C = P.shape[:2]
if mirror:
for i in range(R):
if abs(P[i, 0, 0]) > MIRROR_EPS:
raise KitError(f"sheet.rings[{i}][0] has x = {P[i, 0, 0]:.6g}: a mirrored ring starts on x = 0")
for j in range(C):
if P[i, j, 0] < -MIRROR_EPS:
raise KitError(f"sheet.rings[{i}][{j}] has x = {P[i, j, 0]:.6g}: a mirrored ring is authored on the +x side")
P[:, 0, 0] = 0.0
P = np.concatenate([P[:, :0:-1] * (-1.0, 1.0, 1.0), P], axis=1)
N = P.shape[1] # points in a ring as built
wrap = N if closed else N - 1 # quads, and ring edges, around a ring
columns = (lambda j: (C - 1 - j, C - 1 + j) if j else (C - 1,)) if mirror else (lambda j: (j,))
vertex = lambda i, j: i * N + j % N # noqa: E731
quads = np.array([[vertex(i, j), vertex(i, j + 1), vertex(i + 1, j + 1), vertex(i + 1, j)] for i in range(R - 1) for j in range(wrap)], dtype=np.int32)
V = P.reshape(-1, 3)
corners = V[quads]
areas = 0.5 * (np.linalg.norm(np.cross(corners[:, 1] - corners[:, 0], corners[:, 3] - corners[:, 0]), axis=1)
+ np.linalg.norm(np.cross(corners[:, 3] - corners[:, 2], corners[:, 1] - corners[:, 2]), axis=1))
if areas.min() < SHEET_AREA:
worst = int(areas.argmin())
raise KitError(f"sheet: the quad between rings {worst // wrap} and {worst // wrap + 1} at point {worst % wrap} (as built) has area {areas[worst]:.3g} m2, "
f"under {SHEET_AREA:g}: a collapsed corner. Move its points apart")
if flip:
quads = quads[:, ::-1]
edges, verts = {}, {} # (low, high) or vertex -> (weight, the run that stated it)
def state(table, key, weight, where):
if key in table and table[key][0] != weight:
raise KitError(f"{where} gives an edge weight {weight:g} that {table[key][1]} gives {table[key][0]:g}: an edge has one weight" if table is edges else
f"{where} gives a point weight {weight:g} that {table[key][1]} gives {table[key][0]:g}: a point has one weight")
table.setdefault(key, (weight, where))
def edge(a, b):
return (min(a, b), max(a, b))
creases = document.get("creases", [])
if not isinstance(creases, list):
raise KitError("sheet.creases must be an array")
for k, run in enumerate(creases):
where = f"sheet.creases[{k}]"
if isinstance(run, dict) and "point" in run:
_keys(run, where, ("point", "weight"))
at = run["point"]
if not isinstance(at, list) or len(at) != 2:
raise KitError(f"{where}.point must be [ring, point]")
i, j = _index(at[0], f"{where}.point[0]", 0, R - 1), _index(at[1], f"{where}.point[1]", 0, C - 1)
weight = _weight(run["weight"], f"{where}.weight")
for column in columns(j):
state(verts, vertex(i, column), weight, where)
continue
if not isinstance(run, dict) or ("ring" in run) == ("column" in run):
raise KitError(f"{where} must be {{ring, from, to, weight}}, {{column, from, to, weight}} or {{point, weight}}")
along_ring = "ring" in run
_keys(run, where, ("ring" if along_ring else "column", "from", "to", "weight"))
weight = _weight(run["weight"], f"{where}.weight")
if along_ring:
i = _index(run["ring"], f"{where}.ring", 0, R - 1)
first, last = _index(run["from"], f"{where}.from", 0, C - 1), _index(run["to"], f"{where}.to", 0, C if closed else C - 1)
else:
j = _index(run["column"], f"{where}.column", 0, C - 1)
first, last = _index(run["from"], f"{where}.from", 0, R - 1), _index(run["to"], f"{where}.to", 0, R - 1)
if first >= last:
raise KitError(f"{where}: from {first} must be under to {last}")
for step in range(first, last):
if along_ring:
for a, b in zip(columns(step), columns(step + 1)) if step or not mirror else ((C - 1, C - 2), (C - 1, C)):
state(edges, edge(vertex(i, a), vertex(i, b)), weight, where)
else:
for column in columns(j):
state(edges, edge(vertex(step, column), vertex(step + 1, column)), weight, where)
boundary = [edge(vertex(i, j), vertex(i, j + 1)) for i in (0, R - 1) for j in range(wrap)]
if not closed:
boundary += [edge(vertex(i, j), vertex(i + 1, j)) for j in (0, N - 1) for i in range(R - 1)]
for key in boundary:
edges.setdefault(key, (rim, "sheet.rim"))
kept = sorted((key, weight) for key, (weight, _) in edges.items() if weight > 0)
pinned = sorted((key, weight) for key, (weight, _) in verts.items() if weight > 0)
return Sheet(V=V.copy(), faces=quads.ravel().astype(np.int32), counts=np.full(len(quads), 4, dtype=np.int32), smooth=np.ones(len(quads), dtype=bool),
sharp=NO_SHARP, creases=np.array([key for key, _ in kept], dtype=np.int64).reshape(-1, 2), weights=np.array([w for _, w in kept], dtype=np.float64),
corners=np.array([key for key, _ in pinned], dtype=np.int64), corner_weights=np.array([w for _, w in pinned], dtype=np.float64), rings=R, points=N)
# --- reports -------------------------------------------------------------------------------------------------
def rows(matrix) -> list[list[float]]:

View file

@ -1,12 +1,12 @@
# Kitbash parts: machinery from kits
`surfaces/blender/brokkr_kitbash` is a Blender add-on that places parametric machine parts from a **kit**, mates
them **socket** to socket, cuts them with booleans and bakes them. It is the machinery vocabulary of a ship's fixed chassis: the frame, tanks,
them **socket** to socket, cuts them with booleans and bakes them, and makes the faceted armor **shell** they sit under. It is the machinery vocabulary of a ship's fixed chassis: the frame, tanks,
actuators, housings and plumbing an agent assembles offline under a hand-fit armor cage, baked once. It is a host
add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish` and `brokkr_rig`:
it imports the polish package's operator base, `Refused` and `mesh_object`, and nothing from `brokkr_bridge`.
Enable `brokkr_mesh_polish` first; `brokkr_kitbash` refuses to register without it. `brokkr_actions.json` beside
its `__init__.py` lists the fourteen operators agents may run. Every action writes a JSON report to
its `__init__.py` lists the sixteen operators agents may run. Every action writes a JSON report to
`brokkr_mesh_polish_result`, returned in the receipt's `hostResult`.
Who owns what:
@ -306,9 +306,120 @@ so what is attached to it stays attached and new parts can attach to it, and it
`set_params` refuses it, since the params no longer make the mesh. `exportGltf` with `applyModifiers` already
exports the evaluated mesh; `apply` is for a baked `.blend`.
## Making a shell
`shell` makes an armor plate the way one is modelled by hand: fit a sparse subdivision cage, crease the edges that
are facets' borders, give it a wall, then cut into it. The cage is a **loft**: rings of points with equal counts,
quads between neighbouring rings. The description is a JSON object, `sheet`:
| key | default | what it says |
| --- | --- | --- |
| `rings` | required | 2 to 64 rings of 2 to 64 `[x, y, z]` points in the shell's own frame, equal counts |
| `closed` | `false` | each ring joins back to its first point (a sleeve); not with `mirror` |
| `mirror` | `false` | each ring is authored from its point 0 on x = 0 toward +x and mirrored across x: 2C - 1 points |
| `creases` | `[]` | runs: `{"ring": i, "from": a, "to": b, "weight": w}`, `{"column": j, "from": a, "to": b, "weight": w}`, `{"point": [i, j], "weight": w}` |
| `rim` | `1` | the weight of every boundary edge no run names |
| `flip` | `false` | reverse every face |
**Winding.** Quad (i, j) is `P[i][j], P[i][j+1], P[i+1][j+1], P[i+1][j]`: the surface faces out where, seen from
outside, a ring's points run left to right and the rings run upward. If the report's `facing` (the cage's mean
normal) points into the machine, set `flip` or author the rings the other way. Outward matters: the wall grows
inward from the designed surface (`offset` -1), `cut` rays must meet the outer face, and `ribs` stands on the
side the normals face away from.
**Creases.** A ring run creases ring `i`'s edges from point `from` to point `to`; a column run creases column
`j`'s edges from ring `from` to ring `to`; a point is one vertex. A weight of 1 is a hard facet edge, and lower
weights are semi-sharp: on the pauldron below, 1.0 holds 52 degrees across the shoulder line and 0.6 holds 35,
while every edge that carries no crease stays under 6. Runs are partial on purpose: a facet edge that dies out
halfway along a plate is a run that stops there. An edge has one weight; two runs that give it different ones are
refused, naming both. On a mirrored sheet a run names authored indices and lands on both halves, and a ring run
from point 0 joins across the middle. A vertex where exactly two creased edges meet is smoothed along them, so a
closed loop of runs (a raised face's border) rounds into a disc unless each of its corners is also a `point`;
where three or more meet, or a run ends on the rim, the corner holds by itself. `rim` 1 keeps the outline as drawn, corners included; with `rim` 0 the
outline rounds between the corners, which stay (the Subdivision preserves them).
```json
{"action": "brokkr_kitbash.shell", "object_name": "Pauldron", "thickness": 0.06, "bevel": 0.004,
"sheet": "{\"flip\": true, \"creases\": [{\"column\": 3, \"from\": 0, \"to\": 5, \"weight\": 1.0}], \"rings\": [[[0.47, -1.35, 1.02], [-0.17, -1.35, 1.28], [-0.77, -1.35, 1.15], [-1.15, -1.35, 0.85], [-1.32, -1.35, 0.26], [-1.4, -1.35, -0.3]], ...]}"}
```
Six rings of six points run aft to fore; each goes over the crown from inboard and down the outer face, and
column 3, the shoulder line, is creased, so the crown and the steep outer face are two facets of one plate. Ring 2
dips: the plate is concave there, which no convex hull can be.
The object carries the cage, `crease_edge` and `crease_vert`, and the modifiers `Kit Subsurf` (`levels`, creases
used) then `Kit Solidify` (`thickness`, `offset`, even, rim filled), then any Booleans `cut` adds, then the `Kit
Bevel` when `bevel` is over 0. `kit_shell` on it is the request, and it owns the cage as `kit_params` owns a
part's mesh: an edit of the cage by hand is lost at the next `shell` call. `shell` reports `object`, `rebuilt`,
`rings`, `points`, `cageFaces`, `creases` (edges with a weight over 0), `folded` (see Thickness at a crease),
`corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. All but `folded` are facts
of the cage: without `count_folds`, `shell` reads no evaluated mesh.
**Rebuilding.** `shell` on a name that is already a shell rewrites its cage in place. The object, its mesh
datablock, its material slots, its cutters, its ribs and its Booleans stay, so a plate can be reshaped after it is
cut. Cutters stay at their frames in the shell's frame: where the surface moved away from a cutter the cut is
shallower or floats, so raise the cutter's `lift` or `depth` (`set_params`), or cut again. Ribs are a bake: after a
rebuild, delete them and run `ribs` again. A name that is some other object is refused, as are a scaled shell and
one that shares its mesh.
**Outlines.** A loft's outline is its first and last rings and its end columns. Notches and tabs in it are
through cuts at the rim: a `box` or `slot` cutter deeper than the wall, placed across the edge, takes a bite out of
the outline, and the plate left between two bites is a tab.
**With ribs.** `ribs` reads the plate's thickness from `Kit Solidify` and follows a crease, clipping a rib inside
it; a rib deeper than the room a tight crease leaves is refused with the size to lower.
**Thickness at a crease.** `shell` takes any `thickness` in its range and does not refuse one the cage cannot
hold: the limit is a fact of the subdivided mesh, not of the cage. Even thickness moves a vertex on a
full crease along the crease's bisector, which slides it `thickness` x tan(phi) across each facet, phi being half
the angle between the two facets' normals; the vertices beside it move straight in. Where that slide is longer than
the first row of subdivided faces, the wall's far face folds over itself beside the crease: at a wall depth over
(W / 2^`levels`) / tan(phi), W the width across the crease of the narrower of its two facets. The fold is on the
crease's concave side: behind a ridge, so under a wall grown inward, and in front of a valley, under a wall grown
outward; the two read the same. Measured on two flat facets, a crease of 1.0: the fold starts at 1.00 of that
figure in 23 of 23 readings (W 1 and 0.4; phi 15 to 60; levels 1 to 3; a ridge and a valley), which is 0.217 for W
1, phi 30, levels 3, and 0.029 for W 0.4, phi 60, levels 3. Facets 1.0 and 0.3 wide at phi 45, levels 2, fold at
0.075, the narrow facet's figure, not the wide one's 0.25. A crease of 0.5 folds at 1.02 to 1.32 of it, and an
uncreased edge folds too, at 1.17 to 4.2 of it. The fold is inside the wall and one subdivided row wide: the
designed surface is unchanged and the mesh has no open or non-manifold edge, but the solid passes through itself
there, and a cut through that place is untested.
No figure read from the cage bounds this. The flat-facet figure above, taken over every cage edge, is neither a
floor nor a ceiling on a real plate: on seeded lofts of planar trapezoid facets with partial crease runs the
evaluated wall first folded at 0.44 of it with the wall grown inward, at 0.03 of it at `offset` 0 and at 0.08 of it
grown outward, and on the Seraph's plates a first face normal turned at 0.74 to 2.6 of it (`tests/fixtures/fold_lofts.json` holds three of
those lofts; 2026-12-02). So `shell` counts instead of estimating: with `count_folds` it evaluates the wall alone,
`Kit Subsurf` and `Kit Solidify` with every other modifier hidden for the reading and shown again, and reports
`folded`, the number of the wall's inner faces that fold. An inner face folds when the turn at any of its corners
runs with its outer twin's normal: the corner has passed over its neighbour. That is sooner than the face's own
normal turning: on the Seraph's cap a corner turned at 0.033 and no face normal had at 0.0416. Without `count_folds`, `folded` is null
and nothing is evaluated. The count cost 3.9 ms on a new plate of 1600 subdivided faces (a call of 7.7 ms against
3.8 ms), and nothing measurable on a rebuild under six cutters (0.94 s against 0.92 s, the call's own Boolean),
medians of three interleaved calls in the live suite (Blender 5.3 on Starfire). On a shell whose `Kit Subsurf` or
`Kit Solidify` is hidden in viewports `count_folds` is refused before anything is written.
`folded` 0 is not yet a wall an Exact Boolean takes cleanly. Short of the fold the inner quads at a tight rim corner
are twisted, and the Boolean, which cuts quads into triangles, can read the wall as passing through itself and
leave edges with four faces. On the Seraph's cap that began at 0.91 of the thickness at which the first face
folds (0.0301 against 0.033), on the left cap and not on its mirror, the right; on its breast plate at 0.91 as
well (0.032 against 0.035). Read `nonManifoldEdges` after cutting (`boolean`, `apply`, or a count on the evaluated
mesh), and keep `thickness` clear of the first folding one with a thinner wall, fewer `levels` or wider facets at
the corner.
Refused, each before anything is written and naming the field and index: a missing or unknown key; a non-finite
number; fewer than 2 or more than 64 rings or points; rings of unequal counts; a quad under 1e-8 m2 (a collapsed
corner); a mirrored ring that does not start on x = 0 or has a point behind it; `mirror` with `closed`; a run out
of range or with `from` not under `to`; a weight outside 0 to 1; more than 262144 subdivided faces (cage quads
times 4 to the `levels`).
On the pauldron (25 cage quads, 1600 subdivided faces, 3360 with the wall), `shell` took 3.5 ms a call with
Blender's own update after it, and one whole evaluation of the Subdivision and Solidify 1.7 ms. With six cutters
(four panel lines, two insets) and ribs under it, a rebuild took 0.92 s, which is its one Boolean evaluation.
Medians of 3, interleaved, Blender 5.3 on Starfire (`tests/live/kitbash_faceted.py`, `costs`).
## Cutting a shell
An armor plate is not a kit part: it is any mesh, usually a subdivided cage with a Solidify. `cut` cuts it, or a
An armor plate is not a kit part: it is any mesh, usually one made by `shell`. `cut` cuts it, or a
kit part, where a ray meets it, and what it places is itself a kit part, of the kit `cutters`:
| part | params (besides `depth`, `lift`) | socket |
@ -498,6 +609,7 @@ vertices overflow.
| `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans` (with `booleansOmitted`, as `boolean`). |
| `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. |
| `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. |
| `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel`, `count_folds` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `folded` (with `count_folds`, the number of the evaluated wall's inner faces that fold; else null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. |
`params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored
value (`set_params`). A value outside its bounds is refused with the bounds in the message.

View file

@ -0,0 +1,543 @@
{
"about": "Lofts of planar trapezoid facets on which a shell's wall folds well under any figure read from the cage: the seeded lofts of Soul's probe of 2026-12-02 (aetheria-release:verdict:cut-kit-faceted-shell.s3), seed, levels and offset as drawn there. thickness is one at which the evaluated wall folds; holds, where the action's range reaches it, one at which it does not.",
"lofts": [
{
"seed": 5185,
"levels": 1,
"offset": -1.0,
"thickness": 0.006342,
"holds": 0.001,
"sheet": {
"rings": [
[
[
-0.824534,
0.0,
-0.055726
],
[
-0.20124,
0.0,
-0.555671
],
[
0.277571,
0.0,
-0.326276
],
[
0.355141,
0.0,
-0.095203
],
[
0.451529,
0.0,
-0.526972
],
[
0.730665,
0.0,
-0.126214
]
],
[
[
-0.644054,
0.57461,
-0.007851
],
[
-0.166195,
0.57461,
-0.391143
],
[
0.200893,
0.57461,
-0.215272
],
[
0.260364,
0.57461,
-0.038117
],
[
0.334261,
0.57461,
-0.36914
],
[
0.548265,
0.57461,
-0.061892
]
],
[
[
-0.670812,
0.958364,
0.100578
],
[
-0.338388,
0.958364,
-0.16606
],
[
-0.083022,
0.958364,
-0.043715
],
[
-0.041652,
0.958364,
0.079523
],
[
0.009755,
0.958364,
-0.150754
],
[
0.158628,
0.958364,
0.062984
]
],
[
[
-0.121748,
1.402066,
-0.069972
],
[
0.06524,
1.402066,
-0.219956
],
[
0.208883,
1.402066,
-0.151137
],
[
0.232154,
1.402066,
-0.081816
],
[
0.261071,
1.402066,
-0.211346
],
[
0.344812,
1.402066,
-0.091119
]
]
],
"creases": [
{
"ring": 1,
"from": 4,
"to": 5,
"weight": 0.3
},
{
"column": 3,
"from": 0,
"to": 3,
"weight": 1.0
},
{
"ring": 2,
"from": 0,
"to": 3,
"weight": 1.0
}
],
"rim": 0.5
}
},
{
"seed": 5101,
"levels": 3,
"offset": 0.0,
"thickness": 0.010394,
"holds": null,
"sheet": {
"rings": [
[
[
-0.70481,
0.0,
0.07744
],
[
-0.108308,
0.0,
0.00574
],
[
0.492256,
0.0,
-0.339801
],
[
0.608357,
0.0,
-0.456893
],
[
0.685935,
0.0,
-0.379315
],
[
0.817607,
0.0,
0.061337
]
],
[
[
-0.355146,
0.797251,
0.328588
],
[
0.181707,
0.797251,
0.264058
],
[
0.722214,
0.797251,
-0.046929
],
[
0.826705,
0.797251,
-0.152312
],
[
0.896525,
0.797251,
-0.082492
],
[
1.01503,
0.797251,
0.314095
]
],
[
[
-0.785461,
1.527843,
-0.183277
],
[
-0.308259,
1.527843,
-0.240637
],
[
0.172192,
1.527843,
-0.51707
],
[
0.265072,
1.527843,
-0.610743
],
[
0.327135,
1.527843,
-0.548681
],
[
0.432473,
1.527843,
-0.19616
]
],
[
[
-0.488084,
2.123542,
-0.236617
],
[
-0.070532,
2.123542,
-0.286807
],
[
0.349863,
2.123542,
-0.528686
],
[
0.431133,
2.123542,
-0.61065
],
[
0.485438,
2.123542,
-0.556346
],
[
0.577608,
2.123542,
-0.247889
]
],
[
[
-0.714517,
2.852512,
0.062817
],
[
-0.356616,
2.852512,
0.019796
],
[
0.003723,
2.852512,
-0.187528
],
[
0.073383,
2.852512,
-0.257783
],
[
0.11993,
2.852512,
-0.211237
],
[
0.198933,
2.852512,
0.053154
]
]
],
"creases": [
{
"ring": 2,
"from": 3,
"to": 5,
"weight": 1.0
},
{
"column": 1,
"from": 3,
"to": 4,
"weight": 0.6
},
{
"column": 3,
"from": 3,
"to": 4,
"weight": 1.0
}
],
"rim": 0.0
}
},
{
"seed": 5196,
"levels": 1,
"offset": 1.0,
"thickness": 0.00617,
"holds": null,
"sheet": {
"rings": [
[
[
-0.383345,
0.0,
-0.359947
],
[
-0.036452,
0.0,
-0.050835
],
[
0.567786,
0.0,
-0.587238
],
[
0.622834,
0.0,
-0.467053
],
[
0.672276,
0.0,
-0.379683
],
[
0.730008,
0.0,
-0.43819
]
],
[
[
-0.557286,
0.459757,
-0.324159
],
[
-0.2711,
0.459757,
-0.069142
],
[
0.227397,
0.459757,
-0.511675
],
[
0.272811,
0.459757,
-0.412522
],
[
0.313601,
0.459757,
-0.340441
],
[
0.36123,
0.459757,
-0.38871
]
],
[
[
-0.062837,
0.80579,
-0.458467
],
[
0.162644,
0.80579,
-0.257545
],
[
0.555399,
0.80579,
-0.606206
],
[
0.591179,
0.80579,
-0.528086
],
[
0.623317,
0.80579,
-0.471295
],
[
0.660843,
0.80579,
-0.509325
]
],
[
[
-0.125811,
1.151684,
-0.10837
],
[
0.038964,
1.151684,
0.038458
],
[
0.325977,
1.151684,
-0.216334
],
[
0.352124,
1.151684,
-0.159246
],
[
0.375609,
1.151684,
-0.117745
],
[
0.403032,
1.151684,
-0.145536
]
],
[
[
0.161946,
1.542628,
0.17642
],
[
0.266014,
1.542628,
0.269154
],
[
0.447285,
1.542628,
0.108233
],
[
0.463799,
1.542628,
0.144288
],
[
0.478632,
1.542628,
0.170499
],
[
0.495952,
1.542628,
0.152947
]
]
],
"creases": [
{
"ring": 3,
"from": 3,
"to": 4,
"weight": 1.0
},
{
"column": 3,
"from": 3,
"to": 4,
"weight": 1.0
}
],
"rim": 0.5
}
}
]
}

View file

@ -5,13 +5,16 @@ assignMaterial, set_params, report, the refusals, and exportGltf. Not part of th
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash.py -- <out>
Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses
without them). Writes <out>.result.json and exits 1 when a check failed.
without them). Writes <out>.result.json and exits 1 when a check failed. The checks run inside one try: an uncaught error is a failed check that names
the check before it, the checks are printed and the result file written whatever happened, and the exit is 1 with or
without --python-exit-code.
"""
import importlib.util
import json
import math
import os
import sys
import traceback
import tempfile
import types
from pathlib import Path
@ -49,9 +52,17 @@ target.reload_host_actions()
R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1],
"hostRows": [row["name"] for row in target.host_actions()[0]]}
COUNT = [0]
# the rows the add-on's action table names, in its order: what the host must load, whatever rows the table grows
TABLE = [row["name"] for row in json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8"))["actions"]]
# the operators the add-on registered: each is an action the table must have a row for, so a row lost from the table is seen
OPERATORS = sorted(f"brokkr_kitbash.{name}" for name in dir(bpy.ops.brokkr_kitbash))
def check(name, ok, detail=None):
try:
json.dumps(detail, default=str)
except TypeError: # a detail keyed by tuples: the result file takes it as text, so a failed check is written and not a crash
detail = repr(detail)
R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) # what was seen, when it was not what was promised
@ -73,188 +84,191 @@ def extent(obj, axis=2):
return float(co[:, axis].max() - co[:, axis].min())
check("the kitbash rows load as host actions with no errors", not R["hostErrors"]
and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == [f"brokkr_kitbash.{name}" for name in (
"place_part", "set_params", "describe", "report", "attach", "detach", "roll", "aim", "reach", "close", "boolean", "cut", "cut_many", "apply", "ribs")], [R["hostErrors"], R["hostRows"]])
try:
check("the kitbash rows load as host actions with no errors", not R["hostErrors"]
and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == TABLE != [] and sorted(TABLE) == OPERATORS, [R["hostErrors"], R["hostRows"], OPERATORS])
# --- describe ---------------------------------------------------------------------------------------------------------
kit = core.load_kit("mechanical")
receipt, described = send("brokkr_kitbash.describe")
names = [p["name"] for p in described["parts"]] if described else []
check("describe lists eleven parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 11
and "[truncated]" not in receipt["hostResult"], [names, len(receipt.get("hostResult") or "")])
receipt, one = send("brokkr_kitbash.describe", part="actuator")
check("describe of one part gives its params and its sockets at default params", one and [p["name"] for p in one["parts"]] == ["actuator"]
and [p["name"] for p in one["parts"][0]["params"]] == ["body_r", "body_len", "rod_r", "extension", "segments"]
and one["parts"][0]["sockets"] == core.socket_rows(core.build(kit["parts"]["actuator"]).sockets), one)
check("describe changes nothing", len(bpy.data.objects) == 0 and len(bpy.data.meshes) == 0, [len(bpy.data.objects), len(bpy.data.meshes)])
# --- describe ---------------------------------------------------------------------------------------------------------
kit = core.load_kit("mechanical")
receipt, described = send("brokkr_kitbash.describe")
names = [p["name"] for p in described["parts"]] if described else []
check("describe lists eleven parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 11
and "[truncated]" not in receipt["hostResult"], [names, len(receipt.get("hostResult") or "")])
receipt, one = send("brokkr_kitbash.describe", part="actuator")
check("describe of one part gives its params and its sockets at default params", one and [p["name"] for p in one["parts"]] == ["actuator"]
and [p["name"] for p in one["parts"][0]["params"]] == ["body_r", "body_len", "rod_r", "extension", "segments"]
and one["parts"][0]["sockets"] == core.socket_rows(core.build(kit["parts"]["actuator"]).sockets), one)
check("describe changes nothing", len(bpy.data.objects) == 0 and len(bpy.data.meshes) == 0, [len(bpy.data.objects), len(bpy.data.meshes)])
# --- place every part at default -----------------------------------------------------------------------------------------
placed = {}
for index, name in enumerate(names):
receipt, report = send("brokkr_kitbash.place_part", part=name, object_name=f"P_{name}")
obj = bpy.data.objects.get(f"P_{name}")
reference = core.build(kit["parts"][name])
faces = len(obj.data.polygons) if obj else -1
clean = obj is not None and not obj.data.validate(verbose=False)
flat = np.zeros(max(faces, 0), dtype=bool)
if obj:
obj.data.attributes["sharp_face"].data.foreach_get("value", flat)
crease = obj.data.attributes.get("sharp_edge") if obj else None
creased = np.zeros(len(obj.data.edges) if crease else 0, dtype=bool)
if crease:
crease.data.foreach_get("value", creased)
marked = sorted(tuple(sorted(edge.vertices)) for edge, on in zip(obj.data.edges, creased) if on) if crease else None
check(f"place_part {name}: sharp_edge is true on exactly core's sharp edges ({len(reference.sharp)})",
marked == sorted(tuple(sorted(pair)) for pair in reference.sharp.tolist()), [marked and len(marked), len(reference.sharp)])
bevel = obj.modifiers.get("Kit Bevel") if obj else None
evaluated = len(obj.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) if obj else -1
placed[name] = report
check(f"place_part {name}: core's faces, a valid mesh, core's flat faces, at the origin", receipt["status"] == "accepted" and report
and faces == len(reference.counts) == report["faces"] and clean and report["shells"] == reference.shell_count
and flat.tolist() == (~reference.smooth).tolist() and list(obj.location) == [0.0, 0.0, 0.0]
and np.allclose(np.array([v.co[:] for v in obj.data.vertices]), reference.V, atol=1e-6),
[receipt["message"], faces, len(reference.counts), clean])
check(f"place_part {name}: a Bevel of the part's width, 2 segments, angle 30, that evaluates", bevel is not None
and abs(bevel.width - reference.bevel) < 1e-7 and bevel.segments == 2 and bevel.limit_method == "ANGLE"
and abs(bevel.angle_limit - math.radians(30)) < 1e-6 and evaluated > faces, [bevel and bevel.width, reference.bevel, evaluated, faces])
check(f"place_part {name}: kit, part and every resolved param stored on the object, sockets reported in the part frame", obj is not None
and obj["kit_kit"] == "mechanical" and obj["kit_part"] == name and json.loads(obj["kit_params"]) == reference.params == report["params"]
and report["sockets"] == core.socket_rows(reference.sockets), report)
check("eleven parts are eleven mesh objects", len(bpy.data.objects) == 11 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects))
# --- place every part at default -----------------------------------------------------------------------------------------
placed = {}
for index, name in enumerate(names):
receipt, report = send("brokkr_kitbash.place_part", part=name, object_name=f"P_{name}")
obj = bpy.data.objects.get(f"P_{name}")
reference = core.build(kit["parts"][name])
faces = len(obj.data.polygons) if obj else -1
clean = obj is not None and not obj.data.validate(verbose=False)
flat = np.zeros(max(faces, 0), dtype=bool)
if obj:
obj.data.attributes["sharp_face"].data.foreach_get("value", flat)
crease = obj.data.attributes.get("sharp_edge") if obj else None
creased = np.zeros(len(obj.data.edges) if crease else 0, dtype=bool)
if crease:
crease.data.foreach_get("value", creased)
marked = sorted(tuple(sorted(edge.vertices)) for edge, on in zip(obj.data.edges, creased) if on) if crease else None
check(f"place_part {name}: sharp_edge is true on exactly core's sharp edges ({len(reference.sharp)})",
marked == sorted(tuple(sorted(pair)) for pair in reference.sharp.tolist()), [marked and len(marked), len(reference.sharp)])
bevel = obj.modifiers.get("Kit Bevel") if obj else None
evaluated = len(obj.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) if obj else -1
placed[name] = report
check(f"place_part {name}: core's faces, a valid mesh, core's flat faces, at the origin", receipt["status"] == "accepted" and report
and faces == len(reference.counts) == report["faces"] and clean and report["shells"] == reference.shell_count
and flat.tolist() == (~reference.smooth).tolist() and list(obj.location) == [0.0, 0.0, 0.0]
and np.allclose(np.array([v.co[:] for v in obj.data.vertices]), reference.V, atol=1e-6),
[receipt["message"], faces, len(reference.counts), clean])
check(f"place_part {name}: a Bevel of the part's width, 2 segments, angle 30, that evaluates", bevel is not None
and abs(bevel.width - reference.bevel) < 1e-7 and bevel.segments == 2 and bevel.limit_method == "ANGLE"
and abs(bevel.angle_limit - math.radians(30)) < 1e-6 and evaluated > faces, [bevel and bevel.width, reference.bevel, evaluated, faces])
check(f"place_part {name}: kit, part and every resolved param stored on the object, sockets reported in the part frame", obj is not None
and obj["kit_kit"] == "mechanical" and obj["kit_part"] == name and json.loads(obj["kit_params"]) == reference.params == report["params"]
and report["sockets"] == core.socket_rows(reference.sockets), report)
check("eleven parts are eleven mesh objects", len(bpy.data.objects) == 11 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects))
# --- set_params keeps what is not derived --------------------------------------------------------------------------------
reducer = bpy.data.objects["P_reducer"]
send("brokkr_kitbash.set_params", object_name="P_reducer", params="segments=12")
creased = np.zeros(len(reducer.data.edges), dtype=bool)
reducer.data.attributes["sharp_edge"].data.foreach_get("value", creased)
rings = [np.array([reducer.data.vertices[v].co[:] for edge, on in zip(reducer.data.edges, creased) if on for v in edge.vertices])]
check("the reducer's creases are its two cone rings, 24 edges each at 24 segments, and set_params writes them again: 12 each at 12",
len(core.build(kit["parts"]["reducer"]).sharp) == 48 and int(creased.sum()) == 24
and sorted(set(np.round(np.linalg.norm(rings[0][:, :2], axis=1), 5).tolist())) == [0.05, 0.12], int(creased.sum()))
tank = bpy.data.objects["P_tank"]
send("setObjectTransform", targetObjectName="P_tank", location=[1.0, 2.0, 3.0], rotationEuler=[0.3, -0.2, 0.5], scale=[1.0, 1.0, 1.0])
send("assignMaterial", targetObjectName="P_tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35])
send("setObjectParent", targetObjectName="P_tank", parentObjectName="P_plate")
before = {"z": extent(tank), "mesh": tank.data.name, "basis": [list(r) for r in tank.matrix_basis], "parent": tank.parent and tank.parent.name,
"materials": [s.material and s.material.name for s in tank.material_slots], "modifiers": [m.name for m in tank.modifiers],
"faces": len(tank.data.polygons)}
receipt, grown = send("brokkr_kitbash.set_params", object_name="P_tank", params="length=1.8")
after = {"z": extent(tank), "mesh": tank.data.name, "basis": [list(r) for r in tank.matrix_basis], "parent": tank.parent and tank.parent.name,
"materials": [s.material and s.material.name for s in tank.material_slots], "modifiers": [m.name for m in tank.modifiers],
"faces": len(tank.data.polygons)}
check("set_params doubling the tank's length doubles its z extent", receipt["status"] == "accepted" and abs(before["z"] - 0.9) < 1e-6
and abs(after["z"] - 1.8) < 1e-6, [before["z"], after["z"]])
check("set_params keeps the mesh datablock, transform, parent, Bevel and the assigned material", before["parent"] == "P_plate"
and before["materials"] == ["Tank Paint"] and before["modifiers"] == ["Kit Bevel"]
and {k: v for k, v in after.items() if k != "z"} == {k: v for k, v in before.items() if k != "z"} and not tank.data.validate(verbose=False), [before, after])
check("set_params stores the merged params and reports them", grown and json.loads(tank["kit_params"]) == grown["params"]
== {"radius": 0.22, "length": 1.8, "segments": 24}, grown)
receipt, wide = send("brokkr_kitbash.set_params", object_name="P_tank", params="radius=0.3; segments=12")
check("set_params overlays the stored params, and the Bevel width follows the part's bevel", wide and wide["params"] == {"radius": 0.3, "length": 1.8, "segments": 12}
and abs(tank.modifiers["Kit Bevel"].width - 0.008 * 0.3) < 1e-7 and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], wide["params"]).counts),
[wide and wide["params"], tank.modifiers["Kit Bevel"].width])
# --- set_params keeps what is not derived --------------------------------------------------------------------------------
reducer = bpy.data.objects["P_reducer"]
send("brokkr_kitbash.set_params", object_name="P_reducer", params="segments=12")
creased = np.zeros(len(reducer.data.edges), dtype=bool)
reducer.data.attributes["sharp_edge"].data.foreach_get("value", creased)
rings = [np.array([reducer.data.vertices[v].co[:] for edge, on in zip(reducer.data.edges, creased) if on for v in edge.vertices])]
check("the reducer's creases are its two cone rings, 24 edges each at 24 segments, and set_params writes them again: 12 each at 12",
len(core.build(kit["parts"]["reducer"]).sharp) == 48 and int(creased.sum()) == 24
and sorted(set(np.round(np.linalg.norm(rings[0][:, :2], axis=1), 5).tolist())) == [0.05, 0.12], int(creased.sum()))
tank = bpy.data.objects["P_tank"]
send("setObjectTransform", targetObjectName="P_tank", location=[1.0, 2.0, 3.0], rotationEuler=[0.3, -0.2, 0.5], scale=[1.0, 1.0, 1.0])
send("assignMaterial", targetObjectName="P_tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35])
send("setObjectParent", targetObjectName="P_tank", parentObjectName="P_plate")
before = {"z": extent(tank), "mesh": tank.data.name, "basis": [list(r) for r in tank.matrix_basis], "parent": tank.parent and tank.parent.name,
"materials": [s.material and s.material.name for s in tank.material_slots], "modifiers": [m.name for m in tank.modifiers],
"faces": len(tank.data.polygons)}
receipt, grown = send("brokkr_kitbash.set_params", object_name="P_tank", params="length=1.8")
after = {"z": extent(tank), "mesh": tank.data.name, "basis": [list(r) for r in tank.matrix_basis], "parent": tank.parent and tank.parent.name,
"materials": [s.material and s.material.name for s in tank.material_slots], "modifiers": [m.name for m in tank.modifiers],
"faces": len(tank.data.polygons)}
check("set_params doubling the tank's length doubles its z extent", receipt["status"] == "accepted" and abs(before["z"] - 0.9) < 1e-6
and abs(after["z"] - 1.8) < 1e-6, [before["z"], after["z"]])
check("set_params keeps the mesh datablock, transform, parent, Bevel and the assigned material", before["parent"] == "P_plate"
and before["materials"] == ["Tank Paint"] and before["modifiers"] == ["Kit Bevel"]
and {k: v for k, v in after.items() if k != "z"} == {k: v for k, v in before.items() if k != "z"} and not tank.data.validate(verbose=False), [before, after])
check("set_params stores the merged params and reports them", grown and json.loads(tank["kit_params"]) == grown["params"]
== {"radius": 0.22, "length": 1.8, "segments": 24}, grown)
receipt, wide = send("brokkr_kitbash.set_params", object_name="P_tank", params="radius=0.3; segments=12")
check("set_params overlays the stored params, and the Bevel width follows the part's bevel", wide and wide["params"] == {"radius": 0.3, "length": 1.8, "segments": 12}
and abs(tank.modifiers["Kit Bevel"].width - 0.008 * 0.3) < 1e-7 and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], wide["params"]).counts),
[wide and wide["params"], tank.modifiers["Kit Bevel"].width])
# --- report: sockets in the world -------------------------------------------------------------------------------------------
send("setObjectTransform", targetObjectName="P_pipe_fitting", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7])
receipt, reported = send("brokkr_kitbash.report") # straight after the move, before anything here updates the view layer: the frames are already the moved ones
bpy.context.view_layer.update()
worst, listed = 0.0, []
for entry in (reported or {}).get("parts", []):
obj = bpy.data.objects[entry["object"]]
listed.append(entry["object"])
local = core.build(core.part(kit, entry["part"]), entry["params"]).sockets
world = np.array(obj.matrix_world)
for socket, mine in zip(entry["sockets"], local):
worst = max(worst, float(np.abs(np.array(socket["matrix"]) - world @ mine["matrix"]).max()))
check("report lists every kit part with socket frames equal to matrix_world times the local frame", receipt["status"] == "accepted"
and listed == sorted(f"P_{n}" for n in names) and worst < 1e-6, [listed, worst])
receipt, single = send("brokkr_kitbash.report", object_name="P_tank")
tank_world = np.array(tank.matrix_world)
check("report of the parented, rotated tank carries its parent's and its own transform", single and len(single["parts"]) == 1
and single["parts"][0]["params"] == wide["params"] and single["parts"][0]["faces"] == len(tank.data.polygons)
and np.abs(np.array(single["parts"][0]["sockets"][2]["matrix"]) - tank_world @ core.build(kit["parts"]["tank"], wide["params"]).sockets[2]["matrix"]).max() < 1e-6
and np.abs(tank_world[:3, 3] - [1.0, 2.0, 3.0]).max() < 1e-6, single)
# --- report: sockets in the world -------------------------------------------------------------------------------------------
send("setObjectTransform", targetObjectName="P_pipe_fitting", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7])
receipt, reported = send("brokkr_kitbash.report") # straight after the move, before anything here updates the view layer: the frames are already the moved ones
bpy.context.view_layer.update()
worst, listed = 0.0, []
for entry in (reported or {}).get("parts", []):
obj = bpy.data.objects[entry["object"]]
listed.append(entry["object"])
local = core.build(core.part(kit, entry["part"]), entry["params"]).sockets
world = np.array(obj.matrix_world)
for socket, mine in zip(entry["sockets"], local):
worst = max(worst, float(np.abs(np.array(socket["matrix"]) - world @ mine["matrix"]).max()))
check("report lists every kit part with socket frames equal to matrix_world times the local frame", receipt["status"] == "accepted"
and listed == sorted(f"P_{n}" for n in names) and worst < 1e-6, [listed, worst])
receipt, single = send("brokkr_kitbash.report", object_name="P_tank")
tank_world = np.array(tank.matrix_world)
check("report of the parented, rotated tank carries its parent's and its own transform", single and len(single["parts"]) == 1
and single["parts"][0]["params"] == wide["params"] and single["parts"][0]["faces"] == len(tank.data.polygons)
and np.abs(np.array(single["parts"][0]["sockets"][2]["matrix"]) - tank_world @ core.build(kit["parts"]["tank"], wide["params"]).sockets[2]["matrix"]).max() < 1e-6
and np.abs(tank_world[:3, 3] - [1.0, 2.0, 3.0]).max() < 1e-6, single)
# --- per-face materials ride on the part's shapes ----------------------------------------------------------------------------
strut = bpy.data.objects["P_strut"]
send("assignMaterial", targetObjectName="P_strut", materialName="Strut Paint", color=[0.35, 0.35, 0.35])
strut.data.materials.append(bpy.data.materials.new("Pin Steel"))
PINS = 2 # the strut's third shape: the repeat of two pins
was = core.build(kit["parts"]["strut"])
strut.data.polygons.foreach_set("material_index", np.where(was.shape == PINS, 1, 0).astype(np.int32))
receipt, _ = send("brokkr_kitbash.set_params", object_name="P_strut", params="segments=12; length=1.2")
now = core.build(kit["parts"]["strut"], {"segments": 12, "length": 1.2})
index = np.zeros(len(strut.data.polygons), dtype=np.int32)
strut.data.polygons.foreach_get("material_index", index)
check("set_params with other segments keeps each shape's material: the pins stay Pin Steel, the rest Strut Paint", receipt["status"] == "accepted"
and len(now.counts) != len(was.counts) and index.tolist() == np.where(now.shape == PINS, 1, 0).tolist() and int(index.sum()) == 2 * (12 + 2)
and [s.material.name for s in strut.material_slots] == ["Strut Paint", "Pin Steel"], [receipt["message"], int(index.sum()), len(index)])
# --- per-face materials ride on the part's shapes ----------------------------------------------------------------------------
strut = bpy.data.objects["P_strut"]
send("assignMaterial", targetObjectName="P_strut", materialName="Strut Paint", color=[0.35, 0.35, 0.35])
strut.data.materials.append(bpy.data.materials.new("Pin Steel"))
PINS = 2 # the strut's third shape: the repeat of two pins
was = core.build(kit["parts"]["strut"])
strut.data.polygons.foreach_set("material_index", np.where(was.shape == PINS, 1, 0).astype(np.int32))
receipt, _ = send("brokkr_kitbash.set_params", object_name="P_strut", params="segments=12; length=1.2")
now = core.build(kit["parts"]["strut"], {"segments": 12, "length": 1.2})
index = np.zeros(len(strut.data.polygons), dtype=np.int32)
strut.data.polygons.foreach_get("material_index", index)
check("set_params with other segments keeps each shape's material: the pins stay Pin Steel, the rest Strut Paint", receipt["status"] == "accepted"
and len(now.counts) != len(was.counts) and index.tolist() == np.where(now.shape == PINS, 1, 0).tolist() and int(index.sum()) == 2 * (12 + 2)
and [s.material.name for s in strut.material_slots] == ["Strut Paint", "Pin Steel"], [receipt["message"], int(index.sum()), len(index)])
# --- refusals leave the scene as it was --------------------------------------------------------------------------------------
bpy.ops.mesh.primitive_cube_add()
bpy.context.active_object.name = "Plain"
twin = bpy.data.objects["P_vent"].copy() # a linked duplicate: one mesh, two objects, each with its own kit_params
twin.name = "P_vent_twin"
bpy.context.scene.collection.objects.link(twin)
send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[2.0, 2.0, 2.0])
send("setObjectTransform", targetObjectName="P_actuator", scale=[-1.0, 1.0, 1.0])
# --- refusals leave the scene as it was --------------------------------------------------------------------------------------
bpy.ops.mesh.primitive_cube_add()
bpy.context.active_object.name = "Plain"
twin = bpy.data.objects["P_vent"].copy() # a linked duplicate: one mesh, two objects, each with its own kit_params
twin.name = "P_vent_twin"
bpy.context.scene.collection.objects.link(twin)
send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[2.0, 2.0, 2.0])
send("setObjectTransform", targetObjectName="P_actuator", scale=[-1.0, 1.0, 1.0])
def scene_state():
return (sorted(o.name for o in bpy.data.objects), sorted(m.name for m in bpy.data.meshes),
{o.name: (len(o.data.polygons), o.get("kit_params")) for o in bpy.data.objects})
def scene_state():
return (sorted(o.name for o in bpy.data.objects), sorted(m.name for m in bpy.data.meshes),
{o.name: (len(o.data.polygons), o.get("kit_params")) for o in bpy.data.objects})
state = scene_state()
refusals = [
("an unknown kit", "brokkr_kitbash.place_part", {"kit": "hydraulic", "part": "tank", "object_name": "X"}, "no kit named 'hydraulic'"),
("a kit name that spells a path", "brokkr_kitbash.place_part", {"kit": "../x", "part": "tank", "object_name": "X"}, "kit"),
("a kit name with a dot", "brokkr_kitbash.place_part", {"kit": "mechanical.v0", "part": "tank", "object_name": "X"}, "must be 1 to 32 of"),
("an unknown part", "brokkr_kitbash.place_part", {"part": "wing", "object_name": "X"}, "has no part 'wing'"),
("an out-of-range param", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "X", "params": "radius=5"}, "param 'radius' = 5.0 is outside [0.12, 0.35]"),
("a fraction for an integer param", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "X", "params": "segments=12.5"}, "is an integer"),
("an existing name", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "P_plate"}, "An object named 'P_plate' exists"),
("set_params on a plain mesh", "brokkr_kitbash.set_params", {"object_name": "Plain", "params": "length=1"}, "is not a kit part"),
("set_params with an unknown param", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "girth=1"}, "has no param 'girth'"),
("set_params out of range", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=0.1"}, "is outside [0.6, 2.0]"),
("set_params with a repeated key", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=1; length=1.2"}, "'length' is given twice"),
("report of a plain mesh", "brokkr_kitbash.report", {"object_name": "Plain"}, "is not a kit part"),
("set_params on a mesh a linked duplicate shares", "brokkr_kitbash.set_params", {"object_name": "P_vent", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"),
("set_params on the linked duplicate", "brokkr_kitbash.set_params", {"object_name": "P_vent_twin", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"),
("report of a scaled part", "brokkr_kitbash.report", {"object_name": "P_radiator_stack"}, "'P_radiator_stack' is scaled, mirrored or sheared in the world (scale 2, 2, 2)"),
("set_params on a scaled part", "brokkr_kitbash.set_params", {"object_name": "P_radiator_stack", "params": "fins=5"}, "is scaled, mirrored or sheared"),
("report of a mirrored part", "brokkr_kitbash.report", {"object_name": "P_actuator"}, "'P_actuator' is scaled, mirrored or sheared"),
("report of every part while one is scaled", "brokkr_kitbash.report", {}, "is scaled, mirrored or sheared"),
("describe of an unknown part", "brokkr_kitbash.describe", {"part": "wing"}, "has no part 'wing'"),
]
for label, action, fields, expected in refusals:
receipt, _ = send(action, **fields)
check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state,
[receipt["status"], receipt["message"]])
state = scene_state()
refusals = [
("an unknown kit", "brokkr_kitbash.place_part", {"kit": "hydraulic", "part": "tank", "object_name": "X"}, "no kit named 'hydraulic'"),
("a kit name that spells a path", "brokkr_kitbash.place_part", {"kit": "../x", "part": "tank", "object_name": "X"}, "kit"),
("a kit name with a dot", "brokkr_kitbash.place_part", {"kit": "mechanical.v0", "part": "tank", "object_name": "X"}, "must be 1 to 32 of"),
("an unknown part", "brokkr_kitbash.place_part", {"part": "wing", "object_name": "X"}, "has no part 'wing'"),
("an out-of-range param", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "X", "params": "radius=5"}, "param 'radius' = 5.0 is outside [0.12, 0.35]"),
("a fraction for an integer param", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "X", "params": "segments=12.5"}, "is an integer"),
("an existing name", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "P_plate"}, "An object named 'P_plate' exists"),
("set_params on a plain mesh", "brokkr_kitbash.set_params", {"object_name": "Plain", "params": "length=1"}, "is not a kit part"),
("set_params with an unknown param", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "girth=1"}, "has no param 'girth'"),
("set_params out of range", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=0.1"}, "is outside [0.6, 2.0]"),
("set_params with a repeated key", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=1; length=1.2"}, "'length' is given twice"),
("report of a plain mesh", "brokkr_kitbash.report", {"object_name": "Plain"}, "is not a kit part"),
("set_params on a mesh a linked duplicate shares", "brokkr_kitbash.set_params", {"object_name": "P_vent", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"),
("set_params on the linked duplicate", "brokkr_kitbash.set_params", {"object_name": "P_vent_twin", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"),
("report of a scaled part", "brokkr_kitbash.report", {"object_name": "P_radiator_stack"}, "'P_radiator_stack' is scaled, mirrored or sheared in the world (scale 2, 2, 2)"),
("set_params on a scaled part", "brokkr_kitbash.set_params", {"object_name": "P_radiator_stack", "params": "fins=5"}, "is scaled, mirrored or sheared"),
("report of a mirrored part", "brokkr_kitbash.report", {"object_name": "P_actuator"}, "'P_actuator' is scaled, mirrored or sheared"),
("report of every part while one is scaled", "brokkr_kitbash.report", {}, "is scaled, mirrored or sheared"),
("describe of an unknown part", "brokkr_kitbash.describe", {"part": "wing"}, "has no part 'wing'"),
]
for label, action, fields, expected in refusals:
receipt, _ = send(action, **fields)
check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state,
[receipt["status"], receipt["message"]])
bpy.data.objects.remove(twin)
send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[1.0, 1.0, 1.0])
send("setObjectTransform", targetObjectName="P_actuator", scale=[1.0, 1.0, 1.0])
receipt, alone = send("brokkr_kitbash.set_params", object_name="P_vent", params="slats=9")
check("with the duplicate gone the vent's mesh is its own again and set_params rebuilds it", receipt["status"] == "accepted" and alone
and alone["params"]["slats"] == 9 and len(bpy.data.objects["P_vent"].data.polygons) == len(core.build(kit["parts"]["vent"], {"slats": 9}).counts), receipt["message"])
receipt, whole = send("brokkr_kitbash.report")
check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 11, receipt["message"])
bpy.data.objects.remove(twin)
send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[1.0, 1.0, 1.0])
send("setObjectTransform", targetObjectName="P_actuator", scale=[1.0, 1.0, 1.0])
receipt, alone = send("brokkr_kitbash.set_params", object_name="P_vent", params="slats=9")
check("with the duplicate gone the vent's mesh is its own again and set_params rebuilds it", receipt["status"] == "accepted" and alone
and alone["params"]["slats"] == 9 and len(bpy.data.objects["P_vent"].data.polygons) == len(core.build(kit["parts"]["vent"], {"slats": 9}).counts), receipt["message"])
receipt, whole = send("brokkr_kitbash.report")
check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 11, receipt["message"])
# --- export ---------------------------------------------------------------------------------------------------------------
receipt, _ = send("exportGltf", filepath="kit.glb", extras=False, yUp=True, applyModifiers=True, selection=[f"P_{n}" for n in names])
glb = WORK / "kit.glb"
meshes = -1
if glb.is_file():
blob = glb.read_bytes()
meshes = len(json.loads(blob[20:20 + int.from_bytes(blob[12:16], "little")]).get("meshes", []))
check("exportGltf of all eleven parts succeeds", receipt["status"] == "accepted" and meshes == 11, [receipt["message"], meshes])
# --- export ---------------------------------------------------------------------------------------------------------------
receipt, _ = send("exportGltf", filepath="kit.glb", extras=False, yUp=True, applyModifiers=True, selection=[f"P_{n}" for n in names])
glb = WORK / "kit.glb"
meshes = -1
if glb.is_file():
blob = glb.read_bytes()
meshes = len(json.loads(blob[20:20 + int.from_bytes(blob[12:16], "little")]).get("meshes", []))
check("exportGltf of all eleven parts succeeds", receipt["status"] == "accepted" and meshes == 11, [receipt["message"], meshes])
R["placed"] = {name: {"faces": report["faces"], "shells": report["shells"], "bevel": report["bevel"], "sockets": [s["name"] for s in report["sockets"]]}
for name, report in placed.items() if report}
except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file
check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:])
R["placed"] = {name: {"faces": report["faces"], "shells": report["shells"], "bevel": report["bevel"], "sockets": [s["name"] for s in report["sockets"]]}
for name, report in placed.items() if report}
R["ok"] = all(c["ok"] for c in R["checks"])
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
for c in R["checks"]:
print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True)
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
sys.exit(0 if R["ok"] else 1)

View file

@ -420,7 +420,8 @@
"brokkr_kitbash.cut",
"brokkr_kitbash.cut_many",
"brokkr_kitbash.apply",
"brokkr_kitbash.ribs"
"brokkr_kitbash.ribs",
"brokkr_kitbash.shell"
],
"placed": {
"nozzle": {

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,452 @@
"""Live proof, in a background Blender, of brokkr_kitbash.shell through run_intent: a loft of rings becomes a cage whose
crease runs stay crisp under subdivision while the rest stays smooth, a wall of even thickness with a filled rim, a
mirror, a rebuild in place under cutters and ribs, cut_many and ribs on the shell, and the refusals. Not part of the
unittest run: it needs Blender.
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_faceted.py -- <out>
Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses
without them). <out> is an absolute path; writes <out>.result.json and exits 1 when a check failed.
Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the geometric mean of the shipped worst reading
and the least claimed mutant's, both written beside it; the result file carries the readings. Costs are wall times
of this run, reported and never bounded. The checks run inside one try: an uncaught error is a failed check that
names its section, and the result file is always written.
"""
import importlib.util
import json
import math
import os
import statistics
import sys
import tempfile
import time
import traceback
import types
from pathlib import Path
import bmesh
import bpy
import numpy as np
from mathutils import Matrix, Vector
from mathutils.bvhtree import BVHTree
from mathutils.geometry import normal as triangle_normal
SURFACE = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(SURFACE / "tools"))
import private_dirs # noqa: E402
_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
if _refused:
raise SystemExit(_refused)
OUT = sys.argv[sys.argv.index("--") + 1]
if not Path(OUT).is_absolute():
raise SystemExit(f"{OUT!r} is not an absolute path")
package = types.ModuleType("brokkr_bridge")
package.__path__ = [str(SURFACE / "brokkr_bridge")]
sys.modules["brokkr_bridge"] = package
from brokkr_bridge import blender_target as bt # noqa: E402
import addon_utils # noqa: E402
spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_reference", SURFACE / "brokkr_kitbash" / "core.py")
core = importlib.util.module_from_spec(spec) # core as the unit tests load it
spec.loader.exec_module(core)
sys.path.append(str(SURFACE))
bpy.ops.wm.read_factory_settings(use_empty=True)
for module in ("brokkr_mesh_polish", "brokkr_kitbash"):
addon_utils.enable(module, default_set=True)
target = bt.BrokkrBlenderTarget(bpy)
WORK = Path(tempfile.mkdtemp(prefix="brokkr-kitbash-faceted-"))
target.configure_action_dirs("", str(WORK))
target.reload_host_actions()
R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}, "costs": {}}
COUNT, SECTION = [0], ["setup"]
WALL = 0.06
# Degrees: the largest dihedral angle anywhere inside the subdivided pauldron (not on its rim), which is on its creased
# column. Shipped 52; least claimed mutant 6.5 (S1, crease_edge not written: the cage subdivides smooth); the geometric
# mean, separation 2.8 each side.
CRISP = 18.0
# Degrees: the largest dihedral angle across a subdivided edge that carries no crease. Shipped 5.8; least claimed
# mutant 25 (W1, the weights written at the creases' own indices, not at the edges found by vertex pair: a crease
# lands on an edge that should have none); the geometric mean, separation 2.07 each side. C1 (a Subdivision that only
# splits, SIMPLE: every cage edge stays an edge) reads 51 here. S1 reads 6.5, 1.13 of shipped: CRISP claims it. W1 is
# also caught by the exact check below, crease_edge edge for edge.
SOFT = 12.0
# Metres from a corner of a sheet whose rim is 0 to the nearest vertex of its subdivided surface: with corners preserved
# the surface keeps the cage's corner. Shipped 0 (read as 1e-7, what a float32 mesh is good to); least claimed mutant
# 0.15 (S5, boundary_smooth ALL: the corner rounds off); the geometric mean, separation 900 each side.
CORNER = 1.6e-4
# The wall's volume over the designed surface's area times the thickness, less 1, as a magnitude. Shipped 0.027 (a wall
# grown inward loses volume inside the crown's curve); least claimed mutant 0.036 (S6, the Solidify above the
# Subdivision: the wall's own edges are rounded off); the geometric mean, a total separation of 1.34.
SOLID = 0.0313
# Metres between the thickness and the distance from a vertex of the wall's inner face to the designed surface. Shipped
# 0.0001 (a float32 mesh under three levels of subdivision); least claimed mutant 0.024 (S6: the inner face is subdivided again and pulls in); the geometric mean, separation 15 each side.
EVEN = 1.5e-3
# Metres: the thickness at which the wedge of shell-fold folds, (W / 2^levels) / tan(phi) of its narrower facet, as
# measured on flat facets (docs/kitbash.md, Thickness at a crease). The wall is built at FOLD / FOLD_STEP (no inner
# face folded) and at FOLD x FOLD_STEP (some folded); FOLD_STEP is the 1.2 separation the margin rule asks on each
# side of the onset. The counts themselves are exact: count_folds is held to this script's own count, face for face.
FOLD, FOLD_STEP = 0.075, 1.2
def check(name, ok, detail=None):
try:
json.dumps(detail, default=str)
except TypeError: # a detail keyed by vertex pairs: the result file takes it as text, so a failed check is written and not a crash
detail = repr(detail)
R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail})
def reading(name, value, least=False):
"""The worst of a metric: the largest, or with `least` the smallest."""
R["readings"][name] = (min if least else max)(R["readings"].get(name, float(value)), float(value))
return float(value)
def section(name):
SECTION[0] = name
def send(action, **fields):
COUNT[0] += 1
receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "nibu/hands", "action": action, **fields})
result = None
if receipt.get("hostResult"):
try:
result = json.loads(receipt["hostResult"])
except ValueError:
result = None
print("SEND", action, receipt["status"], str(receipt["message"])[:300], flush=True)
return receipt, result
def scene_state():
return {o.name: (o.parent and o.parent.name, np.round(np.array(o.matrix_basis), 6).tolist(), {k: repr(o[k]) for k in sorted(o.keys()) if k.startswith("kit_")},
[(m.name, m.type, m.show_viewport) for m in o.modifiers], o.data.name if o.type == "MESH" else None, len(o.data.polygons) if o.type == "MESH" else None,
np.round(points(o), 6).tolist() if o.type == "MESH" else None)
for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes), sorted(c.name for c in bpy.data.collections)
def refused(label, fields, expected):
state = scene_state()
receipt, _ = send("brokkr_kitbash.shell", **fields)
check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state,
[receipt["status"], receipt["message"]])
def points(obj):
V = np.zeros(3 * len(obj.data.vertices))
obj.data.vertices.foreach_get("co", V)
return V.reshape(-1, 3)
def evaluated(obj, off=()):
"""This script's own copy of an object evaluated with the modifiers of the named types off, as a bmesh in its frame."""
hidden = [m for m in obj.modifiers if m.type in off and m.show_viewport]
for m in hidden:
m.show_viewport = False
try:
bpy.context.view_layer.update()
owner = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
bm = bmesh.new()
bm.from_mesh(owner.to_mesh())
owner.to_mesh_clear()
finally:
for m in hidden:
m.show_viewport = True
bpy.context.view_layer.update()
bm.normal_update()
return bm
def dihedrals(bm):
"""(degrees, crease weight, convex) of every edge between two faces."""
layer = bm.edges.layers.float.get("crease_edge")
rows = []
for e in bm.edges:
if len(e.link_faces) == 2:
a, b = e.link_faces
rows.append((math.degrees(a.normal.angle(b.normal, 0.0)), e[layer] if layer else 0.0, (b.calc_center_median() - a.calc_center_median()).dot(a.normal) < 0))
return rows
def crease_weights(obj) -> dict:
"""{(low vertex, high vertex): weight} of the cage's crease_edge attribute, weights over 0 only."""
attribute = obj.data.attributes.get("crease_edge")
if attribute is None:
return {}
return {tuple(sorted(e.vertices)): round(attribute.data[e.index].value, 6) for e in obj.data.edges if attribute.data[e.index].value > 0}
def stack(obj):
return [m.name for m in obj.modifiers]
def ring(y, s, dip=0.0):
"""One ring of the pauldron: over the crown from inboard (+x) to outboard and down the outer face, at y."""
return [[x * s, y, z * s] for x, z in ((0.55, 1.2), (-0.2, 1.5), (-0.9, 1.35 - dip), (-1.35, 1.0), (-1.55, 0.3), (-1.65, -0.35))]
# A pauldron-like sheet, the one the cut's probes measured: 6 rings of 6 points running aft to fore, a concave dip in ring
# 2, the shoulder line (column 3) creased. Its rings run toward +y and its points toward -x, so by the winding rule the
# crown would face down: flip turns it up.
RINGS = [ring(-1.35, 0.85), ring(-0.8, 0.97), ring(-0.2, 1.0, dip=0.25), ring(0.4, 1.0), ring(0.9, 0.95), ring(1.2, 0.8)]
PAULDRON = {"rings": RINGS, "flip": True, "creases": [{"column": 3, "from": 0, "to": 5, "weight": 1.0}]}
CUTS = [{"name": f"Line{k}", "part": "slab", "params": "gap=0.02; length=0.8; depth=0.025", "origin": [x, y, 3.0], "direction": [0, 0, -1], **({"roll": 90} if k % 2 else {})}
for k, (x, y) in enumerate(((-0.3, -0.5), (-0.3, 0.1), (-0.6, 0.6), (0.1, 0.7)))] + [
{"name": f"Inset{k}", "part": "box", "params": "width=0.25; height=0.2; depth=0.03", "origin": [-3.0, y, 0.5], "direction": [1, 0, 0]} for k, y in enumerate((-0.5, 0.5))]
PLANES = json.dumps([{"origin": [0.0, y, 0.0], "normal": [0.0, 1.0, 0.0]} for y in (-0.6, 0.0, 0.6)])
try:
# --- shell-crisp ------------------------------------------------------------------------------------------------------------
section("shell-crisp")
request = {"object_name": "Pauldron", "sheet": json.dumps(PAULDRON), "thickness": WALL, "bevel": 0.004}
receipt, report = send("brokkr_kitbash.shell", **request)
pauldron = bpy.data.objects.get("Pauldron")
stored = json.loads(pauldron["kit_shell"]) if pauldron is not None and "kit_shell" in pauldron else {}
built = core.sheet(PAULDRON)
check("shell makes one mesh object in the scene: the cage as core.sheet builds it, vertex for vertex, and kit_shell the request",
receipt["status"] == "accepted" and pauldron is not None and pauldron.users_collection == (bpy.context.scene.collection,) and pauldron.parent is None
and np.abs(points(pauldron) - built.V).max() < 1e-6 and [tuple(p.vertices) for p in pauldron.data.polygons] == [tuple(q) for q in built.faces.reshape(-1, 4).tolist()]
and sorted(stored) == ["bevel", "levels", "offset", "sheet", "thickness"] and stored["sheet"] == PAULDRON
and (stored["levels"], stored["offset"]) == (3, -1.0) and abs(stored["thickness"] - WALL) < 1e-7, [receipt["message"], stored])
check("shell reports cage facts: rings, points, quads, creased edges, the subdivided count, an upward facing, no children",
report and sorted(report) == ["cageFaces", "children", "corners", "creases", "facing", "folded", "levels", "object", "offset", "points", "rebuilt", "rings", "subdividedFaces", "thickness"]
and (report["object"], report["rebuilt"], report["rings"], report["points"], report["cageFaces"], report["creases"], report["corners"], report["subdividedFaces"], report["levels"],
report["thickness"], report["offset"], report["children"]) == ("Pauldron", False, 6, 6, 25, 25, 0, 1600, 3, 0.06, -1.0, [])
and report["facing"][2] > 0.5 and abs(np.linalg.norm(report["facing"]) - 1.0) < 1e-5, report)
smooth, wall = pauldron.modifiers.get("Kit Subsurf"), pauldron.modifiers.get("Kit Solidify")
check("the stack is Kit Subsurf, Kit Solidify, Kit Bevel: creases used, corners preserved, an even wall inward with its rim filled",
stack(pauldron) == ["Kit Subsurf", "Kit Solidify", "Kit Bevel"] and (smooth.levels, smooth.render_levels, smooth.use_creases, smooth.boundary_smooth) == (3, 3, True, "PRESERVE_CORNERS")
and (wall.use_even_offset, wall.use_rim, wall.offset) == (True, True, -1.0) and abs(wall.thickness - WALL) < 1e-7 and abs(pauldron.modifiers["Kit Bevel"].width - 0.004) < 1e-7,
stack(pauldron))
# W1 dies here: the mesh's edges are not in the order core.sheet lists its creases, so the weights must be looked up by pair
expected = {tuple(pair): round(weight, 6) for pair, weight in zip(built.creases.tolist(), built.weights.tolist())}
check("crease_edge on the cage is the sheet's creases, edge for edge, and crease_vert is all zero", crease_weights(pauldron) == expected and len(expected) == 25
and pauldron.data.attributes.get("crease_vert") is not None and max(d.value for d in pauldron.data.attributes["crease_vert"].data) == 0.0, crease_weights(pauldron))
designed = evaluated(pauldron, ("SOLIDIFY", "BEVEL", "BOOLEAN"))
rows = dihedrals(designed)
reading("crisp", max(angle for angle, _, _ in rows), least=True)
reading("soft", max([angle for angle, weight, _ in rows if weight == 0.0] or [180.0]))
concave = sum(1 for angle, _, convex in rows if not convex and angle > 1.0)
check("shell-crisp: the creased column stays a facet edge under three levels of subdivision, every other edge inside the plate stays smooth, and the dip is concave",
R["readings"]["crisp"] > CRISP and R["readings"]["soft"] < SOFT and len(designed.faces) == report["subdividedFaces"] and concave > 20,
[R["readings"], len(designed.faces), concave])
# a semi-sharp ring, a vertex crease and a soft rim, written edge for edge
MIXED = {"rings": RINGS, "flip": True, "rim": 0.0, "creases": [{"ring": 2, "from": 1, "to": 4, "weight": 0.6}, {"column": 3, "from": 0, "to": 5, "weight": 1.0},
{"point": [4, 1], "weight": 0.8}]}
receipt, report = send("brokkr_kitbash.shell", object_name="Mixed", sheet=json.dumps(MIXED), thickness=WALL, levels=2)
mixed, built = bpy.data.objects.get("Mixed"), core.sheet(MIXED)
expected = {tuple(pair): round(weight, 6) for pair, weight in zip(built.creases.tolist(), built.weights.tolist())}
corner = [round(d.value, 6) for d in mixed.data.attributes["crease_vert"].data] if mixed is not None else []
check("a semi-sharp ring run, a column run and a point land on their own edges and vertex; with rim 0 the boundary carries no crease",
receipt["status"] == "accepted" and crease_weights(mixed) == expected and sorted(set(expected.values())) == [0.6, 1.0] and len(expected) == 8
and corner == [0.8 if k == 4 * 6 + 1 else 0.0 for k in range(36)] and (report["creases"], report["corners"], report["subdividedFaces"]) == (8, 1, 400) and "Kit Bevel" not in stack(mixed),
[receipt["message"], crease_weights(mixed)])
surface = evaluated(mixed, ("SOLIDIFY",))
for corner_at in (RINGS[0][0], RINGS[0][-1], RINGS[-1][0], RINGS[-1][-1]):
reading("corner", max(1e-7, min((v.co - Vector(corner_at)).length for v in surface.verts)))
surface.free()
check("shell-crisp: a sheet whose rim is soft keeps its four corners", R["readings"]["corner"] < CORNER, R["readings"])
# --- shell-fold: count_folds, against this script's own count on the evaluated wall -------------------------------------------
section("shell-fold")
# a ridge of two flat facets 0.3 and 1.0 wide, each tilted 45 degrees, full crease, levels 2: the narrower facet binds, (0.3 / 4) / tan 45 = 0.075
wedge = {"rings": [[[-1.0 * math.sqrt(0.5), y, -1.0 * math.sqrt(0.5)], [0.0, y, 0.0], [0.3 * math.sqrt(0.5), y, -0.3 * math.sqrt(0.5)]] for y in (0.0, 0.5, 1.0)],
"creases": [{"column": 1, "from": 0, "to": 2, "weight": 1.0}]}
def own_folds(obj):
"""This script's count on its own evaluation: inner faces of the wall (Subsurf and Solidify alone) with a corner
whose triangle, the corner and its two neighbours, faces with their outer twin's normal (mathutils' normals)."""
wall_mesh = evaluated(obj, off=("BOOLEAN", "BEVEL"))
wall_mesh.faces.ensure_lookup_table()
count = len(obj.data.polygons) * 4 ** obj.modifiers["Kit Subsurf"].levels # Solidify lists the outer faces, then their inner twins in the same order, then the rim
found = 0
for k in range(count):
at = [v.co for v in wall_mesh.faces[count + k].verts]
found += any(triangle_normal(at[i - 1], at[i], at[(i + 1) % len(at)]).dot(wall_mesh.faces[k].normal) > 0 for i in range(len(at)))
wall_mesh.free()
return found
def folded(name, sheet, thickness, offset=-1.0, levels=2, **asked):
"""[the report's folded (-1: no report), this script's own count]."""
_, told = send("brokkr_kitbash.shell", object_name=name, sheet=json.dumps(sheet), thickness=thickness, offset=offset, levels=levels, **asked)
return [told.get("folded", -1) if told else -1, own_folds(bpy.data.objects[name]) if name in bpy.data.objects else -1]
under, over = folded("FoldUnder", wedge, FOLD / FOLD_STEP, count_folds=True), folded("FoldOver", wedge, FOLD * FOLD_STEP, count_folds=True)
reading("foldUnder", under[1])
reading("foldOver", over[1], least=True)
check("shell-fold: count_folds counts no folded face on a creased ridge under the thickness its narrower facet holds, and the faces this script counts over it",
under == [0, 0] and over[0] == over[1] > 0, [under, over])
unasked, outward = folded("FoldUnasked", wedge, FOLD * FOLD_STEP), folded("FoldOut", wedge, 0.3, offset=1.0, count_folds=True)
check("shell-fold: folded is null unless count_folds asks, whatever the wall does, and a ridge under a wall grown outward folds nowhere",
unasked[0] is None and unasked[1] == over[1] and outward == [0, 0], [unasked, outward])
lofts = json.loads((SURFACE / "tests" / "fixtures" / "fold_lofts.json").read_text(encoding="utf-8"))["lofts"]
seeded = {f"{loft['seed']} offset {loft['offset']:g}": folded(f"Loft{loft['seed']}", loft["sheet"], loft["thickness"], offset=loft["offset"], levels=loft["levels"], count_folds=True) for loft in lofts}
held = {f"{loft['seed']} offset {loft['offset']:g}": folded(f"Held{loft['seed']}", loft["sheet"], loft["holds"], offset=loft["offset"], levels=loft["levels"], count_folds=True) for loft in lofts if loft["holds"]}
R["folds"] = {"seeded": seeded, "held": held}
check("shell-fold: on seeded lofts whose walls fold under any figure of the cage, at offsets -1, 0 and 1, count_folds counts the faces this script counts, and none at a thickness the wall holds",
len(seeded) == 3 and all(told == own > 0 for told, own in seeded.values()) and held and all(pair == [0, 0] for pair in held.values()), [seeded, held])
for name in ["FoldUnder", "FoldOver", "FoldUnasked", "FoldOut"] + [f"{kind}{loft['seed']}" for loft in lofts for kind in ("Loft", "Held")]:
if name in bpy.data.objects:
bpy.data.objects.remove(bpy.data.objects[name])
# --- shell-solid ------------------------------------------------------------------------------------------------------------
section("shell-solid")
pauldron.modifiers["Kit Bevel"].show_viewport = False # the wall alone: a bevel rounds its edges
whole = evaluated(pauldron)
pauldron.modifiers["Kit Bevel"].show_viewport = True
area = sum(f.calc_area() for f in designed.faces)
outer = BVHTree.FromBMesh(designed)
inner = [v.co for v in whole.verts if all(outer.find_nearest(f.calc_center_median())[3] > WALL / 2 for f in v.link_faces)]
reading("solid", abs(whole.calc_volume(signed=True) / (area * WALL) - 1.0))
for co in inner:
reading("even", abs(outer.find_nearest(co)[3] - WALL))
check("shell-solid: the plate is a closed wall of even thickness behind the designed surface, its rim filled",
sum(1 for e in whole.edges if not e.is_manifold) == 0 and whole.calc_volume(signed=True) > 0 and len(whole.faces) == 2 * 1600 + 4 * 40 and len(inner) > 0.9 * len(designed.verts)
and R["readings"]["solid"] < SOLID and R["readings"]["even"] < EVEN, [R["readings"], len(whole.faces), len(inner), len(designed.verts)])
whole.free()
# a mirrored breast sheet: symmetric as evaluated
half = [[[0.0, -0.5 - 0.05 * i, 0.3 * i], [0.3, -0.45 - 0.05 * i, 0.3 * i], [0.6, -0.2, 0.3 * i + 0.05], [0.7, 0.2, 0.3 * i]] for i in range(4)]
BREAST = {"rings": half, "mirror": True, "creases": [{"column": 1, "from": 0, "to": 3, "weight": 1.0}, {"ring": 2, "from": 0, "to": 1, "weight": 0.7}]}
receipt, report = send("brokkr_kitbash.shell", object_name="Breast", sheet=json.dumps(BREAST), thickness=0.05, levels=2)
breast = bpy.data.objects.get("Breast")
plate = evaluated(breast) if breast is not None else None
V = np.array([v.co[:] for v in plate.verts]) if plate is not None else np.zeros((1, 3))
mirrored = {tuple(np.round(v * (-1.0, 1.0, 1.0), 5) + 0.0) for v in V} == {tuple(np.round(v, 5) + 0.0) for v in V}
check("a mirrored sheet is a plate symmetric in x, facing forward (-y), its creases on both halves", receipt["status"] == "accepted" and mirrored and report["points"] == 7
and report["facing"][1] < -0.5 and abs(report["facing"][0]) < 1e-6 and report["creases"] == 2 * 6 + 2 * 3 + 2 * 3 + 2
and sum(1 for e in plate.edges if not e.is_manifold) == 0, [receipt["message"], report])
if plate is not None:
plate.free()
# --- shell-composes ---------------------------------------------------------------------------------------------------------
section("shell-composes")
receipt, cut = send("brokkr_kitbash.cut_many", object_name="Pauldron", cuts=json.dumps(CUTS))
check("shell-composes: cut_many takes four panel lines and two insets on a shell, and its Boolean goes after the wall and above the bevel",
receipt["status"] == "accepted" and stack(pauldron) == ["Kit Subsurf", "Kit Solidify", "Kit Difference", "Kit Bevel"]
and sorted(c.name for c in pauldron.children) == sorted(c["name"] for c in CUTS), [receipt["message"], stack(pauldron)])
receipt, ribbed = send("brokkr_kitbash.ribs", object_name="Pauldron", ribs_name="PauldronRibs", planes=PLANES, standoff=0.01, depth=0.03, thickness=0.014)
ribs = bpy.data.objects.get("PauldronRibs")
behind = ribs is not None
for v in (points(ribs) if ribs is not None else ()):
on, normal, _, _ = outer.find_nearest(Vector(v))
behind = behind and (Vector(v) - on).dot(normal) < 0
check("shell-composes: ribs takes a shell, reads its thickness from Kit Solidify, and stands behind the plate: on the side the cage's normals face away from",
receipt["status"] == "accepted" and behind and ribs.parent == pauldron and ribbed["thickness"] == 0.06 and ribbed["ribs"] >= 3 and ribbed["nonManifoldEdges"] == 0,
[receipt["message"], ribbed])
receipt, deep = send("brokkr_kitbash.ribs", object_name="Pauldron", ribs_name="PauldronDeep", planes=PLANES, standoff=0.03, depth=0.08, thickness=0.014)
R["readings"]["ribsAcrossTheCrease"] = 1.0 if receipt["status"] == "accepted" else 0.0 # a reading, not a check: deep ribs behind a creased plate are ribs' to clip or refuse
R["creaseRibs"] = str(receipt["message"])[:300]
if bpy.data.objects.get("PauldronDeep") is not None:
bpy.data.objects.remove(bpy.data.objects["PauldronDeep"])
bpy.context.view_layer.update()
# --- shell-rebuild ----------------------------------------------------------------------------------------------------------
section("shell-rebuild")
before = {"pointer": pauldron.as_pointer(), "mesh": pauldron.data.as_pointer(), "children": {c.name: (c.as_pointer(), np.array(c.matrix_basis).tolist(), c.parent.name) for c in pauldron.children},
"cutters": sorted(o.name for o in pauldron.modifiers["Kit Difference"].collection.objects), "collection": pauldron.modifiers["Kit Difference"].collection.as_pointer(),
"ribs": points(ribs).copy(), "slots": len(pauldron.material_slots)}
MOVED = {**PAULDRON, "rings": [[[x, y, z + 0.1 * (1.0 - abs(y))] for x, y, z in r] for r in RINGS]} # the crown lifted, most in the middle
receipt, report = send("brokkr_kitbash.shell", object_name="Pauldron", sheet=json.dumps(MOVED), thickness=0.05, levels=2, bevel=0.004)
again = bpy.data.objects.get("Pauldron")
wall = again.modifiers.get("Kit Solidify")
check("shell-rebuild: the same object and mesh datablock, its cutters and ribs still its children at unchanged matrices, the Boolean's collection untouched, the stack in order",
receipt["status"] == "accepted" and again is not None and (again.as_pointer(), again.data.as_pointer()) == (before["pointer"], before["mesh"])
and {c.name: (c.as_pointer(), np.array(c.matrix_basis).tolist(), c.parent.name) for c in again.children} == before["children"] and len(before["children"]) == 7
and (sorted(o.name for o in again.modifiers["Kit Difference"].collection.objects), again.modifiers["Kit Difference"].collection.as_pointer()) == (before["cutters"], before["collection"])
and len(before["cutters"]) == 6 and stack(again) == ["Kit Subsurf", "Kit Solidify", "Kit Difference", "Kit Bevel"] and np.array_equal(points(ribs), before["ribs"]),
[receipt["message"], stack(again), sorted(c.name for c in again.children)])
check("shell-rebuild: the cage is the new sheet's, the modifiers' settings and kit_shell follow, and the report says rebuilt and names the children",
report and report["rebuilt"] is True and report["children"] == sorted(before["children"]) and (report["levels"], report["thickness"], report["subdividedFaces"]) == (2, 0.05, 400)
and np.abs(points(again) - core.sheet(MOVED).V).max() < 1e-6 and abs(points(again)[:, 2].max() - (1.5 + 0.1 * 0.8)) < 1e-6 and (again.modifiers["Kit Subsurf"].levels, again.modifiers["Kit Subsurf"].render_levels) == (2, 2)
and abs(wall.thickness - 0.05) < 1e-7 and json.loads(again["kit_shell"])["sheet"] == MOVED and json.loads(again["kit_shell"])["levels"] == 2
and crease_weights(again) == {tuple(pair): round(weight, 6) for pair, weight in zip(core.sheet(MOVED).creases.tolist(), core.sheet(MOVED).weights.tolist())}, report)
plate = evaluated(again)
check("shell-rebuild: the rebuilt plate is still cut, and closed", sum(1 for e in plate.edges if not e.is_manifold) == 0 and len(plate.faces) > 2 * 400 + 4 * 20 + 20, len(plate.faces))
plate.free()
receipt, report = send("brokkr_kitbash.shell", object_name="Pauldron", sheet=json.dumps(MOVED), thickness=0.05, levels=2, bevel=0.004, count_folds=True)
check("shell-rebuild: count_folds under cutters counts the wall as this script does and leaves the stack shown, in order",
receipt["status"] == "accepted" and report and report["folded"] == own_folds(again) and [(m.name, m.show_viewport) for m in again.modifiers]
== [("Kit Subsurf", True), ("Kit Solidify", True), ("Kit Difference", True), ("Kit Bevel", True)], [receipt["message"], report and report.get("folded"), [(m.name, m.show_viewport) for m in again.modifiers]])
# --- costs: wall times of this run, never bounded -----------------------------------------------------------------------------
section("costs")
times = {"shell": [], "shellCountingFolds": [], "evaluation": [], "rebuildUnderCuts": [], "rebuildCall": [], "rebuildCallCountingFolds": []}
for k in range(3):
name = f"Timed{k}"
start = time.perf_counter()
bpy.ops.brokkr_kitbash.shell(object_name=name, sheet=json.dumps(PAULDRON), thickness=WALL)
times["shell"].append(time.perf_counter() - start)
start = time.perf_counter()
bpy.ops.brokkr_kitbash.shell(object_name=name + "Counted", sheet=json.dumps(PAULDRON), thickness=WALL, count_folds=True)
times["shellCountingFolds"].append(time.perf_counter() - start)
bpy.data.objects[name].update_tag() # Blender's own update after the action evaluated it already: once more, alone
start = time.perf_counter()
faces = len(bpy.data.objects[name].evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) # one whole evaluation: Subdivision and Solidify
times["evaluation"].append(time.perf_counter() - start)
start = time.perf_counter()
bpy.ops.brokkr_kitbash.shell(object_name="Pauldron", sheet=json.dumps(MOVED if k % 2 else PAULDRON), thickness=WALL, bevel=0.004)
cut_faces = len(pauldron.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) # with its one Boolean of six cutters
times["rebuildUnderCuts"].append(time.perf_counter() - start)
for counting in (False, True): # the call alone: what count_folds adds to a rebuild under six cutters
start = time.perf_counter()
bpy.ops.brokkr_kitbash.shell(object_name="Pauldron", sheet=json.dumps(MOVED if k % 2 else PAULDRON), thickness=WALL, bevel=0.004, count_folds=counting)
times["rebuildCallCountingFolds" if counting else "rebuildCall"].append(time.perf_counter() - start)
R["costs"] = {name: float(f"{statistics.median(values):.2g}") for name, values in times.items()}
check("costs: the timed shells evaluated whole", faces == 3360 and cut_faces > 3360, [faces, cut_faces])
# --- shell-refusals ---------------------------------------------------------------------------------------------------------
section("shell-refusals")
SHEET = json.dumps(PAULDRON)
plain = bpy.data.objects.new("Plain", bpy.data.meshes.new("Plain"))
plain.data.from_pydata([(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)], [], [(0, 1, 2, 3)])
bpy.context.scene.collection.objects.link(plain)
empty = bpy.data.objects.new("Empty", None)
bpy.context.scene.collection.objects.link(empty)
bpy.context.view_layer.update()
refused("a mesh of that name that is no shell", {"object_name": "Plain", "sheet": SHEET}, "An object named 'Plain' exists and is no shell")
refused("an object of that name that is no mesh", {"object_name": "Empty", "sheet": SHEET}, "An object named 'Empty' exists and is no shell")
refused("a ribs object", {"object_name": "PauldronRibs", "sheet": SHEET}, "An object named 'PauldronRibs' exists and is no shell")
mixed.scale = (1.0, 1.0, 1.01)
bpy.context.view_layer.update()
refused("a scaled shell", {"object_name": "Mixed", "sheet": SHEET}, "'Mixed' is scaled, mirrored or sheared in the world")
mixed.scale = (1.0, 1.0, 1.0)
twin = bpy.data.objects.new("Twin", mixed.data)
bpy.context.scene.collection.objects.link(twin)
bpy.context.view_layer.update()
refused("a shell that shares its mesh", {"object_name": "Mixed", "sheet": SHEET}, "'Mixed' shares its mesh 'Mixed' with 1 other user(s)")
bpy.data.objects.remove(twin)
bpy.context.view_layer.update()
uneven = {"rings": [RINGS[0], RINGS[1][:5]]}
refused("a sheet of unequal rings, on a new name", {"object_name": "New", "sheet": json.dumps(uneven)}, "sheet.rings[1] has 5 points and sheet.rings[0] has 6")
refused("a sheet of unequal rings, on a shell", {"object_name": "Mixed", "sheet": json.dumps(uneven)}, "sheet.rings[1] has 5 points and sheet.rings[0] has 6")
refused("a run past the ring", {"object_name": "Mixed", "sheet": json.dumps({**PAULDRON, "creases": [{"ring": 0, "from": 0, "to": 6, "weight": 1}]})},
"sheet.creases[0].to must be a whole number from 0 to 5, not 6")
refused("two weights on one edge", {"object_name": "Mixed", "sheet": json.dumps({**PAULDRON, "creases": [{"ring": 1, "from": 0, "to": 2, "weight": 1}, {"ring": 1, "from": 1, "to": 3, "weight": 0.5}]})},
"sheet.creases[1] gives an edge weight 0.5 that sheet.creases[0] gives 1")
mixed.modifiers["Kit Solidify"].show_viewport = False
refused("count_folds on a shell whose Kit Solidify is hidden", {"object_name": "Mixed", "sheet": SHEET, "count_folds": True}, "'Mixed' has its Kit Solidify hidden in viewports")
mixed.modifiers["Kit Solidify"].show_viewport = True
refused("a sheet that is not JSON", {"object_name": "Mixed", "sheet": "{rings"}, "sheet is not JSON")
refused("a sheet with an unknown key", {"object_name": "New", "sheet": json.dumps({**PAULDRON, "inside": [0, 0, 0]})}, "sheet has no key 'inside'")
dense = {"rings": [[[j / 10, 0, i / 10] for j in range(34)] for i in range(34)]}
refused("too many faces", {"object_name": "New", "sheet": json.dumps(dense), "levels": 4}, "1089 cage quads at 4 levels subdivide to 278784 faces, over 262144")
receipt, report = send("brokkr_kitbash.shell", object_name="Dense", sheet=json.dumps(dense), levels=3, thickness=0.01)
check("the same sheet at three levels is taken", receipt["status"] == "accepted" and report["subdividedFaces"] == 69696, receipt["message"])
check("no refusal made an object", "New" not in bpy.data.objects, None)
except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file
check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-6:])
finally:
R["ok"] = all(c["ok"] for c in R["checks"])
R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())}
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
for c in R["checks"]:
print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True)
print("READINGS", R["readings"], R["costs"], flush=True)
sys.exit(0 if R["ok"] else 1)

View file

@ -0,0 +1,218 @@
{
"blender": "5.3.0",
"checks": [
{
"name": "shell makes one mesh object in the scene: the cage as core.sheet builds it, vertex for vertex, and kit_shell the request",
"ok": true,
"detail": null
},
{
"name": "shell reports cage facts: rings, points, quads, creased edges, the subdivided count, an upward facing, no children",
"ok": true,
"detail": null
},
{
"name": "the stack is Kit Subsurf, Kit Solidify, Kit Bevel: creases used, corners preserved, an even wall inward with its rim filled",
"ok": true,
"detail": null
},
{
"name": "crease_edge on the cage is the sheet's creases, edge for edge, and crease_vert is all zero",
"ok": true,
"detail": null
},
{
"name": "shell-crisp: the creased column stays a facet edge under three levels of subdivision, every other edge inside the plate stays smooth, and the dip is concave",
"ok": true,
"detail": null
},
{
"name": "a semi-sharp ring run, a column run and a point land on their own edges and vertex; with rim 0 the boundary carries no crease",
"ok": true,
"detail": null
},
{
"name": "shell-crisp: a sheet whose rim is soft keeps its four corners",
"ok": true,
"detail": null
},
{
"name": "shell-fold: count_folds counts no folded face on a creased ridge under the thickness its narrower facet holds, and the faces this script counts over it",
"ok": true,
"detail": null
},
{
"name": "shell-fold: folded is null unless count_folds asks, whatever the wall does, and a ridge under a wall grown outward folds nowhere",
"ok": true,
"detail": null
},
{
"name": "shell-fold: on seeded lofts whose walls fold under any figure of the cage, at offsets -1, 0 and 1, count_folds counts the faces this script counts, and none at a thickness the wall holds",
"ok": true,
"detail": null
},
{
"name": "shell-solid: the plate is a closed wall of even thickness behind the designed surface, its rim filled",
"ok": true,
"detail": null
},
{
"name": "a mirrored sheet is a plate symmetric in x, facing forward (-y), its creases on both halves",
"ok": true,
"detail": null
},
{
"name": "shell-composes: cut_many takes four panel lines and two insets on a shell, and its Boolean goes after the wall and above the bevel",
"ok": true,
"detail": null
},
{
"name": "shell-composes: ribs takes a shell, reads its thickness from Kit Solidify, and stands behind the plate: on the side the cage's normals face away from",
"ok": true,
"detail": null
},
{
"name": "shell-rebuild: the same object and mesh datablock, its cutters and ribs still its children at unchanged matrices, the Boolean's collection untouched, the stack in order",
"ok": true,
"detail": null
},
{
"name": "shell-rebuild: the cage is the new sheet's, the modifiers' settings and kit_shell follow, and the report says rebuilt and names the children",
"ok": true,
"detail": null
},
{
"name": "shell-rebuild: the rebuilt plate is still cut, and closed",
"ok": true,
"detail": null
},
{
"name": "shell-rebuild: count_folds under cutters counts the wall as this script does and leaves the stack shown, in order",
"ok": true,
"detail": null
},
{
"name": "costs: the timed shells evaluated whole",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a mesh of that name that is no shell",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: an object of that name that is no mesh",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a ribs object",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a scaled shell",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a shell that shares its mesh",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a sheet of unequal rings, on a new name",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a sheet of unequal rings, on a shell",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a run past the ring",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: two weights on one edge",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: count_folds on a shell whose Kit Solidify is hidden",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a sheet that is not JSON",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a sheet with an unknown key",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: too many faces",
"ok": true,
"detail": null
},
{
"name": "the same sheet at three levels is taken",
"ok": true,
"detail": null
},
{
"name": "no refusal made an object",
"ok": true,
"detail": null
}
],
"hostErrors": [],
"readings": {
"corner": 1.8e-07,
"crisp": 52.0,
"even": 0.0001,
"foldOver": 8.0,
"foldUnder": 0.0,
"ribsAcrossTheCrease": 1.0,
"soft": 5.8,
"solid": 0.027
},
"costs": {
"shell": 0.0059,
"shellCountingFolds": 0.0091,
"evaluation": 0.0022,
"rebuildUnderCuts": 1.7,
"rebuildCall": 1.6,
"rebuildCallCountingFolds": 1.6
},
"folds": {
"seeded": {
"5185 offset -1": [
2,
2
],
"5101 offset 0": [
13,
13
],
"5196 offset 1": [
4,
4
]
},
"held": {
"5185 offset -1": [
0,
0
]
}
},
"creaseRibs": "Operator brokkr_kitbash.ribs finished.",
"ok": true
}

View file

@ -5,7 +5,9 @@ and each refusal changes nothing. Not part of the unittest run: it needs Blender
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_pose.py -- <out>
Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses
without them). <out> is an absolute path; writes <out>.result.json and exits 1 when a check failed.
without them). <out> is an absolute path; writes <out>.result.json and exits 1 when a check failed. The checks run inside one try: an uncaught error is a failed check that names
the check before it, the checks are printed and the result file written whatever happened, and the exit is 1 with or
without --python-exit-code.
The scene: a tank, a bracket on its lug, a strut pinned in the bracket, an actuator pinned on the strut's far end,
and a loose strut whose closure names the actuator's rod pin. Bounds follow lodur:ruling:deterministic-bound-margin:
@ -17,6 +19,7 @@ import json
import math
import os
import sys
import traceback
import tempfile
import types
from pathlib import Path
@ -84,6 +87,10 @@ EDGE, PAST = 1e-5, 3.2e-5
def check(name, ok, detail=None):
try:
json.dumps(detail, default=str)
except TypeError: # a detail keyed by tuples: the result file takes it as text, so a failed check is written and not a crash
detail = repr(detail)
R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) # what was seen, when it was not what was promised
@ -164,148 +171,151 @@ def refused(label, action, fields, expected):
[receipt["status"], receipt["message"]])
rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")]
check("roll, aim and reach load as host actions after detach, with no errors", not R["hostErrors"] and "brokkr_kitbash.detach" in rows
and rows[rows.index("brokkr_kitbash.detach") + 1:][:3] == ["brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach"], [R["hostErrors"], rows])
try:
rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")]
check("roll, aim and reach load as host actions after detach, with no errors", not R["hostErrors"] and "brokkr_kitbash.detach" in rows
and rows[rows.index("brokkr_kitbash.detach") + 1:][:3] == ["brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach"], [R["hostErrors"], rows])
# --- the scene ----------------------------------------------------------------------------------------------------------
tank = place("Tank", "tank", "radius=0.3; length=1.2", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # lug size 0.09
mount = place("Mount", "bracket") # pin 0.054, plate 0.09
strut, ram = place("Strut", "strut", "width=0.09"), place("Ram", "actuator")
spare, orphan = place("Spare", "strut", "width=0.09", location=[0.0, 6.0, 0.0]), place("Orphan", "bracket")
send("createObject", objectType="MESH", name="Plain", location=[0.0, 12.0, 0.0], size=0.3)
send("brokkr_kitbash.attach", object_name="Mount", socket="mount", parent_name="Tank", parent_socket="lug_b")
send("brokkr_kitbash.attach", object_name="Orphan", socket="mount", parent_name="Tank", parent_socket="lug_a")
send("brokkr_kitbash.attach", object_name="Strut", socket="end_a", parent_name="Mount", parent_socket="pivot", roll=20.0)
receipt, report = send("brokkr_kitbash.attach", object_name="Ram", socket="base", parent_name="Strut", parent_socket="end_b", roll=-35.0)
check("the chain stands: tank, bracket, strut, actuator", receipt["status"] == "accepted" and holds(connection("Strut"), "Mount", "end_a", "pivot", 20.0)
and holds(report["connection"], "Strut", "base", "end_b", -35.0), [receipt["message"], connection("Strut")])
# --- the scene ----------------------------------------------------------------------------------------------------------
tank = place("Tank", "tank", "radius=0.3; length=1.2", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # lug size 0.09
mount = place("Mount", "bracket") # pin 0.054, plate 0.09
strut, ram = place("Strut", "strut", "width=0.09"), place("Ram", "actuator")
spare, orphan = place("Spare", "strut", "width=0.09", location=[0.0, 6.0, 0.0]), place("Orphan", "bracket")
send("createObject", objectType="MESH", name="Plain", location=[0.0, 12.0, 0.0], size=0.3)
send("brokkr_kitbash.attach", object_name="Mount", socket="mount", parent_name="Tank", parent_socket="lug_b")
send("brokkr_kitbash.attach", object_name="Orphan", socket="mount", parent_name="Tank", parent_socket="lug_a")
send("brokkr_kitbash.attach", object_name="Strut", socket="end_a", parent_name="Mount", parent_socket="pivot", roll=20.0)
receipt, report = send("brokkr_kitbash.attach", object_name="Ram", socket="base", parent_name="Strut", parent_socket="end_b", roll=-35.0)
check("the chain stands: tank, bracket, strut, actuator", receipt["status"] == "accepted" and holds(connection("Strut"), "Mount", "end_a", "pivot", 20.0)
and holds(report["connection"], "Strut", "base", "end_b", -35.0), [receipt["message"], connection("Strut")])
def meeting(name, other, other_socket, roll):
"""Place a loose strut so its end_a meets a socket of another part, and close it there."""
loose = place(name, "strut", "width=0.09")
meet = Matrix((np.array(other.matrix_world) @ core.mate(socket(other, other_socket), socket(loose, "end_a"), roll)).tolist())
send("setObjectTransform", targetObjectName=name, location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ")))
return send("brokkr_kitbash.close", object_name=name, socket="end_a", other_name=other.name, other_socket=other_socket)
def meeting(name, other, other_socket, roll):
"""Place a loose strut so its end_a meets a socket of another part, and close it there."""
loose = place(name, "strut", "width=0.09")
meet = Matrix((np.array(other.matrix_world) @ core.mate(socket(other, other_socket), socket(loose, "end_a"), roll)).tolist())
send("setObjectTransform", targetObjectName=name, location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ")))
return send("brokkr_kitbash.close", object_name=name, socket="end_a", other_name=other.name, other_socket=other_socket)
anchor = place("Aa_Anchor", "strut", "width=0.09", location=[0.0, -20.0, 0.0])
receipt, report = meeting("Brace", ram, "rod_end", 50.0)
check("a brace closes on the actuator's rod pin", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]])
receipt, report = meeting("Aa_Loose", anchor, "end_b", 40.0)
check("and a second closure, named to sort first, holds far from it", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]])
brace = bpy.data.objects["Brace"]
closing = {k: brace[k] for k in brace.keys() if k.startswith("kit_close")}
anchor = place("Aa_Anchor", "strut", "width=0.09", location=[0.0, -20.0, 0.0])
receipt, report = meeting("Brace", ram, "rod_end", 50.0)
check("a brace closes on the actuator's rod pin", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]])
receipt, report = meeting("Aa_Loose", anchor, "end_b", 40.0)
check("and a second closure, named to sort first, holds far from it", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]])
brace = bpy.data.objects["Brace"]
closing = {k: brace[k] for k in brace.keys() if k.startswith("kit_close")}
# --- roll: in place -----------------------------------------------------------------------------------------------------
for turn in (65.0, -160.0, 35.0): # from the 20 it was attached at
was, pin, before = stated(strut), frame(ram, "base")[:3, 3].copy(), (stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist())
sent = COUNT[0]
receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=turn)
gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", turn)), R["readings"]["roll"]
check(f"roll {turn:g} turns the strut where it hangs: one intent, its parent, sockets and parent inverse as they were, its roll stated and seated",
receipt["status"] == "accepted" and COUNT[0] == sent + 1 and stated(strut) == was and strut["kit_roll"] == turn and gap < SEATED and off < ROLL
and report and report["object"] == "Strut" and holds(report["connection"], "Mount", "end_a", "pivot", turn) and holds(connection("Strut"), "Mount", "end_a", "pivot", turn),
[receipt["message"], report and report["connection"], gap, off])
moved, gap = least("turned", float(np.linalg.norm(frame(ram, "base")[:3, 3] - pin))), reading("seated", seated(ram, "base", strut, "end_b", -35.0))
check(f"and the actuator follows through its own connection, which nothing rewrote (roll {turn:g})",
(stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist()) == before and moved > TURNED and gap < SEATED and R["readings"]["roll"] < ROLL
and holds(connection("Ram"), "Strut", "base", "end_b", -35.0), [moved, gap, connection("Ram"), R["readings"]])
# --- roll: in place -----------------------------------------------------------------------------------------------------
for turn in (65.0, -160.0, 35.0): # from the 20 it was attached at
was, pin, before = stated(strut), frame(ram, "base")[:3, 3].copy(), (stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist())
sent = COUNT[0]
receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=turn)
gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", turn)), R["readings"]["roll"]
check(f"roll {turn:g} turns the strut where it hangs: one intent, its parent, sockets and parent inverse as they were, its roll stated and seated",
receipt["status"] == "accepted" and COUNT[0] == sent + 1 and stated(strut) == was and strut["kit_roll"] == turn and gap < SEATED and off < ROLL
and report and report["object"] == "Strut" and holds(report["connection"], "Mount", "end_a", "pivot", turn) and holds(connection("Strut"), "Mount", "end_a", "pivot", turn),
[receipt["message"], report and report["connection"], gap, off])
moved, gap = least("turned", float(np.linalg.norm(frame(ram, "base")[:3, 3] - pin))), reading("seated", seated(ram, "base", strut, "end_b", -35.0))
check(f"and the actuator follows through its own connection, which nothing rewrote (roll {turn:g})",
(stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist()) == before and moved > TURNED and gap < SEATED and R["readings"]["roll"] < ROLL
and holds(connection("Ram"), "Strut", "base", "end_b", -35.0), [moved, gap, connection("Ram"), R["readings"]])
# --- roll: the closures it opens ----------------------------------------------------------------------------------------
check("the rolls above opened the brace's closure and reported it before the one that holds, whatever its name", (report or {}).get("closures") == [
{"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}] and report["closure"] is None, report and report.get("closures"))
receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=20.0)
check("rolled back to where the brace met it, the closure holds again: read from where the parts stand", receipt["status"] == "accepted" and (report or {}).get("closures") == [
{"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}, {"part": "Brace", "to": "Ram", "holds": True}], report and report.get("closures"))
send("setObjectTransform", targetObjectName="Aa_Loose", location=[0.0, -25.0, 0.0], rotationEuler=[0.0, 0.0, 0.0])
receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-35.0)
check("a roll lists the closures its own part is an end of first, before a broken one elsewhere", receipt["status"] == "accepted" and (report or {}).get("closures") == [
{"part": "Brace", "to": "Ram", "holds": True}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}], report and report.get("closures"))
receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-36.0)
check("and a roll of the part a closure names opens it; no roll seats or rewrites a closure", receipt["status"] == "accepted" and (report or {}).get("closures") == [
{"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}]
and {k: brace[k] for k in brace.keys() if k.startswith("kit_close")} == closing and brace.parent is None, [report and report.get("closures"), dict(brace.items())])
# --- roll: the closures it opens ----------------------------------------------------------------------------------------
check("the rolls above opened the brace's closure and reported it before the one that holds, whatever its name", (report or {}).get("closures") == [
{"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}] and report["closure"] is None, report and report.get("closures"))
receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=20.0)
check("rolled back to where the brace met it, the closure holds again: read from where the parts stand", receipt["status"] == "accepted" and (report or {}).get("closures") == [
{"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}, {"part": "Brace", "to": "Ram", "holds": True}], report and report.get("closures"))
send("setObjectTransform", targetObjectName="Aa_Loose", location=[0.0, -25.0, 0.0], rotationEuler=[0.0, 0.0, 0.0])
receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-35.0)
check("a roll lists the closures its own part is an end of first, before a broken one elsewhere", receipt["status"] == "accepted" and (report or {}).get("closures") == [
{"part": "Brace", "to": "Ram", "holds": True}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}], report and report.get("closures"))
receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-36.0)
check("and a roll of the part a closure names opens it; no roll seats or rewrites a closure", receipt["status"] == "accepted" and (report or {}).get("closures") == [
{"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}]
and {k: brace[k] for k in brace.keys() if k.startswith("kit_close")} == closing and brace.parent is None, [report and report.get("closures"), dict(brace.items())])
# --- aim ----------------------------------------------------------------------------------------------------------------
for axis, direction in (("+z", (1.0, 0.0, 0.0)), ("-x", (0.0, -3.0, 4.0)), ("+z", (0.2, 0.1, -2.0))):
world, unit = np.array(mount.matrix_world, dtype=np.float64), np.array(direction) / np.linalg.norm(direction)
receipt, report = send("brokkr_kitbash.aim", object_name="Strut", axis=axis, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2])
aimed = (report or {}).get("aimed") or {"roll": 1e9, "dot": 1e9}
read = float(np.array(strut.matrix_world, dtype=np.float64)[:3, :3] @ np.array(core.AXES[axis]) @ unit)
grid = max(float((world @ core.mate(socket(mount, "pivot"), socket(strut, "end_a"), float(r)))[:3, :3] @ np.array(core.AXES[axis]) @ unit) for r in range(-180, 180))
apart, short = reading("aimed", abs(aimed["dot"] - read)), reading("aimed short", max(grid - read, 0.0))
check(f"aim points the strut's {axis} at {direction} as far as its pin lets it: the dot it reports is the dot the scene reads, and no roll on a 1-degree grid passes it",
receipt["status"] == "accepted" and apart < AIMED and short < AIMED and 0.2 < aimed["dot"] < 0.999, [receipt["message"], aimed, read, grid])
gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", aimed["roll"])), R["readings"]["roll"]
check(f"and it is stated and seated as roll's: the connection holds at the aimed roll, the actuator with it, closures reported ({axis})",
aimed["roll"] == round(strut["kit_roll"], 6) and -180.0 < aimed["roll"] <= 180.0 and holds(report and report["connection"], "Mount", "end_a", "pivot", aimed["roll"])
and gap < SEATED and off < ROLL and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len((report or {}).get("closures", [])) == 2,
[dict(strut.items()), report and report["connection"], report and report.get("closures"), gap, off])
# --- aim ----------------------------------------------------------------------------------------------------------------
for axis, direction in (("+z", (1.0, 0.0, 0.0)), ("-x", (0.0, -3.0, 4.0)), ("+z", (0.2, 0.1, -2.0))):
world, unit = np.array(mount.matrix_world, dtype=np.float64), np.array(direction) / np.linalg.norm(direction)
receipt, report = send("brokkr_kitbash.aim", object_name="Strut", axis=axis, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2])
aimed = (report or {}).get("aimed") or {"roll": 1e9, "dot": 1e9}
read = float(np.array(strut.matrix_world, dtype=np.float64)[:3, :3] @ np.array(core.AXES[axis]) @ unit)
grid = max(float((world @ core.mate(socket(mount, "pivot"), socket(strut, "end_a"), float(r)))[:3, :3] @ np.array(core.AXES[axis]) @ unit) for r in range(-180, 180))
apart, short = reading("aimed", abs(aimed["dot"] - read)), reading("aimed short", max(grid - read, 0.0))
check(f"aim points the strut's {axis} at {direction} as far as its pin lets it: the dot it reports is the dot the scene reads, and no roll on a 1-degree grid passes it",
receipt["status"] == "accepted" and apart < AIMED and short < AIMED and 0.2 < aimed["dot"] < 0.999, [receipt["message"], aimed, read, grid])
gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", aimed["roll"])), R["readings"]["roll"]
check(f"and it is stated and seated as roll's: the connection holds at the aimed roll, the actuator with it, closures reported ({axis})",
aimed["roll"] == round(strut["kit_roll"], 6) and -180.0 < aimed["roll"] <= 180.0 and holds(report and report["connection"], "Mount", "end_a", "pivot", aimed["roll"])
and gap < SEATED and off < ROLL and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len((report or {}).get("closures", [])) == 2,
[dict(strut.items()), report and report["connection"], report and report.get("closures"), gap, off])
# --- reach --------------------------------------------------------------------------------------------------------------
for direction, part, offset in (((0.0, 0.0, 1.0), 0.5, 40.0), ((0.0, 0.0, 1.0), 0.5, -40.0), ((1.0, 2.0, -0.5), -0.8, 100.0)):
world, unit = np.array(mount.matrix_world, dtype=np.float64), np.array(direction) / np.linalg.norm(direction)
A, B, C = core.roll_terms(world, socket(mount, "pivot"), socket(strut, "end_a"), socket(strut, "end_b")["matrix"][:3, 3], 1.0, unit)
current = float(round(math.degrees(math.atan2(B, A)) + offset)) # the two rolls that reach stand either side of the middle: start nearer one
send("brokkr_kitbash.roll", object_name="Strut", roll=current)
height = round(C + part * math.hypot(A, B), 3)
fields = {"direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]} if direction != (0.0, 0.0, 1.0) else {} # world z is the default
receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=height, **fields)
# --- reach --------------------------------------------------------------------------------------------------------------
for direction, part, offset in (((0.0, 0.0, 1.0), 0.5, 40.0), ((0.0, 0.0, 1.0), 0.5, -40.0), ((1.0, 2.0, -0.5), -0.8, 100.0)):
world, unit = np.array(mount.matrix_world, dtype=np.float64), np.array(direction) / np.linalg.norm(direction)
A, B, C = core.roll_terms(world, socket(mount, "pivot"), socket(strut, "end_a"), socket(strut, "end_b")["matrix"][:3, 3], 1.0, unit)
current = float(round(math.degrees(math.atan2(B, A)) + offset)) # the two rolls that reach stand either side of the middle: start nearer one
send("brokkr_kitbash.roll", object_name="Strut", roll=current)
height = round(C + part * math.hypot(A, B), 3)
fields = {"direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]} if direction != (0.0, 0.0, 1.0) else {} # world z is the default
receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=height, **fields)
reached = (report or {}).get("reached") or {"roll": 1e9, "residual": 1e9}
apart = lambda roll: abs((roll - current + 180.0) % 360.0 - 180.0) # noqa: E731
off_plane = reading("reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - height))
farther = least("reach other root", apart(2.0 * math.degrees(math.atan2(B, A)) - reached["roll"]) - apart(reached["roll"])) # the other root mirrors it about the middle
check(f"reach brings the strut's end_b to {height} m along {direction} from roll {current:g}, by the nearer of the two rolls that do",
receipt["status"] == "accepted" and off_plane < REACHED and reached["residual"] < REACHED and farther > NEARER,
[receipt["message"], reached, off_plane, farther])
gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", reached["roll"])), R["readings"]["roll"]
check(f"and it is stated and seated as roll's ({direction}, from {current:g})", reached["roll"] == round(strut["kit_roll"], 6) and -180.0 < reached["roll"] <= 180.0
and holds(report and report["connection"], "Mount", "end_a", "pivot", reached["roll"]) and gap < SEATED and off < ROLL
and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len((report or {}).get("closures", [])) == 2,
[dict(strut.items()), report and report["connection"], gap, off])
# --- refusals -----------------------------------------------------------------------------------------------------------
send("setObjectParent", targetObjectName="Orphan", parentObjectName="")
low, high = C - math.hypot(A, B), C + math.hypot(A, B)
refused("roll of a part nobody attached", "brokkr_kitbash.roll", {"object_name": "Spare", "roll": 10.0}, "'Spare' is not attached (it has no kit_socket property)")
refused("aim of a part nobody attached", "brokkr_kitbash.aim", {"object_name": "Spare", "axis": "+z", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "'Spare' is not attached")
refused("reach of a part nobody attached", "brokkr_kitbash.reach", {"object_name": "Spare", "socket": "end_b", "height": 0.0}, "'Spare' is not attached")
refused("roll of a part whose parent was cleared", "brokkr_kitbash.roll", {"object_name": "Orphan", "roll": 10.0}, "'Orphan' states a connection and has no parent: detach it")
refused("roll of a mesh that is not a kit part", "brokkr_kitbash.roll", {"object_name": "Plain", "roll": 10.0}, "'Plain' is not a kit part")
refused("aim of the axis along the pin", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+y", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0},
"'Strut' on 'Mount': socket 'end_a' on parent socket 'pivot': the axis (0.0, 1.0, 0.0) of the part or the direction (1.0, 0.0, 0.0) lies along the pin")
refused("aim at no direction", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+z", "direction_x": 0.0, "direction_y": 0.0, "direction_z": 0.0}, "The direction is zero")
refused("reach past the circle the socket turns on, naming what it reaches", "brokkr_kitbash.reach",
{"object_name": "Strut", "socket": "end_b", "height": 900.0, "direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]},
f"no roll brings the point to 900.000000 m along ({unit[0]:.6f}".rstrip("0"))
receipt, _ = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=900.0, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2])
check("and the range it names is the one core solves", f"it reaches {low:.6f} m to {high:.6f} m" in str(receipt["message"]) and high - low > 1.0, [receipt["message"], low, high])
skew = {"direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]}
refused("reach a little past the top it names", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": float(f"{high:.6f}") + PAST, **skew}, "no roll brings the point to")
receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=float(f"{high:.6f}"), **skew)
reached = (report or {}).get("reached") or {"roll": 1e9, "residual": 1e9}
apart = lambda roll: abs((roll - current + 180.0) % 360.0 - 180.0) # noqa: E731
off_plane = reading("reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - height))
farther = least("reach other root", apart(2.0 * math.degrees(math.atan2(B, A)) - reached["roll"]) - apart(reached["roll"])) # the other root mirrors it about the middle
check(f"reach brings the strut's end_b to {height} m along {direction} from roll {current:g}, by the nearer of the two rolls that do",
receipt["status"] == "accepted" and off_plane < REACHED and reached["residual"] < REACHED and farther > NEARER,
[receipt["message"], reached, off_plane, farther])
gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", reached["roll"])), R["readings"]["roll"]
check(f"and it is stated and seated as roll's ({direction}, from {current:g})", reached["roll"] == round(strut["kit_roll"], 6) and -180.0 < reached["roll"] <= 180.0
and holds(report and report["connection"], "Mount", "end_a", "pivot", reached["roll"]) and gap < SEATED and off < ROLL
and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len((report or {}).get("closures", [])) == 2,
[dict(strut.items()), report and report["connection"], gap, off])
# --- refusals -----------------------------------------------------------------------------------------------------------
send("setObjectParent", targetObjectName="Orphan", parentObjectName="")
low, high = C - math.hypot(A, B), C + math.hypot(A, B)
refused("roll of a part nobody attached", "brokkr_kitbash.roll", {"object_name": "Spare", "roll": 10.0}, "'Spare' is not attached (it has no kit_socket property)")
refused("aim of a part nobody attached", "brokkr_kitbash.aim", {"object_name": "Spare", "axis": "+z", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "'Spare' is not attached")
refused("reach of a part nobody attached", "brokkr_kitbash.reach", {"object_name": "Spare", "socket": "end_b", "height": 0.0}, "'Spare' is not attached")
refused("roll of a part whose parent was cleared", "brokkr_kitbash.roll", {"object_name": "Orphan", "roll": 10.0}, "'Orphan' states a connection and has no parent: detach it")
refused("roll of a mesh that is not a kit part", "brokkr_kitbash.roll", {"object_name": "Plain", "roll": 10.0}, "'Plain' is not a kit part")
refused("aim of the axis along the pin", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+y", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0},
"'Strut' on 'Mount': socket 'end_a' on parent socket 'pivot': the axis (0.0, 1.0, 0.0) of the part or the direction (1.0, 0.0, 0.0) lies along the pin")
refused("aim at no direction", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+z", "direction_x": 0.0, "direction_y": 0.0, "direction_z": 0.0}, "The direction is zero")
refused("reach past the circle the socket turns on, naming what it reaches", "brokkr_kitbash.reach",
{"object_name": "Strut", "socket": "end_b", "height": 900.0, "direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]},
f"no roll brings the point to 900.000000 m along ({unit[0]:.6f}".rstrip("0"))
receipt, _ = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=900.0, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2])
check("and the range it names is the one core solves", f"it reaches {low:.6f} m to {high:.6f} m" in str(receipt["message"]) and high - low > 1.0, [receipt["message"], low, high])
skew = {"direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]}
refused("reach a little past the top it names", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": float(f"{high:.6f}") + PAST, **skew}, "no roll brings the point to")
receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=float(f"{high:.6f}"), **skew)
reached = (report or {}).get("reached") or {"roll": 1e9, "residual": 1e9}
over, stands = reading("edge typed past", max(float(np.float32(f"{high:.6f}")) - high, 0.0)), reading("edge reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - high))
check("reach to the top of the circle, typed back from the range the refusal named, is taken: the socket stands at the top", receipt["status"] == "accepted"
and reached["residual"] <= EDGE and over <= EDGE and stands < REACHED and holds(report["connection"], "Mount", "end_a", "pivot", reached["roll"]),
[receipt["message"], reached, over, stands, high])
refused("reach with the socket the part hangs by: it lies on the pin", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_a", "height": 0.0},
"'Strut' on 'Mount': socket 'end_a' on parent socket 'pivot': no roll moves the point along (0.0, 0.0, 1.0): it lies on the pin")
pin = np.array(mount.matrix_world, dtype=np.float64) @ socket(mount, "pivot")["matrix"]
for label, along in (("as the scene holds it", pin[:3, 2]), ("to 6 decimals", np.round(pin[:3, 2], 6)), ("to 4 decimals", np.round(pin[:3, 2], 4)), ("reversed, to 4 decimals", -np.round(pin[:3, 2], 4))):
refused(f"aim at the pin's own direction {label}", "brokkr_kitbash.aim",
{"object_name": "Strut", "axis": "+z", "direction_x": float(along[0]), "direction_y": float(along[1]), "direction_z": float(along[2])}, "lies along the pin, so no roll turns one toward the other")
refused("reach with a socket the part does not have", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_c", "height": 0.0},
"'Strut' has no socket 'end_c'; its sockets: end_a, end_a_back, end_b, end_b_back")
refused("reach along no direction", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": 0.0, "direction_z": 0.0}, "The direction is zero")
refused("a roll past a turn, by the action table", "brokkr_kitbash.roll", {"object_name": "Strut", "roll": 361.0}, "roll")
refused("an axis that is not one of the six, by the action table", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "x", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "axis")
over, stands = reading("edge typed past", max(float(np.float32(f"{high:.6f}")) - high, 0.0)), reading("edge reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - high))
check("reach to the top of the circle, typed back from the range the refusal named, is taken: the socket stands at the top", receipt["status"] == "accepted"
and reached["residual"] <= EDGE and over <= EDGE and stands < REACHED and holds(report["connection"], "Mount", "end_a", "pivot", reached["roll"]),
[receipt["message"], reached, over, stands, high])
refused("reach with the socket the part hangs by: it lies on the pin", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_a", "height": 0.0},
"'Strut' on 'Mount': socket 'end_a' on parent socket 'pivot': no roll moves the point along (0.0, 0.0, 1.0): it lies on the pin")
pin = np.array(mount.matrix_world, dtype=np.float64) @ socket(mount, "pivot")["matrix"]
for label, along in (("as the scene holds it", pin[:3, 2]), ("to 6 decimals", np.round(pin[:3, 2], 6)), ("to 4 decimals", np.round(pin[:3, 2], 4)), ("reversed, to 4 decimals", -np.round(pin[:3, 2], 4))):
refused(f"aim at the pin's own direction {label}", "brokkr_kitbash.aim",
{"object_name": "Strut", "axis": "+z", "direction_x": float(along[0]), "direction_y": float(along[1]), "direction_z": float(along[2])}, "lies along the pin, so no roll turns one toward the other")
refused("reach with a socket the part does not have", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_c", "height": 0.0},
"'Strut' has no socket 'end_c'; its sockets: end_a, end_a_back, end_b, end_b_back")
refused("reach along no direction", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": 0.0, "direction_z": 0.0}, "The direction is zero")
refused("a roll past a turn, by the action table", "brokkr_kitbash.roll", {"object_name": "Strut", "roll": 361.0}, "roll")
refused("an axis that is not one of the six, by the action table", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "x", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "axis")
except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file
check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:])
R["ok"] = all(c["ok"] for c in R["checks"])
R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())}
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
for c in R["checks"]:
print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True)
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
print("READINGS", R["readings"], flush=True)
sys.exit(0 if R["ok"] else 1)

View file

@ -6,12 +6,15 @@ and does what its doc says to real bpy meshes and images. Not part of the unitte
Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses
without them). Every action is sent through BrokkrBlenderTarget.run_intent, as tools/run_intents.py sends it.
With BROKKR_POLISH_HULLS=<a directory of generated .glb hulls> it also repairs each and checks that no face was
turned. Writes <out>.result.json and exits 1 when a check failed.
turned. Writes <out>.result.json and exits 1 when a check failed. The checks run inside one try: an uncaught error is a failed check that names
the check before it, the checks are printed and the result file written whatever happened, and the exit is 1 with or
without --python-exit-code.
"""
import json
import math
import os
import sys
import traceback
import types
from pathlib import Path
@ -47,6 +50,10 @@ RATIO_BOUND, DEFICIT_BOUND, SHADE_BOUND = 1.906, 0.136, 0.684 # each derived wh
def check(name, ok, detail=None):
try:
json.dumps(detail, default=str)
except TypeError: # a detail keyed by tuples: the result file takes it as text, so a failed check is written and not a crash
detail = repr(detail)
R["checks"].append({"name": name, "ok": bool(ok), "detail": detail})
@ -94,334 +101,337 @@ def pixels_of(obj):
return flat.reshape(image.size[1], image.size[0], 4)[..., :3], image
check("host file admitted", not R["hostErrors"] and len(R["hostRows"]) == 7, R["hostErrors"] or R["hostRows"])
try:
check("host file admitted", not R["hostErrors"] and len(R["hostRows"]) == 7, R["hostErrors"] or R["hostRows"])
# --- audit and repair: a generator's sphere, torn at every edge, half its faces wound inside out under outward
# --- custom normals, is welded back into one closed shell with no face turned and its shading normals intact ------
size = 256
rows = np.clip(((np.arange(size) + 0.5) / size - 0.1) / 0.8, 0.0, 1.0) # latitude: 0 at the south pole, 1 at the north
baked = np.repeat((0.8 * (0.2 + 0.8 * rows))[:, None, None], size, axis=1) * np.ones((1, 1, 3))
# --- audit and repair: a generator's sphere, torn at every edge, half its faces wound inside out under outward
# --- custom normals, is welded back into one closed shell with no face turned and its shading normals intact ------
size = 256
rows = np.clip(((np.arange(size) + 0.5) / size - 0.1) / 0.8, 0.0, 1.0) # latitude: 0 at the south pole, 1 at the north
baked = np.repeat((0.8 * (0.2 + 0.8 * rows))[:, None, None], size, axis=1) * np.ones((1, 1, 3))
def ball(bm):
bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=1.0, calc_uvs=True)
layer = bm.loops.layers.uv.active
for face in bm.faces: # the island sits inside the texture with a margin, as a generator's atlas does
for loop in face.loops:
loop[layer].uv = loop[layer].uv * 0.8 + Vector((0.1, 0.1))
sphere = new_object("Ball", ball, new_image("ball_bake", baked.astype(np.float32)))
sphere.data.polygons.foreach_set("use_smooth", [True] * len(sphere.data.polygons))
torn = bmesh.new()
torn.from_mesh(sphere.data)
bmesh.ops.split_edges(torn, edges=torn.edges[:])
inside_out = [f for f in torn.faces if f.calc_center_median().x > 0]
reversed_faces, reversed_triangles = len(inside_out), sum(len(f.verts) - 2 for f in inside_out)
bmesh.ops.reverse_faces(torn, faces=inside_out)
torn.to_mesh(sphere.data)
torn.free()
sphere.data.normals_split_custom_set([tuple(sphere.data.vertices[loop.vertex_index].co.normalized()) for loop in sphere.data.loops])
def polygon_normals(mesh):
flat = np.empty(len(mesh.polygons) * 3, dtype=np.float32)
mesh.polygons.foreach_get("normal", flat)
return flat.reshape(-1, 3)
def shading_error(mesh):
"""The worst angle, in degrees, between a corner's shading normal and the sphere's own outward direction."""
flat = np.empty(len(mesh.loops) * 3, dtype=np.float32)
mesh.corner_normals.foreach_get("vector", flat)
outward = np.array([mesh.vertices[loop.vertex_index].co.normalized() for loop in mesh.loops])
return float(np.degrees(np.arccos(np.clip((flat.reshape(-1, 3) * outward).sum(axis=1), -1, 1))).max())
receipt, before = send("brokkr_mesh_polish.audit", object_name="Ball")
check("audit: accepted, no undo step", receipt["status"] == "accepted" and not receipt.get("undoLabel"), receipt["message"])
check("audit: welded topology sees one closed shell in the torn sphere",
before["Ball"]["shells"] == 1 and before["Ball"]["boundaryEdges"] == 0 and before["Ball"]["nonManifoldEdges"] == 0, before["Ball"])
check("audit: texture and UV facts", before["Ball"]["baseColorSize"] == [size, size] and before["Ball"]["uvOverlap"] < 0.02
and before["Ball"]["texelDensityMedian"] > 0 and 0.55 < before["Ball"]["uvCoverage"] < 0.64, before["Ball"]) # an 0.8 x 0.8 island less the pole gaps
check("audit: counts the triangles wound against their shading normals, and none of them as a mirrored texture",
reversed_triangles > 1000 and before["Ball"]["windingAgainstNormals"] == reversed_triangles
and before["Ball"]["uvMirroredTriangles"] == 0, [reversed_triangles, before["Ball"].get("windingAgainstNormals"), before["Ball"].get("uvMirroredTriangles")])
torn_vertices, normals_before = len(sphere.data.vertices), polygon_normals(sphere.data)
receipt, repaired = send("brokkr_mesh_polish.repair", object_name="Ball")
check("repair: accepted as one undo step", receipt["status"] == "accepted" and "repair" in receipt.get("undoLabel", ""), receipt)
check("repair: welds the torn vertices", repaired["changes"]["welded"] == torn_vertices - len(sphere.data.vertices)
and len(sphere.data.vertices) == 48 * 23 + 2, repaired)
check("repair: every edge has two faces again", len(sphere.data.edges) == 48 * 23 + 48 * 24, len(sphere.data.edges))
normals_after = polygon_normals(sphere.data)
turned = int(((normals_before * normals_after).sum(axis=1) < 0).sum()) if len(normals_before) == len(normals_after) else -1
R["winding"] = {"reversedTriangles": reversed_triangles, "turnedByDefaultRepair": turned, "shadingErrorDegrees": shading_error(sphere.data)}
check("repair: by default turns no face (a single-sided material would cull a turned one)",
turned == 0 and repaired["changes"]["windingFlipped"] == 0
and repaired["after"]["windingAgainstNormals"] == repaired["before"]["windingAgainstNormals"] == reversed_triangles, [turned, repaired])
check("repair: the shading normals survive the weld", "custom_normal" in sphere.data.attributes and R["winding"]["shadingErrorDegrees"] < 0.5
and not repaired["changes"]["customNormalsDropped"], R["winding"])
# --- delight: a bake that darkens with latitude is levelled, reading the shading normals, not the windings --------
receipt, lit = send("brokkr_mesh_polish.delight", object_name="Ball", clusters=1, fit_size=128, occlusion_rays=8, max_gain=8)
after_pixels, after_image = pixels_of(sphere)
column = after_pixels[:, size // 2, 0]
north, south = int(size * (0.1 + 0.8 * 0.9)), int(size * (0.1 + 0.8 * 0.1)) # rows at latitude 0.9 and 0.1
ratio_before = float(baked[north, 0, 0] / baked[south, 0, 0])
ratio_after = float(column[north] / column[south])
# On the island's left border the gain field meets texels no triangle covers. With the field filled outward the
# border reads as the middle of the row does; left unfilled, the neutral gain of the uncovered texels bleeds in.
border = int(math.ceil(size * 0.1))
deficit = float(np.median(1.0 - after_pixels[south - 8:south + 8, border, 0] / after_pixels[south - 8:south + 8, size // 2, 0]))
R["delight"] = {"report": lit, "ratioBefore": ratio_before, "ratioAfter": ratio_after, "borderDeficit": deficit}
check("delight: accepted, new packed image on the material, in the old image's colour space", receipt["status"] == "accepted"
and after_image.name == "ball_bake.delit" and after_image.packed_file is not None
and after_image.colorspace_settings.name == "Non-Color", [receipt["message"], after_image.colorspace_settings.name])
check("delight: finds the baked light", lit["explainedByLight"]["before"] > 0.5 and lit["before"]["upDownLuminanceRatio"] > 2.0, lit)
# bound: shipped ratioAfter 1.114; a no-op leaves 3.261 and so do normals taken from the windings (the inside-out half
# cancels the light the fit could find): sqrt(1.114 * 3.261) = 1.906
check("delight: levels top against bottom", ratio_before > RATIO_BOUND * 1.2 and ratio_after < RATIO_BOUND / 1.2, [ratio_before, ratio_after])
# bound: shipped deficit 0.000, an unfilled gain field leaves 0.164; the shipped reading being zero, the bound sits 1.2 under the mutant: 0.136
check("delight: the gain reaches the island's border unweakened", abs(deficit) < DEFICIT_BOUND, deficit)
receipt, rewound = send("brokkr_mesh_polish.repair", object_name="Ball", recalc_normals=True, sharp_angle=30)
check("repair: recalc_normals rewinds the inside-out half and says how many faces it turned",
receipt["status"] == "accepted" and rewound["changes"]["windingFlipped"] == reversed_faces
and rewound["changes"]["customNormalsDropped"] and "custom_normal" not in sphere.data.attributes
and rewound["after"]["windingAgainstNormals"] == 0, rewound)
# --- repair: only holes up to the size asked are filled, and only shells below the share asked are dropped -----
def holey(bm):
bmesh.ops.create_grid(bm, x_segments=6, y_segments=6, size=3.0, calc_uvs=True) # 36 quads, each 1 x 1
at = lambda face: (round(face.calc_center_median().x, 1), round(face.calc_center_median().y, 1))
small = [f for f in bm.faces if at(f) == (1.5, 1.5)] # one quad inside: a 4-edge hole
large = [f for f in bm.faces if at(f)[0] in (-1.5, -0.5) and at(f)[1] in (-1.5, -0.5)] # a 2 x 2 block: an 8-edge hole
bmesh.ops.delete(bm, geom=small + large, context="FACES")
bm.faces.new([bm.verts.new(co) for co in ((9.0, 9.0, 0.0), (9.2, 9.0, 0.0), (9.0, 9.2, 0.0))]) # a far chip: 0.02 of area against 31
sheet = new_object("Sheet", holey)
flipped_sheet = bmesh.new() # the generator's sheet faces down: a fill must follow it, whichever way Blender would guess
flipped_sheet.from_mesh(sheet.data)
bmesh.ops.reverse_faces(flipped_sheet, faces=flipped_sheet.faces[:])
flipped_sheet.to_mesh(sheet.data)
flipped_sheet.free()
TILT = (0.6, 0.0, -0.8) # the generator's shading normals lean: the old faces must keep them, a fill must not borrow them
sheet.data.normals_split_custom_set([TILT] * len(sheet.data.loops))
receipt, mended = send("brokkr_mesh_polish.repair", object_name="Sheet", fill_holes_sides=4, min_shell_area=0.01)
R["mend"] = mended
check("repair: fills the 4-edge hole, leaves the 8-edge hole and the rim, drops the chip",
receipt["status"] == "accepted" and mended["changes"]["holesFilled"] == 1 and mended["changes"]["shellsRemoved"] == 1
and mended["after"]["shells"] == 1 and mended["after"]["boundaryEdges"] == 24 + 8, mended)
facing = polygon_normals(sheet.data)[:, 2]
check("repair: a filled hole is wound as the faces around it", len(facing) == 31 * 1 + 2 and bool((facing < -0.9).all()), [len(facing), float(facing.max())])
shading = np.empty(len(sheet.data.loops) * 3, dtype=np.float32)
sheet.data.corner_normals.foreach_get("vector", shading)
shading = shading.reshape(-1, 3)
fill_loops = [i for polygon in sheet.data.polygons if abs(polygon.center.x - 1.5) < 0.4 and abs(polygon.center.y - 1.5) < 0.4 for i in polygon.loop_indices]
old_loops = [i for i in range(len(shading)) if i not in set(fill_loops)]
check("repair: old faces keep their shading normals through the weld and the fill; the fill is shaded by its own direction",
len(fill_loops) == 6 and np.allclose(shading[old_loops], TILT, atol=1e-3) and np.allclose(shading[fill_loops], (0.0, 0.0, -1.0), atol=1e-3),
[len(fill_loops), shading[fill_loops].tolist()[:2], shading[old_loops[0]].tolist()])
bpy.data.objects.remove(sheet)
# --- delight: darkness that follows occlusion is levelled ---------------------------------------------------------
def pair(bm):
layer = bm.loops.layers.uv.active
for side in (-1.0, 1.0): # two unit spheres 0.1 apart: their facing sides occlude each other
made = bmesh.ops.create_uvsphere(bm, u_segments=32, v_segments=16, radius=1.0, calc_uvs=True, matrix=Matrix.Translation((side * 1.05, 0, 0)))
for face in {f for v in made["verts"] for f in v.link_faces}:
def ball(bm):
bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=1.0, calc_uvs=True)
layer = bm.loops.layers.uv.active
for face in bm.faces: # the island sits inside the texture with a margin, as a generator's atlas does
for loop in face.loops:
loop[layer].uv = Vector((loop[layer].uv.x * 0.5 + (0.0 if side < 0 else 0.5), loop[layer].uv.y))
loop[layer].uv = loop[layer].uv * 0.8 + Vector((0.1, 0.1))
import brokkr_mesh_polish as polish # noqa: E402 the fixture's bake uses the add-on's own occlusion, so the light is exactly what it can explain
twins = new_object("Twins", pair, new_image("twins_bake", np.ones((size, size, 3), dtype=np.float32)))
twins.data.polygons.foreach_set("use_smooth", [True] * len(twins.data.polygons))
twin = polish.arrays(twins)
twin_sky = polish.ambient_occlusion(twin["V"], twin["T"], twin["N"], 64, 0.35 * float(np.linalg.norm(twin["V"].max(axis=0) - twin["V"].min(axis=0))))
owner, bary, _ = polish.core.rasterize(twin["UV"], size)
sky_map = polish.core.interpolate(owner, bary, twin_sky[twin["T"]][..., None])[..., 0]
occluded, open_sky = (owner >= 0) & (sky_map < 0.6), (owner >= 0) & (sky_map > 0.95)
twin_bake = np.where((owner >= 0)[..., None], 0.8 * np.clip(sky_map, 0.05, 1.0)[..., None], 0.5) * np.ones((1, 1, 3))
flat = np.ones((size, size, 4), dtype=np.float32)
flat[..., :3] = twin_bake
bpy.data.images["twins_bake"].pixels.foreach_set(flat.reshape(-1))
receipt, unshadowed = send("brokkr_mesh_polish.delight", object_name="Twins", clusters=1, fit_size=256, occlusion_rays=64, max_gain=8)
twin_after, _ = pixels_of(twins)
shade_before = float(np.median(twin_bake[..., 0][occluded]) / np.median(twin_bake[..., 0][open_sky]))
shade_after = float(np.median(twin_after[..., 0][occluded]) / np.median(twin_after[..., 0][open_sky]))
R["occlusion"] = {"report": unshadowed, "occludedTexels": int(occluded.sum()), "shadeBefore": shade_before, "shadeAfter": shade_after}
# bound: shipped shadeAfter 1.000; with occlusion ignored (a sky of 1 everywhere) it stays 0.468: sqrt(1.000 * 0.468) = 0.684
check("delight: lifts occluded surface to the level of open surface", receipt["status"] == "accepted" and occluded.sum() > 500
and shade_before < SHADE_BOUND / 1.2 and shade_after > SHADE_BOUND * 1.2, R["occlusion"])
bpy.data.objects.remove(twins)
# --- orient: a turned slab is laid along Y, thin on Z, centred, scaled; nothing outside it moves -----------------
slab = new_object("Slab", lambda bm: bmesh.ops.create_cube(bm, size=1.0, matrix=Matrix.Diagonal((3.0, 1.0, 0.5, 1.0))))
slab.matrix_world = Matrix.Translation((4, 5, 6)) @ Matrix.Rotation(math.radians(37), 4, (0.3, 0.5, 0.8))
sphere.location = (20, 0, 0)
bpy.context.view_layer.update()
receipt, oriented = send("brokkr_mesh_polish.orient", object_name="Slab", length=12.0)
corners = np.array([slab.matrix_world @ v.co for v in slab.data.vertices])
extent = corners.max(axis=0) - corners.min(axis=0)
check("orient: long on Y, thin on Z, scaled to the length, centred",
receipt["status"] == "accepted" and np.allclose(extent, [4.0, 12.0, 2.0], atol=1e-3)
and np.allclose((corners.max(axis=0) + corners.min(axis=0)) / 2, 0, atol=1e-4), [list(map(float, extent)), oriented])
check("orient: reports the mirror error of a symmetric body as small", max(oriented["mirrorError"].values()) < 0.05, oriented["mirrorError"])
check("orient: an object outside the named root is not touched", oriented["objects"] == ["Slab"]
and np.allclose(sphere.matrix_world.translation, [20, 0, 0]) and abs(max(v.co.length for v in sphere.data.vertices) - 1.0) < 1e-5, oriented["objects"])
receipt, _ = send("brokkr_mesh_polish.orient", object_name="Nobody")
check("orient: an unknown root is refused", receipt["status"] == "failed", receipt["message"])
bpy.data.objects.remove(slab)
# --- cut_parts: a knob fused to a block is cut off at the crease, capped, and rooted at its cut -----------------
def knobbed(bm):
bmesh.ops.create_cube(bm, size=2.0)
top = next(f for f in bm.faces if f.normal.z > 0.9)
bmesh.ops.inset_region(bm, faces=[top], thickness=0.6)
extruded = bmesh.ops.extrude_face_region(bm, geom=[top])
bmesh.ops.translate(bm, verts=[g for g in extruded["geom"] if isinstance(g, bmesh.types.BMVert)], vec=(0, 0, 1.0))
bmesh.ops.delete(bm, geom=[top], context="FACES")
bmesh.ops.triangulate(bm, faces=bm.faces[:])
bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:])
sphere = new_object("Ball", ball, new_image("ball_bake", baked.astype(np.float32)))
sphere.data.polygons.foreach_set("use_smooth", [True] * len(sphere.data.polygons))
torn = bmesh.new()
torn.from_mesh(sphere.data)
bmesh.ops.split_edges(torn, edges=torn.edges[:])
inside_out = [f for f in torn.faces if f.calc_center_median().x > 0]
reversed_faces, reversed_triangles = len(inside_out), sum(len(f.verts) - 2 for f in inside_out)
bmesh.ops.reverse_faces(torn, faces=inside_out)
torn.to_mesh(sphere.data)
torn.free()
sphere.data.normals_split_custom_set([tuple(sphere.data.vertices[loop.vertex_index].co.normalized()) for loop in sphere.data.loops])
block = new_object("Block", knobbed)
receipt, single = send("brokkr_mesh_polish.audit", object_name="Block")
check("cut fixture is one closed skin", single["Block"]["shells"] == 1 and single["Block"]["boundaryEdges"] == 0, single["Block"])
receipt, cut = send("brokkr_mesh_polish.cut_parts", object_name="Block", seeds="body=0,0,-1; knob=0,0,2", joint_scale=0.5)
R["cut"] = cut
check("cut_parts: accepted, one undo step, the fused object is replaced", receipt["status"] == "accepted" and bool(receipt.get("undoLabel"))
and "Block" not in bpy.data.objects and {"Block.body", "Block.knob"} <= set(bpy.data.objects.keys()), receipt["message"])
if receipt["status"] == "accepted":
knob, body = bpy.data.objects["Block.knob"], bpy.data.objects["Block.body"]
part = {entry["name"]: entry for entry in cut["parts"]}
check("cut_parts: the knob is cut at the crease and rooted at the centre of the cut",
np.allclose(part["Block.knob"]["root"], [0, 0, 1], atol=1e-5) and np.allclose(knob.matrix_world.translation, [0, 0, 1], atol=1e-5)
and abs(abs(part["Block.knob"]["cutNormal"][2]) - 1) < 1e-5, part["Block.knob"])
check("cut_parts: the knob hangs from the body and has not moved", knob.parent == body
and abs(max((knob.matrix_world @ v.co).z for v in knob.data.vertices) - 2.0) < 1e-5, None)
_, closed = send("brokkr_mesh_polish.audit")
check("cut_parts: both sides of the cut are capped (closed shells)",
all(closed[name]["boundaryEdges"] == 0 and closed[name]["shells"] == 1 for name in ("Block.body", "Block.knob")),
{name: [closed[name]["boundaryEdges"], closed[name]["shells"]] for name in ("Block.body", "Block.knob")})
capped = {o.name: sum(1 for polygon in o.data.polygons if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap") for o in (body, knob)}
check("cut_parts: exactly the cap faces carry the cap material", capped["Block.knob"] == part["Block.knob"]["capTriangles"] > 0
and capped["Block.body"] == part["Block.body"]["capTriangles"] > 0, capped)
cap_normals = {o.name: [polygon.normal.z for polygon in o.data.polygons
if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap"] for o in (body, knob)}
check("cut_parts: each cap faces out of its own part, and no old face was turned",
all(z < -0.9 for z in cap_normals["Block.knob"]) and all(z > 0.9 for z in cap_normals["Block.body"])
and closed["Block.body"]["windingAgainstNormals"] == 0 and closed["Block.knob"]["windingAgainstNormals"] == 0, cap_normals)
check("cut_parts: a joint sits at the root", "Polish Cap" in [getattr(m, "name", "") for m in knob.data.materials]
and np.allclose(bpy.data.objects[part["Block.knob"]["joint"]].matrix_world.translation, [0, 0, 1], atol=1e-5), part["Block.knob"].get("joint"))
# orient after the cut: the body and what hangs from it turn as one; the knob keeps its parent and its pivot
receipt, turned_parts = send("brokkr_mesh_polish.orient", object_name="Block.body", length=6.0)
pivot = knob.matrix_world.translation
reach = max(abs((knob.matrix_world @ v.co).y) for v in knob.data.vertices)
R["orientParts"] = {"report": turned_parts, "knobPivot": list(pivot), "knobReach": reach, "parent": knob.parent.name if knob.parent else None}
# the 2 x 2 x 3 body-and-knob is laid along Y and doubled: the cut centre (0, 0, 1), half a unit above the middle, lands 1 along Y
check("orient: after a cut the parts keep their parent and their pivot at the cut", receipt["status"] == "accepted" and knob.parent == body
and abs(abs(pivot.y) - 1.0) < 1e-4 and abs(pivot.x) < 1e-4 and abs(pivot.z) < 1e-4 and abs(reach - 3.0) < 1e-4
and np.allclose(np.array(knob.matrix_world.to_3x3()), np.eye(3), atol=1e-6), R["orientParts"])
receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Block.body", seeds="only=0,0,-1")
check("cut_parts: one part is refused with nothing changed", receipt["status"] == "failed" and "Block.body" in bpy.data.objects, receipt["message"])
def polygon_normals(mesh):
flat = np.empty(len(mesh.polygons) * 3, dtype=np.float32)
mesh.polygons.foreach_get("normal", flat)
return flat.reshape(-1, 3)
# --- cut_parts through: a seed on one face of a thin plate also holds the face behind it -----------------------
def plate_body(bm):
bmesh.ops.create_cube(bm, size=2.0, matrix=Matrix.Diagonal((1.0, 1.0, 0.05, 1.0))) # 2 x 2 x 0.1
bmesh.ops.subdivide_edges(bm, edges=bm.edges[:], cuts=7, use_grid_fill=True)
bmesh.ops.triangulate(bm, faces=bm.faces[:])
def shading_error(mesh):
"""The worst angle, in degrees, between a corner's shading normal and the sphere's own outward direction."""
flat = np.empty(len(mesh.loops) * 3, dtype=np.float32)
mesh.corner_normals.foreach_get("vector", flat)
outward = np.array([mesh.vertices[loop.vertex_index].co.normalized() for loop in mesh.loops])
return float(np.degrees(np.arccos(np.clip((flat.reshape(-1, 3) * outward).sum(axis=1), -1, 1))).max())
def underside(name):
"""Triangles of the part that face down and are surface, not cap."""
part_object = bpy.data.objects[name]
return sum(1 for polygon in part_object.data.polygons
if polygon.normal.z < -0.9 and getattr(part_object.data.materials[polygon.material_index], "name", "") != "Polish Cap")
receipt, before = send("brokkr_mesh_polish.audit", object_name="Ball")
check("audit: accepted, no undo step", receipt["status"] == "accepted" and not receipt.get("undoLabel"), receipt["message"])
check("audit: welded topology sees one closed shell in the torn sphere",
before["Ball"]["shells"] == 1 and before["Ball"]["boundaryEdges"] == 0 and before["Ball"]["nonManifoldEdges"] == 0, before["Ball"])
check("audit: texture and UV facts", before["Ball"]["baseColorSize"] == [size, size] and before["Ball"]["uvOverlap"] < 0.02
and before["Ball"]["texelDensityMedian"] > 0 and 0.55 < before["Ball"]["uvCoverage"] < 0.64, before["Ball"]) # an 0.8 x 0.8 island less the pole gaps
check("audit: counts the triangles wound against their shading normals, and none of them as a mirrored texture",
reversed_triangles > 1000 and before["Ball"]["windingAgainstNormals"] == reversed_triangles
and before["Ball"]["uvMirroredTriangles"] == 0, [reversed_triangles, before["Ball"].get("windingAgainstNormals"), before["Ball"].get("uvMirroredTriangles")])
torn_vertices, normals_before = len(sphere.data.vertices), polygon_normals(sphere.data)
receipt, repaired = send("brokkr_mesh_polish.repair", object_name="Ball")
check("repair: accepted as one undo step", receipt["status"] == "accepted" and "repair" in receipt.get("undoLabel", ""), receipt)
check("repair: welds the torn vertices", repaired["changes"]["welded"] == torn_vertices - len(sphere.data.vertices)
and len(sphere.data.vertices) == 48 * 23 + 2, repaired)
check("repair: every edge has two faces again", len(sphere.data.edges) == 48 * 23 + 48 * 24, len(sphere.data.edges))
normals_after = polygon_normals(sphere.data)
turned = int(((normals_before * normals_after).sum(axis=1) < 0).sum()) if len(normals_before) == len(normals_after) else -1
R["winding"] = {"reversedTriangles": reversed_triangles, "turnedByDefaultRepair": turned, "shadingErrorDegrees": shading_error(sphere.data)}
check("repair: by default turns no face (a single-sided material would cull a turned one)",
turned == 0 and repaired["changes"]["windingFlipped"] == 0
and repaired["after"]["windingAgainstNormals"] == repaired["before"]["windingAgainstNormals"] == reversed_triangles, [turned, repaired])
check("repair: the shading normals survive the weld", "custom_normal" in sphere.data.attributes and R["winding"]["shadingErrorDegrees"] < 0.5
and not repaired["changes"]["customNormalsDropped"], R["winding"])
# --- delight: a bake that darkens with latitude is levelled, reading the shading normals, not the windings --------
receipt, lit = send("brokkr_mesh_polish.delight", object_name="Ball", clusters=1, fit_size=128, occlusion_rays=8, max_gain=8)
after_pixels, after_image = pixels_of(sphere)
column = after_pixels[:, size // 2, 0]
north, south = int(size * (0.1 + 0.8 * 0.9)), int(size * (0.1 + 0.8 * 0.1)) # rows at latitude 0.9 and 0.1
ratio_before = float(baked[north, 0, 0] / baked[south, 0, 0])
ratio_after = float(column[north] / column[south])
# On the island's left border the gain field meets texels no triangle covers. With the field filled outward the
# border reads as the middle of the row does; left unfilled, the neutral gain of the uncovered texels bleeds in.
border = int(math.ceil(size * 0.1))
deficit = float(np.median(1.0 - after_pixels[south - 8:south + 8, border, 0] / after_pixels[south - 8:south + 8, size // 2, 0]))
R["delight"] = {"report": lit, "ratioBefore": ratio_before, "ratioAfter": ratio_after, "borderDeficit": deficit}
check("delight: accepted, new packed image on the material, in the old image's colour space", receipt["status"] == "accepted"
and after_image.name == "ball_bake.delit" and after_image.packed_file is not None
and after_image.colorspace_settings.name == "Non-Color", [receipt["message"], after_image.colorspace_settings.name])
check("delight: finds the baked light", lit["explainedByLight"]["before"] > 0.5 and lit["before"]["upDownLuminanceRatio"] > 2.0, lit)
# bound: shipped ratioAfter 1.114; a no-op leaves 3.261 and so do normals taken from the windings (the inside-out half
# cancels the light the fit could find): sqrt(1.114 * 3.261) = 1.906
check("delight: levels top against bottom", ratio_before > RATIO_BOUND * 1.2 and ratio_after < RATIO_BOUND / 1.2, [ratio_before, ratio_after])
# bound: shipped deficit 0.000, an unfilled gain field leaves 0.164; the shipped reading being zero, the bound sits 1.2 under the mutant: 0.136
check("delight: the gain reaches the island's border unweakened", abs(deficit) < DEFICIT_BOUND, deficit)
receipt, rewound = send("brokkr_mesh_polish.repair", object_name="Ball", recalc_normals=True, sharp_angle=30)
check("repair: recalc_normals rewinds the inside-out half and says how many faces it turned",
receipt["status"] == "accepted" and rewound["changes"]["windingFlipped"] == reversed_faces
and rewound["changes"]["customNormalsDropped"] and "custom_normal" not in sphere.data.attributes
and rewound["after"]["windingAgainstNormals"] == 0, rewound)
# --- repair: only holes up to the size asked are filled, and only shells below the share asked are dropped -----
def holey(bm):
bmesh.ops.create_grid(bm, x_segments=6, y_segments=6, size=3.0, calc_uvs=True) # 36 quads, each 1 x 1
at = lambda face: (round(face.calc_center_median().x, 1), round(face.calc_center_median().y, 1))
small = [f for f in bm.faces if at(f) == (1.5, 1.5)] # one quad inside: a 4-edge hole
large = [f for f in bm.faces if at(f)[0] in (-1.5, -0.5) and at(f)[1] in (-1.5, -0.5)] # a 2 x 2 block: an 8-edge hole
bmesh.ops.delete(bm, geom=small + large, context="FACES")
bm.faces.new([bm.verts.new(co) for co in ((9.0, 9.0, 0.0), (9.2, 9.0, 0.0), (9.0, 9.2, 0.0))]) # a far chip: 0.02 of area against 31
R["through"] = {}
for label, through in (("without", 0.0), ("with", 0.1)):
new_object("Plate", plate_body)
# by distance alone (no crease cost) the underside's middle is nearer the body's seed, at an underside corner,
# than the lid's seed on top, which must go round the rim; a ray inward from the lid's seed finds it at once
receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Plate", seeds="body=-0.9,-0.9,-0.05; lid=0,0,0.05", crease_cost=0, through=through)
R["through"][label] = underside("Plate.lid") if receipt["status"] == "accepted" else None
for leftover in [o for o in bpy.data.objects if o.name.startswith("Plate")]:
bpy.data.objects.remove(leftover)
check("cut_parts: through seeds the far face of a thin part", R["through"]["without"] == 0 and (R["through"]["with"] or 0) >= 8, R["through"])
sheet = new_object("Sheet", holey)
flipped_sheet = bmesh.new() # the generator's sheet faces down: a fill must follow it, whichever way Blender would guess
flipped_sheet.from_mesh(sheet.data)
bmesh.ops.reverse_faces(flipped_sheet, faces=flipped_sheet.faces[:])
flipped_sheet.to_mesh(sheet.data)
flipped_sheet.free()
TILT = (0.6, 0.0, -0.8) # the generator's shading normals lean: the old faces must keep them, a fill must not borrow them
sheet.data.normals_split_custom_set([TILT] * len(sheet.data.loops))
receipt, mended = send("brokkr_mesh_polish.repair", object_name="Sheet", fill_holes_sides=4, min_shell_area=0.01)
R["mend"] = mended
check("repair: fills the 4-edge hole, leaves the 8-edge hole and the rim, drops the chip",
receipt["status"] == "accepted" and mended["changes"]["holesFilled"] == 1 and mended["changes"]["shellsRemoved"] == 1
and mended["after"]["shells"] == 1 and mended["after"]["boundaryEdges"] == 24 + 8, mended)
facing = polygon_normals(sheet.data)[:, 2]
check("repair: a filled hole is wound as the faces around it", len(facing) == 31 * 1 + 2 and bool((facing < -0.9).all()), [len(facing), float(facing.max())])
shading = np.empty(len(sheet.data.loops) * 3, dtype=np.float32)
sheet.data.corner_normals.foreach_get("vector", shading)
shading = shading.reshape(-1, 3)
fill_loops = [i for polygon in sheet.data.polygons if abs(polygon.center.x - 1.5) < 0.4 and abs(polygon.center.y - 1.5) < 0.4 for i in polygon.loop_indices]
old_loops = [i for i in range(len(shading)) if i not in set(fill_loops)]
check("repair: old faces keep their shading normals through the weld and the fill; the fill is shaded by its own direction",
len(fill_loops) == 6 and np.allclose(shading[old_loops], TILT, atol=1e-3) and np.allclose(shading[fill_loops], (0.0, 0.0, -1.0), atol=1e-3),
[len(fill_loops), shading[fill_loops].tolist()[:2], shading[old_loops[0]].tolist()])
bpy.data.objects.remove(sheet)
# --- pick and scrub_markings: lettering on one panel is found from a camera and painted out ----------------------
panel = np.full((128, 128, 3), [0.1, 0.35, 0.4], dtype=np.float32)
panel += np.random.default_rng(0).normal(0, 0.01, panel.shape).astype(np.float32)
for column_start in range(8, 120, 8): # yellow strokes over the whole texture
panel[:, column_start:column_start + 2] = [0.85, 0.75, 0.2]
# --- delight: darkness that follows occlusion is levelled ---------------------------------------------------------
def pair(bm):
layer = bm.loops.layers.uv.active
for side in (-1.0, 1.0): # two unit spheres 0.1 apart: their facing sides occlude each other
made = bmesh.ops.create_uvsphere(bm, u_segments=32, v_segments=16, radius=1.0, calc_uvs=True, matrix=Matrix.Translation((side * 1.05, 0, 0)))
for face in {f for v in made["verts"] for f in v.link_faces}:
for loop in face.loops:
loop[layer].uv = Vector((loop[layer].uv.x * 0.5 + (0.0 if side < 0 else 0.5), loop[layer].uv.y))
def plate(bm):
bmesh.ops.create_grid(bm, x_segments=2, y_segments=1, size=1.0, matrix=Matrix.Diagonal((2.0, 1.0, 1.0, 1.0)), calc_uvs=True)
import brokkr_mesh_polish as polish # noqa: E402 the fixture's bake uses the add-on's own occlusion, so the light is exactly what it can explain
twins = new_object("Twins", pair, new_image("twins_bake", np.ones((size, size, 3), dtype=np.float32)))
twins.data.polygons.foreach_set("use_smooth", [True] * len(twins.data.polygons))
twin = polish.arrays(twins)
twin_sky = polish.ambient_occlusion(twin["V"], twin["T"], twin["N"], 64, 0.35 * float(np.linalg.norm(twin["V"].max(axis=0) - twin["V"].min(axis=0))))
owner, bary, _ = polish.core.rasterize(twin["UV"], size)
sky_map = polish.core.interpolate(owner, bary, twin_sky[twin["T"]][..., None])[..., 0]
occluded, open_sky = (owner >= 0) & (sky_map < 0.6), (owner >= 0) & (sky_map > 0.95)
twin_bake = np.where((owner >= 0)[..., None], 0.8 * np.clip(sky_map, 0.05, 1.0)[..., None], 0.5) * np.ones((1, 1, 3))
flat = np.ones((size, size, 4), dtype=np.float32)
flat[..., :3] = twin_bake
bpy.data.images["twins_bake"].pixels.foreach_set(flat.reshape(-1))
receipt, unshadowed = send("brokkr_mesh_polish.delight", object_name="Twins", clusters=1, fit_size=256, occlusion_rays=64, max_gain=8)
twin_after, _ = pixels_of(twins)
shade_before = float(np.median(twin_bake[..., 0][occluded]) / np.median(twin_bake[..., 0][open_sky]))
shade_after = float(np.median(twin_after[..., 0][occluded]) / np.median(twin_after[..., 0][open_sky]))
R["occlusion"] = {"report": unshadowed, "occludedTexels": int(occluded.sum()), "shadeBefore": shade_before, "shadeAfter": shade_after}
# bound: shipped shadeAfter 1.000; with occlusion ignored (a sky of 1 everywhere) it stays 0.468: sqrt(1.000 * 0.468) = 0.684
check("delight: lifts occluded surface to the level of open surface", receipt["status"] == "accepted" and occluded.sum() > 500
and shade_before < SHADE_BOUND / 1.2 and shade_after > SHADE_BOUND * 1.2, R["occlusion"])
bpy.data.objects.remove(twins)
# --- orient: a turned slab is laid along Y, thin on Z, centred, scaled; nothing outside it moves -----------------
slab = new_object("Slab", lambda bm: bmesh.ops.create_cube(bm, size=1.0, matrix=Matrix.Diagonal((3.0, 1.0, 0.5, 1.0))))
slab.matrix_world = Matrix.Translation((4, 5, 6)) @ Matrix.Rotation(math.radians(37), 4, (0.3, 0.5, 0.8))
sphere.location = (20, 0, 0)
bpy.context.view_layer.update()
receipt, oriented = send("brokkr_mesh_polish.orient", object_name="Slab", length=12.0)
corners = np.array([slab.matrix_world @ v.co for v in slab.data.vertices])
extent = corners.max(axis=0) - corners.min(axis=0)
check("orient: long on Y, thin on Z, scaled to the length, centred",
receipt["status"] == "accepted" and np.allclose(extent, [4.0, 12.0, 2.0], atol=1e-3)
and np.allclose((corners.max(axis=0) + corners.min(axis=0)) / 2, 0, atol=1e-4), [list(map(float, extent)), oriented])
check("orient: reports the mirror error of a symmetric body as small", max(oriented["mirrorError"].values()) < 0.05, oriented["mirrorError"])
check("orient: an object outside the named root is not touched", oriented["objects"] == ["Slab"]
and np.allclose(sphere.matrix_world.translation, [20, 0, 0]) and abs(max(v.co.length for v in sphere.data.vertices) - 1.0) < 1e-5, oriented["objects"])
receipt, _ = send("brokkr_mesh_polish.orient", object_name="Nobody")
check("orient: an unknown root is refused", receipt["status"] == "failed", receipt["message"])
bpy.data.objects.remove(slab)
# --- cut_parts: a knob fused to a block is cut off at the crease, capped, and rooted at its cut -----------------
def knobbed(bm):
bmesh.ops.create_cube(bm, size=2.0)
top = next(f for f in bm.faces if f.normal.z > 0.9)
bmesh.ops.inset_region(bm, faces=[top], thickness=0.6)
extruded = bmesh.ops.extrude_face_region(bm, geom=[top])
bmesh.ops.translate(bm, verts=[g for g in extruded["geom"] if isinstance(g, bmesh.types.BMVert)], vec=(0, 0, 1.0))
bmesh.ops.delete(bm, geom=[top], context="FACES")
bmesh.ops.triangulate(bm, faces=bm.faces[:])
bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:])
sign = new_object("Sign", plate, new_image("sign_paint", panel)) # 4 x 2, flat on z = 0, u along x
sign.location = (40, 0, 5) # clear of the block
bpy.context.view_layer.update()
camera = bpy.data.objects.new("Eye", bpy.data.cameras.new("Eye"))
bpy.context.scene.collection.objects.link(camera)
camera.data.type = "ORTHO"
camera.data.ortho_scale = 4.0
camera.location = (40, 0, 9)
receipt, picked = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.25, v=0.5, resolution_x=400, resolution_y=200)
check("pick: names the surface point under (u, v) of a picture of that shape", receipt["status"] == "accepted" and picked["hit"]
and picked["object"] == "Sign" and np.allclose(picked["point"], [39.0, 0.0, 5.0], atol=1e-4), picked)
receipt, missed = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.5, v=0.99, resolution_x=200, resolution_y=400)
check("pick: off the surface is a miss, not an error", receipt["status"] == "accepted" and missed == {"hit": False}, missed)
block = new_object("Block", knobbed)
receipt, single = send("brokkr_mesh_polish.audit", object_name="Block")
check("cut fixture is one closed skin", single["Block"]["shells"] == 1 and single["Block"]["boundaryEdges"] == 0, single["Block"])
receipt, cut = send("brokkr_mesh_polish.cut_parts", object_name="Block", seeds="body=0,0,-1; knob=0,0,2", joint_scale=0.5)
R["cut"] = cut
check("cut_parts: accepted, one undo step, the fused object is replaced", receipt["status"] == "accepted" and bool(receipt.get("undoLabel"))
and "Block" not in bpy.data.objects and {"Block.body", "Block.knob"} <= set(bpy.data.objects.keys()), receipt["message"])
if receipt["status"] == "accepted":
knob, body = bpy.data.objects["Block.knob"], bpy.data.objects["Block.body"]
part = {entry["name"]: entry for entry in cut["parts"]}
check("cut_parts: the knob is cut at the crease and rooted at the centre of the cut",
np.allclose(part["Block.knob"]["root"], [0, 0, 1], atol=1e-5) and np.allclose(knob.matrix_world.translation, [0, 0, 1], atol=1e-5)
and abs(abs(part["Block.knob"]["cutNormal"][2]) - 1) < 1e-5, part["Block.knob"])
check("cut_parts: the knob hangs from the body and has not moved", knob.parent == body
and abs(max((knob.matrix_world @ v.co).z for v in knob.data.vertices) - 2.0) < 1e-5, None)
_, closed = send("brokkr_mesh_polish.audit")
check("cut_parts: both sides of the cut are capped (closed shells)",
all(closed[name]["boundaryEdges"] == 0 and closed[name]["shells"] == 1 for name in ("Block.body", "Block.knob")),
{name: [closed[name]["boundaryEdges"], closed[name]["shells"]] for name in ("Block.body", "Block.knob")})
capped = {o.name: sum(1 for polygon in o.data.polygons if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap") for o in (body, knob)}
check("cut_parts: exactly the cap faces carry the cap material", capped["Block.knob"] == part["Block.knob"]["capTriangles"] > 0
and capped["Block.body"] == part["Block.body"]["capTriangles"] > 0, capped)
cap_normals = {o.name: [polygon.normal.z for polygon in o.data.polygons
if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap"] for o in (body, knob)}
check("cut_parts: each cap faces out of its own part, and no old face was turned",
all(z < -0.9 for z in cap_normals["Block.knob"]) and all(z > 0.9 for z in cap_normals["Block.body"])
and closed["Block.body"]["windingAgainstNormals"] == 0 and closed["Block.knob"]["windingAgainstNormals"] == 0, cap_normals)
check("cut_parts: a joint sits at the root", "Polish Cap" in [getattr(m, "name", "") for m in knob.data.materials]
and np.allclose(bpy.data.objects[part["Block.knob"]["joint"]].matrix_world.translation, [0, 0, 1], atol=1e-5), part["Block.knob"].get("joint"))
# orient after the cut: the body and what hangs from it turn as one; the knob keeps its parent and its pivot
receipt, turned_parts = send("brokkr_mesh_polish.orient", object_name="Block.body", length=6.0)
pivot = knob.matrix_world.translation
reach = max(abs((knob.matrix_world @ v.co).y) for v in knob.data.vertices)
R["orientParts"] = {"report": turned_parts, "knobPivot": list(pivot), "knobReach": reach, "parent": knob.parent.name if knob.parent else None}
# the 2 x 2 x 3 body-and-knob is laid along Y and doubled: the cut centre (0, 0, 1), half a unit above the middle, lands 1 along Y
check("orient: after a cut the parts keep their parent and their pivot at the cut", receipt["status"] == "accepted" and knob.parent == body
and abs(abs(pivot.y) - 1.0) < 1e-4 and abs(pivot.x) < 1e-4 and abs(pivot.z) < 1e-4 and abs(reach - 3.0) < 1e-4
and np.allclose(np.array(knob.matrix_world.to_3x3()), np.eye(3), atol=1e-6), R["orientParts"])
receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Block.body", seeds="only=0,0,-1")
check("cut_parts: one part is refused with nothing changed", receipt["status"] == "failed" and "Block.body" in bpy.data.objects, receipt["message"])
def ink(pixels):
return np.linalg.norm(pixels - [0.1, 0.35, 0.4], axis=-1) > 0.25
# --- cut_parts through: a seed on one face of a thin plate also holds the face behind it -----------------------
def plate_body(bm):
bmesh.ops.create_cube(bm, size=2.0, matrix=Matrix.Diagonal((1.0, 1.0, 0.05, 1.0))) # 2 x 2 x 0.1
bmesh.ops.subdivide_edges(bm, edges=bm.edges[:], cuts=7, use_grid_fill=True)
bmesh.ops.triangulate(bm, faces=bm.faces[:])
receipt, scrubbed = send("brokkr_mesh_polish.scrub_markings", object_name="Sign", x=picked["point"][0], y=0.0, z=5.0, radius=0.5, tolerance=0.25)
after, image = pixels_of(sign)
inside = np.zeros((128, 128), dtype=bool)
inside[48:80, 20:44] = True # well within the sphere: u 0.25 +- 0.09, v 0.5 +- 0.12
far = np.zeros((128, 128), dtype=bool)
far[:, 72:] = True # the other half of the sign
R["scrub"] = {"report": scrubbed, "inkInsideBefore": int(ink(panel)[inside].sum()), "inkInsideAfter": int(ink(after)[inside].sum())}
check("scrub_markings: accepted, the lettering inside the sphere is gone", receipt["status"] == "accepted"
and ink(panel)[inside].sum() > 100 and ink(after)[inside].sum() == 0, R["scrub"])
check("scrub_markings: nothing outside the sphere is touched (to the 8 bits the image stores)", np.allclose(after[far], panel[far], atol=0.6 / 255) and image.name == "sign_paint.scrubbed", image.name)
receipt, _ = send("brokkr_mesh_polish.scrub_markings", object_name="Sign", x=50.0, y=0.0, z=0.0, radius=0.5)
check("scrub_markings: a sphere off the surface is refused", receipt["status"] == "failed", receipt["message"])
receipt, _ = send("brokkr_mesh_polish.delight", object_name="Sign", max_gain=9)
check("a bound miss is denied by Brokkr's table before the operator runs", receipt["status"] == "denied", receipt["message"])
def underside(name):
"""Triangles of the part that face down and are surface, not cap."""
part_object = bpy.data.objects[name]
return sum(1 for polygon in part_object.data.polygons
if polygon.normal.z < -0.9 and getattr(part_object.data.materials[polygon.material_index], "name", "") != "Polish Cap")
# --- real generated hulls, when a directory of .glb files is given: repair must turn none of their faces ---------
HULLS = os.environ.get("BROKKR_POLISH_HULLS", "")
R["hulls"] = {}
for path in sorted(Path(HULLS).glob("*.glb")) if HULLS else []:
known = set(bpy.data.objects.keys())
bpy.ops.import_scene.gltf(filepath=str(path))
for hull in [o for o in bpy.data.objects if o.name not in known and o.type == "MESH"]:
was = polygon_normals(hull.data)
_, raw = send("brokkr_mesh_polish.audit", object_name=hull.name)
against = raw[hull.name]["windingAgainstNormals"]
receipt, mended = send("brokkr_mesh_polish.repair", object_name=hull.name)
now = polygon_normals(hull.data)
turned = int(((was * now).sum(axis=1) < 0).sum()) if len(was) == len(now) else None
R["hulls"][path.name] = {"polygons": len(was), "polygonsAfter": len(now), "turned": turned, "againstBefore": against,
"againstAfter": mended["after"]["windingAgainstNormals"], "changes": mended["changes"]}
check(f"hull {path.name}: repair turns no face and keeps the shading normals' sides", receipt["status"] == "accepted"
and mended["changes"]["windingFlipped"] == 0 and turned in (0, None) # None: faces were removed, so indices no longer pair
and 0 <= against - mended["after"]["windingAgainstNormals"] <= len(was) - len(now), R["hulls"][path.name])
bpy.data.objects.remove(hull)
R["through"] = {}
for label, through in (("without", 0.0), ("with", 0.1)):
new_object("Plate", plate_body)
# by distance alone (no crease cost) the underside's middle is nearer the body's seed, at an underside corner,
# than the lid's seed on top, which must go round the rim; a ray inward from the lid's seed finds it at once
receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Plate", seeds="body=-0.9,-0.9,-0.05; lid=0,0,0.05", crease_cost=0, through=through)
R["through"][label] = underside("Plate.lid") if receipt["status"] == "accepted" else None
for leftover in [o for o in bpy.data.objects if o.name.startswith("Plate")]:
bpy.data.objects.remove(leftover)
check("cut_parts: through seeds the far face of a thin part", R["through"]["without"] == 0 and (R["through"]["with"] or 0) >= 8, R["through"])
# --- pick and scrub_markings: lettering on one panel is found from a camera and painted out ----------------------
panel = np.full((128, 128, 3), [0.1, 0.35, 0.4], dtype=np.float32)
panel += np.random.default_rng(0).normal(0, 0.01, panel.shape).astype(np.float32)
for column_start in range(8, 120, 8): # yellow strokes over the whole texture
panel[:, column_start:column_start + 2] = [0.85, 0.75, 0.2]
def plate(bm):
bmesh.ops.create_grid(bm, x_segments=2, y_segments=1, size=1.0, matrix=Matrix.Diagonal((2.0, 1.0, 1.0, 1.0)), calc_uvs=True)
sign = new_object("Sign", plate, new_image("sign_paint", panel)) # 4 x 2, flat on z = 0, u along x
sign.location = (40, 0, 5) # clear of the block
bpy.context.view_layer.update()
camera = bpy.data.objects.new("Eye", bpy.data.cameras.new("Eye"))
bpy.context.scene.collection.objects.link(camera)
camera.data.type = "ORTHO"
camera.data.ortho_scale = 4.0
camera.location = (40, 0, 9)
receipt, picked = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.25, v=0.5, resolution_x=400, resolution_y=200)
check("pick: names the surface point under (u, v) of a picture of that shape", receipt["status"] == "accepted" and picked["hit"]
and picked["object"] == "Sign" and np.allclose(picked["point"], [39.0, 0.0, 5.0], atol=1e-4), picked)
receipt, missed = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.5, v=0.99, resolution_x=200, resolution_y=400)
check("pick: off the surface is a miss, not an error", receipt["status"] == "accepted" and missed == {"hit": False}, missed)
def ink(pixels):
return np.linalg.norm(pixels - [0.1, 0.35, 0.4], axis=-1) > 0.25
receipt, scrubbed = send("brokkr_mesh_polish.scrub_markings", object_name="Sign", x=picked["point"][0], y=0.0, z=5.0, radius=0.5, tolerance=0.25)
after, image = pixels_of(sign)
inside = np.zeros((128, 128), dtype=bool)
inside[48:80, 20:44] = True # well within the sphere: u 0.25 +- 0.09, v 0.5 +- 0.12
far = np.zeros((128, 128), dtype=bool)
far[:, 72:] = True # the other half of the sign
R["scrub"] = {"report": scrubbed, "inkInsideBefore": int(ink(panel)[inside].sum()), "inkInsideAfter": int(ink(after)[inside].sum())}
check("scrub_markings: accepted, the lettering inside the sphere is gone", receipt["status"] == "accepted"
and ink(panel)[inside].sum() > 100 and ink(after)[inside].sum() == 0, R["scrub"])
check("scrub_markings: nothing outside the sphere is touched (to the 8 bits the image stores)", np.allclose(after[far], panel[far], atol=0.6 / 255) and image.name == "sign_paint.scrubbed", image.name)
receipt, _ = send("brokkr_mesh_polish.scrub_markings", object_name="Sign", x=50.0, y=0.0, z=0.0, radius=0.5)
check("scrub_markings: a sphere off the surface is refused", receipt["status"] == "failed", receipt["message"])
receipt, _ = send("brokkr_mesh_polish.delight", object_name="Sign", max_gain=9)
check("a bound miss is denied by Brokkr's table before the operator runs", receipt["status"] == "denied", receipt["message"])
# --- real generated hulls, when a directory of .glb files is given: repair must turn none of their faces ---------
HULLS = os.environ.get("BROKKR_POLISH_HULLS", "")
R["hulls"] = {}
for path in sorted(Path(HULLS).glob("*.glb")) if HULLS else []:
known = set(bpy.data.objects.keys())
bpy.ops.import_scene.gltf(filepath=str(path))
for hull in [o for o in bpy.data.objects if o.name not in known and o.type == "MESH"]:
was = polygon_normals(hull.data)
_, raw = send("brokkr_mesh_polish.audit", object_name=hull.name)
against = raw[hull.name]["windingAgainstNormals"]
receipt, mended = send("brokkr_mesh_polish.repair", object_name=hull.name)
now = polygon_normals(hull.data)
turned = int(((was * now).sum(axis=1) < 0).sum()) if len(was) == len(now) else None
R["hulls"][path.name] = {"polygons": len(was), "polygonsAfter": len(now), "turned": turned, "againstBefore": against,
"againstAfter": mended["after"]["windingAgainstNormals"], "changes": mended["changes"]}
check(f"hull {path.name}: repair turns no face and keeps the shading normals' sides", receipt["status"] == "accepted"
and mended["changes"]["windingFlipped"] == 0 and turned in (0, None) # None: faces were removed, so indices no longer pair
and 0 <= against - mended["after"]["windingAgainstNormals"] <= len(was) - len(now), R["hulls"][path.name])
bpy.data.objects.remove(hull)
except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file
check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:])
R["ok"] = all(c["ok"] for c in R["checks"])
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
for c in R["checks"]:
print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True)
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
sys.exit(0 if R["ok"] else 1)

View file

@ -125,7 +125,7 @@
"undoLabel": "Brokkr test/driver: brokkr_mesh_polish.repair live-2",
"lookPath": "",
"hostResult": "{\"object\":\"Ball\",\"changes\":{\"welded\":3406,\"facesCollapsedByWeld\":0,\"degenerateFacesRemoved\":0,\"looseEdgesRemoved\":0,\"looseVertsRemoved\":0,\"shellsRemoved\":0,\"holesFilled\":0,\"windingFlipped\":0,\"customNormalsDropped\":false},\"before\":{\"triangles\":2208,\"vertices\":4512,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1,\"windingAgainstNormals\":1104},\"after\":{\"triangles\":2208,\"vertices\":1106,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1,\"windingAgainstNormals\":1104}}",
"observedAt": "2026-12-01T01:10:29.202522+00:00"
"observedAt": "2026-12-02T12:26:00.225314+00:00"
}
},
{
@ -231,21 +231,21 @@
"Ball"
],
"explainedByLight": {
"before": 0.9718638595466577,
"after": 0.0005166823179215685
"before": 0.9718639234640993,
"after": 0.0005166608648451421
},
"before": {
"upDownLuminanceRatio": 2.562451830544031,
"occlusionCorrelation": 0.0
},
"after": {
"upDownLuminanceRatio": 1.0166067038538378,
"upDownLuminanceRatio": 1.016606182115671,
"occlusionCorrelation": 0.0
},
"gain": {
"min": 0.9857558709602762,
"median": 1.457103285957073,
"max": 3.0649151172981792,
"min": 0.9857558916878914,
"median": 1.4570992824185989,
"max": 3.0649098409031676,
"clamped": 0.0
}
}
@ -374,21 +374,21 @@
"Twins"
],
"explainedByLight": {
"before": 0.9999597575085393,
"after": 0.028075104342772272
"before": 0.9999597575085377,
"after": 0.02807510434956728
},
"before": {
"upDownLuminanceRatio": 1.0000084632254227,
"occlusionCorrelation": 0.983967648279407
},
"after": {
"upDownLuminanceRatio": 0.9999964767503613,
"occlusionCorrelation": 0.40471079036691976
"upDownLuminanceRatio": 0.9999964767498971,
"occlusionCorrelation": 0.4047107903548106
},
"gain": {
"min": 0.9999809983875252,
"median": 1.0000990920451596,
"max": 5.493916964800697,
"min": 0.9999809983877584,
"median": 1.0000990920471027,
"max": 5.493916964801517,
"clamped": 0.0
}
},
@ -572,9 +572,9 @@
5.656854
],
"mirrorError": {
"X": 1.8120748396336225e-08,
"X": 1.8120748396474917e-08,
"Y": 0.1508370330678463,
"Z": 1.8363068583553207e-08
"Z": 1.836306858237196e-08
}
},
"knobPivot": [
@ -653,72 +653,6 @@
"name": "a bound miss is denied by Brokkr's table before the operator runs",
"ok": true,
"detail": "max_gain must be between 1 and 8."
},
{
"name": "hull fourth.glb: repair turns no face and keeps the shading normals' sides",
"ok": true,
"detail": {
"polygons": 28426,
"polygonsAfter": 28420,
"turned": null,
"againstBefore": 388,
"againstAfter": 387,
"changes": {
"welded": 6437,
"facesCollapsedByWeld": 2,
"degenerateFacesRemoved": 4,
"looseEdgesRemoved": 0,
"looseVertsRemoved": 0,
"shellsRemoved": 0,
"holesFilled": 0,
"windingFlipped": 0,
"customNormalsDropped": false
}
}
},
{
"name": "hull sub.glb: repair turns no face and keeps the shading normals' sides",
"ok": true,
"detail": {
"polygons": 10406,
"polygonsAfter": 10406,
"turned": 0,
"againstBefore": 64,
"againstAfter": 64,
"changes": {
"welded": 2454,
"facesCollapsedByWeld": 0,
"degenerateFacesRemoved": 0,
"looseEdgesRemoved": 0,
"looseVertsRemoved": 0,
"shellsRemoved": 0,
"holesFilled": 0,
"windingFlipped": 0,
"customNormalsDropped": false
}
}
},
{
"name": "hull third.glb: repair turns no face and keeps the shading normals' sides",
"ok": true,
"detail": {
"polygons": 23341,
"polygonsAfter": 23340,
"turned": null,
"againstBefore": 189,
"againstAfter": 189,
"changes": {
"welded": 3810,
"facesCollapsedByWeld": 0,
"degenerateFacesRemoved": 1,
"looseEdgesRemoved": 0,
"looseVertsRemoved": 0,
"shellsRemoved": 0,
"holesFilled": 0,
"windingFlipped": 0,
"customNormalsDropped": false
}
}
}
],
"hostErrors": [],
@ -744,21 +678,21 @@
"Ball"
],
"explainedByLight": {
"before": 0.9718638595466577,
"after": 0.0005166823179215685
"before": 0.9718639234640993,
"after": 0.0005166608648451421
},
"before": {
"upDownLuminanceRatio": 2.562451830544031,
"occlusionCorrelation": 0.0
},
"after": {
"upDownLuminanceRatio": 1.0166067038538378,
"upDownLuminanceRatio": 1.016606182115671,
"occlusionCorrelation": 0.0
},
"gain": {
"min": 0.9857558709602762,
"median": 1.457103285957073,
"max": 3.0649151172981792,
"min": 0.9857558916878914,
"median": 1.4570992824185989,
"max": 3.0649098409031676,
"clamped": 0.0
}
},
@ -804,21 +738,21 @@
"Twins"
],
"explainedByLight": {
"before": 0.9999597575085393,
"after": 0.028075104342772272
"before": 0.9999597575085377,
"after": 0.02807510434956728
},
"before": {
"upDownLuminanceRatio": 1.0000084632254227,
"occlusionCorrelation": 0.983967648279407
},
"after": {
"upDownLuminanceRatio": 0.9999964767503613,
"occlusionCorrelation": 0.40471079036691976
"upDownLuminanceRatio": 0.9999964767498971,
"occlusionCorrelation": 0.4047107903548106
},
"gain": {
"min": 0.9999809983875252,
"median": 1.0000990920451596,
"max": 5.493916964800697,
"min": 0.9999809983877584,
"median": 1.0000990920471027,
"max": 5.493916964801517,
"clamped": 0.0
}
},
@ -880,9 +814,9 @@
5.656854
],
"mirrorError": {
"X": 1.8120748396336225e-08,
"X": 1.8120748396474917e-08,
"Y": 0.1508370330678463,
"Z": 1.8363068583553207e-08
"Z": 1.836306858237196e-08
}
},
"knobPivot": [
@ -908,61 +842,6 @@
"inkInsideBefore": 192,
"inkInsideAfter": 0
},
"hulls": {
"fourth.glb": {
"polygons": 28426,
"polygonsAfter": 28420,
"turned": null,
"againstBefore": 388,
"againstAfter": 387,
"changes": {
"welded": 6437,
"facesCollapsedByWeld": 2,
"degenerateFacesRemoved": 4,
"looseEdgesRemoved": 0,
"looseVertsRemoved": 0,
"shellsRemoved": 0,
"holesFilled": 0,
"windingFlipped": 0,
"customNormalsDropped": false
}
},
"sub.glb": {
"polygons": 10406,
"polygonsAfter": 10406,
"turned": 0,
"againstBefore": 64,
"againstAfter": 64,
"changes": {
"welded": 2454,
"facesCollapsedByWeld": 0,
"degenerateFacesRemoved": 0,
"looseEdgesRemoved": 0,
"looseVertsRemoved": 0,
"shellsRemoved": 0,
"holesFilled": 0,
"windingFlipped": 0,
"customNormalsDropped": false
}
},
"third.glb": {
"polygons": 23341,
"polygonsAfter": 23340,
"turned": null,
"againstBefore": 189,
"againstAfter": 189,
"changes": {
"welded": 3810,
"facesCollapsedByWeld": 0,
"degenerateFacesRemoved": 1,
"looseEdgesRemoved": 0,
"looseVertsRemoved": 0,
"shellsRemoved": 0,
"holesFilled": 0,
"windingFlipped": 0,
"customNormalsDropped": false
}
}
},
"hulls": {},
"ok": true
}

View file

@ -7,7 +7,9 @@ as a GLB the exporter hook has given VRMC_springBone. Not part of the unittest r
Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses
without them). Writes <out>.result.json and <out>.glb (the synthetic whale's rig, for the runtime's own parse,
Aetheria SpringRigVerify.VerifyGlb) and exits 1 when a check failed. The acceptance is the runtime's parse, not
Aetheria SpringRigVerify.VerifyGlb) and exits 1 when a check failed. The checks run inside one try: an uncaught error is a failed check that names
the check before it, the checks are printed and the result file written whatever happened, and the exit is 1 with or
without --python-exit-code. The acceptance is the runtime's parse, not
anything here: the structure checks below are what this builder promised, not the runtime's rules.
"""
import json
@ -15,6 +17,7 @@ import math
import os
import struct
import sys
import traceback
import tempfile
import time
import types
@ -56,6 +59,10 @@ T0 = time.time()
def check(name, ok, detail=None):
try:
json.dumps(detail, default=str)
except TypeError: # a detail keyed by tuples: the result file takes it as text, so a failed check is written and not a crash
detail = repr(detail)
R["checks"].append({"name": name, "ok": bool(ok), "detail": detail})
@ -153,186 +160,189 @@ def world_of(nodes, parent, i):
return out
whale = make_whale()
check("host file admitted", not R["hostErrors"] and {"brokkr_rig.body", "brokkr_rig.tendrils", "brokkr_rig.colliders"} <= set(R["hostRows"]),
R["hostErrors"] or R["hostRows"])
whale.rotation_euler = (0.0, 0.0, math.radians(90)) # lying along x with a non-identity transform and an offset
whale.location = (0.4, -0.2, 0.1)
bpy.context.view_layer.update()
receipt, audit = send("brokkr_mesh_polish.audit", object_name="Whale")
R["audit"] = audit
check("fixture: one fused shell and a detached bead", audit and audit["Whale"]["shells"] == 2, audit)
receipt, _ = send("brokkr_mesh_polish.repair", object_name="Whale")
check("repair accepted", receipt["status"] == "accepted", receipt["message"])
receipt, oriented = send("brokkr_mesh_polish.orient", object_name="Whale", length=1.0)
check("orient accepted", receipt["status"] == "accepted", receipt["message"])
receipt, body = send("brokkr_rig.body", object_name="Whale", spine_bones=6, head="+y", seeds="jaw=0,0.45,0.05", smooth_rounds=2)
check("body accepted", receipt["status"] == "accepted", receipt["message"])
R["body"] = body
if body:
arm = bpy.data.objects[body["armature"]]
check("body: a spine of six, a jaw bone parented to a spine bone", body["spine"] == [f"spine_{i:02d}" for i in range(6)]
and [p["name"] for p in body["parts"]] == ["jaw"] and body["parts"][0]["triangles"] > 0
and arm.data.bones["jaw"].parent.name in body["spine"], body["parts"])
head, tail = np.array(body["head"]), np.array(body["tail"])
check("body: the root bone is at the +y end and the object's transform is baked", head[1] > tail[1]
and np.allclose(np.array(whale.matrix_world), np.eye(4), atol=1e-9) and arm.data.bones["spine_00"].parent is None, [head, tail])
receipt, tendrils = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01)
check("tendrils accepted", receipt["status"] == "accepted", receipt["message"])
R["tendrils"] = tendrils
if tendrils:
check("tendrils: five chains (the vein folded), the fork made one chain with a rigid branch, the bead attached",
tendrils["chains"] == 5 and tendrils["veinsFolded"] >= 1 and tendrils["branchesRigid"] >= 1 and tendrils["shellsAttached"] >= 1, tendrils)
receipt, colliders = send("brokkr_rig.colliders", object_name="Whale")
check("colliders accepted", receipt["status"] == "accepted", receipt["message"])
R["colliders"] = colliders
try:
whale = make_whale()
check("host file admitted", not R["hostErrors"] and {"brokkr_rig.body", "brokkr_rig.tendrils", "brokkr_rig.colliders"} <= set(R["hostRows"]),
R["hostErrors"] or R["hostRows"])
whale.rotation_euler = (0.0, 0.0, math.radians(90)) # lying along x with a non-identity transform and an offset
whale.location = (0.4, -0.2, 0.1)
bpy.context.view_layer.update()
receipt, audit = send("brokkr_mesh_polish.audit", object_name="Whale")
R["audit"] = audit
check("fixture: one fused shell and a detached bead", audit and audit["Whale"]["shells"] == 2, audit)
receipt, _ = send("brokkr_mesh_polish.repair", object_name="Whale")
check("repair accepted", receipt["status"] == "accepted", receipt["message"])
receipt, oriented = send("brokkr_mesh_polish.orient", object_name="Whale", length=1.0)
check("orient accepted", receipt["status"] == "accepted", receipt["message"])
receipt, body = send("brokkr_rig.body", object_name="Whale", spine_bones=6, head="+y", seeds="jaw=0,0.45,0.05", smooth_rounds=2)
check("body accepted", receipt["status"] == "accepted", receipt["message"])
R["body"] = body
if body:
arm = bpy.data.objects[body["armature"]]
check("body: a spine of six, a jaw bone parented to a spine bone", body["spine"] == [f"spine_{i:02d}" for i in range(6)]
and [p["name"] for p in body["parts"]] == ["jaw"] and body["parts"][0]["triangles"] > 0
and arm.data.bones["jaw"].parent.name in body["spine"], body["parts"])
head, tail = np.array(body["head"]), np.array(body["tail"])
check("body: the root bone is at the +y end and the object's transform is baked", head[1] > tail[1]
and np.allclose(np.array(whale.matrix_world), np.eye(4), atol=1e-9) and arm.data.bones["spine_00"].parent is None, [head, tail])
receipt, tendrils = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01)
check("tendrils accepted", receipt["status"] == "accepted", receipt["message"])
R["tendrils"] = tendrils
if tendrils:
check("tendrils: five chains (the vein folded), the fork made one chain with a rigid branch, the bead attached",
tendrils["chains"] == 5 and tendrils["veinsFolded"] >= 1 and tendrils["branchesRigid"] >= 1 and tendrils["shellsAttached"] >= 1, tendrils)
receipt, colliders = send("brokkr_rig.colliders", object_name="Whale")
check("colliders accepted", receipt["status"] == "accepted", receipt["message"])
R["colliders"] = colliders
def skin_state():
"""Every vertex's (group name, weight) pairs and every chain bone's properties, exactly as stored."""
groups = [g.name for g in whale.vertex_groups]
weights = [sorted((groups[e.group], e.weight) for e in v.groups) for v in whale.data.vertices]
props = {b.name: [b[k] for k in ("rig_chain", "rig_index", "rig_stiffness", "rig_drag", "rig_gravity", "rig_hit_radius")]
for b in arm.data.bones if "rig_chain" in b}
return weights, props
def skin_state():
"""Every vertex's (group name, weight) pairs and every chain bone's properties, exactly as stored."""
groups = [g.name for g in whale.vertex_groups]
weights = [sorted((groups[e.group], e.weight) for e in v.groups) for v in whale.data.vertices]
props = {b.name: [b[k] for k in ("rig_chain", "rig_index", "rig_stiffness", "rig_drag", "rig_gravity", "rig_hit_radius")]
for b in arm.data.bones if "rig_chain" in b}
return weights, props
first = skin_state()
send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.06, dilate=0.02)
other = skin_state()
receipt, again = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01)
check("tendrils with other knobs changes the skin", other != first, None)
check("tendrils, other knobs, then the first knobs again restores the weights and bone properties exactly", skin_state() == first, None)
check("the tendrils report says what it sees", tendrils and {"warnings", "largestChainShare", "chainVertexShare", "fusedContacts"} <= set(tendrils)
and len(tendrils["warnings"]) == 1 and "one chain holds" in tendrils["warnings"][0], tendrils) # five chains hold 13% each at most: hull-like by the gauge
receipt, colliders = send("brokkr_rig.colliders", object_name="Whale")
check("the colliders report lists each shrink and the largest share taken", colliders and colliders["shrunk"] > 0
and len(colliders["shrinks"]) == colliders["shrunk"] and all(x["after"] < x["before"] for x in colliders["shrinks"])
and abs(colliders["shrunkMax"] - max(1 - x["after"] / x["before"] for x in colliders["shrinks"])) < 1e-3, colliders)
R["colliders"] = colliders
first = skin_state()
send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.06, dilate=0.02)
other = skin_state()
receipt, again = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01)
check("tendrils with other knobs changes the skin", other != first, None)
check("tendrils, other knobs, then the first knobs again restores the weights and bone properties exactly", skin_state() == first, None)
check("the tendrils report says what it sees", tendrils and {"warnings", "largestChainShare", "chainVertexShare", "fusedContacts"} <= set(tendrils)
and len(tendrils["warnings"]) == 1 and "one chain holds" in tendrils["warnings"][0], tendrils) # five chains hold 13% each at most: hull-like by the gauge
receipt, colliders = send("brokkr_rig.colliders", object_name="Whale")
check("the colliders report lists each shrink and the largest share taken", colliders and colliders["shrunk"] > 0
and len(colliders["shrinks"]) == colliders["shrunk"] and all(x["after"] < x["before"] for x in colliders["shrinks"])
and abs(colliders["shrunkMax"] - max(1 - x["after"] / x["before"] for x in colliders["shrinks"])) < 1e-3, colliders)
R["colliders"] = colliders
# --- export: the five attributes, weights, extension, structure ----------------------------------------------------
receipt, _ = send("exportGltf", filepath="whale.glb", extras=False, yUp=True, applyModifiers=True)
check("exportGltf accepted", receipt["status"] == "accepted", receipt["message"])
gltf, blob, bin_at = glb_json(WORK / "whale.glb")
ext = gltf.get("extensions", {}).get("VRMC_springBone")
check("VRMC_springBone is in extensions and extensionsUsed", ext is not None and "VRMC_springBone" in gltf.get("extensionsUsed", []), list(gltf.get("extensions", {})))
if ext and tendrils and colliders:
check("the springs, joints and colliders are the built ones", len(ext["springs"]) == tendrils["chains"]
and sum(len(s["joints"]) for s in ext["springs"]) == tendrils["springBones"]
and len(ext["colliders"]) == colliders["capsules"] + colliders["spheres"]
and all(s["colliderGroups"] == [0] for s in ext["springs"]) and [g["name"] for g in ext["colliderGroups"]] == ["body"],
[len(ext["springs"]), len(ext["colliders"])])
check("the extension is not required", "VRMC_springBone" not in gltf.get("extensionsRequired", []), gltf.get("extensionsRequired"))
if ext:
check("stiffness tapers from the root's 3 to the tip's 1.5 and hit radii are half a tube's diameter or less",
all(abs(s["joints"][0]["stiffness"] - 3.0) < 1e-6 and abs(s["joints"][-1]["stiffness"] - 1.5) < 1e-6
and all(0 <= j["hitRadius"] <= 0.016 for j in s["joints"]) for s in ext["springs"]),
[[j["stiffness"] for j in ext["springs"][0]["joints"]], [j["hitRadius"] for j in ext["springs"][0]["joints"]]])
prims = [p for m in gltf["meshes"] for p in m["primitives"]]
check("mesh primitives carry exactly the five attributes", all(set(p["attributes"]) == {"POSITION", "NORMAL", "TEXCOORD_0", "JOINTS_0", "WEIGHTS_0"} for p in prims),
[sorted(p["attributes"]) for p in prims])
worst_sum, worst_count = 0.0, 0
for p in prims:
if "WEIGHTS_0" not in p["attributes"]:
check("every primitive is skinned", False, sorted(p["attributes"]))
continue
acc = gltf["accessors"][p["attributes"]["WEIGHTS_0"]]
view = gltf["bufferViews"][acc["bufferView"]]
W = np.frombuffer(blob, np.float32, acc["count"] * 4, bin_at + view.get("byteOffset", 0) + acc.get("byteOffset", 0)).reshape(-1, 4)
worst_sum = max(worst_sum, float(np.abs(W.sum(axis=1) - 1).max()))
worst_count = max(worst_count, int((W > 0).sum(axis=1).max()))
check("weights sum to 1 with at most four influences", worst_sum < 1e-5 and worst_count <= 4, [worst_sum, worst_count])
nodes = gltf["nodes"]
parent = {c: i for i, n in enumerate(nodes) for c in n.get("children", [])}
check("no node carries a matrix and every scale is 1", all("matrix" not in n and all(abs(s - 1) < 1e-4 for s in n.get("scale", (1, 1, 1))) for n in nodes), None)
joints = gltf["skins"][0]["joints"]
check("one skin over every bone", len(gltf["skins"]) == 1 and len(joints) == len(arm.data.bones), [len(joints), len(arm.data.bones)])
if ext:
in_spring = {j["node"] for s in ext["springs"] for j in s["joints"]}
linear = all(parent.get(s["joints"][0]["node"]) in set(joints) - in_spring and all(parent[s["joints"][k]["node"]] == s["joints"][k - 1]["node"] for k in range(1, len(s["joints"])))
for s in ext["springs"])
check("each spring is a linear chain, its first joint hung from a body bone, no bone in two springs", linear
and len(in_spring) == sum(len(s["joints"]) for s in ext["springs"]), None)
check("every segment has length", all(np.linalg.norm(nodes[j["node"]].get("translation", (0, 0, 0))) > 1e-6 for s in ext["springs"] for j in s["joints"][1:]), None)
check("colliders sit on body bones", all(c["node"] in set(joints) - in_spring for c in ext["colliders"]), None)
swing = np.array([[1.0, 0, 0], [0, 0, 1.0], [0, -1.0, 0]])
where = [world_of(nodes, parent, j["node"])[:3, 3] for s in ext["springs"] for j in s["joints"]]
expect = [swing @ np.array(arm.matrix_world @ arm.data.bones[nodes[j["node"]]["name"]].head_local) for s in ext["springs"] for j in s["joints"]]
check("every joint's node stands where its bone's head is in the scene", np.allclose(where, expect, atol=1e-4), float(np.abs(np.array(where) - np.array(expect)).max()))
R["glb"] = {"nodes": len(nodes), "joints": len(joints), "springs": len(ext["springs"]) if ext else 0, "colliders": len(ext["colliders"]) if ext else 0}
Path(OUT + ".glb").write_bytes((WORK / "whale.glb").read_bytes())
# --- export: the five attributes, weights, extension, structure ----------------------------------------------------
receipt, _ = send("exportGltf", filepath="whale.glb", extras=False, yUp=True, applyModifiers=True)
check("exportGltf accepted", receipt["status"] == "accepted", receipt["message"])
gltf, blob, bin_at = glb_json(WORK / "whale.glb")
ext = gltf.get("extensions", {}).get("VRMC_springBone")
check("VRMC_springBone is in extensions and extensionsUsed", ext is not None and "VRMC_springBone" in gltf.get("extensionsUsed", []), list(gltf.get("extensions", {})))
if ext and tendrils and colliders:
check("the springs, joints and colliders are the built ones", len(ext["springs"]) == tendrils["chains"]
and sum(len(s["joints"]) for s in ext["springs"]) == tendrils["springBones"]
and len(ext["colliders"]) == colliders["capsules"] + colliders["spheres"]
and all(s["colliderGroups"] == [0] for s in ext["springs"]) and [g["name"] for g in ext["colliderGroups"]] == ["body"],
[len(ext["springs"]), len(ext["colliders"])])
check("the extension is not required", "VRMC_springBone" not in gltf.get("extensionsRequired", []), gltf.get("extensionsRequired"))
if ext:
check("stiffness tapers from the root's 3 to the tip's 1.5 and hit radii are half a tube's diameter or less",
all(abs(s["joints"][0]["stiffness"] - 3.0) < 1e-6 and abs(s["joints"][-1]["stiffness"] - 1.5) < 1e-6
and all(0 <= j["hitRadius"] <= 0.016 for j in s["joints"]) for s in ext["springs"]),
[[j["stiffness"] for j in ext["springs"][0]["joints"]], [j["hitRadius"] for j in ext["springs"][0]["joints"]]])
prims = [p for m in gltf["meshes"] for p in m["primitives"]]
check("mesh primitives carry exactly the five attributes", all(set(p["attributes"]) == {"POSITION", "NORMAL", "TEXCOORD_0", "JOINTS_0", "WEIGHTS_0"} for p in prims),
[sorted(p["attributes"]) for p in prims])
worst_sum, worst_count = 0.0, 0
for p in prims:
if "WEIGHTS_0" not in p["attributes"]:
check("every primitive is skinned", False, sorted(p["attributes"]))
continue
acc = gltf["accessors"][p["attributes"]["WEIGHTS_0"]]
view = gltf["bufferViews"][acc["bufferView"]]
W = np.frombuffer(blob, np.float32, acc["count"] * 4, bin_at + view.get("byteOffset", 0) + acc.get("byteOffset", 0)).reshape(-1, 4)
worst_sum = max(worst_sum, float(np.abs(W.sum(axis=1) - 1).max()))
worst_count = max(worst_count, int((W > 0).sum(axis=1).max()))
check("weights sum to 1 with at most four influences", worst_sum < 1e-5 and worst_count <= 4, [worst_sum, worst_count])
nodes = gltf["nodes"]
parent = {c: i for i, n in enumerate(nodes) for c in n.get("children", [])}
check("no node carries a matrix and every scale is 1", all("matrix" not in n and all(abs(s - 1) < 1e-4 for s in n.get("scale", (1, 1, 1))) for n in nodes), None)
joints = gltf["skins"][0]["joints"]
check("one skin over every bone", len(gltf["skins"]) == 1 and len(joints) == len(arm.data.bones), [len(joints), len(arm.data.bones)])
if ext:
in_spring = {j["node"] for s in ext["springs"] for j in s["joints"]}
linear = all(parent.get(s["joints"][0]["node"]) in set(joints) - in_spring and all(parent[s["joints"][k]["node"]] == s["joints"][k - 1]["node"] for k in range(1, len(s["joints"])))
for s in ext["springs"])
check("each spring is a linear chain, its first joint hung from a body bone, no bone in two springs", linear
and len(in_spring) == sum(len(s["joints"]) for s in ext["springs"]), None)
check("every segment has length", all(np.linalg.norm(nodes[j["node"]].get("translation", (0, 0, 0))) > 1e-6 for s in ext["springs"] for j in s["joints"][1:]), None)
check("colliders sit on body bones", all(c["node"] in set(joints) - in_spring for c in ext["colliders"]), None)
swing = np.array([[1.0, 0, 0], [0, 0, 1.0], [0, -1.0, 0]])
where = [world_of(nodes, parent, j["node"])[:3, 3] for s in ext["springs"] for j in s["joints"]]
expect = [swing @ np.array(arm.matrix_world @ arm.data.bones[nodes[j["node"]]["name"]].head_local) for s in ext["springs"] for j in s["joints"]]
check("every joint's node stands where its bone's head is in the scene", np.allclose(where, expect, atol=1e-4), float(np.abs(np.array(where) - np.array(expect)).max()))
R["glb"] = {"nodes": len(nodes), "joints": len(joints), "springs": len(ext["springs"]) if ext else 0, "colliders": len(ext["colliders"]) if ext else 0}
Path(OUT + ".glb").write_bytes((WORK / "whale.glb").read_bytes())
# --- determinism, yUp, and a scene with no rig ------------------------------------------------------------------------
send("exportGltf", filepath="again.glb", extras=False, yUp=True, applyModifiers=True)
a, b = glb_json(WORK / "whale.glb")[0], glb_json(WORK / "again.glb")[0]
check("two exports have identical JSON chunks", json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True), None)
send("exportGltf", filepath="flat.glb", extras=False, yUp=False, applyModifiers=True)
flat, _, _ = glb_json(WORK / "flat.glb")
fext = flat.get("extensions", {}).get("VRMC_springBone")
if ext and fext:
nodes_f = flat["nodes"]
parent_f = {c: i for i, n in enumerate(nodes_f) for c in n.get("children", [])}
names = {n["name"]: i for i, n in enumerate(nodes)}
# --- determinism, yUp, and a scene with no rig ------------------------------------------------------------------------
send("exportGltf", filepath="again.glb", extras=False, yUp=True, applyModifiers=True)
a, b = glb_json(WORK / "whale.glb")[0], glb_json(WORK / "again.glb")[0]
check("two exports have identical JSON chunks", json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True), None)
send("exportGltf", filepath="flat.glb", extras=False, yUp=False, applyModifiers=True)
flat, _, _ = glb_json(WORK / "flat.glb")
fext = flat.get("extensions", {}).get("VRMC_springBone")
if ext and fext:
nodes_f = flat["nodes"]
parent_f = {c: i for i, n in enumerate(nodes_f) for c in n.get("children", [])}
names = {n["name"]: i for i, n in enumerate(nodes)}
def collider_world(gl, nd, par, c, key):
return (world_of(nd, par, c["node"]) @ np.append(c["shape"][list(c["shape"])[0]][key], 1.0))[:3]
def collider_world(gl, nd, par, c, key):
return (world_of(nd, par, c["node"]) @ np.append(c["shape"][list(c["shape"])[0]][key], 1.0))[:3]
pairs = [(collider_world(gltf, nodes, parent, c, "offset"), collider_world(flat, nodes_f, parent_f, f, "offset"))
for c, f in zip(ext["colliders"], fext["colliders"])]
check("yUp false: a collider's node-local offset composes to the same scene point (up to the axis swing)",
bool(pairs) and all(np.allclose(up, swing @ flat_point, atol=1e-4) for up, flat_point in pairs), pairs[:1])
bpy.ops.mesh.primitive_cube_add()
cube = bpy.context.active_object
cube.name = "Cube"
send("exportGltf", filepath="cube.glb", extras=False, yUp=True, applyModifiers=True, selection=["Cube"])
cube_json, _, _ = glb_json(WORK / "cube.glb")
check("a scene with no rig springs exports no VRMC_springBone", "VRMC_springBone" not in cube_json.get("extensions", {})
and "VRMC_springBone" not in cube_json.get("extensionsUsed", []), list(cube_json.get("extensions", {})))
pairs = [(collider_world(gltf, nodes, parent, c, "offset"), collider_world(flat, nodes_f, parent_f, f, "offset"))
for c, f in zip(ext["colliders"], fext["colliders"])]
check("yUp false: a collider's node-local offset composes to the same scene point (up to the axis swing)",
bool(pairs) and all(np.allclose(up, swing @ flat_point, atol=1e-4) for up, flat_point in pairs), pairs[:1])
bpy.ops.mesh.primitive_cube_add()
cube = bpy.context.active_object
cube.name = "Cube"
send("exportGltf", filepath="cube.glb", extras=False, yUp=True, applyModifiers=True, selection=["Cube"])
cube_json, _, _ = glb_json(WORK / "cube.glb")
check("a scene with no rig springs exports no VRMC_springBone", "VRMC_springBone" not in cube_json.get("extensions", {})
and "VRMC_springBone" not in cube_json.get("extensionsUsed", []), list(cube_json.get("extensions", {})))
# --- body again on its own armature: the chains go, nothing is left weighing nothing; colliders alone export no springs
chain_bones = sum(1 for b in arm.data.bones if "rig_chain" in b)
receipt, rebody = send("brokkr_rig.body", object_name="Whale", armature_name=arm.name, seeds="jaw=0,0.45,0.05")
check("body again clears the chain bones it would orphan",
rebody and rebody["chainBonesCleared"] == chain_bones > 0 and not any("rig_chain" in b for b in arm.data.bones), rebody)
check("body again leaves no collider from the old body", not any("rig_colliders" in b for b in arm.data.bones), None)
send("exportGltf", filepath="cleared.glb", extras=False, yUp=True, applyModifiers=True)
cleared_json, _, _ = glb_json(WORK / "cleared.glb")
check("an armature with no chains exports no springs", "VRMC_springBone" not in cleared_json.get("extensions", {}), None)
receipt, lone = send("brokkr_rig.colliders", object_name="Whale")
send("exportGltf", filepath="colliders_only.glb", extras=False, yUp=True, applyModifiers=True)
only_json, _, _ = glb_json(WORK / "colliders_only.glb")
check("colliders without chains export no VRMC_springBone", lone and lone["capsules"] > 0 and "VRMC_springBone" not in only_json.get("extensions", {})
and "VRMC_springBone" not in only_json.get("extensionsUsed", []), lone)
receipt, rerun = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01)
check("tendrils after the second body rebuilds the same chains", rerun and tendrils and rerun["chains"] == tendrils["chains"]
and rerun["springBones"] == tendrils["springBones"], [rerun, tendrils])
# --- body again on its own armature: the chains go, nothing is left weighing nothing; colliders alone export no springs
chain_bones = sum(1 for b in arm.data.bones if "rig_chain" in b)
receipt, rebody = send("brokkr_rig.body", object_name="Whale", armature_name=arm.name, seeds="jaw=0,0.45,0.05")
check("body again clears the chain bones it would orphan",
rebody and rebody["chainBonesCleared"] == chain_bones > 0 and not any("rig_chain" in b for b in arm.data.bones), rebody)
check("body again leaves no collider from the old body", not any("rig_colliders" in b for b in arm.data.bones), None)
send("exportGltf", filepath="cleared.glb", extras=False, yUp=True, applyModifiers=True)
cleared_json, _, _ = glb_json(WORK / "cleared.glb")
check("an armature with no chains exports no springs", "VRMC_springBone" not in cleared_json.get("extensions", {}), None)
receipt, lone = send("brokkr_rig.colliders", object_name="Whale")
send("exportGltf", filepath="colliders_only.glb", extras=False, yUp=True, applyModifiers=True)
only_json, _, _ = glb_json(WORK / "colliders_only.glb")
check("colliders without chains export no VRMC_springBone", lone and lone["capsules"] > 0 and "VRMC_springBone" not in only_json.get("extensions", {})
and "VRMC_springBone" not in only_json.get("extensionsUsed", []), lone)
receipt, rerun = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01)
check("tendrils after the second body rebuilds the same chains", rerun and tendrils and rerun["chains"] == tendrils["chains"]
and rerun["springBones"] == tendrils["springBones"], [rerun, tendrils])
# --- a mesh with no thin part: no chains is an outcome, not a crash, and the skin stays the body's --------------------------
ball = bmesh.new()
bmesh.ops.create_uvsphere(ball, u_segments=24, v_segments=12, radius=0.3, calc_uvs=True)
ball_mesh = bpy.data.meshes.new("Ball")
ball.to_mesh(ball_mesh)
ball.free()
ball_obj = bpy.data.objects.new("Ball", ball_mesh)
bpy.context.scene.collection.objects.link(ball_obj)
send("brokkr_rig.body", object_name="Ball", spine_bones=4)
# --- a mesh with no thin part: no chains is an outcome, not a crash, and the skin stays the body's --------------------------
ball = bmesh.new()
bmesh.ops.create_uvsphere(ball, u_segments=24, v_segments=12, radius=0.3, calc_uvs=True)
ball_mesh = bpy.data.meshes.new("Ball")
ball.to_mesh(ball_mesh)
ball.free()
ball_obj = bpy.data.objects.new("Ball", ball_mesh)
bpy.context.scene.collection.objects.link(ball_obj)
send("brokkr_rig.body", object_name="Ball", spine_bones=4)
def ball_weights():
names = [g.name for g in ball_obj.vertex_groups]
return [sorted((names[e.group], e.weight) for e in v.groups) for v in ball_obj.data.vertices]
def ball_weights():
names = [g.name for g in ball_obj.vertex_groups]
return [sorted((names[e.group], e.weight) for e in v.groups) for v in ball_obj.data.vertices]
before = ball_weights()
receipt, bald = send("brokkr_rig.tendrils", object_name="Ball", tau=0.05, band=0.04, dilate=0.01)
check("tendrils on a mesh with no thin part is accepted and reports no chains", receipt["status"] == "accepted" and bald and bald["chains"] == 0
and bald["springBones"] == 0 and bald["rings"] == 0 and bald["fusedContacts"] == 0, [receipt["message"], bald])
check("and leaves the skin as body made it, with no chain bones", ball_weights() == before
and not any("rig_chain" in b for b in bpy.data.objects["Ball.rig"].data.bones), None)
before = ball_weights()
receipt, bald = send("brokkr_rig.tendrils", object_name="Ball", tau=0.05, band=0.04, dilate=0.01)
check("tendrils on a mesh with no thin part is accepted and reports no chains", receipt["status"] == "accepted" and bald and bald["chains"] == 0
and bald["springBones"] == 0 and bald["rings"] == 0 and bald["fusedContacts"] == 0, [receipt["message"], bald])
check("and leaves the skin as body made it, with no chain bones", ball_weights() == before
and not any("rig_chain" in b for b in bpy.data.objects["Ball.rig"].data.bones), None)
except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file
check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:])
R["ok"] = all(c["ok"] for c in R["checks"])
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
for c in R["checks"]:
print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True)
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
sys.exit(0 if R["ok"] else 1)

View file

@ -197,8 +197,8 @@
},
{
"bone": "spine_04",
"before": 0.106817,
"after": 0.074496
"before": 0.107081,
"after": 0.07411
}
],
"shrunkMax": 0.6571,
@ -210,7 +210,7 @@
{
"name": "exportGltf accepted",
"ok": true,
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-l9ustbpi\\whale.glb (301188 bytes)."
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-qccur36g\\whale.glb (301168 bytes)."
},
{
"name": "VRMC_springBone is in extensions and extensionsUsed",
@ -630,8 +630,8 @@
},
{
"bone": "spine_04",
"before": 0.106817,
"after": 0.074496
"before": 0.107081,
"after": 0.07411
}
],
"shrunkMax": 0.6571,

View file

@ -1439,9 +1439,130 @@ class StructureTests(unittest.TestCase):
self.assertEqual((len(core.joined([]).V), len(core.joined([]).counts)), (0, 0))
class SheetTests(unittest.TestCase):
"""core.sheet: the cage and creases of a shell description. Exact arithmetic: each assertion is the built value
and names the mutant it kills."""
@staticmethod
def rings(count=3, points=4, x0=0.0):
"""Rings upward in z, points toward +x, bowed toward -y: by the winding rule their outside is -y."""
return [[[x0 + 0.2 * j, -0.3 + 0.05 * j * j, 0.25 * i] for j in range(points)] for i in range(count)]
@staticmethod
def normals(built):
V = built.V[built.faces.reshape(-1, 4)]
return np.cross(V[:, 1] - V[:, 0], V[:, 3] - V[:, 0])
@staticmethod
def weights(built) -> dict:
return {tuple(pair): weight for pair, weight in zip(built.creases.tolist(), built.weights.tolist())}
def test_a_grid_of_quads_wound_by_the_rule(self):
"""sheet-grid. S2 (winding reversed): every quad's normal faces the known outside, -y; flip turns all."""
built = core.sheet({"rings": self.rings(3, 4)})
self.assertEqual((built.rings, built.points, len(built.V), len(built.counts), set(built.counts.tolist())), (3, 4, 12, 6, {4}))
self.assertEqual(built.faces[:4].tolist(), [0, 1, 5, 4]) # P[0][0], P[0][1], P[1][1], P[1][0]
self.assertTrue((self.normals(built)[:, 1] < 0).all())
self.assertTrue(built.smooth.all() and len(built.sharp) == 0)
flipped = core.sheet({"rings": self.rings(3, 4), "flip": True})
self.assertTrue((self.normals(flipped)[:, 1] > 0).all())
self.assertEqual(flipped.faces[:4].tolist(), [4, 5, 1, 0])
ring = [[math.cos(a), math.sin(a)] for a in (0.0, 2.0, 4.0)] # counter-clockwise from above, rings upward: outward
tube = core.sheet({"rings": [[[x, y, z] for x, y in ring] for z in (0.0, 1.0, 2.0)], "closed": True})
self.assertEqual((tube.points, len(tube.counts)), (3, 6))
centres = tube.V[tube.faces.reshape(-1, 4)].mean(axis=1)
self.assertTrue((np.einsum("ij,ij->i", self.normals(tube)[:, :2], centres[:, :2]) > 0).all())
self.assertEqual(sorted(self.weights(tube)), [(0, 1), (0, 2), (1, 2), (6, 7), (6, 8), (7, 8)]) # a closed loft's rim: its two end rings
def test_a_mirrored_sheet_is_symmetric(self):
"""sheet-mirror. S3 (the mirrored half not reversed): the ring runs from -x to +x through point 0, vertex for
vertex the mirror of itself, and every quad faces the same outside. S10 (creases on one half)."""
built = core.sheet({"rings": self.rings(3, 3), "mirror": True, "rim": 0.0, "creases": [
{"ring": 1, "from": 0, "to": 2, "weight": 0.75}, {"column": 1, "from": 0, "to": 2, "weight": 0.5}, {"point": [2, 2], "weight": 0.25},
{"point": [1, 0], "weight": 1.0}]})
self.assertEqual((built.rings, built.points, len(built.V)), (3, 5, 15))
P = built.V.reshape(3, 5, 3)
self.assertEqual(P[:, :, 0].tolist(), [[-0.4, -0.2, 0.0, 0.2, 0.4]] * 3)
np.testing.assert_array_equal(P[:, ::-1] * (-1.0, 1.0, 1.0), P)
self.assertTrue((self.normals(built)[:, 1] < 0).all())
quads = {tuple(q) for q in built.faces.reshape(-1, 4).tolist()}
across = lambda v: v // 5 * 5 + 4 - v % 5 # noqa: E731
self.assertEqual({tuple(across(v) for v in (q[1], q[0], q[3], q[2])) for q in quads}, quads) # mirrored and rewound, the same faces
self.assertEqual(self.weights(built), {(5, 6): 0.75, (6, 7): 0.75, (7, 8): 0.75, (8, 9): 0.75, # ring 1, joined across point 0
(1, 6): 0.5, (6, 11): 0.5, (3, 8): 0.5, (8, 13): 0.5}) # column 1, on both halves
self.assertEqual((built.corners.tolist(), built.corner_weights.tolist()), ([7, 10, 14], [1.0, 0.25, 0.25]))
def test_runs_map_to_edges_and_the_rim_takes_the_rest(self):
"""sheet-creases. S4 (rim ignored): every boundary edge no run names carries rim. S9 (a second run wins)."""
built = core.sheet({"rings": self.rings(3, 4), "rim": 0.4, "creases": [
{"ring": 1, "from": 1, "to": 3, "weight": 1.0}, {"column": 2, "from": 0, "to": 1, "weight": 0.6}, {"ring": 0, "from": 0, "to": 1, "weight": 0.0},
{"ring": 2, "from": 2, "to": 3, "weight": 0.9}, {"point": [0, 3], "weight": 0.7}]})
rim = {(1, 2), (2, 3), (8, 9), (9, 10), (0, 4), (4, 8), (3, 7), (7, 11)} # the boundary less (0, 1), stated 0, and (10, 11), stated 0.9
self.assertEqual(self.weights(built), {**{e: 0.4 for e in rim}, (5, 6): 1.0, (6, 7): 1.0, (2, 6): 0.6, (10, 11): 0.9})
self.assertEqual((built.corners.tolist(), built.corner_weights.tolist()), ([3], [0.7]))
self.assertEqual(len(core.sheet({"rings": self.rings(3, 4), "rim": 0.0}).creases), 0)
self.assertEqual(set(core.sheet({"rings": self.rings(3, 4)}).weights.tolist()), {1.0})
ring = [[math.cos(a), math.sin(a), 0.0] for a in (0.0, 1.5, 3.0, 4.5)]
tube = core.sheet({"rings": [[[x, y, z] for x, y, _ in ring] for z in (0.0, 1.0, 2.0)], "closed": True, "rim": 0.0,
"creases": [{"ring": 1, "from": 2, "to": 4, "weight": 1.0}]})
self.assertEqual(self.weights(tube), {(6, 7): 1.0, (4, 7): 1.0}) # points 2-3, and 3 back to 0
same = {"rings": self.rings(3, 4), "creases": [{"ring": 1, "from": 0, "to": 2, "weight": 0.5}, {"ring": 1, "from": 1, "to": 3, "weight": 0.5}]}
self.assertEqual(self.weights(core.sheet({**same, "rim": 0.0})), {(4, 5): 0.5, (5, 6): 0.5, (6, 7): 0.5})
same["creases"][1]["weight"] = 0.6
with self.assertRaisesRegex(core.KitError, r"sheet\.creases\[1\] gives an edge weight 0\.6 that sheet\.creases\[0\] gives 0\.5"):
core.sheet(same)
with self.assertRaisesRegex(core.KitError, r"sheet\.creases\[1\] gives a point weight 1 that sheet\.creases\[0\] gives 0\.5"):
core.sheet({"rings": self.rings(), "creases": [{"point": [0, 0], "weight": 0.5}, {"point": [0, 0], "weight": 1.0}]})
def test_refusals_name_the_field_and_index(self):
"""sheet-refusals."""
good = self.rings(3, 4)
bad_ring, short, nan, collapsed = copy.deepcopy(good), copy.deepcopy(good), copy.deepcopy(good), copy.deepcopy(good)
bad_ring[2] = bad_ring[2][:3]
short[1][2] = [0.0, 1.0]
nan[1][2][0] = math.nan
collapsed[1][1] = collapsed[1][2] = collapsed[0][1] = list(collapsed[0][2])
off, behind = self.rings(3, 3, 0.01), self.rings(3, 3)
behind[1][2][0] = -0.2
run = lambda **keys: {"rings": good, "creases": [keys]} # noqa: E731
cases = [
([], "sheet must be an object"), ({}, "sheet lacks 'rings'"), ({"rings": good, "ring": 1}, "sheet has no key 'ring'"),
({"rings": good[:1]}, r"sheet\.rings must be 2 to 64 rings, not 1"), ({"rings": [good[0]] * 65}, r"2 to 64 rings, not 65"),
({"rings": [[[0, 0, 0]], [[0, 0, 1]]]}, r"sheet\.rings\[0\] must be 2 to 64 points, not 1"),
({"rings": [[[float(j), 0.0, float(i)] for j in range(65)] for i in range(2)]}, r"sheet\.rings\[0\] must be 2 to 64 points, not 65"),
({"rings": bad_ring}, r"sheet\.rings\[2\] has 3 points and sheet\.rings\[0\] has 4"),
({"rings": short}, r"sheet\.rings\[1\]\[2\] must be three finite numbers"), ({"rings": nan}, r"sheet\.rings\[1\]\[2\] must be three finite"),
({"rings": collapsed}, r"the quad between rings 0 and 1 at point 1 \(as built\) has area 0 m2"),
({"rings": off, "mirror": True}, r"sheet\.rings\[0\]\[0\] has x = 0\.01: a mirrored ring starts on x = 0"),
({"rings": behind, "mirror": True}, r"sheet\.rings\[1\]\[2\] has x = -0\.2: a mirrored ring is authored on the \+x side"),
({"rings": self.rings(3, 3), "mirror": True, "closed": True}, r"sheet\.mirror with sheet\.closed"),
({"rings": good, "closed": 1}, r"sheet\.closed must be true or false"), ({"rings": good, "rim": 1.5}, r"sheet\.rim must be a number from 0 to 1"),
({"rings": good, "rim": math.inf}, r"sheet\.rim must be"), ({"rings": good, "creases": {}}, r"sheet\.creases must be an array"),
(run(ring=3, **{"from": 0, "to": 1}, weight=1), r"sheet\.creases\[0\]\.ring must be a whole number from 0 to 2, not 3"),
(run(ring=0, **{"from": 0, "to": 4}, weight=1), r"sheet\.creases\[0\]\.to must be a whole number from 0 to 3, not 4"),
(run(column=4, **{"from": 0, "to": 1}, weight=1), r"sheet\.creases\[0\]\.column must be a whole number from 0 to 3"),
(run(column=0, **{"from": 0, "to": 3}, weight=1), r"sheet\.creases\[0\]\.to must be a whole number from 0 to 2"),
(run(ring=0, **{"from": 2, "to": 2}, weight=1), r"sheet\.creases\[0\]: from 2 must be under to 2"),
(run(ring=0, **{"from": 0, "to": 1}, weight=1.01), r"sheet\.creases\[0\]\.weight must be a number from 0 to 1"),
(run(ring=0, **{"from": 0, "to": 1}), r"sheet\.creases\[0\] lacks 'weight'"),
(run(ring=0, **{"from": 0.0, "to": 1}, weight=1), r"sheet\.creases\[0\]\.from must be a whole number"),
(run(ring=0, column=0, **{"from": 0, "to": 1}, weight=1), r"sheet\.creases\[0\] must be \{ring, from, to, weight\}"),
(run(weight=1), r"sheet\.creases\[0\] must be \{ring"), (run(point=[0, 4], weight=1), r"sheet\.creases\[0\]\.point\[1\] must be a whole number from 0 to 3"),
(run(point=[0], weight=1), r"sheet\.creases\[0\]\.point must be \[ring, point\]"), (run(point=[0, 0], weight=1, ring=0), r"sheet\.creases\[0\] has no key 'ring'"),
]
for document, message in cases:
with self.assertRaisesRegex(core.KitError, message, msg=message):
core.sheet(document)
closed = {"rings": [[[math.cos(a), math.sin(a), z] for a in (0.0, 2.0, 4.0)] for z in (0.0, 1.0)], "closed": True}
core.sheet({**closed, "creases": [{"ring": 0, "from": 0, "to": 3, "weight": 1}]}) # a closed ring's run may end at the count
with self.assertRaisesRegex(core.KitError, r"\.to must be a whole number from 0 to 3, not 4"):
core.sheet({**closed, "creases": [{"ring": 0, "from": 0, "to": 4, "weight": 1}]})
ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report",
"brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close",
"brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", "brokkr_kitbash.ribs"]
"brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", "brokkr_kitbash.ribs",
"brokkr_kitbash.shell"]
class HostFileTests(unittest.TestCase):
@ -1507,7 +1628,20 @@ class HostFileTests(unittest.TestCase):
with self.assertRaises(at.IntentInvalid, msg=str(bad)):
at.validate(bad, host)
for row in self.document["actions"][4:]:
self.assertTrue(all(field["type"] in ("string", "number") for field in row["fields"]), row["name"])
self.assertTrue(all(field["type"] in ("string", "number", "integer", "boolean") for field in row["fields"]), row["name"])
self.assertEqual([(row["name"], field["name"], field["default"]) for row in self.document["actions"] for field in row["fields"] if field["type"] == "boolean"],
[("brokkr_kitbash.shell", "count_folds", False)]) # the one evaluation shell makes is asked for, never the default
self.assertEqual([(row["name"], field["name"]) for row in self.document["actions"] for field in row["fields"] if field["type"] == "integer"],
[("brokkr_kitbash.shell", "levels")])
sheet = json.dumps({"rings": [[[0, 0, 0], [1, 0, 0]], [[0, 0, 1], [1, 0, 1]]]})
shell = {**envelope, "action": "brokkr_kitbash.shell", "object_name": "Plate", "sheet": sheet}
self.assertEqual([at.validate(shell, host)[k] for k in ("thickness", "offset", "levels", "bevel", "count_folds")], [0.05, -1, 3, 0, False])
self.assertEqual(at.validate({**shell, "thickness": 0.001, "levels": 4}, host)["levels"], 4)
for bad in ({**shell, "levels": 5}, {**shell, "levels": 2.5}, {**shell, "levels": 0}, {**shell, "thickness": 0.0005}, {**shell, "offset": 1.5}, {**shell, "bevel": 0.2},
{**shell, "sheet": "{" + " " * 32000}, {**shell, "sheet": ""}, {k: v for k, v in shell.items() if k != "sheet"}, {**shell, "object_name": "x" * 64},
{**shell, "rings": []}, {**shell, "count_folds": 1}):
with self.assertRaises(at.IntentInvalid, msg=str(bad)[:200]):
at.validate(bad, host)
def test_the_ribs_row_takes_64_planes_and_16_longerons_at_full_precision(self):
"""planes-string-cap-below-64. A float's longest repr is 24 characters (-1.2345678901234567e-05): 64 planes of
@ -1589,9 +1723,9 @@ class OwnershipTests(unittest.TestCase):
self.assertLess(place.index("evaluable("), place.index("modifier.show_viewport = True"))
# unevaluable-target: every action that evaluates refuses an object Blender does not evaluate before its first write
for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["apply"], "bpy.data.meshes.new_from_object("),
(bodies["ribs"], "show_viewport = False")):
(bodies["ribs"], "show_viewport = False"), (bodies["shell"], "clear_geometry()")):
self.assertLess(body.index("evaluable("), body.index(first_write))
self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply", "ribs"])
self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply", "ribs", "shell"])
ribs = bodies["ribs"] # every refusal before the ribs object is written, and the cage's modifiers shown again whatever happened
self.assertLess(ribs.rindex("raise Refused("), ribs.index("mesh = bpy.data.meshes.new(self.ribs_name)"))
self.assertLess(ribs.index("finally:"), ribs.index("modifier.show_viewport = True"))
@ -1599,7 +1733,22 @@ class OwnershipTests(unittest.TestCase):
for body in (place, *(source.split(f"class BROKKR_KITBASH_OT_{name}(")[1].split("class BROKKR_KITBASH_OT_")[0] for name in ("cut", "cut_many"))):
self.assertNotIn("view_layer.update", body) # an update after a cutter joins would evaluate the Boolean
self.assertEqual(body.count("place_cutters("), 0 if body is place else 1)
self.assertEqual(source.count("to_mesh("), 4) # boolean's report, and in ribs the designed surface, the plate's two faces and the holed webs
shell, count = bodies["shell"].split(" def folded_faces(") # shell evaluates nothing unless count_folds asks, and then the wall alone: no Boolean runs for it
shell, alone = shell.split(" def wall_alone(")
for call in ("evaluated_of(", "to_mesh(", "view_layer.update", "evaluated_get(", "depsgraph"):
self.assertNotIn(call, shell)
self.assertEqual((shell.count("evaluable("), shell.count("folded_faces("), shell.count("self.count_folds")), (1, 1, 2))
self.assertLess(shell.index("if self.count_folds:"), shell.index("with self.wall_alone(obj):"))
self.assertLess(shell.index("with self.wall_alone(obj):"), shell.index("evaluable("))
self.assertIn("self.folded_faces(context, obj, cage_faces * 4 ** self.levels) if self.count_folds else None", shell)
self.assertLess(count.index("wall_alone(shell):"), count.index("evaluable("))
self.assertEqual((count.count("evaluable("), count.count("to_mesh("), source.count("folded_faces("), source.count("wall_alone(")), (1, 1, 2, 3))
self.assertLess(alone.index("finally:"), alone.index("modifier.show_viewport = True"))
self.assertLess(shell.rindex("raise Refused("), shell.index("clear_geometry()")) # every refusal before any write
self.assertLess(shell.index("core.sheet("), shell.index("clear_geometry()"))
self.assertLess(shell.index("clear_geometry()"), shell.index("bpy.data.meshes.new("))
self.assertNotIn("objects.remove(", shell) # a rebuild rewrites the mesh in place: a new object would orphan its cutters and ribs
self.assertEqual(source.count("to_mesh("), 5) # boolean's report, in ribs the designed surface, the plate's two faces and the holed webs, and shell's fold count
def test_only_ribs_writes_kit_ribs(self):
"""kit_ribs is the request a ribs object was derived from: ribs assigns it once and nothing reads it back to
@ -1610,6 +1759,20 @@ class OwnershipTests(unittest.TestCase):
self.assertIn(writes[0], source.split("class BROKKR_KITBASH_OT_ribs(")[1].split("class BROKKR_KITBASH_OT_")[0])
self.assertEqual(len(re.findall(r'\[RIBS\]|\bRIBS\b(?! =)|"kit_ribs"', source)), 2) # the constant's own line, and that write
def test_only_shell_writes_kit_shell(self):
"""kit_shell is the request a shell's cage is derived from: shell assigns it once, and elsewhere it is only
asked for (its presence admits a rebuild); shell alone names its two modifiers and its crease attributes."""
source = self.sources()["__init__.py"]
body = source.split("class BROKKR_KITBASH_OT_shell(")[1].split("class BROKKR_KITBASH_OT_")[0]
writes = re.findall(r'[^\n]*\[(?:SHELL|"kit_shell")\]\s*=(?!=)[^\n]*', source)
self.assertEqual(len(writes), 1)
self.assertIn(writes[0], body)
self.assertEqual(len(re.findall(r'\bSHELL\b|"kit_shell"', source.replace(body, ""))), 2) # outside shell: the constant's own line, its name and its value
self.assertEqual(re.findall(r"\[SHELL\]|SHELL not in obj|SHELL in obj", body), ["SHELL not in obj", "[SHELL]"])
for name in ("SUBSURF", "SOLIDIFY", '"crease_edge"', '"crease_vert"'):
self.assertEqual(len(re.findall(rf"(?<!['\"])\b{name}\b(?!['\"])" if name[0] != '"' else name, source.replace(body, ""))), 0 if name[0] == '"' else 1, name)
self.assertIn(name, body)
def test_only_write_connection_writes_the_roll(self):
"""one-writer. kit_roll is the one statement of a connection's roll, and write_connection its one writer: attach
and pose (roll, aim and reach) call it; set_params and the reports read the roll and never write it back.