brokkr_kitbash: roll, aim and reach pose an attached part in place, the roll solved in closed form

write_connection is the one writer of a connection (parent, seat, kit_socket, kit_parent_socket, kit_roll);
attach's inline write moves into it. roll states an attached part's roll where it hangs; aim and reach solve
it from core.roll_terms (d . p = A cos + B sin + C): aim_roll = atan2(B, A), reach_roll = atan2(B, A) +- acos,
the root nearer the current roll. Each reports closures as set_params does and never seats one.

PoseTests pin the solves against core.mate; tests/live/kitbash_pose.py exercises the three operators and their
refusals through run_intent. Cut kit-roll-aim (aetheria-release:cut_spec:cut-kit-roll-aim.r1).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-02 02:08:31 +01:00
commit bdad28ff53
8 changed files with 807 additions and 25 deletions

View file

@ -14,7 +14,9 @@ params).
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
params by core.mate; attach and set_params write it, and a report says how far the child stands from it.
write_connection is the one writer of a connection. roll, aim and reach rewrite an attached part's roll through it,
in place: roll states the roll, aim and reach solve it in closed form (core.aim_roll, core.reach_roll). 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,
@ -209,6 +211,15 @@ def seat(child, basis) -> None:
child.matrix_basis = Matrix(np.asarray(basis).tolist())
def write_connection(child, parent, sockets, stated) -> None:
"""State a connection and seat it: the child's parent, its derived matrix_basis and its three properties.
`sockets` is mated()'s answer for `stated`. attach, roll, aim and reach write a connection here and nowhere
else."""
child.parent = parent
seat(child, core.mate(*sockets, stated[2]))
child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated
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 roll is a number, the parent inverse is the identity and the child
@ -450,9 +461,7 @@ class BROKKR_KITBASH_OT_attach(PolishOperator):
sockets = mated(parent, parent_part, parent_built, child, part, built, stated)
free(parent, self.parent_socket)
free(child, self.socket)
child.parent = parent
seat(child, core.mate(*sockets, stated[2]))
child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated
write_connection(child, parent, sockets, stated)
context.view_layer.update()
return part_report(child, part, built)
@ -480,6 +489,97 @@ class BROKKR_KITBASH_OT_detach(PolishOperator):
return part_report(obj, part, built)
def pose(context, name: str, solve) -> dict:
"""Give an attached part a new roll where it hangs: its parent and both sockets stay, and what is attached to
it follows. `solve(child, built, sockets, stated)` answers (the roll, what to add to the report), or refuses.
Refuses a part that states no connection or has no parent, and what mated() refuses. The report is the part's
and, as set_params', every closure in the scene with the part's own first: a roll can open one, and never
seats one."""
child = mesh_object(name)
part, built = built_part(child)
stated = link(child)
if stated is None:
raise Refused(f"{child.name!r} is not attached (it has no {SOCKET} property): attach gives it a connection to pose; nothing changed.")
if child.parent is None:
raise Refused(f"{child.name!r} states a connection and has no parent: detach it to clear the connection; nothing changed.")
sockets = mated(child.parent, *built_part(child.parent), child, part, built, stated)
try:
roll, solved = solve(child, built, sockets, stated)
except core.KitError as error:
raise Refused(f"{child.name!r} on {child.parent.name!r}: {error}; nothing changed.") from None
write_connection(child, child.parent, sockets, (stated[0], stated[1], float(roll)))
context.view_layer.update()
report = {**part_report(child, part, built), **solved}
report["closures"] = scene_closures(context, report, (child,))
return report
def unit(operator) -> np.ndarray:
"""An operator's direction_x, direction_y and direction_z as a unit vector; zero is refused."""
direction = np.array([operator.direction_x, operator.direction_y, operator.direction_z], dtype=np.float64)
if not np.linalg.norm(direction) > 0:
raise Refused("The direction is zero: give direction_x, direction_y and direction_z a world direction; nothing changed.")
return direction / np.linalg.norm(direction)
class BROKKR_KITBASH_OT_roll(PolishOperator):
"""Turn an attached kit part to a roll about its parent socket's normal, in place: its parent and sockets stay
and what hangs from it follows"""
bl_idname = "brokkr_kitbash.roll"
bl_label = "Roll Kit Part"
object_name: bpy.props.StringProperty(name="Object", description="An attached part")
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):
return pose(context, self.object_name, lambda child, built, sockets, stated: (self.roll, {}))
class BROKKR_KITBASH_OT_aim(PolishOperator):
"""Turn an attached kit part about its pin until one of its own axes points as near a world direction as the
pin lets it: the roll is solved, not searched"""
bl_idname = "brokkr_kitbash.aim"
bl_label = "Aim Kit Part"
object_name: bpy.props.StringProperty(name="Object", description="An attached part")
axis: bpy.props.EnumProperty(name="Axis", description="An axis of the part's own frame", default="+z",
items=[(name, name, "") for name in core.AXES])
direction_x: bpy.props.FloatProperty(name="Direction X", default=0.0, description="World direction, any length")
direction_y: bpy.props.FloatProperty(name="Direction Y", default=0.0)
direction_z: bpy.props.FloatProperty(name="Direction Z", default=0.0)
@kit_work
def work(self, context):
def solve(child, built, sockets, stated):
roll, dot = core.aim_roll(child.parent.matrix_world, *sockets, core.AXES[self.axis], unit(self))
return roll, {"aimed": {"roll": round(roll, 6), "dot": round(dot, 9)}}
return pose(context, self.object_name, solve)
class BROKKR_KITBASH_OT_reach(PolishOperator):
"""Turn an attached kit part about its pin until one of its sockets stands at a height along a world direction:
of the two rolls that do it, the one nearer the roll it has"""
bl_idname = "brokkr_kitbash.reach"
bl_label = "Reach With Kit Part"
object_name: bpy.props.StringProperty(name="Object", description="An attached part")
socket: bpy.props.StringProperty(name="Socket", description="The socket of the part whose origin is brought to the plane")
direction_x: bpy.props.FloatProperty(name="Direction X", default=0.0, description="World direction, any length")
direction_y: bpy.props.FloatProperty(name="Direction Y", default=0.0)
direction_z: bpy.props.FloatProperty(name="Direction Z", default=1.0)
height: bpy.props.FloatProperty(name="Height", default=0.0, min=-1000.0, max=1000.0,
description="Metres along the unit direction, in the world: the plane is direction . x = height")
@kit_work
def work(self, context):
def solve(child, built, sockets, stated):
found = [s for s in built.sockets if s["name"] == self.socket]
if not found:
raise Refused(f"{child.name!r} has no socket {self.socket!r}; its sockets: {', '.join(s['name'] for s in built.sockets)}; nothing changed.")
roll, residual = core.reach_roll(child.parent.matrix_world, *sockets, found[0]["matrix"][:3, 3], unit(self), self.height, stated[2])
return roll, {"reached": {"roll": round(roll, 6), "residual": round(residual, 9)}}
return pose(context, self.object_name, solve)
class BROKKR_KITBASH_OT_close(PolishOperator):
"""State that a socket of a kit part meets a socket of another part of its kit, closing a loop the tree of
connections cannot: accepted only when the two already meet, origins together and normals opposed, and it
@ -614,7 +714,8 @@ class BROKKR_KITBASH_OT_report(PolishOperator):
classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report,
BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_apply)
BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_roll, BROKKR_KITBASH_OT_aim, BROKKR_KITBASH_OT_reach,
BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_apply)
def register():

View file

@ -174,6 +174,140 @@
}
]
},
{
"name": "brokkr_kitbash.roll",
"doc": "Turn an attached kit part to a roll about its parent socket's normal, in place: its parent and both sockets stay, and what is attached to it follows. Refuses a part that is not attached. Reports the part and closures, every closure in the scene as {part, to, holds}, its own first: a roll can open one and never seats one.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "object_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "an attached part"
},
{
"name": "roll",
"type": "number",
"required": true,
"minimum": -360,
"maximum": 360,
"doc": "degrees about the parent socket's normal, right-handed; at 0 the two sockets' up axes line up"
}
]
},
{
"name": "brokkr_kitbash.aim",
"doc": "Turn an attached kit part about its pin until one of its own axes points as near a world direction as the pin lets it. The roll is solved exactly, not searched. Refuses an axis or a direction that lies along the pin, and a zero direction. Reports the part, aimed: {roll, dot} (dot 1 when the axis reaches the direction) and closures as roll does.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "object_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "an attached part"
},
{
"name": "axis",
"type": "string",
"required": true,
"enum": [
"+x",
"-x",
"+y",
"-y",
"+z",
"-z"
],
"doc": "an axis of the part's own frame"
},
{
"name": "direction_x",
"type": "number",
"minimum": -1000,
"maximum": 1000,
"required": true,
"doc": "the world direction to aim at, any length"
},
{
"name": "direction_y",
"type": "number",
"minimum": -1000,
"maximum": 1000,
"required": true
},
{
"name": "direction_z",
"type": "number",
"minimum": -1000,
"maximum": 1000,
"required": true
}
]
},
{
"name": "brokkr_kitbash.reach",
"doc": "Turn an attached kit part about its pin until one of its sockets' origins stands at a height along a world direction (by default world z): of the two rolls that do it, the one nearer the roll it has. Solved exactly. Refuses a height the socket cannot reach, naming the range it can. Reports the part, reached: {roll, residual} and closures as roll does.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "object_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "an attached part"
},
{
"name": "socket",
"type": "string",
"required": true,
"chars": "id",
"minLength": 1,
"maxLength": 32,
"doc": "the socket of the part that is brought to the plane; brokkr_kitbash.report lists a part's sockets"
},
{
"name": "direction_x",
"type": "number",
"minimum": -1000,
"maximum": 1000,
"default": 0,
"doc": "the world direction the height is measured along, any length"
},
{
"name": "direction_y",
"type": "number",
"minimum": -1000,
"maximum": 1000,
"default": 0
},
{
"name": "direction_z",
"type": "number",
"minimum": -1000,
"maximum": 1000,
"default": 1
},
{
"name": "height",
"type": "number",
"required": true,
"minimum": -1000,
"maximum": 1000,
"doc": "metres along the unit direction, in the world"
}
]
},
{
"name": "brokkr_kitbash.close",
"doc": "Close a loop: state that a socket of a kit part meets a socket of another part of its kit, where attach cannot (the part already has its parent). Accepted only when the two sockets already meet, origins together and normals opposed, any roll; it moves nothing. Attach the parts with the rolls that make them meet first; brokkr_kitbash.report shows the closure and whether it holds.",

View file

@ -14,6 +14,10 @@ Two sockets mate through mate (the child's matrix under its parent), mate_refusa
(how far a placed child stands from its mate). closure_residual is how far two sockets stand from meeting as a pin,
whatever the roll: what closes a loop the tree of connections cannot state.
A pin's roll is its one degree of freedom, and it is solved in closed form: roll_terms gives how a point or an axis
of the child moves along a world direction as the roll turns (a cosine, a sine and a constant), aim_roll the roll
that points an axis of the child at a direction, reach_roll the roll that brings a point of the child to a plane.
Every refusal is a KitError whose message names the kit, part and field.
"""
from __future__ import annotations
@ -621,6 +625,59 @@ def residual(parent_world, parent_socket: dict, child_world, child_socket: dict,
return float(np.abs(wanted - np.asarray(child_world, dtype=np.float64) @ child_socket["matrix"]).max())
def roll_terms(parent_world, parent_socket: dict, child_socket: dict, local, w: float, direction) -> tuple[float, float, float]:
"""(A, B, C) with direction . (the child's `local`, in the world) = A cos(roll) + B sin(roll) + C when the child
is mated on parent_socket at that roll. `local` is in the child's own frame: a point with w 1, an axis with w 0.
Everything but the roll is held: the parent's world matrix and both sockets."""
M = np.asarray(parent_world, dtype=np.float64) @ parent_socket["matrix"]
q = FLIP @ np.linalg.inv(child_socket["matrix"]) @ np.array([*local, w], dtype=np.float64)
direction = np.asarray(direction, dtype=np.float64)
e = M[:3, :3].T @ direction
return (float(e[0] * q[0] + e[1] * q[1]), float(e[1] * q[0] - e[0] * q[1]), float(e[2] * q[2] + w * (direction @ M[:3, 3])))
# The least hypot(A, B) aim_roll solves for: below it the axis or the direction lies along the pin and no roll turns
# one toward the other. Least aimable case of the tests 0.0175 (a direction 1 degree off the pin); a degenerate case
# reads at most 1.2e-16 (float rounding of an axis along the pin); the geometric mean, separation 1.2e7 each side.
AIM_FLOOR = 1.5e-9
def _wrapped(degrees: float) -> float:
"""An angle in (-180, 180]."""
return 180.0 - (180.0 - degrees) % 360.0
def aim_roll(parent_world, parent_socket: dict, child_socket: dict, axis, direction) -> tuple[float, float]:
"""(roll in degrees in (-180, 180], the dot it achieves) that turns the child's own `axis` as far toward the
world `direction` as its pin lets it: roll = atan2(B, A), dot = C + hypot(A, B), for unit vectors. Refuses an
axis or a direction along the pin, which no roll turns."""
direction = np.asarray(direction, dtype=np.float64)
direction = direction / np.linalg.norm(direction)
A, B, C = roll_terms(parent_world, parent_socket, child_socket, axis, 0.0, direction)
if math.hypot(A, B) <= AIM_FLOOR:
raise KitError(f"socket {child_socket['name']!r} on parent socket {parent_socket['name']!r}: the axis {tuple(float(v) for v in axis)} of the part "
f"or the direction {tuple(round(float(v), 6) for v in direction)} lies along the pin, so no roll turns one toward the other")
return _wrapped(math.degrees(math.atan2(B, A))), C + math.hypot(A, B)
def reach_roll(parent_world, parent_socket: dict, child_socket: dict, point, direction, height: float, current_roll: float) -> tuple[float, float]:
"""(roll in degrees in (-180, 180], residual |direction . p - height| in metres) that brings the child's own
`point` to the plane direction . x = height, for a unit direction: atan2(B, A) +- acos((height - C) / hypot(A, B)),
of the two the one nearer current_roll round the circle (a tie takes the smaller roll). Refuses a height the
point cannot reach, naming the range it can."""
direction = np.asarray(direction, dtype=np.float64)
direction = direction / np.linalg.norm(direction)
A, B, C = roll_terms(parent_world, parent_socket, child_socket, point, 1.0, direction)
swing = math.hypot(A, B)
if abs(height - C) > swing:
raise KitError(f"socket {child_socket['name']!r} on parent socket {parent_socket['name']!r}: no roll brings the point to {height:.6g} m along "
f"{tuple(round(float(v), 6) for v in direction)}; it reaches {C - swing:.6g} m to {C + swing:.6g} m")
middle, spread = math.degrees(math.atan2(B, A)), math.degrees(math.acos((height - C) / swing)) if swing > 0 else 0.0
roots = sorted({_wrapped(middle - spread), _wrapped(middle + spread)})
roll = min(roots, key=lambda root: (round(abs(_wrapped(root - current_roll)), 9), root))
return roll, abs(A * math.cos(math.radians(roll)) + B * math.sin(math.radians(roll)) + C - height)
def closure_residual(world_a, socket_a: dict, world_b, socket_b: dict) -> float:
"""How far two sockets of two placed parts stand from meeting as a pin: the larger of the largest difference
between their origins (metres) and the largest entry of the sum of their normals (0 when opposed). Roll is not

View file

@ -6,7 +6,7 @@ actuators, housings and plumbing an agent assembles offline under a hand-fit arm
add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish` and `brokkr_rig`:
it imports the polish package's operator base, `Refused` and `mesh_object`, and nothing from `brokkr_bridge`.
Enable `brokkr_mesh_polish` first; `brokkr_kitbash` refuses to register without it. `brokkr_actions.json` beside
its `__init__.py` lists the nine operators agents may run. Every action writes a JSON report to
its `__init__.py` lists the twelve operators agents may run. Every action writes a JSON report to
`brokkr_mesh_polish_result`, returned in the receipt's `hostResult`.
Who owns what:
@ -136,8 +136,8 @@ Nothing else stores it: no parent name, no world matrix, no empties. The child's
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.
with `S` each socket's frame in its own part at that part's stored params (`core.mate`). `attach`, `set_params`,
`roll`, `aim` and `reach` 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
@ -151,8 +151,8 @@ refuses, changing nothing:
- 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. Connections are a tree: tank, then a tee on
its port, then a nozzle on each free flange of the tee. Nothing moves a part but `attach` and `set_params`,
through that tree.
its port, then a nozzle on each free flange of the tee. Nothing moves a part but `attach`, `set_params` and the
three that pose a hinge, through that tree.
**A closure** states the one thing a tree cannot: that a part's second socket also meets something. A brace
hangs from its own bracket by one pin (a connection); its other pin meets the leg's rod (a closure), and the
@ -181,6 +181,34 @@ which gives the point where the free pins meet. Each member's roll is then the a
`z`, from that socket's `y` to the direction of the meeting point. `report` gives every socket's world frame to
read these from.
**Posing a hinge.** The roll is a connection's one degree of freedom, and three actions change it where the part
hangs: its parent and both sockets stay, the part is seated again at the new roll, and what is attached to it
follows through parenting. None of them detaches anything. `roll` states the roll. `aim` and `reach` solve it:
with everything but the roll held, a point or an axis of the child moves on a circle as the roll turns, so along
a world direction `d` it reads
```text
d . p(roll) = A cos(roll) + B sin(roll) + C
```
with `A`, `B` and `C` from the parent's world frame, the two sockets and the point or axis in the child's own
frame (`core.roll_terms`). `aim` turns one of the child's own axes (`+x` to `-z`) as far toward `d` as the pin
lets it: `roll = atan2(B, A)`, and the dot it reaches is `C + hypot(A, B)`, reported as `aimed: {roll, dot}`; a
dot under 1 says the pin does not let the axis reach the direction. `reach` brings the origin of one of the
child's sockets to the plane `d . x = height`: `roll = atan2(B, A) ± acos((height - C) / hypot(A, B))`, of the two
the one nearer the roll the part has (a tie takes the smaller), reported as `reached: {roll, residual}`. Both are
exact: nothing is searched. The roll they write is in (-180, 180] and is stored as `kit_roll`; the direction or
plane it was solved for is stored nowhere, so a parent that moves afterwards carries the part with it and nothing
re-aims it.
They refuse, changing nothing: a part that states no connection (`attach` it first), one whose parent was
cleared, a connection `attach` would refuse now (sockets that no longer mate), a zero direction, an `aim` whose
axis or direction lies along the pin (no roll turns one toward the other), and a `reach` to a height the socket's
circle does not cross, naming the range it does. A leg is posed with them from the hip down: `aim` the yoke's
front at where the leg should point, `reach` the last link's clevis to the ground plus the foot's drop, `aim`
the foot's sole at the ground. Each reports `closures` as `set_params` does, the part's own first: a roll moves
everything below the part, can open a closure anywhere there, and never seats one.
A part's report carries `closure`: `null`, or
```json
@ -197,7 +225,7 @@ after which the two sockets may no longer mate (a pin of another size), naming t
moves a socket (an actuator's `extension` under a closed brace) is accepted and opens the closure: the report
of `set_params` lists every closure in the scene as `closures: [{part, to, holds}]`, those its own part is an
end of first, then those that do not hold, then the rest, so the caller sees which
ones it opened and can solve the rolls again, `detach` and `attach` the members, and find the closure holding.
ones it opened and can solve the rolls again, turn the members with `roll` or `reach`, and find the closure holding.
`detach` clears the closing part's closure together with its connection.
**`set_params` keeps an assembly together.** Sockets move with params (an actuator's `rod_end` with `extension`, a
@ -274,6 +302,9 @@ vertices overflow.
| `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`, `closure` 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 and the closure it states; it stays where it stands. Refuses a part that has neither. |
| `brokkr_kitbash.roll` | `object_name`, `roll` (degrees, -360 to 360) | Turns an attached part to that roll where it hangs. Refuses a part that is not attached. Reports the part and `closures` as `set_params` does. |
| `brokkr_kitbash.aim` | `object_name`, `axis` (`+x`, `-x`, `+y`, `-y`, `+z` or `-z`, the part's own), `direction_x`, `direction_y`, `direction_z` (world, any length) | Solves the roll that turns the axis as far toward the direction as the pin lets it, and turns the part to it. Refuses an axis or direction along the pin. Reports the part, `aimed: {roll, dot}` and `closures`. |
| `brokkr_kitbash.reach` | `object_name`, `socket` (one of the part's), `height` (metres, -1000 to 1000), `direction_x`, `direction_y`, `direction_z` (world; default 0, 0, 1) | Solves the roll that brings the socket's origin to `height` along the direction, the nearer of the two, and turns the part to it. Refuses a height out of reach, naming the range. Reports the part, `reached: {roll, residual}` and `closures`. |
| `brokkr_kitbash.close` | `object_name` (the closing part), `socket`, `other_name`, `other_socket` | States that the closing part's socket meets the other part's, closing a loop. Accepted only when they already meet; moves nothing. Reports the closing part. |
| `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. |
@ -373,6 +404,7 @@ 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
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_eleven_parts_and_three_socket_types`.
`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, a braced leg closed by `close`, boolean and apply).
`MateTests` covers the mate arithmetic and what may mate, `PoseTests` the closed-form rolls. The operators are
exercised in a real Blender by `tests/live/kitbash.py` (placing and re-parameterising),
`tests/live/kitbash_assembly.py` (attach, detach, `set_params` on assemblies, a braced leg closed by `close`,
boolean and apply) and `tests/live/kitbash_pose.py` (roll, aim and reach).

View file

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

View file

@ -176,8 +176,8 @@ def evaluated(obj):
rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")]
check("the nine 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", "close", "boolean", "apply")], [R["hostErrors"], rows])
check("the twelve 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", "roll", "aim", "reach", "close", "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

View file

@ -0,0 +1,291 @@
"""Live proof, in a background Blender, of brokkr_kitbash posing through run_intent: roll turns an attached part
where it hangs, aim and reach solve the roll (core.aim_roll, core.reach_roll), each reports the closures it opened,
and each refusal changes nothing. Not part of the unittest run: it needs Blender.
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_pose.py -- <out>
Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses
without them). <out> is an absolute path; writes <out>.result.json and exits 1 when a check failed.
The scene: a tank, a bracket on its lug, a strut pinned in the bracket, an actuator pinned on the strut's far end,
and a loose strut whose closure names the actuator's rod pin. Bounds follow lodur:ruling:deterministic-bound-margin:
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 bpy
import numpy as np
from mathutils import Matrix
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-pose-"))
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 posed part's socket is and where its mate puts it, read
# from the two world matrices. Shipped worst 2.4e-07 (float32 matrices); least claimed mutant 0.24 (R3, roll writes
# kit_roll without seating: the actuator, read against the roll its strut states); separation 1.0e6.
SEATED = 2.4e-4
# Degrees between the roll read from the two world frames and the roll stated. Shipped worst 1.4e-05; least claimed
# mutant 15 (R3, at the smallest turn here); separation 1.1e6.
ROLL = 1.4e-2
# Metres between how far the actuator's pin moved and how far the strut's socket that carries it moved. Shipped
# worst 2.4e-07; least claimed mutant 0.38 (R3: the strut's socket is read at the stated roll, the actuator stays).
CARRIED = 3.0e-4
# The dot aim reports against the dot read from the scene, and its roll (degrees) against core.aim_roll on the
# scene's float32 matrices. Shipped worst 6.0e-08 and 3.4e-06; least claimed mutant 1.0 and 90 (R1); the roll's
# bound is ROLL's.
AIMED = 2.4e-4
# Metres between the socket reach moved and the plane asked for, read from the scene. Shipped worst 2.4e-07; least
# claimed mutant 0.36 (R6, a left-handed roll_terms: the root it solves is the mirror's).
REACHED = 2.9e-4
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 socket(obj, name):
built = core.build(core.part(kit, obj["kit_part"]), json.loads(obj["kit_params"]))
return next(s for s in built.sockets if s["name"] == name)
def frame(obj, name):
"""A socket's world frame, from the object's matrix_world and core's build of its stored params."""
return np.array(obj.matrix_world, dtype=np.float64) @ socket(obj, name)["matrix"]
def seated(child, name, 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, name)
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(found, parent, name, parent_socket, roll):
"""A connection row that states this connection and holds."""
found = found or {}
return found == {**found, "parent": parent, "socket": name, "parentSocket": parent_socket, "roll": roll, "holds": True} and found.get("residual", 1.0) <= 1e-5
def stated(obj):
return obj.parent and obj.parent.name, {k: obj[k] for k in sorted(obj.keys()) if k.startswith("kit_") and k != "kit_roll"}, np.array(obj.matrix_parent_inverse).tolist()
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: repr(o[k]) for k in sorted(o.keys()) if k.startswith("kit_")}) for o in bpy.data.objects}
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"]])
rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")]
check("roll, aim and reach load as host actions after detach, with no errors", not R["hostErrors"] and "brokkr_kitbash.detach" in rows
and rows[rows.index("brokkr_kitbash.detach") + 1:][:3] == ["brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach"], [R["hostErrors"], rows])
# --- the scene ----------------------------------------------------------------------------------------------------------
tank = place("Tank", "tank", "radius=0.3; length=1.2", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # lug size 0.09
mount = place("Mount", "bracket") # pin 0.054, plate 0.09
strut, ram = place("Strut", "strut", "width=0.09"), place("Ram", "actuator")
spare, orphan = place("Spare", "strut", "width=0.09", location=[0.0, 6.0, 0.0]), place("Orphan", "bracket")
send("createObject", objectType="MESH", name="Plain", location=[0.0, 12.0, 0.0], size=0.3)
send("brokkr_kitbash.attach", object_name="Mount", socket="mount", parent_name="Tank", parent_socket="lug_b")
send("brokkr_kitbash.attach", object_name="Orphan", socket="mount", parent_name="Tank", parent_socket="lug_a")
send("brokkr_kitbash.attach", object_name="Strut", socket="end_a", parent_name="Mount", parent_socket="pivot", roll=20.0)
receipt, report = send("brokkr_kitbash.attach", object_name="Ram", socket="base", parent_name="Strut", parent_socket="end_b", roll=-35.0)
check("the chain stands: tank, bracket, strut, actuator", receipt["status"] == "accepted" and holds(connection("Strut"), "Mount", "end_a", "pivot", 20.0)
and holds(report["connection"], "Strut", "base", "end_b", -35.0), [receipt["message"], connection("Strut")])
def meeting(name, other, other_socket, roll):
"""Place a loose strut so its end_a meets a socket of another part, and close it there."""
loose = place(name, "strut", "width=0.09")
meet = Matrix((np.array(other.matrix_world) @ core.mate(socket(other, other_socket), socket(loose, "end_a"), roll)).tolist())
send("setObjectTransform", targetObjectName=name, location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ")))
return send("brokkr_kitbash.close", object_name=name, socket="end_a", other_name=other.name, other_socket=other_socket)
anchor = place("Aa_Anchor", "strut", "width=0.09", location=[0.0, -20.0, 0.0])
receipt, report = meeting("Brace", ram, "rod_end", 50.0)
check("a brace closes on the actuator's rod pin", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]])
receipt, report = meeting("Aa_Loose", anchor, "end_b", 40.0)
check("and a second closure, named to sort first, holds far from it", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]])
brace = bpy.data.objects["Brace"]
closing = {k: brace[k] for k in brace.keys() if k.startswith("kit_close")}
# --- roll: in place -----------------------------------------------------------------------------------------------------
for turn in (65.0, -160.0, 35.0): # from the 20 it was attached at
was, pin, before = stated(strut), frame(ram, "base")[:3, 3].copy(), (stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist())
sent = COUNT[0]
receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=turn)
carried = frame(strut, "end_b")[:3, 3] - pin # where the socket that carries the actuator stands now, from where the actuator's pin was
check(f"roll {turn:g} turns the strut where it hangs: one intent, its parent, sockets and parent inverse as they were, its roll stated and seated",
receipt["status"] == "accepted" and COUNT[0] == sent + 1 and stated(strut) == was and strut["kit_roll"] == turn
and reading("seated", seated(strut, "end_a", mount, "pivot", turn)) < SEATED and R["readings"]["roll"] < ROLL
and report and report["object"] == "Strut" and holds(report["connection"], "Mount", "end_a", "pivot", turn) and holds(connection("Strut"), "Mount", "end_a", "pivot", turn),
[receipt["message"], report and report["connection"], R["readings"]])
check(f"and the actuator follows through its own connection, which nothing rewrote (roll {turn:g})",
(stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist()) == before and float(np.linalg.norm(carried)) > 0.1
and reading("carried", np.abs(frame(ram, "base")[:3, 3] - pin - carried).max()) < CARRIED
and reading("seated", seated(ram, "base", strut, "end_b", -35.0)) < SEATED and R["readings"]["roll"] < ROLL and holds(connection("Ram"), "Strut", "base", "end_b", -35.0),
[carried.tolist(), connection("Ram"), R["readings"]])
reading("turned", float(np.linalg.norm(carried)))
# --- roll: the closures it opens ----------------------------------------------------------------------------------------
check("the rolls above opened the brace's closure and reported it before the one that holds, whatever its name", report and report.get("closures") == [
{"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}] and report["closure"] is None, report and report.get("closures"))
receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=20.0)
check("rolled back to where the brace met it, the closure holds again: read from where the parts stand", receipt["status"] == "accepted" and report["closures"] == [
{"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}, {"part": "Brace", "to": "Ram", "holds": True}], report and report.get("closures"))
send("setObjectTransform", targetObjectName="Aa_Loose", location=[0.0, -25.0, 0.0], rotationEuler=[0.0, 0.0, 0.0])
receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-35.0)
check("a roll lists the closures its own part is an end of first, before a broken one elsewhere", receipt["status"] == "accepted" and report["closures"] == [
{"part": "Brace", "to": "Ram", "holds": True}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}], report and report.get("closures"))
receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-36.0)
check("and a roll of the part a closure names opens it; no roll seats or rewrites a closure", receipt["status"] == "accepted" and report["closures"] == [
{"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}]
and {k: brace[k] for k in brace.keys() if k.startswith("kit_close")} == closing and brace.parent is None, [report and report.get("closures"), dict(brace.items())])
# --- aim ----------------------------------------------------------------------------------------------------------------
for axis, direction in (("+z", (1.0, 0.0, 0.0)), ("-x", (0.0, -3.0, 4.0)), ("+z", (0.2, 0.1, -2.0))):
world = np.array(mount.matrix_world, dtype=np.float64)
want, dot = core.aim_roll(world, socket(mount, "pivot"), socket(strut, "end_a"), core.AXES[axis], direction)
receipt, report = send("brokkr_kitbash.aim", object_name="Strut", axis=axis, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2])
aimed = (report or {}).get("aimed") or {"roll": 1e9, "dot": 1e9}
read = float(np.array(strut.matrix_world, dtype=np.float64)[:3, :3] @ np.array(core.AXES[axis]) @ (np.array(direction) / np.linalg.norm(direction)))
grid = max(float((world @ core.mate(socket(mount, "pivot"), socket(strut, "end_a"), float(r)))[:3, :3] @ np.array(core.AXES[axis]) @ (np.array(direction) / np.linalg.norm(direction)))
for r in range(-180, 180))
check(f"aim points the strut's {axis} at {direction} as far as its pin lets it: the dot core solves, the dot the scene reads, and no roll on a 1-degree grid passes it",
receipt["status"] == "accepted" and reading("aimed roll", abs((aimed["roll"] - want + 180.0) % 360.0 - 180.0)) < ROLL
and reading("aimed dot", max(abs(aimed["dot"] - dot), abs(aimed["dot"] - read))) < AIMED and grid < aimed["dot"] + AIMED and 0.2 < aimed["dot"] < 0.999,
[receipt["message"], aimed, want, dot, read, grid])
check(f"and it is stated and seated as roll's: the connection holds at the aimed roll, the actuator with it, closures reported ({axis})",
aimed["roll"] == round(strut["kit_roll"], 6) and -180.0 < aimed["roll"] <= 180.0
and holds(report and report["connection"], "Mount", "end_a", "pivot", aimed["roll"]) and reading("seated", seated(strut, "end_a", mount, "pivot", aimed["roll"])) < SEATED
and R["readings"]["roll"] < ROLL and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len(report.get("closures", [])) == 2,
[dict(strut.items()), report and report["connection"], report and report.get("closures")])
# --- reach --------------------------------------------------------------------------------------------------------------
for direction, part, offset in (((0.0, 0.0, 1.0), 0.5, 40.0), ((0.0, 0.0, 1.0), 0.5, -40.0), ((1.0, 2.0, -0.5), -0.8, 100.0)):
world, unit = np.array(mount.matrix_world, dtype=np.float64), np.array(direction) / np.linalg.norm(direction)
A, B, C = core.roll_terms(world, socket(mount, "pivot"), socket(strut, "end_a"), socket(strut, "end_b")["matrix"][:3, 3], 1.0, unit)
current = float(round(math.degrees(math.atan2(B, A)) + offset)) # the two rolls that reach stand either side of the middle: start nearer one
send("brokkr_kitbash.roll", object_name="Strut", roll=current)
height = round(C + part * math.hypot(A, B), 3)
want, _ = core.reach_roll(world, socket(mount, "pivot"), socket(strut, "end_a"), socket(strut, "end_b")["matrix"][:3, 3], unit, height, current)
other = (2.0 * math.degrees(math.atan2(B, A)) - want + 180.0) % 360.0 - 180.0
fields = {"direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]} if direction != (0.0, 0.0, 1.0) else {} # world z is the default
receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=height, **fields)
reached = (report or {}).get("reached") or {"roll": 1e9, "residual": 1e9}
check(f"reach brings the strut's end_b to {height} m along {direction} from roll {current:g}, by the nearer of the two rolls that do",
receipt["status"] == "accepted" and reading("reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - height)) < REACHED and reached["residual"] < REACHED
and reading("reached roll", abs((reached["roll"] - want + 180.0) % 360.0 - 180.0)) < ROLL
and abs((want - current + 180.0) % 360.0 - 180.0) + 10.0 < abs((other - current + 180.0) % 360.0 - 180.0),
[receipt["message"], reached, want, other, float(frame(strut, "end_b")[:3, 3] @ unit)])
check(f"and it is stated and seated as roll's ({direction}, from {current:g})", reached["roll"] == round(strut["kit_roll"], 6) and -180.0 < reached["roll"] <= 180.0
and holds(report and report["connection"], "Mount", "end_a", "pivot", reached["roll"]) and reading("seated", seated(strut, "end_a", mount, "pivot", reached["roll"])) < SEATED
and R["readings"]["roll"] < ROLL and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len(report.get("closures", [])) == 2,
[dict(strut.items()), report and report["connection"]])
# --- refusals -----------------------------------------------------------------------------------------------------------
send("setObjectParent", targetObjectName="Orphan", parentObjectName="")
low, high = C - math.hypot(A, B), C + math.hypot(A, B)
refused("roll of a part nobody attached", "brokkr_kitbash.roll", {"object_name": "Spare", "roll": 10.0}, "'Spare' is not attached (it has no kit_socket property)")
refused("aim of a part nobody attached", "brokkr_kitbash.aim", {"object_name": "Spare", "axis": "+z", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "'Spare' is not attached")
refused("reach of a part nobody attached", "brokkr_kitbash.reach", {"object_name": "Spare", "socket": "end_b", "height": 0.0}, "'Spare' is not attached")
refused("roll of a part whose parent was cleared", "brokkr_kitbash.roll", {"object_name": "Orphan", "roll": 10.0}, "'Orphan' states a connection and has no parent: detach it")
refused("roll of a mesh that is not a kit part", "brokkr_kitbash.roll", {"object_name": "Plain", "roll": 10.0}, "'Plain' is not a kit part")
refused("aim of the axis along the pin", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+y", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0},
"'Strut' on 'Mount': socket 'end_a' on parent socket 'pivot': the axis (0.0, 1.0, 0.0) of the part or the direction (1.0, 0.0, 0.0) lies along the pin")
refused("aim at no direction", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+z", "direction_x": 0.0, "direction_y": 0.0, "direction_z": 0.0}, "The direction is zero")
refused("reach past the circle the socket turns on, naming what it reaches", "brokkr_kitbash.reach",
{"object_name": "Strut", "socket": "end_b", "height": 900.0, "direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]},
f"no roll brings the point to 900 m along ({unit[0]:.6f}".rstrip("0"))
receipt, _ = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=900.0, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2])
check("and the range it names is the one core solves", f"it reaches {low:.6g} m to {high:.6g} m" in str(receipt["message"]) and high - low > 1.0, [receipt["message"], low, high])
refused("reach with a socket the part does not have", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_c", "height": 0.0},
"'Strut' has no socket 'end_c'; its sockets: end_a, end_a_back, end_b, end_b_back")
refused("reach along no direction", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": 0.0, "direction_z": 0.0}, "The direction is zero")
refused("a roll past a turn, by the action table", "brokkr_kitbash.roll", {"object_name": "Strut", "roll": 361.0}, "roll")
refused("an axis that is not one of the six, by the action table", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "x", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "axis")
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

@ -2,7 +2,8 @@
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)
The operators are exercised in a real Blender by tests/live/kitbash.py and tests/live/kitbash_assembly.py.
The operators are exercised in a real Blender by tests/live/kitbash.py, tests/live/kitbash_assembly.py and
tests/live/kitbash_pose.py.
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.
@ -771,8 +772,144 @@ class MateTests(unittest.TestCase):
core.joint(parts["tank"], tank, "port_b", parts["pipe_fitting"], fitting, "d")
@unittest.skipIf(np is None, "numpy is not installed")
class PoseTests(unittest.TestCase):
"""core.roll_terms, aim_roll and reach_roll: a pin's roll solved in closed form, read back through core.mate. The
bounds sit at the geometric mean of the shipped worst reading and the least claimed mutant's
(lodur:ruling:deterministic-bound-margin)."""
PAIRS = MateTests.PAIRS
AIMED = 2.1e-8 # shipped 2.2e-16; least mutant 1.91 (R1, atan2(A, B)); R6 (roll_terms' B with its sign flipped) reads 1.97; separation 8.6e15
BEATEN = 5.0e-9 # how far a roll on the 1-degree grid may pass the solved dot. shipped 0, taken as one float step; least mutant 0.114 (R8, the dot reported without its hypot); separation 5.1e14
REACHED = 6.6e-8 # metres off the plane. shipped 1.8e-15; least mutant 2.44 (R6); separation 1.4e15
NEARER = 2.2e-6 # degrees the chosen root may stand farther from the current roll than the other. shipped 0, taken as 2.8e-14; least mutant 172 (R2, the farther root)
@classmethod
def setUpClass(cls):
cls.kit = core.load_kit("mechanical")
def joints(self, seed):
"""Each PAIRS joint under four seeded random parent frames: (parent world, parent socket, child socket, rng)."""
rng, parts = random.Random(seed), self.kit["parts"]
for parent, parent_params, parent_socket, child, child_params, child_socket in self.PAIRS:
sp, sc = core.joint(parts[parent], core.build(parts[parent], parent_params), parent_socket,
parts[child], core.build(parts[child], child_params), child_socket)
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)]
yield world, sp, sc, rng
@staticmethod
def direction(rng):
d = np.array([rng.gauss(0, 1) for _ in range(3)])
return d / np.linalg.norm(d)
def aim_readings(self):
worst = {"aimed": 0.0, "terms": 0.0, "beaten": 0.0, "least": math.inf, "cases": 0}
for world, sp, sc, rng in self.joints("aim"):
for name, axis in core.AXES.items():
if abs(np.array(axis) @ sc["matrix"][:3, 2]) == 1.0:
continue # the socket's own normal: the pin
d = self.direction(rng)
roll, dot = core.aim_roll(world, sp, sc, axis, 3.0 * d) # any length
A, B, C = core.roll_terms(world, sp, sc, axis, 0.0, d)
turned = lambda r: float(d @ (world @ core.mate(sp, sc, r))[:3, :3] @ np.array(axis)) # noqa: E731
self.assertTrue(-180.0 < roll <= 180.0, roll)
worst["aimed"] = max(worst["aimed"], abs(dot - turned(roll)))
worst["terms"] = max(worst["terms"], abs(dot - (C + math.hypot(A, B))))
worst["beaten"] = max(worst["beaten"], max(turned(float(r)) for r in range(-180, 180)) - dot)
worst["least"] = min(worst["least"], math.hypot(A, B))
worst["cases"] += 1
return worst
def test_aim_is_the_roll_no_other_roll_beats(self):
"""aim-closed-form. The dot aim_roll reports is the axis's world dot after core.mate at that roll, is C + hypot(A, B),
and no roll on a 1-degree grid passes it. Mutants R1 (atan2(A, B)) and R6 (B's sign flipped: a left-handed roll)."""
ident = {"name": "s", "matrix": np.eye(4)}
roll, dot = core.aim_roll(np.eye(4), ident, ident, (0.0, 1.0, 0.0), (1.0, 0.0, 0.0)) # the child's y stands at (-sin, cos, 0)
self.assertEqual((round(roll, 9), round(dot, 12)), (-90.0, 1.0))
roll, dot = core.aim_roll(np.eye(4), ident, ident, (1.0, 0.0, 0.0), (1.0, 1.0, 5.0)) # its x at (-cos, -sin, 0): the pin lets it reach 0.272 of the way
self.assertEqual((round(roll, 9), round(dot, 12)), (-135.0, round(math.sqrt(2.0 / 27.0), 12)))
worst = self.aim_readings()
self.assertEqual(worst["cases"], 80)
self.assertLess(worst["aimed"], self.AIMED)
self.assertLess(worst["terms"], self.AIMED)
self.assertLess(worst["beaten"], self.BEATEN)
def reach_readings(self):
worst = {"reached": 0.0, "residual": 0.0, "nearer": 0.0, "cases": 0}
for world, sp, sc, rng in self.joints("reach"):
for _ in range(3):
point, d = [rng.uniform(-1, 1) for _ in range(3)], self.direction(rng)
A, B, C = core.roll_terms(world, sp, sc, point, 1.0, d)
swing, middle = math.hypot(A, B), math.degrees(math.atan2(B, A))
for part in (-0.999, -0.4, 0.0, 0.6, 0.999):
height, current = C + part * swing, rng.uniform(-360, 360)
roll, residual = core.reach_roll(world, sp, sc, point, 2.0 * d, height, current)
stands = float(d @ (world @ core.mate(sp, sc, roll) @ np.array([*point, 1.0]))[:3])
apart = lambda r: abs((r - current + 180.0) % 360.0 - 180.0) # noqa: E731
self.assertTrue(-180.0 < roll <= 180.0, roll)
worst["reached"] = max(worst["reached"], abs(stands - height))
worst["residual"] = max(worst["residual"], abs(residual - abs(stands - height)))
worst["nearer"] = max(worst["nearer"], apart(roll) - apart(2.0 * middle - roll)) # the other root mirrors it about the middle
worst["cases"] += 1
for beyond in (-1.01, 1.01):
with self.assertRaisesRegex(core.KitError, re.escape(f"it reaches {C - swing:.6g} m to {C + swing:.6g} m")):
core.reach_roll(world, sp, sc, point, d, C + beyond * swing, 0.0)
return worst
def test_reach_lands_on_the_plane_by_the_nearer_root(self):
"""reach-closed-form. The chosen roll puts the point on the plane, it is the root nearer the current roll (a tie takes
the smaller), and a height past the circle is refused with the range. Mutants R2 (the farther root) and R6."""
ident = {"name": "s", "matrix": np.eye(4)}
reach = lambda height, current: tuple(round(v, 9) for v in core.reach_roll(np.eye(4), ident, ident, (0.0, 1.0, 0.0), (1.0, 0.0, 0.0), height, current)) # noqa: E731
self.assertEqual(reach(0.5, 0.0), (-30.0, 0.0)) # the point stands at x = -sin(roll): rolls -30 and -150
self.assertEqual(reach(0.5, 170.0), (-150.0, 0.0))
self.assertEqual(reach(0.5, -90.0), (-150.0, 0.0)) # a tie
self.assertEqual(reach(0.5, 90.0), (-150.0, 0.0)) # and the tie across the circle
self.assertEqual(reach(0.5, 330.0), (-30.0, 0.0)) # the current roll is read round the circle
with self.assertRaisesRegex(core.KitError, r"no roll brings the point to 1\.5 m along \(1\.0, 0\.0, 0\.0\); it reaches -1 m to 1 m"):
reach(1.5, 0.0)
worst = self.reach_readings()
self.assertEqual(worst["cases"], 300)
self.assertLess(worst["reached"], self.REACHED)
self.assertLess(worst["residual"], self.REACHED)
self.assertLess(worst["nearer"], self.NEARER)
def floor_readings(self):
"""(the largest hypot(A, B) of an axis or a direction along the pin, the least of an axis 1 degree off it)."""
along, least = 0.0, math.inf
for world, sp, sc, rng in self.joints("floor"):
pin_local, pin_world = sc["matrix"][:3, 2], (world @ sp["matrix"])[:3, 2]
side = (world @ sp["matrix"])[:3, 0]
near = math.cos(math.radians(1.0)) * pin_world + math.sin(math.radians(1.0)) * side
for axis, d, refused in ((pin_local, self.direction(rng), True), ((1.0, 0.0, 0.0) if abs(pin_local[0]) < 0.5 else (0.0, 1.0, 0.0), pin_world, True),
((1.0, 0.0, 0.0) if abs(pin_local[0]) < 0.5 else (0.0, 1.0, 0.0), near, False)):
A, B, _ = core.roll_terms(world, sp, sc, axis, 0.0, d)
if refused:
along = max(along, math.hypot(A, B))
with self.assertRaisesRegex(core.KitError, "lies along the pin, so no roll turns one toward the other"):
core.aim_roll(world, sp, sc, axis, d)
else:
least = min(least, math.hypot(A, B))
core.aim_roll(world, sp, sc, axis, d)
return along, least
def test_aim_along_the_pin_is_refused(self):
"""aim-floor. An axis along the pin, or a direction along it, is refused; a direction 1 degree off it is solved.
AIM_FLOOR sits between the two readings by the margin rule. Mutant R5 (no floor: aim along the pin returns a roll)."""
along, least = self.floor_readings()
self.assertLess(along * 1.2, core.AIM_FLOOR)
self.assertGreater(least, core.AIM_FLOOR * 1.2)
self.assertLess(least, 0.0175) # sin(1 degree): the least case the floor is set against
self.assertGreater(min(self.aim_readings()["least"], least), core.AIM_FLOOR * 1.2)
ident = {"name": "s", "matrix": np.eye(4)}
with self.assertRaisesRegex(core.KitError, r"socket 's' on parent socket 's': the axis \(0\.0, 0\.0, 1\.0\) of the part or the direction \(1\.0, 0\.0, 0\.0\) lies along the pin"):
core.aim_roll(np.eye(4), ident, ident, (0.0, 0.0, 1.0), (1.0, 0.0, 0.0))
ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report",
"brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.apply"]
"brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.apply"]
class HostFileTests(unittest.TestCase):
@ -826,6 +963,22 @@ class HostFileTests(unittest.TestCase):
for row in self.document["actions"][4:]:
self.assertTrue(all(field["type"] in ("string", "number") for field in row["fields"]), row["name"])
def test_the_pose_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", "object_name": "Strut"}
roll = {**envelope, "action": "brokkr_kitbash.roll", "roll": -360}
aim = {**envelope, "action": "brokkr_kitbash.aim", "axis": "-y", "direction_x": 0, "direction_y": 0.5, "direction_z": -1}
reach = {**envelope, "action": "brokkr_kitbash.reach", "socket": "end_b", "height": 0.3}
self.assertEqual(at.validate(roll, host)["roll"], -360)
self.assertEqual(at.validate(aim, host)["axis"], "-y")
admitted = at.validate(reach, host)
self.assertEqual((admitted["direction_x"], admitted["direction_y"], admitted["direction_z"], admitted["height"]), (0, 0, 1, 0.3))
for bad in ({**roll, "roll": 361}, {k: v for k, v in roll.items() if k != "roll"}, {**aim, "axis": "x"},
{k: v for k, v in aim.items() if k != "direction_z"}, {**aim, "roll": 10}, {**reach, "height": 1e4},
{**reach, "socket": "end b"}, {k: v for k, v in reach.items() if k != "height"}, {**reach, "direction_z": "up"}):
with self.assertRaises(at.IntentInvalid, msg=str(bad)):
at.validate(bad, host)
class OwnershipTests(unittest.TestCase):
"""The negative patterns of the cut: expressions are walked and never run, the bridge stays out, core needs no
@ -862,12 +1015,26 @@ class OwnershipTests(unittest.TestCase):
self.assertEqual(source.count("evaluated_of("), 3)
self.assertEqual(source.count("to_mesh("), 1)
def test_only_attach_writes_the_roll(self):
"""kit_roll is the one statement of a connection's roll: set_params and the reports read it and never write it back."""
def test_only_write_connection_writes_the_roll(self):
"""one-writer. kit_roll is the one statement of a connection's roll, and write_connection its one writer: attach
and pose (roll, aim and reach) call it; set_params and the reports read the roll and never write it back.
Mutant R7 (attach keeps its own inline write beside write_connection)."""
source = self.sources()["__init__.py"]
writes = re.findall(r'[^\n]*(?:\[ROLL\]|\["kit_roll"\])\s*=(?!=)[^\n]*', source)
self.assertEqual(writes, [" child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated"])
self.assertIn(writes[0], source.split("class BROKKR_KITBASH_OT_attach")[1].split("class BROKKR_KITBASH_OT_")[0])
self.assertEqual(writes, [" child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated"])
self.assertIn(writes[0], source.split("def write_connection(")[1].split("\n\n\n")[0])
bodies = {body.split("(")[0]: body.split("\n\n\n")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:]}
callers = [name for name, body in bodies.items() if "write_connection(" in body]
self.assertEqual((callers, source.count("write_connection("), source.split("def pose(")[1].split("\n\n\n")[0].count("write_connection(")), (["attach"], 3, 1))
for name in ("roll", "aim", "reach"):
self.assertEqual((bodies[name].count("pose(context, self.object_name, "), bool(re.search(r"\.parent\s*=(?!=)|\bseat\(|matrix_basis", bodies[name]))), (1, False), name)
self.assertIsNone(re.search(r"\.parent\s*=(?!=)|\bseat\(|matrix_basis", bodies["attach"]))
def test_no_roll_is_searched(self):
"""A roll is solved, never scanned: no loop in the package steps a roll."""
for name in ("__init__.py", "core.py"):
self.assertIsNone(re.search(r"for [^\n]* in range\([^\n]*\):\s*\n[^\n]*roll", self.sources()[name]), name)
self.assertIsNotNone(re.search(r"for [^\n]* in range\([^\n]*\):\s*\n[^\n]*roll", "for k in range(72):\n reroll(child, k * 5)"))
def test_only_close_writes_a_closure(self):
"""A closure is the closing part's three properties: close assigns them, detach deletes them, nothing else does
@ -885,7 +1052,7 @@ class OwnershipTests(unittest.TestCase):
self.assertIsNone(re.search(placing, bodies["close"]))
for text in ("child.matrix_basis = basis", "obj.matrix_world = world", "obj.parent = other", "seat(obj, basis)"):
self.assertIsNotNone(re.search(placing, text))
self.assertIsNotNone(re.search(placing, bodies["attach"]))
self.assertIsNotNone(re.search(placing, source.split("def write_connection(")[1].split("\n\n\n")[0]))
def test_the_patterns_bite(self):
planted = ("value = eval(text)", "from brokkr_bridge import x", 'modifier.solver = "MANIFOLD"', "cutter.hide_render = True", 'obj["kit_parent"] = parent.name',