Merge pull request 'brokkr_kitbash: roll, aim and reach pose an attached part in place, solved in closed form (cut kit-roll-aim)' (#29) from nibu/kit-roll-aim into main

This commit is contained in:
Eureka 2026-12-02 03:53:32 +00:00
commit fa1468a1f5
10 changed files with 1173 additions and 25 deletions

View file

@ -15,7 +15,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. kit_baked
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). 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).
@ -231,6 +233,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 kit
part, both sockets exist, the roll is a number, the parent inverse is the identity and the child
@ -563,9 +574,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)
@ -593,6 +602,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 or of any kit whose socket types
agree, closing a loop the tree of connections cannot: accepted only when the two already meet, origins together and normals opposed, and it
@ -788,8 +888,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_cut, BROKKR_KITBASH_OT_cut_many,
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_cut, BROKKR_KITBASH_OT_cut_many, 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 (within about 0.06 degrees), 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 (either end of the range is taken), and a socket that lies on the pin. 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 a part of any kit whose socket types agree, 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

@ -17,6 +17,10 @@ both kits declare the socket's type with the same match rule. surface_frame is t
met a surface. closure_residual is how far two sockets stand from meeting as a pin,
whatever the roll: what closes a loop the tree of connections cannot state.
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
@ -640,6 +644,73 @@ 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: at or below it the axis or the direction lies along the pin, as nearly as
# the scene can say, and no roll turns one toward the other. A scene's matrices and an action's fields are float32
# and a direction read from a report has 6 decimals or fewer, so "along the pin" is never exact: the worst reading
# of the tests for a pin direction through a float32 world, as float32, at 6 and at 4 decimals is 6.2e-05 (the 4
# decimal case); the least aimable case is 0.0175 (a direction 1 degree off the pin). The geometric mean,
# separation 17 each side: a direction within about 0.06 degrees of the pin is refused.
AIM_FLOOR = 1e-3
# How far past the top or bottom of its circle a reach may ask, in metres: such a height is taken as the top or
# bottom, and the residual says how far off the socket stands. A rule, the add-on's HELD: a height typed back from
# the range a refusal names (6 decimals, through a float32 field) is within 6.5e-07 of it in the tests, and float32
# steps 1e-06 for parts within 16 m of the origin. A socket whose circle is this small lies on the pin: no roll
# moves it.
REACH_EDGE = 1e-5
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 (hypot(A, B) at most AIM_FLOOR), 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). A height up to REACH_EDGE
past the top or bottom of the circle is taken as the top or bottom. Refuses a height farther out, naming the
range the point reaches, and a point no roll moves along the direction (it lies on the pin, or the direction
does)."""
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, here = math.hypot(A, B), f"socket {child_socket['name']!r} on parent socket {parent_socket['name']!r}"
if swing <= REACH_EDGE:
raise KitError(f"{here}: no roll moves the point along {tuple(round(float(v), 6) for v in direction)}: it lies on the pin, or the direction "
f"runs along it; it stays at {C:.6f} m")
if abs(height - C) > swing + REACH_EDGE:
raise KitError(f"{here}: no roll brings the point to {height:.6f} m along {tuple(round(float(v), 6) for v in direction)}; "
f"it reaches {C - swing:.6f} m to {C + swing:.6f} m")
middle, spread = math.degrees(math.atan2(B, A)), math.degrees(math.acos(max(-1.0, min(1.0, (height - C) / swing))))
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 fourteen 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 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. Socket types are a
@ -155,8 +155,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
@ -185,6 +185,43 @@ 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), a `reach` with a socket that lies on
the pin or a direction along it (no roll moves it), and a `reach` to a height the socket's circle does not cross,
naming the range it does.
A scene's matrices and an action's fields are float32, and a direction read from a report has 6 decimals, so
neither test is exact. "Along the pin" is `hypot(A, B)` at most 1e-3 (`core.AIM_FLOOR`): a direction within about
0.06 degrees of the pin, which covers the pin's own direction read from a report and typed at 4 decimals. A
`reach` to a height up to 1e-5 m past the top or bottom of the circle (`core.REACH_EDGE`) is taken as the top or
bottom, so the range a refusal names can be typed back; `residual` then says how far short the socket stands.
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
@ -201,7 +238,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
@ -347,6 +384,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; the two parts are of one kit or of two whose socket types agree. 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` (any mesh), `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds the cutter to the collection of the target's one live Exact Boolean for the operation, above the Bevel. Refuses a cutter that is the target, is not a mesh, or already cuts it, and a scaled target. Reports the part (or `object` for a mesh that is not one), `booleans: [{cutter, operation}]` (difference, union, intersect; each in the order added) and `evaluated`. |
| `brokkr_kitbash.cut` | `object_name` (any mesh), `cutter_name`, `part` (`box`, `cyl`, `slot`, `slab`), `params`, `origin_x/y/z`, `direction_x/y/z`, `up_x/y/z` (default 0, 0, 1), `roll` (degrees, default 0), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans`. |
@ -449,8 +489,9 @@ seated on a face that faces its `z`, and no build passes 20000 faces. Choose par
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`.
`CuttersKitTests` holds `cutters` to the same, with each floor on its cutter's bottom, and `SurfaceFrameTests` the
frame `cut` gives a cutter. `MateTests` covers the mate arithmetic and what may mate, within a kit and across two. 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) and `tests/live/kitbash_shell.py`
frame `cut` gives a cutter. `MateTests` covers the mate arithmetic and what may mate, within a kit and across two,
`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), `tests/live/kitbash_shell.py`
(`cut` and `cut_many` on a cage that is not a kit part, a part on a cutter's floor, the three Boolean modifiers, an object in no
collection).
collection) and `tests/live/kitbash_pose.py` (roll, aim and reach).

View file

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

View file

@ -412,6 +412,9 @@
"brokkr_kitbash.report",
"brokkr_kitbash.attach",
"brokkr_kitbash.detach",
"brokkr_kitbash.roll",
"brokkr_kitbash.aim",
"brokkr_kitbash.reach",
"brokkr_kitbash.close",
"brokkr_kitbash.boolean",
"brokkr_kitbash.cut",

View file

@ -177,7 +177,7 @@ def evaluated(obj):
rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")]
check("the 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", "cut", "cut_many", "apply")], [R["hostErrors"], rows])
"place_part", "set_params", "describe", "report", "attach", "detach", "roll", "aim", "reach", "close", "boolean", "cut", "cut_many", "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,311 @@
"""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")
# Each mutant's reading below is its least over the cases here that it changes; the shipped reading is the worst.
# 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 1.1e-06 (float32 matrices); least claimed mutant 0.25 (R9,
# write_connection seats with the two sockets swapped); separation 2.3e5.
SEATED = 5.2e-4
# Degrees between the roll read from the two world frames and the roll stated. Shipped worst 8.4e-06; least claimed
# mutant 15 (R3, roll writes kit_roll without seating, at the smallest turn here); separation 1.8e6.
ROLL = 1.1e-2
# Metres the actuator's pin moves when the strut it hangs from is rolled. Shipped least 0.55 (the 45 degree turn);
# least claimed mutant reads at most 5e-08 (R3: nothing moves); separation 1.1e7.
TURNED = 1.7e-4
# The dot aim reports against the dot read from the scene, and how far a roll on the 1-degree grid passes the dot
# read. Shipped worst 3.3e-07; least claimed mutant 0.0014 (R6, a left-handed roll_terms, at the aim nearest its
# mirror); R1 (atan2(A, B)) reads 0.81 and R8 (the dot without its hypot) 0.86; separation 4.2e3.
AIMED = 2.1e-5
# Metres between the socket reach moved and the plane asked for, read from the scene. Shipped worst 2.1e-07; least
# claimed mutant 0.42 (R6); separation 2.0e6.
REACHED = 3.0e-4
# Degrees the other root stands farther from the roll the part had than the root reach took. A rule, the sign: shipped
# least 74; R2 (the farther root) reads -74.
NEARER = 0.0
# Metres past the top of its circle a reach may ask (core.REACH_EDGE, a rule: HELD). A height typed back from a
# refusal's range overshoots by at most 3.2e-07 here and is taken; PAST is refused. The two sit sqrt(10) either side.
EDGE, PAST = 1e-5, 3.2e-5
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 least(name, value):
R["readings"][name] = min(R["readings"].get(name, math.inf), 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)
gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", turn)), R["readings"]["roll"]
check(f"roll {turn:g} turns the strut where it hangs: one intent, its parent, sockets and parent inverse as they were, its roll stated and seated",
receipt["status"] == "accepted" and COUNT[0] == sent + 1 and stated(strut) == was and strut["kit_roll"] == turn and gap < SEATED and off < ROLL
and report and report["object"] == "Strut" and holds(report["connection"], "Mount", "end_a", "pivot", turn) and holds(connection("Strut"), "Mount", "end_a", "pivot", turn),
[receipt["message"], report and report["connection"], gap, off])
moved, gap = least("turned", float(np.linalg.norm(frame(ram, "base")[:3, 3] - pin))), reading("seated", seated(ram, "base", strut, "end_b", -35.0))
check(f"and the actuator follows through its own connection, which nothing rewrote (roll {turn:g})",
(stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist()) == before and moved > TURNED and gap < SEATED and R["readings"]["roll"] < ROLL
and holds(connection("Ram"), "Strut", "base", "end_b", -35.0), [moved, gap, connection("Ram"), R["readings"]])
# --- roll: the closures it opens ----------------------------------------------------------------------------------------
check("the rolls above opened the brace's closure and reported it before the one that holds, whatever its name", (report or {}).get("closures") == [
{"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}] and report["closure"] is None, report and report.get("closures"))
receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=20.0)
check("rolled back to where the brace met it, the closure holds again: read from where the parts stand", receipt["status"] == "accepted" and (report or {}).get("closures") == [
{"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}, {"part": "Brace", "to": "Ram", "holds": True}], report and report.get("closures"))
send("setObjectTransform", targetObjectName="Aa_Loose", location=[0.0, -25.0, 0.0], rotationEuler=[0.0, 0.0, 0.0])
receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-35.0)
check("a roll lists the closures its own part is an end of first, before a broken one elsewhere", receipt["status"] == "accepted" and (report or {}).get("closures") == [
{"part": "Brace", "to": "Ram", "holds": True}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}], report and report.get("closures"))
receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-36.0)
check("and a roll of the part a closure names opens it; no roll seats or rewrites a closure", receipt["status"] == "accepted" and (report or {}).get("closures") == [
{"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}]
and {k: brace[k] for k in brace.keys() if k.startswith("kit_close")} == closing and brace.parent is None, [report and report.get("closures"), dict(brace.items())])
# --- aim ----------------------------------------------------------------------------------------------------------------
for axis, direction in (("+z", (1.0, 0.0, 0.0)), ("-x", (0.0, -3.0, 4.0)), ("+z", (0.2, 0.1, -2.0))):
world, unit = np.array(mount.matrix_world, dtype=np.float64), np.array(direction) / np.linalg.norm(direction)
receipt, report = send("brokkr_kitbash.aim", object_name="Strut", axis=axis, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2])
aimed = (report or {}).get("aimed") or {"roll": 1e9, "dot": 1e9}
read = float(np.array(strut.matrix_world, dtype=np.float64)[:3, :3] @ np.array(core.AXES[axis]) @ unit)
grid = max(float((world @ core.mate(socket(mount, "pivot"), socket(strut, "end_a"), float(r)))[:3, :3] @ np.array(core.AXES[axis]) @ unit) for r in range(-180, 180))
apart, short = reading("aimed", abs(aimed["dot"] - read)), reading("aimed short", max(grid - read, 0.0))
check(f"aim points the strut's {axis} at {direction} as far as its pin lets it: the dot it reports is the dot the scene reads, and no roll on a 1-degree grid passes it",
receipt["status"] == "accepted" and apart < AIMED and short < AIMED and 0.2 < aimed["dot"] < 0.999, [receipt["message"], aimed, read, grid])
gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", aimed["roll"])), R["readings"]["roll"]
check(f"and it is stated and seated as roll's: the connection holds at the aimed roll, the actuator with it, closures reported ({axis})",
aimed["roll"] == round(strut["kit_roll"], 6) and -180.0 < aimed["roll"] <= 180.0 and holds(report and report["connection"], "Mount", "end_a", "pivot", aimed["roll"])
and gap < SEATED and off < ROLL and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len((report or {}).get("closures", [])) == 2,
[dict(strut.items()), report and report["connection"], report and report.get("closures"), gap, off])
# --- reach --------------------------------------------------------------------------------------------------------------
for direction, part, offset in (((0.0, 0.0, 1.0), 0.5, 40.0), ((0.0, 0.0, 1.0), 0.5, -40.0), ((1.0, 2.0, -0.5), -0.8, 100.0)):
world, unit = np.array(mount.matrix_world, dtype=np.float64), np.array(direction) / np.linalg.norm(direction)
A, B, C = core.roll_terms(world, socket(mount, "pivot"), socket(strut, "end_a"), socket(strut, "end_b")["matrix"][:3, 3], 1.0, unit)
current = float(round(math.degrees(math.atan2(B, A)) + offset)) # the two rolls that reach stand either side of the middle: start nearer one
send("brokkr_kitbash.roll", object_name="Strut", roll=current)
height = round(C + part * math.hypot(A, B), 3)
fields = {"direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]} if direction != (0.0, 0.0, 1.0) else {} # world z is the default
receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=height, **fields)
reached = (report or {}).get("reached") or {"roll": 1e9, "residual": 1e9}
apart = lambda roll: abs((roll - current + 180.0) % 360.0 - 180.0) # noqa: E731
off_plane = reading("reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - height))
farther = least("reach other root", apart(2.0 * math.degrees(math.atan2(B, A)) - reached["roll"]) - apart(reached["roll"])) # the other root mirrors it about the middle
check(f"reach brings the strut's end_b to {height} m along {direction} from roll {current:g}, by the nearer of the two rolls that do",
receipt["status"] == "accepted" and off_plane < REACHED and reached["residual"] < REACHED and farther > NEARER,
[receipt["message"], reached, off_plane, farther])
gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", reached["roll"])), R["readings"]["roll"]
check(f"and it is stated and seated as roll's ({direction}, from {current:g})", reached["roll"] == round(strut["kit_roll"], 6) and -180.0 < reached["roll"] <= 180.0
and holds(report and report["connection"], "Mount", "end_a", "pivot", reached["roll"]) and gap < SEATED and off < ROLL
and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len((report or {}).get("closures", [])) == 2,
[dict(strut.items()), report and report["connection"], gap, off])
# --- refusals -----------------------------------------------------------------------------------------------------------
send("setObjectParent", targetObjectName="Orphan", parentObjectName="")
low, high = C - math.hypot(A, B), C + math.hypot(A, B)
refused("roll of a part nobody attached", "brokkr_kitbash.roll", {"object_name": "Spare", "roll": 10.0}, "'Spare' is not attached (it has no kit_socket property)")
refused("aim of a part nobody attached", "brokkr_kitbash.aim", {"object_name": "Spare", "axis": "+z", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "'Spare' is not attached")
refused("reach of a part nobody attached", "brokkr_kitbash.reach", {"object_name": "Spare", "socket": "end_b", "height": 0.0}, "'Spare' is not attached")
refused("roll of a part whose parent was cleared", "brokkr_kitbash.roll", {"object_name": "Orphan", "roll": 10.0}, "'Orphan' states a connection and has no parent: detach it")
refused("roll of a mesh that is not a kit part", "brokkr_kitbash.roll", {"object_name": "Plain", "roll": 10.0}, "'Plain' is not a kit part")
refused("aim of the axis along the pin", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+y", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0},
"'Strut' on 'Mount': socket 'end_a' on parent socket 'pivot': the axis (0.0, 1.0, 0.0) of the part or the direction (1.0, 0.0, 0.0) lies along the pin")
refused("aim at no direction", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+z", "direction_x": 0.0, "direction_y": 0.0, "direction_z": 0.0}, "The direction is zero")
refused("reach past the circle the socket turns on, naming what it reaches", "brokkr_kitbash.reach",
{"object_name": "Strut", "socket": "end_b", "height": 900.0, "direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]},
f"no roll brings the point to 900.000000 m along ({unit[0]:.6f}".rstrip("0"))
receipt, _ = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=900.0, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2])
check("and the range it names is the one core solves", f"it reaches {low:.6f} m to {high:.6f} m" in str(receipt["message"]) and high - low > 1.0, [receipt["message"], low, high])
skew = {"direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]}
refused("reach a little past the top it names", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": float(f"{high:.6f}") + PAST, **skew}, "no roll brings the point to")
receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=float(f"{high:.6f}"), **skew)
reached = (report or {}).get("reached") or {"roll": 1e9, "residual": 1e9}
over, stands = reading("edge typed past", max(float(np.float32(f"{high:.6f}")) - high, 0.0)), reading("edge reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - high))
check("reach to the top of the circle, typed back from the range the refusal named, is taken: the socket stands at the top", receipt["status"] == "accepted"
and reached["residual"] <= EDGE and over <= EDGE and stands < REACHED and holds(report["connection"], "Mount", "end_a", "pivot", reached["roll"]),
[receipt["message"], reached, over, stands, high])
refused("reach with the socket the part hangs by: it lies on the pin", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_a", "height": 0.0},
"'Strut' on 'Mount': socket 'end_a' on parent socket 'pivot': no roll moves the point along (0.0, 0.0, 1.0): it lies on the pin")
pin = np.array(mount.matrix_world, dtype=np.float64) @ socket(mount, "pivot")["matrix"]
for label, along in (("as the scene holds it", pin[:3, 2]), ("to 6 decimals", np.round(pin[:3, 2], 6)), ("to 4 decimals", np.round(pin[:3, 2], 4)), ("reversed, to 4 decimals", -np.round(pin[:3, 2], 4))):
refused(f"aim at the pin's own direction {label}", "brokkr_kitbash.aim",
{"object_name": "Strut", "axis": "+z", "direction_x": float(along[0]), "direction_y": float(along[1]), "direction_z": float(along[2])}, "lies along the pin, so no roll turns one toward the other")
refused("reach with a socket the part does not have", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_c", "height": 0.0},
"'Strut' has no socket 'end_c'; its sockets: end_a, end_a_back, end_b, end_b_back")
refused("reach along no direction", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": 0.0, "direction_z": 0.0}, "The direction is zero")
refused("a roll past a turn, by the action table", "brokkr_kitbash.roll", {"object_name": "Strut", "roll": 361.0}, "roll")
refused("an axis that is not one of the six, by the action table", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "x", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "axis")
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,248 @@
{
"blender": "5.3.0",
"checks": [
{
"name": "roll, aim and reach load as host actions after detach, with no errors",
"ok": true,
"detail": null
},
{
"name": "the chain stands: tank, bracket, strut, actuator",
"ok": true,
"detail": null
},
{
"name": "a brace closes on the actuator's rod pin",
"ok": true,
"detail": null
},
{
"name": "and a second closure, named to sort first, holds far from it",
"ok": true,
"detail": null
},
{
"name": "roll 65 turns the strut where it hangs: one intent, its parent, sockets and parent inverse as they were, its roll stated and seated",
"ok": true,
"detail": null
},
{
"name": "and the actuator follows through its own connection, which nothing rewrote (roll 65)",
"ok": true,
"detail": null
},
{
"name": "roll -160 turns the strut where it hangs: one intent, its parent, sockets and parent inverse as they were, its roll stated and seated",
"ok": true,
"detail": null
},
{
"name": "and the actuator follows through its own connection, which nothing rewrote (roll -160)",
"ok": true,
"detail": null
},
{
"name": "roll 35 turns the strut where it hangs: one intent, its parent, sockets and parent inverse as they were, its roll stated and seated",
"ok": true,
"detail": null
},
{
"name": "and the actuator follows through its own connection, which nothing rewrote (roll 35)",
"ok": true,
"detail": null
},
{
"name": "the rolls above opened the brace's closure and reported it before the one that holds, whatever its name",
"ok": true,
"detail": null
},
{
"name": "rolled back to where the brace met it, the closure holds again: read from where the parts stand",
"ok": true,
"detail": null
},
{
"name": "a roll lists the closures its own part is an end of first, before a broken one elsewhere",
"ok": true,
"detail": null
},
{
"name": "and a roll of the part a closure names opens it; no roll seats or rewrites a closure",
"ok": true,
"detail": null
},
{
"name": "aim points the strut's +z at (1.0, 0.0, 0.0) as far as its pin lets it: the dot it reports is the dot the scene reads, and no roll on a 1-degree grid passes it",
"ok": true,
"detail": null
},
{
"name": "and it is stated and seated as roll's: the connection holds at the aimed roll, the actuator with it, closures reported (+z)",
"ok": true,
"detail": null
},
{
"name": "aim points the strut's -x at (0.0, -3.0, 4.0) as far as its pin lets it: the dot it reports is the dot the scene reads, and no roll on a 1-degree grid passes it",
"ok": true,
"detail": null
},
{
"name": "and it is stated and seated as roll's: the connection holds at the aimed roll, the actuator with it, closures reported (-x)",
"ok": true,
"detail": null
},
{
"name": "aim points the strut's +z at (0.2, 0.1, -2.0) as far as its pin lets it: the dot it reports is the dot the scene reads, and no roll on a 1-degree grid passes it",
"ok": true,
"detail": null
},
{
"name": "and it is stated and seated as roll's: the connection holds at the aimed roll, the actuator with it, closures reported (+z)",
"ok": true,
"detail": null
},
{
"name": "reach brings the strut's end_b to 4.23 m along (0.0, 0.0, 1.0) from roll -38, by the nearer of the two rolls that do",
"ok": true,
"detail": null
},
{
"name": "and it is stated and seated as roll's ((0.0, 0.0, 1.0), from -38)",
"ok": true,
"detail": null
},
{
"name": "reach brings the strut's end_b to 4.23 m along (0.0, 0.0, 1.0) from roll -118, by the nearer of the two rolls that do",
"ok": true,
"detail": null
},
{
"name": "and it is stated and seated as roll's ((0.0, 0.0, 1.0), from -118)",
"ok": true,
"detail": null
},
{
"name": "reach brings the strut's end_b to 0.885 m along (1.0, 2.0, -0.5) from roll 135, by the nearer of the two rolls that do",
"ok": true,
"detail": null
},
{
"name": "and it is stated and seated as roll's ((1.0, 2.0, -0.5), from 135)",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: roll of a part nobody attached",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: aim of a part nobody attached",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: reach of a part nobody attached",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: roll of a part whose parent was cleared",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: roll of a mesh that is not a kit part",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: aim of the axis along the pin",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: aim at no direction",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: reach past the circle the socket turns on, naming what it reaches",
"ok": true,
"detail": null
},
{
"name": "and the range it names is the one core solves",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: reach a little past the top it names",
"ok": true,
"detail": null
},
{
"name": "reach to the top of the circle, typed back from the range the refusal named, is taken: the socket stands at the top",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: reach with the socket the part hangs by: it lies on the pin",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: aim at the pin's own direction as the scene holds it",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: aim at the pin's own direction to 6 decimals",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: aim at the pin's own direction to 4 decimals",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: aim at the pin's own direction reversed, to 4 decimals",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: reach with a socket the part does not have",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: reach along no direction",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a roll past a turn, by the action table",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: an axis that is not one of the six, by the action table",
"ok": true,
"detail": null
}
],
"hostErrors": [],
"readings": {
"aimed": 3.3e-07,
"aimed short": 0.0,
"edge reached": 2.6e-08,
"edge typed past": 3.2e-07,
"reach other root": 74.0,
"reached": 2.1e-07,
"roll": 8.4e-06,
"seated": 1.1e-06,
"turned": 0.55
},
"ok": true
}

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.
@ -947,8 +948,217 @@ 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)))
self.assertEqual(core.aim_roll(np.eye(4), ident, ident, (0.0, 1.0, 0.0), (0.0, -1.0, 0.0)), (180.0, 1.0)) # half a turn is 180, never -180 (S6)
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:.6f} m to {C + swing:.6f} 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
self.assertEqual(reach(0.0, 170.0), (180.0, 0.0)) # rolls 0 and 180: half a turn is 180, never -180 (mutant S6, the wrap's other end)
self.assertEqual(reach(0.0, -170.0), (180.0, 0.0))
self.assertEqual([core._wrapped(v) for v in (-180.0, 180.0, 540.0, -179.0, 0.0, 359.0)], [180.0, 180.0, 180.0, -179.0, 0.0, -1.0])
with self.assertRaisesRegex(core.KitError, r"no roll brings the point to 1\.500000 m along \(1\.0, 0\.0, 0\.0\); it reaches -1\.000000 m to 1\.000000 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 along the pin or a direction along it in doubles; the largest for the pin's
direction as a scene gives it: through a float32 world, as float32, at 6 and at 4 decimals; the least of a
direction 1 degree off the pin, through the same float32 world)."""
along, scene, least = 0.0, 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]
other = (1.0, 0.0, 0.0) if abs(pin_local[0]) < 0.5 else (0.0, 1.0, 0.0) # an axis of the child across its pin
single = world.astype(np.float32).astype(np.float64) # the parent's matrix_world as Blender holds it
near = math.cos(math.radians(1.0)) * pin_world + math.sin(math.radians(1.0)) * (world @ sp["matrix"])[:3, 0]
for frame, axis, d, kind in ((world, pin_local, self.direction(rng), "along"), (world, other, pin_world, "along"),
(single, other, pin_world.astype(np.float32).astype(np.float64), "scene"),
(single, other, np.round(pin_world, 6).astype(np.float32).astype(np.float64), "scene"),
(single, other, np.round(pin_world, 4).astype(np.float32).astype(np.float64), "scene"),
(single, other, near.astype(np.float32).astype(np.float64), "near")):
A, B, _ = core.roll_terms(frame, sp, sc, axis, 0.0, d / np.linalg.norm(d))
if kind == "near":
least = min(least, math.hypot(A, B))
core.aim_roll(frame, sp, sc, axis, d)
continue
along, scene = (max(along, math.hypot(A, B)), scene) if kind == "along" else (along, max(scene, math.hypot(A, B)))
with self.assertRaisesRegex(core.KitError, "lies along the pin, so no roll turns one toward the other", msg=f"{kind} {d}"):
core.aim_roll(frame, sp, sc, axis, d)
return along, scene, least
def test_aim_along_the_pin_is_refused(self):
"""aim-floor. An axis along the pin, or a direction along it as a scene can give it (a float32 world, the pin as
float32, at 6 and at 4 decimals), is refused; a direction 1 degree off it is solved. AIM_FLOOR sits between the
two readings by the margin rule. Mutants R5 (no floor) and E4 (the floor at float64 rounding, 1.5e-9)."""
along, scene, least = self.floor_readings()
self.assertLess(along, 1e-15)
self.assertGreater(scene, 2e-5) # the 4 decimal pin: far above float64 rounding, so the floor is set against it
self.assertLess(scene * 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))
def edge_readings(self):
"""Reach asked for the top and bottom of its circle: exactly, as typed back from a refusal (6 decimals through
float32), 0.32 of REACH_EDGE past and 3.2 of it past (the two sit sqrt(10) either side of the rule)."""
worst = {"exact": 0.0, "typed": 0.0, "typed past": 0.0, "inside": 0.0, "cases": 0}
for world, sp, sc, rng in self.joints("edge"):
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 sign in (1.0, -1.0):
end = core._wrapped(middle if sign > 0 else middle + 180.0) # the one roll at the top, or at the bottom
roll, residual = core.reach_roll(world, sp, sc, point, d, C + sign * swing, rng.uniform(-360, 360))
worst["exact"] = max(worst["exact"], residual, abs(core._wrapped(roll - end)) * 1e-9)
typed = float(np.float32(f"{C + sign * swing:.6f}"))
roll, residual = core.reach_roll(world, sp, sc, point, d, typed, 0.0)
worst["typed"] = max(worst["typed"], residual)
worst["typed past"] = max(worst["typed past"], sign * (typed - C) - swing)
roll, residual = core.reach_roll(world, sp, sc, point, d, C + sign * (swing + 0.32 * core.REACH_EDGE), 0.0)
worst["inside"] = max(worst["inside"], abs(residual - 0.32 * core.REACH_EDGE), abs(core._wrapped(roll - end)) * 1e-9)
with self.assertRaisesRegex(core.KitError, re.escape(f"it reaches {C - swing:.6f} m to {C + swing:.6f} m")):
core.reach_roll(world, sp, sc, point, d, C + sign * (swing + 3.2 * core.REACH_EDGE), 0.0)
worst["cases"] += 1
return worst
def test_reach_takes_the_edge_of_its_circle(self):
"""reach-edge. A height at the top or bottom of the circle is reached, exactly and as typed back from the range a
refusal names; one within REACH_EDGE past it is taken as the edge and the residual says how far off the point
stands; one farther is refused. Mutants E1 (no tolerance: the edge refused a quarter of the time), E2 (the
ratio not clamped into acos) and S7 (Soul's >= at the edge)."""
worst = self.edge_readings()
self.assertEqual(worst["cases"], 120)
self.assertLess(worst["exact"], 6.6e-8) # PoseTests.REACHED: the edge is on the plane as any other height is
self.assertLess(worst["typed"], core.REACH_EDGE / 1.2)
self.assertLess(worst["typed past"], core.REACH_EDGE / 1.2) # a typed edge overshoots by at most a rounding: inside the rule
self.assertGreater(worst["typed past"], 1e-7) # and it does overshoot: without the tolerance these are refused
self.assertLess(worst["inside"], 1e-12)
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(1.0, 0.0), reach(-1.0, 0.0)), ((-90.0, 0.0), (90.0, 0.0))) # the point stands at x = -sin(roll)
self.assertEqual(reach(1.000003, 0.0), (-90.0, 3e-06))
def test_reach_refuses_a_point_no_roll_moves(self):
"""reach-on-the-pin. A point on the pin's axis, or a direction along the pin, is refused whatever the height: no
roll moves the point along the direction, and solving would divide by its swing. Mutant E3 (the guard dropped:
Soul's S8, zero swing with the point on the pin)."""
ident = {"name": "s", "matrix": np.eye(4)}
for point, d, height in (((0.0, 0.0, 2.0), (1.0, 0.0, 0.0), 0.0), ((0.0, 0.0, 2.0), (1.0, 0.0, 0.0), 0.5), ((0.3, 0.4, 2.0), (0.0, 0.0, 1.0), -2.0),
((0.3, 0.4, 2.0), (0.0, 0.0, 1.0), 1.0), ((0.0, 3e-6, 2.0), (1.0, 0.0, 0.0), 0.0)):
with self.assertRaisesRegex(core.KitError, r"socket 's' on parent socket 's': no roll moves the point along .*: it lies on the pin, or the direction runs along it; it stays at -?\d+\.\d{6} m"):
core.reach_roll(np.eye(4), ident, ident, point, d, height, 0.0)
self.assertEqual(round(core.reach_roll(np.eye(4), ident, ident, (0.0, 3.2e-5, 2.0), (1.0, 0.0, 0.0), 0.0, 10.0)[0], 9), 0.0) # sqrt(10) past REACH_EDGE off the pin: solved
for world, sp, sc, rng in self.joints("pin"):
on_pin = sc["matrix"] @ np.array([0.0, 0.0, rng.uniform(-1, 1), 1.0]) # on the child socket's own normal
_, _, C = core.roll_terms(world, sp, sc, on_pin[:3], 1.0, self.direction(rng))
with self.assertRaisesRegex(core.KitError, "no roll moves the point"):
core.reach_roll(world, sp, sc, on_pin[:3], self.direction(rng), C, 0.0)
with self.assertRaisesRegex(core.KitError, "no roll moves the point"):
core.reach_roll(world, sp, sc, [rng.uniform(-1, 1) for _ in range(3)], (world @ sp["matrix"])[:3, 2], 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.cut", "brokkr_kitbash.cut_many", "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.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply"]
class HostFileTests(unittest.TestCase):
@ -1016,6 +1226,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
@ -1062,12 +1288,26 @@ class OwnershipTests(unittest.TestCase):
self.assertEqual(body.count("place_cutters("), 0 if body is place else 1)
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
@ -1085,7 +1325,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',