Merge pull request 'brokkr_kitbash: attach, detach, boolean and apply; set_params keeps an assembly seated (cut chassis-kit-assembly)' (#25) from nibu/chassis-kit-assembly into main

This commit is contained in:
Eureka 2026-12-01 16:01:15 +00:00
commit cd8302fe0e
9 changed files with 1523 additions and 46 deletions

View file

@ -1,4 +1,4 @@
"""Kitbash parts: place a parametric machine part from a kit, re-parameterise it, and report where its sockets are. """Kitbash parts: place parametric machine parts from a kit, mate them socket to socket, cut them, and bake them.
A host add-on for Brokkr beside brokkr_mesh_polish and brokkr_rig (it imports the polish package's operator base, A host add-on for Brokkr beside brokkr_mesh_polish and brokkr_rig (it imports the polish package's operator base,
Refused and mesh_object, and nothing from Brokkr): brokkr_actions.json beside this file lists the operators agents Refused and mesh_object, and nothing from Brokkr): brokkr_actions.json beside this file lists the operators agents
@ -9,9 +9,16 @@ WindowManager.brokkr_mesh_polish_result, as the polish operators do.
What a placed part is lives on its object as three ID properties: kit_kit, kit_part and kit_params. The mesh is What a placed part is lives on its object as three ID properties: kit_kit, kit_part and kit_params. The mesh is
derived from them (set_params rebuilds it), and socket frames are derived again at every report: nothing else in derived from them (set_params rebuilds it), and socket frames are derived again at every report: nothing else in
the scene stores them. Two things would give a part a second owner and are refused: a mesh datablock shared with the scene stores them. Two things would give a part a second owner and are refused: a mesh datablock shared with
another object (set_params), and a world transform that scales, mirrors or shears (set_params and report: a another object (set_params, apply), and a world transform that scales, mirrors or shears (a part's size is its
part's size is its params). Placement, materials and export are Brokkr's own rows (setObjectTransform, assignMaterial, params).
exportGltf).
A connection belongs to the child: its parent pointer (under an identity parent inverse) and three more ID
properties, kit_socket, kit_parent_socket and kit_roll. Its matrix_basis is derived from them and both parts'
params by core.mate; attach and set_params write it, and a report says how far the child stands from it. A boolean
belongs to its Boolean modifier on the target (the modifier's object is the cutter; its name is a label). kit_baked
says apply replaced the mesh with the evaluated one: the params then only place the part's sockets. Placing a
loose part, hiding a cutter, materials and export are Brokkr's own rows (setObjectTransform, setObjectVisibility,
assignMaterial, exportGltf).
""" """
bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0),
"category": "Object", "description": "Parametric machine parts from kits, with socket frames; agent-callable through Brokkr."} "category": "Object", "description": "Parametric machine parts from kits, with socket frames; agent-callable through Brokkr."}
@ -19,8 +26,10 @@ bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0),
import json import json
import math import math
import bmesh
import bpy import bpy
import numpy as np import numpy as np
from mathutils import Matrix
try: try:
from brokkr_mesh_polish import RESULT, PolishOperator, Refused, mesh_object from brokkr_mesh_polish import RESULT, PolishOperator, Refused, mesh_object
@ -31,7 +40,10 @@ except ImportError as error: # register() says so; the classes below only need
from . import core from . import core
KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params"
SOCKET, PARENT_SOCKET, ROLL, BAKED = "kit_socket", "kit_parent_socket", "kit_roll", "kit_baked"
HELD = 1e-5 # a connection holds when its residual is at most this (as RIGID)
BEVEL = "Kit Bevel" BEVEL = "Kit Bevel"
BOOLEAN = "Kit Boolean " # a Boolean modifier's name is this and its cutter's name: a label, the cutter is modifier.object
BEVEL_SEGMENTS, BEVEL_ANGLE = 2, math.radians(30.0) BEVEL_SEGMENTS, BEVEL_ANGLE = 2, math.radians(30.0)
REPORT_LIMIT = 16000 # characters of a result Brokkr copies into a receipt before it truncates REPORT_LIMIT = 16000 # characters of a result Brokkr copies into a receipt before it truncates
@ -90,10 +102,98 @@ def kit_part_of(obj):
return core.part(core.load_kit(str(obj.get(KIT, ""))), str(obj[PART])), stored return core.part(core.load_kit(str(obj.get(KIT, ""))), str(obj[PART])), stored
def built_part(obj):
"""(part, the part built at the object's stored params): where its sockets are, baked or not."""
part, stored = kit_part_of(obj)
return part, core.build(part, stored)
def link(obj):
"""The connection a child states, (its socket, the parent's socket, roll in degrees), or None. The parent is
obj.parent and is stored nowhere else. attach, set_params, detach and every report read it here."""
if SOCKET not in obj:
return None
roll = obj.get(ROLL, 0.0)
return str(obj[SOCKET]), str(obj.get(PARENT_SOCKET, "")), float(roll) if core.finite(roll) else 0.0
def attached(obj) -> list:
"""The children that state a connection to obj."""
return [child for child in obj.children if SOCKET in child]
def mated(parent, parent_part, parent_built, child, child_part, child_built, stated):
"""(parent socket, child socket) of the connection `stated` between two built parts, or a refusal that names
it: parts of two kits, a socket name a part does not have, or sockets core.mate_refusal will not mate."""
try:
sockets = core.joint(parent_part, parent_built, stated[1], child_part, child_built, stated[0])
refusal = core.mate_refusal(core.load_kit(parent_part["kit"])["socketTypes"], *sockets)
except core.KitError as error:
refusal = str(error)
if refusal:
raise Refused(f"{child.name!r} on {parent.name!r}: {refusal}; nothing changed.")
return sockets
def seat(child, basis) -> None:
"""Write an attached child's derived matrix_basis, under an identity parent inverse."""
child.matrix_parent_inverse = Matrix.Identity(4)
child.matrix_basis = Matrix(np.asarray(basis).tolist())
def connection_report(obj, part, built):
"""None for a part that states no connection, else what it states and whether it holds: the parent is a part
of the same kit, both sockets exist, the parent inverse is the identity and the child stands within HELD of
core.mate. A child moved or re-parented by another action reads holds false until set_params seats it again."""
stated = link(obj)
if stated is None:
return None
row = {"parent": obj.parent.name if obj.parent else None, "socket": stated[0], "parentSocket": stated[1],
"roll": round(stated[2], 6), "residual": None, "holds": False}
try:
if obj.parent is None:
return row
parent_part, parent_built = built_part(obj.parent)
parent_socket, socket = core.joint(parent_part, parent_built, stated[1], part, built, stated[0])
except (Refused, core.KitError):
return row
row["residual"] = round(core.residual(obj.parent.matrix_world, parent_socket, obj.matrix_world, socket, stated[2]), 9)
row["holds"] = bool(np.abs(np.array(obj.matrix_parent_inverse) - np.eye(4)).max() <= HELD and row["residual"] <= HELD)
return row
def part_report(obj, part, built) -> dict: def part_report(obj, part, built) -> dict:
"""A part as the scene has it. Reads stored properties and matrices only: no modifier is evaluated."""
return {"object": obj.name, "kit": part["kit"], "part": part["name"], "params": built.params, return {"object": obj.name, "kit": part["kit"], "part": part["name"], "params": built.params,
"faces": len(obj.data.polygons), "shells": built.shell_count, "bevel": round(built.bevel, 6), "faces": len(obj.data.polygons), "shells": built.shell_count, "bevel": round(built.bevel, 6),
"sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world))} "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world)),
"connection": connection_report(obj, part, built), "baked": bool(obj.get(BAKED, False))}
def own_mesh(obj, doing: str) -> None:
if obj.data.users > 1:
raise Refused(f"{obj.name!r} shares its mesh {obj.data.name!r} with {obj.data.users - 1} other user(s): {doing} it would change "
"them while their params stay. Give it its own mesh (place_part a new part) and set that; nothing changed.")
def booleans(obj) -> list:
return [{"cutter": m.object.name if m.object else None, "operation": m.operation} for m in obj.modifiers if m.type == "BOOLEAN"]
def evaluated_of(context, obj):
"""(depsgraph, obj with its modifier stack evaluated). An Exact Boolean costs about a second a part, so only
boolean and apply call this; no report does."""
depsgraph = context.evaluated_depsgraph_get()
return depsgraph, obj.evaluated_get(depsgraph)
def measured(mesh) -> dict:
"""Faces, signed volume (overlapping shells count twice) and edges that do not join exactly two faces."""
bm = bmesh.new()
bm.from_mesh(mesh)
row = {"faces": len(bm.faces), "volume": round(bm.calc_volume(signed=True), 9), "nonManifoldEdges": sum(1 for e in bm.edges if not e.is_manifold)}
bm.free()
return row
def carried_materials(mesh, old, new): def carried_materials(mesh, old, new):
@ -145,8 +245,9 @@ class BROKKR_KITBASH_OT_place_part(PolishOperator):
class BROKKR_KITBASH_OT_set_params(PolishOperator): class BROKKR_KITBASH_OT_set_params(PolishOperator):
"""Change params of a placed kit part and rebuild its mesh in place: its transform, parent, modifiers and """Change params of a placed kit part and rebuild its mesh in place: its modifiers and material slots stay,
material slots stay, each shape keeps its faces' material, and the Bevel width follows""" each shape keeps its faces' material, the Bevel width follows, and its connection and those of the parts
attached to it are seated again on the moved sockets"""
bl_idname = "brokkr_kitbash.set_params" bl_idname = "brokkr_kitbash.set_params"
bl_label = "Set Kit Part Params" bl_label = "Set Kit Part Params"
object_name: bpy.props.StringProperty(name="Object") object_name: bpy.props.StringProperty(name="Object")
@ -156,10 +257,20 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator):
def work(self, context): def work(self, context):
obj = mesh_object(self.object_name) obj = mesh_object(self.object_name)
part, stored = kit_part_of(obj) part, stored = kit_part_of(obj)
if obj.data.users > 1: if obj.get(BAKED):
raise Refused(f"{obj.name!r} shares its mesh {obj.data.name!r} with {obj.data.users - 1} other user(s): rebuilding it would change " raise Refused(f"{obj.name!r} is baked: apply replaced its mesh, and its params now only place its sockets. "
"them while their params stay. Give it its own mesh (place_part a new part) and set that; nothing changed.") "place_part a new part to change them; nothing changed.")
own_mesh(obj, "rebuilding")
built = core.build(part, core.resolve_params(part, core.parse_params(self.params), stored)) built = core.build(part, core.resolve_params(part, core.parse_params(self.params), stored))
seats, stated = [], link(obj) # every connection this part is an end of, checked against its new sockets before anything is written
if stated is not None:
if obj.parent is None:
raise Refused(f"{obj.name!r} states a connection and has no parent: detach it to clear the connection; nothing changed.")
parent_part, parent_built = built_part(obj.parent)
seats.append((obj, core.mate(*mated(obj.parent, parent_part, parent_built, obj, part, built, stated), stated[2])))
for child in attached(obj):
child_part, child_built = built_part(child)
seats.append((child, core.mate(*mated(obj, part, built, child, child_part, child_built, link(child)), link(child)[2])))
try: try:
old = core.build(part, stored) old = core.build(part, stored)
except core.KitError: # stored params an edited kit no longer admits: nothing to map faces by except core.KitError: # stored params an edited kit no longer admits: nothing to map faces by
@ -172,9 +283,145 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator):
obj.data.update() obj.data.update()
sync_bevel(obj, built.bevel) sync_bevel(obj, built.bevel)
obj[PARAMS] = json.dumps(built.params) obj[PARAMS] = json.dumps(built.params)
for seated, basis in seats: # deeper descendants follow through parenting: their sockets did not move
seat(seated, basis)
if seats:
context.view_layer.update()
return part_report(obj, part, built) return part_report(obj, part, built)
class BROKKR_KITBASH_OT_attach(PolishOperator):
"""Seat a socket of a kit part on a socket of another part of its kit and parent it there: origins together,
normals opposed, turned by roll about the parent socket's normal"""
bl_idname = "brokkr_kitbash.attach"
bl_label = "Attach Kit Part"
object_name: bpy.props.StringProperty(name="Object", description="The child: the part that moves")
socket: bpy.props.StringProperty(name="Socket", description="The child's socket")
parent_name: bpy.props.StringProperty(name="Parent")
parent_socket: bpy.props.StringProperty(name="Parent Socket")
roll: bpy.props.FloatProperty(name="Roll", default=0.0, min=-360.0, max=360.0,
description="Degrees about the parent socket's normal, right-handed; at 0 the two sockets' ys line up")
@kit_work
def work(self, context):
child, parent = mesh_object(self.object_name), mesh_object(self.parent_name)
part, built = built_part(child)
parent_part, parent_built = built_part(parent)
if child == parent:
raise Refused(f"{child.name!r} cannot be attached to itself; nothing changed.")
if child.parent is not None:
raise Refused(f"{child.name!r} has a parent, {child.parent.name!r}: detach it first (setObjectParent with an empty parent "
"for a parent it was not attached to); nothing changed.")
ancestor = parent.parent
while ancestor is not None:
if ancestor == child:
raise Refused(f"{parent.name!r} is below {child.name!r}: attaching {child.name!r} to it would close a loop; nothing changed.")
ancestor = ancestor.parent
stated = (self.socket, self.parent_socket, float(self.roll))
sockets = mated(parent, parent_part, parent_built, child, part, built, stated)
users = [c.name for c in attached(parent) if c.get(PARENT_SOCKET) == self.parent_socket]
if parent.get(SOCKET) == self.parent_socket:
users.append(parent.parent.name if parent.parent else parent.name)
if users:
raise Refused(f"Socket {self.parent_socket!r} of {parent.name!r} is occupied (by {users[0]!r}); nothing changed.")
users = [c.name for c in attached(child) if c.get(PARENT_SOCKET) == self.socket]
if users:
raise Refused(f"Socket {self.socket!r} of {child.name!r} is occupied (by {users[0]!r}); nothing changed.")
child.parent = parent
seat(child, core.mate(*sockets, stated[2]))
child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated
context.view_layer.update()
return part_report(child, part, built)
class BROKKR_KITBASH_OT_detach(PolishOperator):
"""Clear a kit part's connection: it stays where it stands in the world, loses its parent, and the parts
attached to it stay attached to it"""
bl_idname = "brokkr_kitbash.detach"
bl_label = "Detach Kit Part"
object_name: bpy.props.StringProperty(name="Object")
@kit_work
def work(self, context):
obj = mesh_object(self.object_name)
if SOCKET not in obj:
raise Refused(f"{obj.name!r} is not attached (it has no {SOCKET} property); nothing changed.")
part, built = built_part(obj)
world = obj.matrix_world.copy()
obj.parent = None
obj.matrix_world = world
for key in (SOCKET, PARENT_SOCKET, ROLL):
if key in obj:
del obj[key]
return part_report(obj, part, built)
class BROKKR_KITBASH_OT_boolean(PolishOperator):
"""Cut a kit part with another mesh object through a live Boolean modifier (Exact, with self-intersection: kit
parts are overlapping shells) placed above the Bevel; evaluates the part once and reports the result"""
bl_idname = "brokkr_kitbash.boolean"
bl_label = "Boolean Kit Part"
object_name: bpy.props.StringProperty(name="Object", description="The kit part that is cut")
cutter: bpy.props.StringProperty(name="Cutter", description="Any other mesh object; it is not changed")
operation: bpy.props.EnumProperty(name="Operation", default="DIFFERENCE", items=[
("DIFFERENCE", "Difference", ""), ("UNION", "Union", ""), ("INTERSECT", "Intersect", "")])
@kit_work
def work(self, context):
obj = mesh_object(self.object_name)
part, built = built_part(obj)
cutter = bpy.data.objects.get(self.cutter)
if cutter is None or cutter.type != "MESH":
raise Refused(f"No mesh object named {self.cutter!r} to cut with; nothing changed.")
if cutter == obj:
raise Refused(f"{obj.name!r} cannot cut itself; nothing changed.")
if any(m.type == "BOOLEAN" and m.object == cutter for m in obj.modifiers):
raise Refused(f"{cutter.name!r} is already the object of a Boolean on {obj.name!r}; nothing changed.")
modifier = obj.modifiers.new(BOOLEAN + cutter.name, "BOOLEAN")
modifier.operation, modifier.object = self.operation, cutter
# TRANSFER: with the default (INDEX) the result gains an empty material slot for a cutter that has no materials
modifier.solver = "EXACT"
modifier.use_self = True
modifier.material_mode = "TRANSFER"
names = [m.name for m in obj.modifiers]
if BEVEL in names: # cut first, then bevel the cut's edges with the rest
obj.modifiers.move(len(names) - 1, names.index(BEVEL))
report = part_report(obj, part, built)
_, evaluated = evaluated_of(context, obj)
report["booleans"], report["evaluated"] = booleans(obj), measured(evaluated.to_mesh())
evaluated.to_mesh_clear()
return report
class BROKKR_KITBASH_OT_apply(PolishOperator):
"""Bake a kit part: its mesh becomes its evaluated mesh (Booleans and Bevel applied), every modifier goes, its
material slots stay, and it is marked baked; its sockets and connections stay as they are"""
bl_idname = "brokkr_kitbash.apply"
bl_label = "Apply Kit Part"
object_name: bpy.props.StringProperty(name="Object")
@kit_work
def work(self, context):
obj = mesh_object(self.object_name)
part, built = built_part(obj)
own_mesh(obj, "baking")
if not obj.modifiers:
raise Refused(f"{obj.name!r} has no modifiers to apply; nothing changed.")
cutters, slots = [row["cutter"] for row in booleans(obj)], len(obj.data.materials)
depsgraph, evaluated = evaluated_of(context, obj)
baked = bpy.data.meshes.new_from_object(evaluated, preserve_all_data_layers=True, depsgraph=depsgraph)
while len(baked.materials) > slots and baked.materials[len(baked.materials) - 1] is None:
baked.materials.pop() # a Boolean gives a part that had no material slot one empty slot
old, name = obj.data, obj.data.name
obj.data = baked
obj.modifiers.clear()
if old.users == 0:
bpy.data.meshes.remove(old)
baked.name = name
obj[BAKED] = True
return {**part_report(obj, part, built), **measured(baked), "cutters": cutters}
class BROKKR_KITBASH_OT_describe(PolishOperator): 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 """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""" at default params"""
@ -190,7 +437,8 @@ class BROKKR_KITBASH_OT_describe(PolishOperator):
class BROKKR_KITBASH_OT_report(PolishOperator): class BROKKR_KITBASH_OT_report(PolishOperator):
"""Report placed kit parts as the scene has them: kit, part, params, faces, shells and each socket's world frame""" """Report placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world frame,
the connection and whether it holds, and whether the part is baked"""
bl_idname = "brokkr_kitbash.report" bl_idname = "brokkr_kitbash.report"
bl_label = "Report Kit Parts" bl_label = "Report Kit Parts"
bl_options = {"REGISTER"} bl_options = {"REGISTER"}
@ -200,14 +448,11 @@ class BROKKR_KITBASH_OT_report(PolishOperator):
def work(self, context): def work(self, context):
chosen = [mesh_object(self.object_name)] if self.object_name else sorted( chosen = [mesh_object(self.object_name)] if self.object_name else sorted(
(o for o in context.scene.objects if o.type == "MESH" and PART in o), key=lambda o: o.name) (o for o in context.scene.objects if o.type == "MESH" and PART in o), key=lambda o: o.name)
parts = [] return bounded({"parts": [part_report(obj, *built_part(obj)) for obj in chosen]}, "name an object to report it alone")
for obj in chosen:
part, stored = kit_part_of(obj)
parts.append(part_report(obj, part, core.build(part, stored)))
return bounded({"parts": parts}, "name an object to report it alone")
classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report) 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_boolean, BROKKR_KITBASH_OT_apply)
def register(): def register():

View file

@ -45,7 +45,7 @@
}, },
{ {
"name": "brokkr_kitbash.set_params", "name": "brokkr_kitbash.set_params",
"doc": "Change params of a placed kit part and rebuild its mesh in place; transform, parent, modifiers and materials stay. Refuses a mesh another object shares and a scaled part. Reports as place_part.", "doc": "Change params of a placed kit part and rebuild its mesh in place; modifiers and materials stay, and its connection and the parts attached to it are seated again. Refuses a change that breaks a connection, a baked part, a mesh another object shares and a scaled part. Reports as place_part.",
"changesScene": true, "changesScene": true,
"editModeSafe": false, "editModeSafe": false,
"result": "brokkr_mesh_polish_result", "result": "brokkr_mesh_polish_result",
@ -93,7 +93,7 @@
}, },
{ {
"name": "brokkr_kitbash.report", "name": "brokkr_kitbash.report",
"doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells and each socket's world 4x4. Refuses a part scaled in the world: resize with set_params.", "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world 4x4, the connection (parent, sockets, roll, residual, holds) and baked. Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.",
"changesScene": false, "changesScene": false,
"editModeSafe": true, "editModeSafe": true,
"result": "brokkr_mesh_polish_result", "result": "brokkr_mesh_polish_result",
@ -106,6 +106,124 @@
"doc": "empty: every object that is a kit part" "doc": "empty: every object that is a kit part"
} }
] ]
},
{
"name": "brokkr_kitbash.attach",
"doc": "Seat a socket of a kit part on a socket of another part of its kit and parent it there: origins together, normals opposed. Refuses sockets of different types or sizes that do not match, an occupied socket, a child that has a parent, and a loop. Reports the child with its connection.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "object_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "the child: the part that moves"
},
{
"name": "socket",
"type": "string",
"required": true,
"chars": "id",
"minLength": 1,
"maxLength": 32,
"doc": "the child's socket; brokkr_kitbash.report lists a part's sockets"
},
{
"name": "parent_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "the part it is attached to"
},
{
"name": "parent_socket",
"type": "string",
"required": true,
"chars": "id",
"minLength": 1,
"maxLength": 32,
"doc": "the parent's socket"
},
{
"name": "roll",
"type": "number",
"minimum": -360,
"maximum": 360,
"default": 0,
"doc": "degrees about the parent socket's normal, right-handed; at 0 the two sockets' up axes line up"
}
]
},
{
"name": "brokkr_kitbash.detach",
"doc": "Clear a kit part's connection: it keeps its place in the world and loses its parent; parts attached to it stay attached to it.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "object_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63
}
]
},
{
"name": "brokkr_kitbash.boolean",
"doc": "Cut a kit part with another mesh object through a live Boolean modifier (Exact, self-intersection on) above its Bevel. Evaluates the part once, about a second: reports the result's faces, volume and non-manifold edges. The cutter is not changed; hide it with setObjectVisibility.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "object_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "the kit part that is cut"
},
{
"name": "cutter",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "any other mesh object"
},
{
"name": "operation",
"type": "string",
"enum": [
"DIFFERENCE",
"UNION",
"INTERSECT"
],
"default": "DIFFERENCE"
}
]
},
{
"name": "brokkr_kitbash.apply",
"doc": "Bake a kit part: its mesh becomes its evaluated mesh, every modifier goes, material slots stay, and it is marked baked (set_params then refuses it). Sockets and connections stay. Refuses a part with no modifiers and a mesh another object shares.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "object_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63
}
]
} }
] ]
} }

View file

@ -8,6 +8,9 @@ expression is parsed with ast.parse and walked against a whitelist; nothing in a
kit = load_kit("mechanical") kit = load_kit("mechanical")
built = build(part(kit, "tank"), {"length": 1.2}) # Built: V, faces, counts, smooth, shell_count, sockets built = build(part(kit, "tank"), {"length": 1.2}) # Built: V, faces, counts, smooth, shell_count, sockets
Two sockets mate through mate (the child's matrix under its parent), mate_refusal (what may mate) and residual
(how far a placed child stands from its mate).
Every refusal is a KitError whose message names the kit, part and field. Every refusal is a KitError whose message names the kit, part and field.
""" """
from __future__ import annotations from __future__ import annotations
@ -493,6 +496,64 @@ def socket_rows(sockets: list, frame=None) -> list[dict]:
return [{"name": s["name"], "type": s["type"], "size": round(s["size"], 6), "matrix": rows(frame @ s["matrix"])} for s in sockets] return [{"name": s["name"], "type": s["type"], "size": round(s["size"], 6), "matrix": rows(frame @ s["matrix"])} for s in sockets]
# --- mating --------------------------------------------------------------------------------------------------
FLIP = np.diag([-1.0, 1.0, -1.0, 1.0]) # half a turn about y: a mating socket's z faces the other's, y stays up
def _roll(degrees: float) -> np.ndarray:
turn = np.eye(4)
turn[:3, :3] = _rotation((0.0, 0.0, degrees))
return turn
def mate(parent_socket: dict, child_socket: dict, roll_degrees: float = 0.0) -> np.ndarray:
"""The child's 4x4 in its parent's frame that seats child_socket on parent_socket: origins together, normals
opposed, the child turned roll_degrees about the parent socket's z (right-handed; at 0 the two ys line up)."""
return parent_socket["matrix"] @ _roll(roll_degrees) @ FLIP @ np.linalg.inv(child_socket["matrix"])
def residual(parent_world, parent_socket: dict, child_world, child_socket: dict, roll_degrees: float) -> float:
"""How far a child stands from where mate puts it: the largest absolute entry of the difference between the
frame its socket should have in the world and the frame it has."""
wanted = np.asarray(parent_world, dtype=np.float64) @ parent_socket["matrix"] @ _roll(roll_degrees) @ FLIP
return float(np.abs(wanted - np.asarray(child_world, dtype=np.float64) @ child_socket["matrix"]).max())
EQUAL, SLACK = 0.01, 1e-9 # 'equal' sizes may differ by 1 percent of the larger; SLACK keeps a size at the limit inside it
def mate_refusal(kit_types: dict, parent_socket: dict, child_socket: dict) -> str | None:
"""None when the two sockets may mate, else a sentence naming both: they are of one type, and their sizes
agree as that type's match says ('equal': within 1 percent of the larger; 'fits': the child at most the parent)."""
p, c = parent_socket, child_socket
both = f"socket {c['name']!r} ({c['type']}, size {c['size']:.6g}) and parent socket {p['name']!r} ({p['type']}, size {p['size']:.6g})"
if p["type"] != c["type"]:
return f"{both} are of different types"
if kit_types[p["type"]]["match"] == "equal":
if abs(p["size"] - c["size"]) > EQUAL * max(p["size"], c["size"]) * (1 + SLACK):
return f"{both} are {p['type']} sockets, which mate at equal sizes (within 1 percent)"
elif c["size"] > p["size"] * (1 + SLACK):
return f"{both} are {p['type']} sockets, where the child fits the parent: it is larger"
return None
def joint(parent_part: dict, parent_built: Built, parent_socket: str, child_part: dict, child_built: Built, child_socket: str):
"""(parent socket, child socket) of a connection between two built parts, by socket name. Refuses parts of
different kits (socket types belong to a kit) and a name the part has no socket for."""
if parent_part["kit"] != child_part["kit"]:
raise KitError(f"part {child_part['name']!r} is of kit {child_part['kit']!r} and part {parent_part['name']!r} of kit "
f"{parent_part['kit']!r}: socket types belong to a kit, so parts of different kits do not mate")
found = []
for part, built, name in ((parent_part, parent_built, parent_socket), (child_part, child_built, child_socket)):
match = [s for s in built.sockets if s["name"] == name]
if not match:
raise KitError(f"kit {part['kit']!r} part {part['name']!r} has no socket {name!r}; its sockets: "
f"{', '.join(s['name'] for s in built.sockets) or 'none'}")
found.append(match[0])
return found[0], found[1]
def describe(kit: dict, name: str = "") -> dict: def describe(kit: dict, name: str = "") -> dict:
"""The kit's parts (or the one named): params with their bounds, and sockets in the part frame at default params.""" """The kit's parts (or the one named): params with their bounds, and sockets in the part frame at default params."""
chosen = [part(kit, name)] if name else list(kit["parts"].values()) chosen = [part(kit, name)] if name else list(kit["parts"].values())

View file

@ -1,12 +1,12 @@
# Kitbash parts: machinery from kits # Kitbash parts: machinery from kits
`surfaces/blender/brokkr_kitbash` is a Blender add-on that places parametric machine parts from a **kit** and `surfaces/blender/brokkr_kitbash` is a Blender add-on that places parametric machine parts from a **kit**, mates
reports where their **sockets** are. 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. 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 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`: 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`. 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 Enable `brokkr_mesh_polish` first; `brokkr_kitbash` refuses to register without it. `brokkr_actions.json` beside
its `__init__.py` lists the four operators agents may run. Every action writes a JSON report to its `__init__.py` lists the eight operators agents may run. Every action writes a JSON report to
`brokkr_mesh_polish_result`, returned in the receipt's `hostResult`. `brokkr_mesh_polish_result`, returned in the receipt's `hostResult`.
Who owns what: Who owns what:
@ -24,8 +24,11 @@ Who owns what:
`set_params` and `report` refuse a part whose world transform scales, mirrors or shears, its parents' `set_params` and `report` refuse a part whose world transform scales, mirrors or shears, its parents'
included: a part's size is its params, and a socket's frame is a rotation and an origin. Set scale to 1 and included: a part's size is its params, and a socket's frame is a rotation and an origin. Set scale to 1 and
resize with `set_params`. resize with `set_params`.
- A connection between two parts belongs to the child: its parent pointer and its `kit_socket`,
This add-on places and re-parameterises parts. Mating sockets, booleans and baking are not here. `kit_parent_socket` and `kit_roll` properties. Where the child stands is derived from them
("Assembling parts").
- A boolean belongs to its Boolean modifier on the part that is cut. `kit_baked` says `apply` replaced the part's
mesh with the evaluated one.
## A part, end to end ## A part, end to end
@ -83,6 +86,73 @@ be compared when sockets are mated: `equal` (within 1 percent) or `fits` (the ch
sits on a flat face of the part whose normal is its `z`; `test_kitbash` checks this for every part of a shipped sits on a flat face of the part whose normal is its `z`; `test_kitbash` checks this for every part of a shipped
kit at its default, smallest and largest params and at seeded draws between. kit at its default, smallest and largest params and at seeded draws between.
## Assembling parts
**A connection** seats one socket of a child part on one socket of a parent part: the two origins together, the
two normals opposed, and the child turned `roll` degrees about the parent socket's normal (right-handed; at 0 the
two sockets' up axes line up). The child owns it. It is the child's parent pointer, under an identity parent
inverse, and three ID properties on the child: `kit_socket` (its own socket), `kit_parent_socket` and `kit_roll`.
Nothing else stores it: no parent name, no world matrix, no empties. The child's `matrix_basis` is derived,
```text
matrix_basis = S_parent @ Rz(roll) @ FLIP @ inverse(S_child) FLIP = half a turn about y
```
with `S` each socket's frame in its own part at that part's stored params (`core.mate`). `attach` and `set_params`
write it; nothing else should.
**What may mate** (`core.mate_refusal`): two sockets of one kit and one type whose sizes agree as the type's
`match` says: `equal` within 1 percent of the larger, `fits` with the child at most the parent. `attach` also
refuses, changing nothing:
- a child that has a parent (`detach` it; `setObjectParent` with an empty parent clears a parent it was not
attached to);
- a parent that is the child, or is below it (a loop);
- an occupied socket: one a child is already attached to, or the one the part itself is attached by;
- a part that is not a kit part, or is scaled in the world.
A part may carry a child on every socket but the one it hangs by, so assemblies are trees: tank, then a tee on
its port, then a nozzle on each free flange of the tee.
**`set_params` keeps an assembly together.** Sockets move with params (an actuator's `rod_end` with `extension`, a
tank's `port_b` with `length`). After the rebuild `set_params` writes the derived `matrix_basis` of the part
itself, if it is attached, and of each part attached to it; what hangs further down follows through parenting.
Before it writes anything it checks every one of those connections against the part's new sockets, and a change
that breaks one (a `pipe_r` that no longer matches the flange it is bolted to) is refused, naming the
connection.
**Drift.** `setObjectTransform` and `setObjectParent` are Brokkr's own rows and can move or re-parent an attached
child. Reports show it: a part's `connection` is `null`, or
```json
{"parent": "Tee", "socket": "mount", "parentSocket": "c", "roll": 37.0, "residual": 2.1e-07, "holds": true}
```
`residual` is the largest entry of the difference between the socket's world frame and the frame its mate asks
for; `holds` is true when the parent is a kit part of the same kit, both sockets exist, the parent inverse is the
identity and the residual is at most 1e-5. The next `set_params` on the child or on its parent (with any param,
even at its current value) seats it again. A child whose parent was cleared or replaced by something that is not
a kit part reads `holds` false with a `null` residual, and `set_params` refuses it: `detach` clears what is left.
`detach` keeps the part where it stands in the world and leaves the parts attached to it attached.
**`boolean`** adds a Boolean modifier named `Kit Boolean <cutter>` to a kit part, above its `Kit Bevel`, so the
cut's edges are bevelled with the rest. The modifier's object is the cutter; the name is a label. The solver is
always Exact with self-intersection on: a kit part is many overlapping closed shells, and the faster solvers
give wrong solids for those (the 1.8 m tank minus a box keeps 0.254 m3 with self-intersection and 0.008 m3
without). That costs about a second per part each time the part is evaluated (0.3 s for a pipe fitting, 1.5 s
for a tank, on Blender 5.3), so keep live booleans few and `apply` them when the shape is settled. `boolean`
evaluates the part once and reports `evaluated: {faces, volume, nonManifoldEdges}`; `report` never evaluates a
modifier. The cutter is any other mesh object and is not changed: hide it with `setObjectVisibility`. A cutter
with no material leaves the part's material slots as they are; a cutter that has materials brings them, after
the part's own, on the faces it makes.
**`apply`** bakes a part: its mesh becomes the evaluated mesh (booleans and bevel applied), every modifier goes,
and `kit_baked` is set. The material slots are the part's own, followed by any a cutter brought. A baked part
keeps `kit_kit`, `kit_part`, `kit_params` and its connections: its sockets are still derived from the params,
so what is attached to it stays attached and new parts can attach to it, and it can be cut and baked again.
`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`.
## Expressions ## Expressions
Every numeric field of a shape or socket, and `bevel`, is a number or a string over the part's params: Every numeric field of a shape or socket, and `bevel`, is a number or a string over the part's params:
@ -103,19 +173,24 @@ vertices overflow.
| --- | --- | --- | | --- | --- | --- |
| `brokkr_kitbash.describe` | `kit` (default `mechanical`), `part` (default: all) | Parts with their params (type, min, max, default, doc) and sockets in the part frame at default params. Changes nothing. | | `brokkr_kitbash.describe` | `kit` (default `mechanical`), `part` (default: all) | Parts with their params (type, min, max, default, doc) and sockets in the part frame at default params. Changes nothing. |
| `brokkr_kitbash.place_part` | `kit`, `part`, `object_name`, `params` | A new mesh object at the origin: the part's mesh, a `Kit Bevel` modifier when the part has a bevel, and the three ID properties. Refuses a name an object already has. | | `brokkr_kitbash.place_part` | `kit`, `part`, `object_name`, `params` | A new mesh object at the origin: the part's mesh, a `Kit Bevel` modifier when the part has a bevel, and the three ID properties. Refuses a name an object already has. |
| `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: transform, parent, modifiers and material slots stay, and the Bevel width follows. Per-face materials are carried by shape: each shape of the part keeps the material most of its faces had, whatever the new face count. | | `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: modifiers and material slots stay, and the Bevel width follows. Per-face materials are carried by shape: each shape of the part keeps the material most of its faces had, whatever the new face count. Seats the part and the parts attached to it again; refuses a change that breaks a connection, and a baked part. |
| `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, and each socket's world frame. Changes nothing. | | `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, each socket's world frame, `connection` and `baked`. Changes nothing and evaluates no modifier. |
| `brokkr_kitbash.attach` | `object_name` (the child), `socket`, `parent_name`, `parent_socket`, `roll` (degrees, -360 to 360, default 0) | Seats the child's socket on the parent's and parents it there. Reports the child. |
| `brokkr_kitbash.detach` | `object_name` | Clears the part's connection; it stays where it stands. Refuses a part that is not attached. |
| `brokkr_kitbash.boolean` | `object_name`, `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds a live Exact Boolean above the Bevel. Refuses a cutter that is the part, is not a mesh, or already cuts it. Reports the part, `booleans: [{cutter, operation}]` and `evaluated`. |
| `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the part and clears its modifiers. Refuses a part with no modifiers and a mesh another object shares. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. |
`params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored `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. value (`set_params`). A value outside its bounds is refused with the bounds in the message.
A socket in a report is `{name, type, size, matrix}`: `matrix` is the 4x4 as four rows of 6 decimals, in world A socket in a report is `{name, type, size, matrix}`: `matrix` is the 4x4 as four rows of 6 decimals, in world
space for `place_part`, `set_params` and `report`. Column 2 is the outward normal, column 1 up, column 3 the space for every action that reports a placed part. Column 2 is the outward normal, column 1 up, column 3 the
origin. A report over 16000 characters (what a receipt carries) is refused with advice to name one part or origin. A report over 16000 characters (what a receipt carries) is refused with advice to name one part or
object. object.
Placement, look and export are Brokkr's own rows: `setObjectTransform`, `assignMaterial`, `exportGltf`. Placing a loose part, look, hiding a cutter and export are Brokkr's own rows: `setObjectTransform`,
`place_part` has no location or colour fields. `assignMaterial`, `setObjectVisibility`, `exportGltf`. `place_part` has no location or colour fields. Move an
assembly by its root: an attached part is placed by its connection.
## A recipe ## A recipe
@ -129,14 +204,23 @@ Placement, look and export are Brokkr's own rows: `setObjectTransform`, `assignM
{"action": "brokkr_kitbash.place_part", "part": "tank", "object_name": "Tank", "params": "radius=0.3; length=1.4"}, {"action": "brokkr_kitbash.place_part", "part": "tank", "object_name": "Tank", "params": "radius=0.3; length=1.4"},
{"action": "setObjectTransform", "targetObjectName": "Tank", "location": [0, 0.6, 0], "rotationEuler": [1.5708, 0, 0]}, {"action": "setObjectTransform", "targetObjectName": "Tank", "location": [0, 0.6, 0], "rotationEuler": [1.5708, 0, 0]},
{"action": "assignMaterial", "targetObjectName": "Tank", "materialName": "Machinery", "color": [0.35, 0.35, 0.35]}, {"action": "assignMaterial", "targetObjectName": "Tank", "materialName": "Machinery", "color": [0.35, 0.35, 0.35]},
{"action": "brokkr_kitbash.place_part", "part": "nozzle", "object_name": "Nozzle"}, {"action": "brokkr_kitbash.place_part", "part": "pipe_fitting", "object_name": "Tee", "params": "pipe_r=0.06"},
{"action": "brokkr_kitbash.set_params", "object_name": "Nozzle", "params": "exit_r=0.32"}, {"action": "brokkr_kitbash.attach", "object_name": "Tee", "socket": "a", "parent_name": "Tank", "parent_socket": "port_b"},
{"action": "brokkr_kitbash.report"}, {"action": "brokkr_kitbash.place_part", "part": "nozzle", "object_name": "Nozzle", "params": "throat_r=0.06"},
{"action": "exportGltf", "filepath": "engine.glb", "selection": ["Tank", "Nozzle"]} {"action": "brokkr_kitbash.attach", "object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "c", "roll": 90},
{"action": "brokkr_kitbash.set_params", "object_name": "Tank", "params": "length=1.8"},
{"action": "createObject", "objectType": "MESH", "name": "Cutter", "location": [0.3, 0.6, 0], "size": 0.2},
{"action": "brokkr_kitbash.boolean", "object_name": "Tank", "cutter": "Cutter"},
{"action": "setObjectVisibility", "targetObjectName": "Cutter", "visible": false},
{"action": "brokkr_kitbash.apply", "object_name": "Tank"},
{"action": "brokkr_kitbash.report", "object_name": "Nozzle"},
{"action": "exportGltf", "filepath": "engine.glb", "selection": ["Tank", "Tee", "Nozzle"]}
]} ]}
``` ```
The receipts file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the saved `.blend`. The tank's port is 0.4 of its radius across (0.12 m here), so the tee and the nozzle are given the matching
`pipe_r` and `throat_r`. `set_params` on the tank carries the tee and the nozzle out with its port. The receipts
file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the saved `.blend`.
## The mechanical kit ## The mechanical kit
@ -157,6 +241,13 @@ The receipts file holds each report in `hostResult`. `tools/turntable_recipe.py`
`describe` gives the bounds and docs. `describe` gives the bounds and docs.
Which flanges can meet follows from the sizes: a tank port is `0.4*radius` (0.048 to 0.14), a pipe fitting's
three faces `2*pipe_r` (0.06 to 0.14), a nozzle's mount `2*throat_r` (0.08 to 0.24), and a ribbed cylinder's ends
`2*radius` (0.16 to 0.6). So tanks, fittings and nozzles plumb together, and a ribbed cylinder takes only a
nozzle (throat 0.08 and up) or another ribbed cylinder: its smallest flange is larger than the largest pipe.
Struts and actuators pin together when `0.6*width` equals `0.9*body_r`. Mounts (`fits`) take any part whose
seat is no larger than theirs.
## Adding a part or a kit ## Adding a part or a kit
Edit the kit's JSON (or add `kits/<name>.v0.json`, whose `kit` field is `<name>`), then run the tests: Edit the kit's JSON (or add `kits/<name>.v0.json`, whose `kit` field is `<name>`), then run the tests:
@ -170,4 +261,6 @@ python -m unittest discover -s surfaces/blender/tests -p "test_kitbash.py" -v
seated on a face that faces its `z`, and no build passes 20000 faces. Choose param ranges so every combination seated on a face that faces its `z`, and no build passes 20000 faces. Choose param ranges so every combination
builds: a `min` or `max` in an expression keeps a derived length positive where two params could cross. A new builds: a `min` or `max` in an expression keeps a derived length positive where two params could cross. A new
part of `mechanical` also joins the part and socket list in `test_the_kit_is_the_nine_parts_and_three_socket_types`. part of `mechanical` also joins the part and socket list in `test_the_kit_is_the_nine_parts_and_three_socket_types`.
The operators are exercised in a real Blender by `tests/live/kitbash.py`. `MateTests` covers the mate arithmetic and what may mate. The operators are exercised in a real Blender by
`tests/live/kitbash.py` (placing and re-parameterising) and `tests/live/kitbash_assembly.py` (attach, detach,
`set_params` on assemblies, boolean and apply).

View file

@ -73,9 +73,9 @@ def extent(obj, axis=2):
return float(co[:, axis].max() - co[:, axis].min()) return float(co[:, axis].max() - co[:, axis].min())
check("the four kitbash rows load as host actions with no errors", not R["hostErrors"] check("the eight kitbash rows load as host actions with no errors", not R["hostErrors"]
and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == [f"brokkr_kitbash.{name}" for name in (
"brokkr_kitbash.describe", "brokkr_kitbash.report"], [R["hostErrors"], R["hostRows"]]) "place_part", "set_params", "describe", "report", "attach", "detach", "boolean", "apply")], [R["hostErrors"], R["hostRows"]])
# --- describe --------------------------------------------------------------------------------------------------------- # --- describe ---------------------------------------------------------------------------------------------------------
kit = core.load_kit("mechanical") kit = core.load_kit("mechanical")

View file

@ -2,7 +2,7 @@
"blender": "5.3.0", "blender": "5.3.0",
"checks": [ "checks": [
{ {
"name": "the four kitbash rows load as host actions with no errors", "name": "the eight kitbash rows load as host actions with no errors",
"ok": true, "ok": true,
"detail": null "detail": null
}, },
@ -319,7 +319,11 @@
"brokkr_kitbash.place_part", "brokkr_kitbash.place_part",
"brokkr_kitbash.set_params", "brokkr_kitbash.set_params",
"brokkr_kitbash.describe", "brokkr_kitbash.describe",
"brokkr_kitbash.report" "brokkr_kitbash.report",
"brokkr_kitbash.attach",
"brokkr_kitbash.detach",
"brokkr_kitbash.boolean",
"brokkr_kitbash.apply"
], ],
"placed": { "placed": {
"nozzle": { "nozzle": {

View file

@ -0,0 +1,446 @@
"""Live proof, in a background Blender, of brokkr_kitbash assembly through run_intent: attach and its refusals,
set_params seating a part and the parts attached to it again, drift and how it is cleared, detach, boolean (Exact,
self-intersection on, above the Bevel) on two targets, and apply. Not part of the unittest run: it needs Blender.
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_assembly.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.
An Exact Boolean costs about a second a part and evaluation, so only two parts are ever cut here (the tank and
one plate). 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.
"""
import importlib.util
import json
import math
import os
import sys
import tempfile
import types
from pathlib import Path
import bmesh
import bpy
import numpy as np
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: the frames every reading here is taken against
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-assembly-"))
target.configure_action_dirs("", str(WORK))
target.reload_host_actions()
R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}}
COUNT = [0]
kit = core.load_kit("mechanical")
# Metres (or a difference of unit vectors) between where a seated socket is and where its mate puts it, read from
# the two world matrices. Shipped worst 1.5e-07 (float32 matrices, parts a few metres from the origin); least
# claimed mutant 0.22 (A8, a part not seated again after its own extension changed); separation 1.5e6.
SEATED = 1.8e-4
# Metres between how far a part moved and how far the socket that carries it moved. Shipped worst 2.7e-07; least
# claimed mutant 0.84 (A7, attached children not seated again); separation 3.1e6.
CARRIED = 4.8e-4
# Degrees between the roll read from the two world frames and the roll asked for. Shipped worst 6.3e-06; least
# claimed mutant 74 (A2, roll sign reversed, at roll 37); separation 1.2e7.
ROLL = 2.2e-2
# Largest entry of matrix_world after detach minus before. Shipped worst 1.5e-08; least claimed mutant 2.9
# (A10, detach drops the world matrix); separation 1.9e8.
KEPT = 2.1e-4
# Cubic metres left of the 1.8 m tank (its 20 shells as one solid) with a 0.3 m box cut from its wall. Shipped
# 0.2539; least claimed mutant 0.0079 (A11, self-intersection off: overlapping shells cancel); separation 32.
CUT = 0.045
def check(name, ok, detail=None):
R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) # what was seen, when it was not what was promised
def reading(name, value):
R["readings"][name] = max(R["readings"].get(name, 0.0), float(value))
return float(value)
def send(action, **fields):
COUNT[0] += 1
receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "test/driver", "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 place(name, part, params="", location=None, rotation=None):
send("brokkr_kitbash.place_part", part=part, object_name=name, params=params)
if location is not None:
send("setObjectTransform", targetObjectName=name, location=location, rotationEuler=rotation or [0.0, 0.0, 0.0])
return bpy.data.objects[name]
def frame(obj, socket):
"""A socket's world frame, from the object's matrix_world and core's build of its stored params."""
built = core.build(core.part(kit, obj["kit_part"]), json.loads(obj["kit_params"]))
return np.array(obj.matrix_world, dtype=np.float64) @ next(s["matrix"] for s in built.sockets if s["name"] == socket)
def seated(child, socket, parent, parent_socket, roll=None):
"""How far a child's socket is from seated on its parent's: origins apart, or normals not opposed. With a roll,
also records the degrees between it and the roll read from the two frames."""
a, b = frame(parent, parent_socket), frame(child, socket)
if roll is not None:
read = math.degrees(math.atan2(np.cross(a[:3, 1], b[:3, 1]) @ a[:3, 2], a[:3, 1] @ b[:3, 1]))
reading("roll", abs((read - roll + 180.0) % 360.0 - 180.0))
return max(float(np.abs(a[:3, 3] - b[:3, 3]).max()), float(np.abs(a[:3, 2] + b[:3, 2]).max()))
def connection(name):
receipt, report = send("brokkr_kitbash.report", object_name=name)
return report["parts"][0]["connection"] if report else {"error": receipt["message"]}
def holds(name, parent, socket, parent_socket, roll=0.0):
found = connection(name) or {}
return found == {**found, "parent": parent, "socket": socket, "parentSocket": parent_socket, "roll": roll, "holds": True} \
and found.get("residual", 1.0) <= 1e-5, found
def held(report):
"""An attach or set_params report whose connection holds."""
return bool(report and report.get("connection") and report["connection"]["holds"] and report["connection"]["residual"] <= 1e-5)
def scene_state():
return {o.name: (o.parent and o.parent.name, np.round(np.array(o.matrix_basis), 6).tolist(), np.round(np.array(o.matrix_parent_inverse), 6).tolist(),
{k: o[k] for k in sorted(o.keys()) if k.startswith("kit_")}, [(m.name, m.type) for m in o.modifiers],
o.data.name if o.type == "MESH" else None, len(o.data.polygons) if o.type == "MESH" else None,
[s.material and s.material.name for s in o.material_slots], o.hide_render)
for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes)
def refused(label, action, fields, expected):
state = scene_state()
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"]])
def measure(mesh):
bm = bmesh.new()
bm.from_mesh(mesh)
row = {"faces": len(bm.faces), "volume": round(bm.calc_volume(signed=True), 9), "nonManifoldEdges": sum(1 for e in bm.edges if not e.is_manifold)}
bm.free()
return row
def evaluated(obj):
"""(faces, volume, non-manifold edges, material slot names) of the object with its modifiers, read here and not through the add-on."""
shown = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
row = measure(shown.to_mesh())
shown.to_mesh_clear()
return row, [m.name if m else None for m in shown.data.materials]
rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")]
check("the eight kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == [f"brokkr_kitbash.{n}" for n in (
"place_part", "set_params", "describe", "report", "attach", "detach", "boolean", "apply")], [R["hostErrors"], rows])
# --- attach -------------------------------------------------------------------------------------------------------------
tank = place("Tank", "tank", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # port size 0.088
tee = place("Tee", "pipe_fitting", "pipe_r=0.044", location=[-2.0, 0.5, 1.0], rotation=[1.1, 0.4, -0.7])
nozzle = place("Nozzle", "nozzle", "throat_r=0.044", location=[0.0, 4.0, 0.0])
spare = place("Spare", "nozzle", "throat_r=0.044", location=[0.0, 6.0, 0.0])
wide = place("Wide", "nozzle", location=[0.0, 8.0, 0.0]) # throat 0.07: flange size 0.14
radiator = place("Radiator", "radiator_stack", location=[0.0, 10.0, 0.0])
send("createObject", objectType="MESH", name="Plain", location=[0.0, 12.0, 0.0], size=0.3)
receipt, report = send("brokkr_kitbash.report", object_name="Tank")
check("a part nobody attached reports connection null and baked false", report and report["parts"][0]["connection"] is None
and report["parts"][0]["baked"] is False, report)
receipt, report = send("brokkr_kitbash.attach", object_name="Nozzle", socket="mount", parent_name="Tee", parent_socket="c", roll=37.0)
check("attach parents the nozzle to the tee under an identity parent inverse and stores the three properties", receipt["status"] == "accepted"
and nozzle.parent == tee and np.array_equal(np.array(nozzle.matrix_parent_inverse), np.eye(4))
and (nozzle["kit_socket"], nozzle["kit_parent_socket"], nozzle["kit_roll"]) == ("mount", "c", 37.0)
and sorted(k for k in nozzle.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_parent_socket", "kit_part", "kit_roll", "kit_socket"],
[receipt["message"], dict(nozzle.items())])
gap = reading("seated", seated(nozzle, "mount", tee, "c", 37.0))
check("attach seats the nozzle's mount on the tee's c: origins together, normals opposed, rolled 37 degrees", gap < SEATED and R["readings"]["roll"] < ROLL, dict(R["readings"]))
check("attach reports the child: its connection holds, and its sockets are the seated world frames", report
and report["connection"] == {**report["connection"], "parent": "Tee", "socket": "mount", "parentSocket": "c", "roll": 37.0, "holds": True}
and report["connection"]["residual"] <= 1e-5 and report["object"] == "Nozzle"
and np.abs(np.array(report["sockets"][0]["matrix"]) - frame(nozzle, "mount")).max() < 2e-6, report)
check("report shows the same connection", holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle"))
receipt, report = send("brokkr_kitbash.attach", object_name="Tee", socket="a", parent_name="Tank", parent_socket="port_b")
check("attach of the tee to the tank's port carries the nozzle with it", receipt["status"] == "accepted" and held(report) and report["connection"]["roll"] == 0.0 and reading("seated", seated(tee, "a", tank, "port_b", 0.0)) < SEATED
and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED and R["readings"]["roll"] < ROLL
and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], [receipt["message"], R["readings"]])
refused("sockets of different types", "brokkr_kitbash.attach", {"object_name": "Radiator", "socket": "base", "parent_name": "Tee", "parent_socket": "b"},
"'Radiator' on 'Tee': socket 'base' (mount, size 0.15) and parent socket 'b' (flange, size 0.088) are of different types")
refused("flanges of different sizes", "brokkr_kitbash.attach", {"object_name": "Wide", "socket": "mount", "parent_name": "Tee", "parent_socket": "b"},
"mate at equal sizes")
refused("a parent socket a child is on", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "c"},
"Socket 'c' of 'Tee' is occupied (by 'Nozzle')")
refused("a parent socket the parent is attached by", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "a"},
"Socket 'a' of 'Tee' is occupied (by 'Tank')")
refused("a loop through a grandchild", "brokkr_kitbash.attach", {"object_name": "Tank", "socket": "port_a", "parent_name": "Nozzle", "parent_socket": "mount"},
"'Nozzle' is below 'Tank'")
refused("a child that has a parent", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "b"},
"'Nozzle' has a parent, 'Tee'")
refused("a part to itself", "brokkr_kitbash.attach", {"object_name": "Tank", "socket": "port_a", "parent_name": "Tank", "parent_socket": "port_b"},
"cannot be attached to itself")
refused("a socket the parent does not have", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "d"},
"'Spare' on 'Tee': kit 'mechanical' part 'pipe_fitting' has no socket 'd'; its sockets: a, b, c")
refused("a socket the child does not have", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "throat", "parent_name": "Tee", "parent_socket": "b"},
"part 'nozzle' has no socket 'throat'")
refused("a child that is not a kit part", "brokkr_kitbash.attach", {"object_name": "Plain", "socket": "a", "parent_name": "Tee", "parent_socket": "b"},
"'Plain' is not a kit part")
refused("a parent that is not a kit part", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Plain", "parent_socket": "b"},
"'Plain' is not a kit part")
refused("detach of a part that is not attached", "brokkr_kitbash.detach", {"object_name": "Spare"}, "'Spare' is not attached")
send("brokkr_kitbash.detach", object_name="Tee")
send("setObjectTransform", targetObjectName="Tee", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7])
refused("a child socket one of its own children is on", "brokkr_kitbash.attach", {"object_name": "Tee", "socket": "c", "parent_name": "Tank", "parent_socket": "port_b"},
"Socket 'c' of 'Tee' is occupied (by 'Nozzle')")
send("brokkr_kitbash.attach", object_name="Tee", socket="a", parent_name="Tank", parent_socket="port_b")
receipt, report = send("brokkr_kitbash.attach", object_name="Spare", socket="mount", parent_name="Tee", parent_socket="b", roll=-90.0)
check("a second nozzle attaches to the tee's free socket, rolled -90", receipt["status"] == "accepted" and held(report)
and reading("seated", seated(spare, "mount", tee, "b", -90.0)) < SEATED and R["readings"]["roll"] < ROLL, [receipt["message"], R["readings"]])
# --- set_params seats what is attached again ----------------------------------------------------------------------------------
was = {name: np.array(bpy.data.objects[name].matrix_world) for name in ("Tank", "Tee", "Nozzle", "Spare")}
receipt, report = send("brokkr_kitbash.set_params", object_name="Tank", params="length=1.8")
moved = {name: np.array(bpy.data.objects[name].matrix_world) - was[name] for name in was}
port = np.array(tank.matrix_world)[:3, :3] @ [0.0, 0.0, 0.9] # where port_b went: 0.9 along the tank's own z
check("set_params doubling the tank's length moves the tee and both nozzles by the port's displacement, and nothing turns",
receipt["status"] == "accepted" and np.abs(moved["Tank"]).max() == 0.0
and all(reading("carried", np.abs(moved[n][:3, 3] - port).max()) < CARRIED and np.abs(moved[n][:3, :3]).max() < 1e-6 for n in ("Tee", "Nozzle", "Spare")),
[receipt["message"], {n: m[:3, 3].tolist() for n, m in moved.items()}, port.tolist()])
check("after it every connection holds", holds("Tee", "Tank", "a", "port_b")[0] and holds("Nozzle", "Tee", "mount", "c", 37.0)[0]
and holds("Spare", "Tee", "mount", "b", -90.0)[0] and reading("seated", seated(tee, "a", tank, "port_b")) < SEATED
and reading("seated", seated(nozzle, "mount", tee, "c")) < SEATED, [connection("Tee"), connection("Nozzle"), connection("Spare")])
refused("set_params that breaks the part's own connection", "brokkr_kitbash.set_params", {"object_name": "Tee", "params": "pipe_r=0.06"},
"'Tee' on 'Tank': socket 'a' (flange, size 0.12) and parent socket 'port_b' (flange, size 0.088)")
refused("set_params that breaks a child's connection", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "radius=0.3"},
"'Tee' on 'Tank': socket 'a' (flange, size 0.088) and parent socket 'port_b' (flange, size 0.12)")
receipt, report = send("brokkr_kitbash.set_params", object_name="Tee", params="branch=0.4; run=0.6")
check("set_params on the tee keeps its own seat and moves each nozzle with its socket", receipt["status"] == "accepted" and held(report)
and reading("seated", seated(tee, "a", tank, "port_b")) < SEATED and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED
and reading("seated", seated(spare, "mount", tee, "b", -90.0)) < SEATED and holds("Nozzle", "Tee", "mount", "c", 37.0)[0]
and holds("Spare", "Tee", "mount", "b", -90.0)[0] and R["readings"]["roll"] < ROLL, [receipt["message"], R["readings"]])
# a strut hangs from one actuator's rod, and a second actuator hangs from the strut by its own rod
lift = place("Lift", "actuator", location=[4.0, 0.0, 0.0], rotation=[0.2, 0.9, -0.4]) # pivot size 0.054
strut = place("Strut", "strut", "width=0.09")
ram = place("Ram", "actuator")
send("brokkr_kitbash.attach", object_name="Strut", socket="end_a", parent_name="Lift", parent_socket="rod_end", roll=90.0)
send("brokkr_kitbash.attach", object_name="Ram", socket="rod_end", parent_name="Strut", parent_socket="end_b")
base = frame(ram, "base")
receipt, report = send("brokkr_kitbash.set_params", object_name="Ram", params="extension=0.5")
back = frame(ram, "base")[:3, 3] - base[:3, 3]
check("extending an actuator that hangs by its rod seats it again: the rod end stays, the body backs off by the travel",
reading("seated", seated(ram, "rod_end", strut, "end_b", 0.0)) < SEATED and receipt["status"] == "accepted" and held(report)
and reading("carried", np.abs(back - base[:3, 2] * 0.35).max()) < CARRIED, [receipt["message"], connection("Ram"), back.tolist()])
tip = frame(strut, "end_b")
receipt, report = send("brokkr_kitbash.set_params", object_name="Lift", params="extension=0.6")
check("extending the actuator above moves the strut on its rod and the ram below with it", receipt["status"] == "accepted"
and holds("Strut", "Lift", "end_a", "rod_end", 90.0)[0] and holds("Ram", "Strut", "rod_end", "end_b")[0]
and reading("seated", seated(strut, "end_a", lift, "rod_end", 90.0)) < SEATED
and reading("carried", np.abs(frame(strut, "end_b")[:3, 3] - tip[:3, 3] - np.array(lift.matrix_world)[:3, 2] * 0.45).max()) < CARRIED,
[receipt["message"], connection("Strut"), connection("Ram")])
# --- drift and detach ---------------------------------------------------------------------------------------------------------
send("setObjectTransform", targetObjectName="Nozzle", location=[0.25, 0.0, 0.0])
found = connection("Nozzle") or {}
check("setObjectTransform on an attached child shows in its report: holds false, with the residual", found.get("holds") is False and found["parent"] == "Tee"
and found["residual"] > 0.1, found)
refused("attach of a drifted child, which still has its parent", "brokkr_kitbash.attach",
{"object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "c"}, "'Nozzle' has a parent, 'Tee'")
send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6")
check("set_params on its parent seats it again", holds("Nozzle", "Tee", "mount", "c", 37.0)[0] and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED,
connection("Nozzle"))
send("setObjectTransform", targetObjectName="Nozzle", rotationEuler=[0.0, 0.5, 0.0])
drifted = connection("Nozzle") or {}
send("brokkr_kitbash.set_params", object_name="Nozzle", params="exit_r=0.3")
check("set_params on the drifted child itself seats it again", drifted.get("holds") is False and holds("Nozzle", "Tee", "mount", "c", 37.0)[0]
and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED, [drifted, connection("Nozzle")])
nozzle.matrix_parent_inverse = nozzle.matrix_basis.inverted() # as parenting by hand in the viewport leaves it; the basis below keeps the nozzle where it is
nozzle.matrix_basis = nozzle.matrix_basis @ nozzle.matrix_basis
bpy.context.view_layer.update()
found = connection("Nozzle") or {}
check("a parent inverse that is not the identity does not hold, wherever the child stands", found.get("holds") is False and found["residual"] <= 1e-5
and seated(nozzle, "mount", tee, "c") < SEATED, found)
send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6")
check("and set_params on the parent writes the identity back", holds("Nozzle", "Tee", "mount", "c", 37.0)[0]
and np.array_equal(np.array(nozzle.matrix_parent_inverse), np.eye(4)), connection("Nozzle"))
send("setObjectParent", targetObjectName="Spare", parentObjectName="")
found = connection("Spare")
check("setObjectParent clearing an attached child's parent shows as a connection with no parent", found and found == {**found, "parent": None, "holds": False, "residual": None}, found)
refused("set_params on a part whose connection has no parent", "brokkr_kitbash.set_params", {"object_name": "Spare", "params": "exit_r=0.3"},
"'Spare' states a connection and has no parent")
send("setObjectParent", targetObjectName="Spare", parentObjectName="Plain")
found = connection("Spare") or {}
refused("set_params on a part parented to something that is not a kit part", "brokkr_kitbash.set_params", {"object_name": "Spare", "params": "exit_r=0.3"},
"'Plain' is not a kit part")
receipt, report = send("brokkr_kitbash.detach", object_name="Spare")
check("detach clears what is left of it", found.get("holds") is False and found.get("parent") == "Plain" and receipt["status"] == "accepted" and spare.parent is None
and report and report["connection"] is None and not [k for k in spare.keys() if k in ("kit_socket", "kit_parent_socket", "kit_roll")], [found, report])
before = {name: np.array(bpy.data.objects[name].matrix_world) for name in ("Tee", "Nozzle")}
receipt, report = send("brokkr_kitbash.detach", object_name="Tee")
check("detach leaves the tee where it stood, with no parent and no connection", receipt["status"] == "accepted" and tee.parent is None
and report and report["connection"] is None and sorted(k for k in tee.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_part"]
and reading("kept", max(np.abs(np.array(bpy.data.objects[n].matrix_world) - before[n]).max() for n in before)) < KEPT, [receipt["message"], R["readings"]])
check("and the nozzle stays attached to the tee", nozzle.parent == tee and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle"))
send("brokkr_kitbash.attach", object_name="Tee", socket="b", parent_name="Tank", parent_socket="port_a", roll=180.0)
check("the freed tee attaches by another socket to the tank's other port", holds("Tee", "Tank", "b", "port_a", 180.0)[0]
and reading("seated", seated(tee, "b", tank, "port_a", 180.0)) < SEATED and R["readings"]["roll"] < ROLL, connection("Tee"))
# --- boolean: the tank, with two material slots -----------------------------------------------------------------------------------
send("assignMaterial", targetObjectName="Tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35])
send("assignMaterial", targetObjectName="Tank", materialName="Strap Steel", color=[0.2, 0.2, 0.2])
tank_built = core.build(kit["parts"]["tank"], json.loads(tank["kit_params"]))
STRAPS = sorted(set(tank_built.shape.tolist()))[-1]
tank.data.polygons.foreach_set("material_index", np.where(tank_built.shape == STRAPS, 1, 0).astype(np.int32))
side = np.array(tank.matrix_world) @ [0.24, 0.0, 0.9, 1.0] # on the barrel's wall, halfway along
send("createObject", objectType="MESH", name="Box", location=side[:3].tolist(), size=0.3)
box = bpy.data.objects["Box"]
box_was = (box.hide_render, box.hide_viewport, len(box.data.polygons), [m.name for m in box.modifiers], box.parent)
raw = measure(tank.data)
receipt, cut = send("brokkr_kitbash.boolean", object_name="Tank", cutter="Box")
modifier = tank.modifiers.get("Kit Boolean Box")
check("boolean adds a Boolean modifier above the Bevel: Exact, self-intersection on, difference, the cutter its object",
receipt["status"] == "accepted" and [m.name for m in tank.modifiers] == ["Kit Boolean Box", "Kit Bevel"] and modifier is not None and modifier.type == "BOOLEAN"
and (modifier.solver, modifier.use_self, modifier.operation, modifier.operand_type, modifier.object) == ("EXACT", True, "DIFFERENCE", "OBJECT", box),
[receipt["message"], [m.name for m in tank.modifiers]])
shown, shown_slots = evaluated(tank)
check("boolean reports the evaluated mesh, with less volume than the uncut tank and no non-manifold edge", cut and cut["evaluated"] == shown
and CUT < cut["evaluated"]["volume"] < raw["volume"] - 0.005 and cut["evaluated"]["nonManifoldEdges"] == 0
and cut["booleans"] == [{"cutter": "Box", "operation": "DIFFERENCE"}] and cut["faces"] == len(tank.data.polygons) == raw["faces"],
[cut and cut["evaluated"], shown, raw])
R["tank"] = {"raw": raw, "cut": cut and cut["evaluated"]}
check("the cut tank shows the tank's two material slots and no other", shown_slots == ["Tank Paint", "Strap Steel"] and modifier is not None and modifier.material_mode == "TRANSFER", shown_slots)
check("boolean leaves the cutter as it was", (box.hide_render, box.hide_viewport, len(box.data.polygons), [m.name for m in box.modifiers], box.parent) == box_was
and "kit_part" not in box, box_was)
refused("a cutter that already cuts the part", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Box", "operation": "UNION"},
"'Box' is already the object of a Boolean on 'Tank'")
refused("the part as its own cutter", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Tank"}, "cannot cut itself")
refused("a cutter that does not exist", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Nothing"}, "No mesh object named 'Nothing'")
send("createObject", objectType="EMPTY", name="Marker")
refused("a cutter that is not a mesh", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Marker"}, "No mesh object named 'Marker'")
refused("boolean on a mesh that is not a kit part", "brokkr_kitbash.boolean", {"object_name": "Plain", "cutter": "Box"}, "'Plain' is not a kit part")
receipt, report = send("brokkr_kitbash.set_params", object_name="Tank", params="segments=16")
resized, _ = evaluated(tank)
check("set_params on the cut tank rebuilds it under the live Boolean, and the tee stays on its port", receipt["status"] == "accepted"
and [m.name for m in tank.modifiers] == ["Kit Boolean Box", "Kit Bevel"] and tank.modifiers["Kit Boolean Box"].object == box
and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], report["params"]).counts) != raw["faces"]
and CUT < resized["volume"] < measure(tank.data)["volume"] - 0.005 and holds("Tee", "Tank", "b", "port_a", 180.0)[0], [receipt["message"], resized])
# --- apply ------------------------------------------------------------------------------------------------------------------------
refused("apply on a mesh that is not a kit part", "brokkr_kitbash.apply", {"object_name": "Plain"}, "'Plain' is not a kit part")
slots = [s.material and s.material.name for s in tank.material_slots]
shown, shown_slots = evaluated(tank)
index = np.zeros(len(tank.data.polygons), dtype=np.int32)
tank.data.polygons.foreach_get("material_index", index)
mesh_name, meshes = tank.data.name, len(bpy.data.meshes)
sockets_before = send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["sockets"]
receipt, baked = send("brokkr_kitbash.apply", object_name="Tank")
after = np.zeros(len(tank.data.polygons), dtype=np.int32)
tank.data.polygons.foreach_get("material_index", after)
check("apply makes the evaluated mesh the tank's mesh: the same faces and volume, no modifiers, one mesh datablock of the old name",
receipt["status"] == "accepted" and baked and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown == measure(tank.data)
and len(tank.modifiers) == 0 and tank.data.name == mesh_name and len(bpy.data.meshes) == meshes and baked["cutters"] == ["Box"], [receipt["message"], baked, shown])
check("apply keeps the material slots exactly, and faces of both materials", slots == shown_slots == ["Tank Paint", "Strap Steel"]
and [s.material and s.material.name for s in tank.material_slots] == slots and [m and m.name for m in tank.data.materials] == slots
and index.max() == 1 and sorted(set(after.tolist())) == [0, 1], [slots, [m and m.name for m in tank.data.materials], sorted(set(after.tolist()))])
check("apply marks the part baked and keeps what it is", tank.get("kit_baked") is True and baked and baked["baked"] is True and tank["kit_part"] == "tank"
and json.loads(tank["kit_params"])["segments"] == 16, dict(tank.items()))
refused("set_params on a baked part", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"}, "'Tank' is baked")
refused("apply on a baked part with no modifiers left", "brokkr_kitbash.apply", {"object_name": "Tank"}, "'Tank' has no modifiers to apply")
receipt, report = send("brokkr_kitbash.report", object_name="Tank")
check("a baked part still reports its sockets where its params put them, and what is attached to it still holds", report and report["parts"][0]["baked"] is True
and report["parts"][0]["sockets"] == sockets_before and report["parts"][0]["faces"] == baked["faces"] and holds("Tee", "Tank", "b", "port_a", 180.0)[0]
and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], report)
receipt, report = send("brokkr_kitbash.attach", object_name="Radiator", socket="base", parent_name="Tank", parent_socket="saddle")
check("a new part attaches to a baked one", receipt["status"] == "accepted" and held(report)
and reading("seated", seated(radiator, "base", tank, "saddle", 0.0)) < SEATED, receipt["message"])
# --- the second target: a plate with no material slot, cut twice ----------------------------------------------------------------------
plate = place("Plate", "plate", location=[0.0, -3.0, 0.0])
send("createObject", objectType="MESH", name="Slot", location=[0.1, -3.0, 0.0], size=0.1)
send("createObject", objectType="MESH", name="Hole", location=[-0.1, -3.0, 0.0], size=0.05)
receipt, first = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Slot")
receipt, second = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Hole")
check("two cutters stack in the order they came, both above the Bevel", receipt["status"] == "accepted"
and [m.name for m in plate.modifiers] == ["Kit Boolean Slot", "Kit Boolean Hole", "Kit Bevel"]
and second["booleans"] == [{"cutter": "Slot", "operation": "DIFFERENCE"}, {"cutter": "Hole", "operation": "DIFFERENCE"}]
and second["evaluated"]["volume"] < first["evaluated"]["volume"] and first["evaluated"]["nonManifoldEdges"] == second["evaluated"]["nonManifoldEdges"] == 0
and all(m.use_self and m.solver == "EXACT" for m in plate.modifiers if m.type == "BOOLEAN"),
[[m.name for m in plate.modifiers], first and first["evaluated"], second and second["evaluated"]])
R["plate"] = {"raw": measure(plate.data), "slot": first and first["evaluated"], "slotAndHole": second and second["evaluated"]}
twin = plate.copy()
twin.name = "Plate_twin"
bpy.context.scene.collection.objects.link(twin)
refused("apply on a mesh a linked duplicate shares", "brokkr_kitbash.apply", {"object_name": "Plate"}, "shares its mesh 'Plate' with 1 other user(s): baking it")
bpy.data.objects.remove(twin)
shown, shown_slots = evaluated(plate)
receipt, baked = send("brokkr_kitbash.apply", object_name="Plate")
check("apply on a part with no material slot leaves it with none (Blender's Boolean shows it with one empty slot)", receipt["status"] == "accepted"
and shown_slots == [None] and len(plate.data.materials) == 0 and len(plate.material_slots) == 0 and baked["cutters"] == ["Slot", "Hole"]
and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown, [shown_slots, len(plate.data.materials), len(plate.material_slots), baked])
send("assignMaterial", targetObjectName="Plate", materialName="Plate Paint", color=[0.35, 0.35, 0.35])
send("createObject", objectType="MESH", name="Boss", location=[0.0, -3.0, 0.1], size=0.06)
send("assignMaterial", targetObjectName="Boss", materialName="Boss Brass", color=[0.6, 0.5, 0.2])
send("setObjectTransform", targetObjectName="Boss", location=[0.0, -3.0, 0.02])
receipt, third = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Boss", operation="UNION")
shown, shown_slots = evaluated(plate)
receipt, baked = send("brokkr_kitbash.apply", object_name="Plate")
used = np.zeros(len(plate.data.polygons), dtype=np.int32)
plate.data.polygons.foreach_get("material_index", used)
check("a baked part is cut and baked again; a cutter that has a material brings it after the part's own slots, on the faces it made",
receipt["status"] == "accepted" and third["booleans"] == [{"cutter": "Boss", "operation": "UNION"}] and third["baked"] is True
and third["evaluated"]["volume"] > R["plate"]["slotAndHole"]["volume"] and shown_slots == ["Plate Paint", "Boss Brass"]
and [m and m.name for m in plate.data.materials] == ["Plate Paint", "Boss Brass"] and sorted(set(used.tolist())) == [0, 1]
and len(plate.modifiers) == 0, [third and third["evaluated"], shown_slots, [m and m.name for m in plate.data.materials], sorted(set(used.tolist()))])
vent = place("Vent", "vent", "width=0.2; height=0.15")
receipt, report = send("brokkr_kitbash.attach", object_name="Vent", socket="back", parent_name="Plate", parent_socket="front")
check("a vent that fits attaches to the baked plate's front", receipt["status"] == "accepted" and held(report)
and reading("seated", seated(vent, "back", plate, "front", 0.0)) < SEATED, receipt["message"])
refused("a loop of two", "brokkr_kitbash.attach", {"object_name": "Plate", "socket": "back", "parent_name": "Vent", "parent_socket": "back"},
"'Vent' is below 'Plate'")
big = place("Big", "vent", "width=0.8; height=0.6")
refused("a part larger than the seat", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Plate", "parent_socket": "back"},
"are mount sockets, where the child fits the parent: it is larger")
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"], flush=True)
sys.exit(0 if R["ok"] else 1)

View file

@ -0,0 +1,372 @@
{
"blender": "5.3.0",
"checks": [
{
"name": "the eight kitbash rows load as host actions with no errors",
"ok": true,
"detail": null
},
{
"name": "a part nobody attached reports connection null and baked false",
"ok": true,
"detail": null
},
{
"name": "attach parents the nozzle to the tee under an identity parent inverse and stores the three properties",
"ok": true,
"detail": null
},
{
"name": "attach seats the nozzle's mount on the tee's c: origins together, normals opposed, rolled 37 degrees",
"ok": true,
"detail": null
},
{
"name": "attach reports the child: its connection holds, and its sockets are the seated world frames",
"ok": true,
"detail": null
},
{
"name": "report shows the same connection",
"ok": true,
"detail": null
},
{
"name": "attach of the tee to the tank's port carries the nozzle with it",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: sockets of different types",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: flanges of different sizes",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a parent socket a child is on",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a parent socket the parent is attached by",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a loop through a grandchild",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a child that has a parent",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a part to itself",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a socket the parent does not have",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a socket the child does not have",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a child that is not a kit part",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a parent that is not a kit part",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: detach of a part that is not attached",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a child socket one of its own children is on",
"ok": true,
"detail": null
},
{
"name": "a second nozzle attaches to the tee's free socket, rolled -90",
"ok": true,
"detail": null
},
{
"name": "set_params doubling the tank's length moves the tee and both nozzles by the port's displacement, and nothing turns",
"ok": true,
"detail": null
},
{
"name": "after it every connection holds",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: set_params that breaks the part's own connection",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: set_params that breaks a child's connection",
"ok": true,
"detail": null
},
{
"name": "set_params on the tee keeps its own seat and moves each nozzle with its socket",
"ok": true,
"detail": null
},
{
"name": "extending an actuator that hangs by its rod seats it again: the rod end stays, the body backs off by the travel",
"ok": true,
"detail": null
},
{
"name": "extending the actuator above moves the strut on its rod and the ram below with it",
"ok": true,
"detail": null
},
{
"name": "setObjectTransform on an attached child shows in its report: holds false, with the residual",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: attach of a drifted child, which still has its parent",
"ok": true,
"detail": null
},
{
"name": "set_params on its parent seats it again",
"ok": true,
"detail": null
},
{
"name": "set_params on the drifted child itself seats it again",
"ok": true,
"detail": null
},
{
"name": "a parent inverse that is not the identity does not hold, wherever the child stands",
"ok": true,
"detail": null
},
{
"name": "and set_params on the parent writes the identity back",
"ok": true,
"detail": null
},
{
"name": "setObjectParent clearing an attached child's parent shows as a connection with no parent",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: set_params on a part whose connection has no parent",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: set_params on a part parented to something that is not a kit part",
"ok": true,
"detail": null
},
{
"name": "detach clears what is left of it",
"ok": true,
"detail": null
},
{
"name": "detach leaves the tee where it stood, with no parent and no connection",
"ok": true,
"detail": null
},
{
"name": "and the nozzle stays attached to the tee",
"ok": true,
"detail": null
},
{
"name": "the freed tee attaches by another socket to the tank's other port",
"ok": true,
"detail": null
},
{
"name": "boolean adds a Boolean modifier above the Bevel: Exact, self-intersection on, difference, the cutter its object",
"ok": true,
"detail": null
},
{
"name": "boolean reports the evaluated mesh, with less volume than the uncut tank and no non-manifold edge",
"ok": true,
"detail": null
},
{
"name": "the cut tank shows the tank's two material slots and no other",
"ok": true,
"detail": null
},
{
"name": "boolean leaves the cutter as it was",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a cutter that already cuts the part",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: the part as its own cutter",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a cutter that does not exist",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a cutter that is not a mesh",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: boolean on a mesh that is not a kit part",
"ok": true,
"detail": null
},
{
"name": "set_params on the cut tank rebuilds it under the live Boolean, and the tee stays on its port",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: apply on a mesh that is not a kit part",
"ok": true,
"detail": null
},
{
"name": "apply makes the evaluated mesh the tank's mesh: the same faces and volume, no modifiers, one mesh datablock of the old name",
"ok": true,
"detail": null
},
{
"name": "apply keeps the material slots exactly, and faces of both materials",
"ok": true,
"detail": null
},
{
"name": "apply marks the part baked and keeps what it is",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: set_params on a baked part",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: apply on a baked part with no modifiers left",
"ok": true,
"detail": null
},
{
"name": "a baked part still reports its sockets where its params put them, and what is attached to it still holds",
"ok": true,
"detail": null
},
{
"name": "a new part attaches to a baked one",
"ok": true,
"detail": null
},
{
"name": "two cutters stack in the order they came, both above the Bevel",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: apply on a mesh a linked duplicate shares",
"ok": true,
"detail": null
},
{
"name": "apply on a part with no material slot leaves it with none (Blender's Boolean shows it with one empty slot)",
"ok": true,
"detail": null
},
{
"name": "a baked part is cut and baked again; a cutter that has a material brings it after the part's own slots, on the faces it made",
"ok": true,
"detail": null
},
{
"name": "a vent that fits attaches to the baked plate's front",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a loop of two",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a part larger than the seat",
"ok": true,
"detail": null
}
],
"hostErrors": [],
"readings": {
"carried": 2.7e-07,
"kept": 1.5e-08,
"roll": 6.3e-06,
"seated": 1.5e-07
},
"tank": {
"raw": {
"faces": 740,
"volume": 0.264901065,
"nonManifoldEdges": 0
},
"cut": {
"faces": 2337,
"volume": 0.25387923,
"nonManifoldEdges": 0
}
},
"plate": {
"raw": {
"faces": 44,
"volume": 0.002056141,
"nonManifoldEdges": 0
},
"slot": {
"faces": 504,
"volume": 0.001448832,
"nonManifoldEdges": 0
},
"slotAndHole": {
"faces": 558,
"volume": 0.001411154,
"nonManifoldEdges": 0
}
},
"ok": true
}

View file

@ -2,7 +2,7 @@
corner of its params, and the host action file against Brokkr's own checker. corner of its params, and the host action file against Brokkr's own checker.
Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it) Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it)
The operators are exercised in a real Blender by tests/live/kitbash.py. The operators are exercised in a real Blender by tests/live/kitbash.py and tests/live/kitbash_assembly.py.
Bounds follow lodur:ruling:deterministic-bound-margin: a deterministic reading is exact here, so each assertion is Bounds follow lodur:ruling:deterministic-bound-margin: a deterministic reading is exact here, so each assertion is
the built value, and each names the mutant it kills. the built value, and each names the mutant it kills.
@ -389,6 +389,111 @@ class MechanicalKitTests(unittest.TestCase):
self.assertEqual(described["parts"][0]["params"][0], {"name": "radius", "type": "number", "min": 0.12, "max": 0.35, "default": 0.22, "doc": "shell radius"}) self.assertEqual(described["parts"][0]["params"][0], {"name": "radius", "type": "number", "min": 0.12, "max": 0.35, "default": 0.22, "doc": "shell radius"})
@unittest.skipIf(np is None, "numpy is not installed")
class MateTests(unittest.TestCase):
"""core.mate, residual, mate_refusal and joint. The four bounds sit at the geometric mean of the shipped worst
reading and the least claimed mutant's (lodur:ruling:deterministic-bound-margin); a shipped reading of exactly
0 is taken as one float step (2.2e-16; 2.8e-14 degrees for the roll, which is read through a sum with 180)."""
PAIRS = [("pipe_fitting", {}, "c", "nozzle", {"throat_r": 0.05}, "mount"), ("pipe_fitting", {}, "b", "tank", {"radius": 0.25}, "port_b"),
("strut", {"width": 0.09}, "end_b", "actuator", {"body_r": 0.06}, "rod_end"), ("tank", {}, "saddle", "radiator_stack", {}, "base"),
("plate", {}, "front", "vent", {"width": 0.2, "height": 0.15}, "back")]
ORIGIN = 6.2e-8 # shipped 8.9e-16; least mutant 4.36 (the child socket's inverse replaced by its transpose); separation 4.9e15
NORMAL = 2.1e-8 # shipped 0; least mutant 1.974 (A1, FLIP dropped); separation above 8e15
ROLL = 2.2e-6 # degrees. shipped 0; least mutant 180 (A2, roll sign reversed, at roll -90); separation above 6e15
RESIDUAL = 4.2e-8 # shipped 8.9e-16; least mutant 1.999 (A1 and A2 both); separation 2.2e15
@classmethod
def setUpClass(cls):
cls.kit = core.load_kit("mechanical")
def sockets(self, parent, parent_params, parent_socket, child, child_params, child_socket):
parts = self.kit["parts"]
return core.joint(parts[parent], core.build(parts[parent], parent_params), parent_socket,
parts[child], core.build(parts[child], child_params), child_socket)
def test_a_mated_child_sits_on_the_parent_socket_at_its_roll(self):
"""mate-math, read from the two world frames and not through core.residual. Mutants A1 (FLIP dropped: the
normals agree instead of opposing) and A2 (roll sign reversed)."""
rng = random.Random("mate")
worst = {"origin": 0.0, "normal": 0.0, "roll": 0.0, "residual": 0.0}
for pair in self.PAIRS:
sp, sc = self.sockets(*pair)
self.assertIsNone(core.mate_refusal(self.kit["socketTypes"], sp, sc), pair)
for _ in range(4):
world = np.eye(4)
world[:3, :3] = core._rotation([rng.uniform(-180, 180) for _ in range(3)])
world[:3, 3] = [rng.uniform(-5, 5) for _ in range(3)]
for roll in (0.0, 37.0, -90.0, 180.0):
child = world @ core.mate(sp, sc, roll)
a, b = world @ sp["matrix"], child @ sc["matrix"]
read = math.degrees(math.atan2(np.cross(a[:3, 1], b[:3, 1]) @ a[:3, 2], a[:3, 1] @ b[:3, 1])) # the child's y from the parent's, about the parent's z
worst["origin"] = max(worst["origin"], float(np.abs(a[:3, 3] - b[:3, 3]).max()))
worst["normal"] = max(worst["normal"], float(np.abs(a[:3, 2] + b[:3, 2]).max()))
worst["roll"] = max(worst["roll"], abs((read - roll + 180.0) % 360.0 - 180.0))
worst["residual"] = max(worst["residual"], core.residual(world, sp, child, sc, roll))
self.assertLess(np.abs(child[:3, :3].T @ child[:3, :3] - np.eye(3)).max(), 1e-12)
if roll == 0.0:
self.assertLess(np.abs(a[:3, 1] - b[:3, 1]).max(), self.NORMAL, "roll 0 lines the two ys up")
self.assertLess(worst["origin"], self.ORIGIN)
self.assertLess(worst["normal"], self.NORMAL)
self.assertLess(worst["roll"], self.ROLL)
self.assertLess(worst["residual"], self.RESIDUAL)
def test_residual_is_how_far_the_child_stands_from_its_mate(self):
sp, sc = self.sockets(*self.PAIRS[0])
world = np.eye(4)
world[:3, 3] = [1.0, 2.0, 3.0]
child = world @ core.mate(sp, sc, 37.0)
moved = child.copy()
moved[0, 3] += 0.25
self.assertAlmostEqual(core.residual(world, sp, moved, sc, 37.0), 0.25, places=12)
self.assertGreater(core.residual(world, sp, child, sc, 38.0), 0.01) # the stated roll is part of the mate
self.assertEqual(core.FLIP.tolist(), [[-1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -1.0, 0.0], [0.0, 0.0, 0.0, 1.0]])
def test_what_may_mate(self):
"""mate-refusal. Mutants A3 (fits reversed) and A4 (equal at 10 percent)."""
types = self.kit["socketTypes"]
socket = lambda name, kind, size: {"name": name, "type": kind, "size": size, "matrix": np.eye(4)} # noqa: E731
self.assertRegex(core.mate_refusal(types, socket("p", "flange", 0.1), socket("c", "mount", 0.1)),
r"socket 'c' \(mount, size 0\.1\) and parent socket 'p' \(flange, size 0\.1\) are of different types")
for kind in ("flange", "pivot"): # equal: within 1 percent of the larger, the limit included
self.assertIsNone(core.mate_refusal(types, socket("p", kind, 100.0), socket("c", kind, 99.0)))
self.assertIsNone(core.mate_refusal(types, socket("p", kind, 99.0), socket("c", kind, 100.0)))
self.assertIsNone(core.mate_refusal(types, socket("p", kind, 0.2), socket("c", kind, 0.198)))
self.assertIn("mate at equal sizes", core.mate_refusal(types, socket("p", kind, 100.0), socket("c", kind, 98.99)))
self.assertIn("mate at equal sizes", core.mate_refusal(types, socket("p", kind, 98.99), socket("c", kind, 100.0)))
self.assertIsNone(core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.3))) # fits: the child at most the parent
self.assertIsNone(core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.1)))
self.assertIn("it is larger", core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.3 + 1e-6)))
self.assertIn("it is larger", core.mate_refusal(types, socket("p", "mount", 0.1), socket("c", "mount", 0.3)))
def test_the_kit_s_own_flanges_do_not_meet_everywhere(self):
"""A chamber flange (ribbed_cylinder, 0.16 and up) and the plumbing (pipe_fitting, 0.14 and down) never mate."""
parts = self.kit["parts"]
drum = core.build(parts["ribbed_cylinder"], {"radius": 0.08}).sockets[1]
pipe = core.build(parts["pipe_fitting"], {"pipe_r": 0.07}).sockets[0]
self.assertEqual((drum["size"], pipe["size"]), (0.16, 0.14))
self.assertIn("mate at equal sizes", core.mate_refusal(self.kit["socketTypes"], drum, pipe))
def test_a_joint_is_two_named_sockets_of_one_kit(self):
"""The cross-kit refusal (one kit ships, so no scene can show it) and the unknown-socket refusals."""
parts = self.kit["parts"]
tank, fitting = core.build(parts["tank"]), core.build(parts["pipe_fitting"])
sp, sc = core.joint(parts["tank"], tank, "port_b", parts["pipe_fitting"], fitting, "a")
self.assertEqual((sp["name"], sc["name"]), ("port_b", "a"))
other = {**parts["pipe_fitting"], "kit": "hydraulic"}
with self.assertRaisesRegex(core.KitError, "part 'pipe_fitting' is of kit 'hydraulic' and part 'tank' of kit 'mechanical'.*do not mate"):
core.joint(parts["tank"], tank, "port_b", other, fitting, "a")
with self.assertRaisesRegex(core.KitError, "part 'tank' has no socket 'port_c'; its sockets: port_a, port_b, saddle"):
core.joint(parts["tank"], tank, "port_c", parts["pipe_fitting"], fitting, "a")
with self.assertRaisesRegex(core.KitError, "part 'pipe_fitting' has no socket 'd'; its sockets: a, b, c"):
core.joint(parts["tank"], tank, "port_b", parts["pipe_fitting"], fitting, "d")
ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report",
"brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.boolean", "brokkr_kitbash.apply"]
class HostFileTests(unittest.TestCase): class HostFileTests(unittest.TestCase):
def setUp(self): def setUp(self):
self.document = json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8")) self.document = json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8"))
@ -396,8 +501,7 @@ class HostFileTests(unittest.TestCase):
def test_brokkr_admits_the_file(self): def test_brokkr_admits_the_file(self):
"""rows-check: Brokkr's own host-file checker.""" """rows-check: Brokkr's own host-file checker."""
at.check_host(self.document, at.table()["charsets"]) at.check_host(self.document, at.table()["charsets"])
self.assertEqual([row["name"] for row in self.document["actions"]], self.assertEqual([row["name"] for row in self.document["actions"]], ROWS)
["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report"])
def test_every_row_names_an_operator_and_property_the_add_on_defines(self): def test_every_row_names_an_operator_and_property_the_add_on_defines(self):
source = (SURFACE / "brokkr_kitbash" / "__init__.py").read_text(encoding="utf-8") source = (SURFACE / "brokkr_kitbash" / "__init__.py").read_text(encoding="utf-8")
@ -421,11 +525,30 @@ class HostFileTests(unittest.TestCase):
with self.assertRaises(at.IntentInvalid): with self.assertRaises(at.IntentInvalid):
at.validate({**envelope, "action": "brokkr_kitbash.place_part", "part": "tank", "object_name": "Tank", "location": "0,0,0"}, host) at.validate({**envelope, "action": "brokkr_kitbash.place_part", "part": "tank", "object_name": "Tank", "location": "0,0,0"}, host)
def test_the_assembly_rows_take_scalars_inside_their_bounds(self):
host = [{**row, "host": "brokkr_kitbash"} for row in self.document["actions"]]
envelope = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver"}
attach = {**envelope, "action": "brokkr_kitbash.attach", "object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "c"}
self.assertEqual(at.validate(attach, host)["roll"], 0)
self.assertEqual(at.validate({**attach, "roll": -360}, host)["roll"], -360)
boolean = {**envelope, "action": "brokkr_kitbash.boolean", "object_name": "Tank", "cutter": "Box"}
self.assertEqual(at.validate(boolean, host)["operation"], "DIFFERENCE")
for bad in ({**attach, "roll": 360.5}, {**attach, "socket": "a b"}, {**attach, "parent_socket": ""}, {**attach, "matrix": [1, 0, 0]},
{**boolean, "operation": "SLICE"}, {**boolean, "solver": "EXACT"}, {**boolean, "cutter": ""},
{**envelope, "action": "brokkr_kitbash.apply"}, {**envelope, "action": "brokkr_kitbash.detach", "object_name": "x" * 64}):
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"])
class OwnershipTests(unittest.TestCase): class OwnershipTests(unittest.TestCase):
"""The negative patterns of the cut: expressions are walked and never run, the bridge stays out, core needs no """The negative patterns of the cut: expressions are walked and never run, the bridge stays out, core needs no
Blender, and schemas/ holds no second statement of the kit format.""" Blender, and schemas/ holds no second statement of the kit format."""
PACKAGE = (r"\beval\(|\bexec\(|\bcompile\(", r"brokkr_bridge") PACKAGE = (r"\beval\(|\bexec\(|\bcompile\(", r"brokkr_bridge",
r"\bsolver\s*=\s*[\"']MANIFOLD|\buse_self\s*=\s*False", # a boolean is Exact with self-intersection, nothing else
r"hide_render|hide_viewport|display_type", # a cutter's visibility is setObjectVisibility's
r"kit_parent_name|kit_parent\b|matrix_world_stored") # obj.parent has no second owner
CORE = r"^import bpy|^from bpy|^import bmesh" CORE = r"^import bpy|^from bpy|^import bmesh"
SCHEMAS = r"brokkr\.kit\.v0" SCHEMAS = r"brokkr\.kit\.v0"
@ -443,9 +566,24 @@ class OwnershipTests(unittest.TestCase):
for path in schemas: for path in schemas:
self.assertIsNone(re.search(self.SCHEMAS, path.read_text(encoding="utf-8", errors="replace")), path.name) self.assertIsNone(re.search(self.SCHEMAS, path.read_text(encoding="utf-8", errors="replace")), path.name)
def test_only_boolean_and_apply_evaluate_a_modifier_stack(self):
"""An Exact Boolean costs about a second a part: report, attach, detach and set_params read stored state only."""
source = self.sources()["__init__.py"]
self.assertEqual(source.count("evaluated_get("), 1)
self.assertIn("evaluated_get(", source.split("def evaluated_of(")[1].split("\n\n\n")[0])
callers = [body.split("(")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:] if "evaluated_of(" in body]
self.assertEqual(callers, ["boolean", "apply"])
self.assertEqual(source.count("evaluated_of("), 3)
self.assertEqual(source.count("to_mesh("), 1)
def test_the_patterns_bite(self): def test_the_patterns_bite(self):
for pattern, planted in zip(self.PACKAGE, ("value = eval(text)", "from brokkr_bridge import x")): planted = ("value = eval(text)", "from brokkr_bridge import x", 'modifier.solver = "MANIFOLD"', "cutter.hide_render = True", 'obj["kit_parent"] = parent.name')
self.assertIsNotNone(re.search(pattern, planted)) self.assertEqual(len(planted), len(self.PACKAGE))
for pattern, text in zip(self.PACKAGE, planted):
self.assertIsNotNone(re.search(pattern, text))
for text in ("modifier.use_self = False", "cutter.display_type = 'WIRE'", "obj.hide_viewport = True", 'KEY = "kit_parent_name"'):
self.assertTrue(any(re.search(pattern, text) for pattern in self.PACKAGE[2:]), text)
self.assertIsNone(re.search(self.PACKAGE[4], 'PARENT_SOCKET = "kit_parent_socket"'))
for planted in ("exec(text)", "code = compile(text, 'kit', 'eval')", "KIT = re.compile('x')"): for planted in ("exec(text)", "code = compile(text, 'kit', 'eval')", "KIT = re.compile('x')"):
self.assertIsNotNone(re.search(self.PACKAGE[0], planted)) self.assertIsNotNone(re.search(self.PACKAGE[0], planted))
for planted in ("import bpy", "x = 1\nfrom bpy import props", "import bmesh"): for planted in ("import bpy", "x = 1\nfrom bpy import props", "import bmesh"):