brokkr_kitbash joint records: DOF from the socket type, limits, slide, the joints report; hose reads its range from the pin (cut kit-joint-records) #39

Merged
eureka merged 6 commits from nibu/kit-joint-records into main 2026-12-02 22:39:27 +00:00
14 changed files with 1513 additions and 137 deletions

View file

@ -71,6 +71,7 @@ bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0),
import contextlib
import json
import math
import re
import bmesh
import bpy
@ -88,6 +89,10 @@ from . import core, route
KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params"
SOCKET, PARENT_SOCKET, ROLL = "kit_socket", "kit_parent_socket", "kit_roll"
SLIDE, LIMIT_MIN, LIMIT_MAX, MECHANISM, COMPLIANCE = "kit_slide", "kit_min", "kit_max", "kit_mechanism", "kit_compliance" # a connection's joint record; write_connection is its one writer
RECORD = (SLIDE, LIMIT_MIN, LIMIT_MAX, MECHANISM, COMPLIANCE)
LABEL = r"[a-z0-9_]{1,32}" # a mechanism label
TURN, TRAVEL, HERTZ, DAMPING = 360.0, 10.0, 30.0, 2.0 # what a joint record may state: degrees a revolute joint's limits span and stand from 0, metres a prismatic one's stand from 0, a compliance's hertz and damping ratio
FROZEN = "kit_frozen" # on a frozen object: an ID pointer to its live mesh; its presence is the frozen state. hold writes it and nothing else does
KEPT = "kit_kept" # on a live mesh a frozen object holds: an ID pointer to that object's frozen mesh, beside the fake user that keeps the live mesh through a purge. hold writes both
CLOSE, CLOSE_TO, CLOSE_TO_SOCKET = "kit_close_socket", "kit_close_to", "kit_close_to_socket"
@ -190,13 +195,51 @@ def built_part(obj, kits=None):
def link(obj):
"""The connection a child states, (its socket, the parent's socket, roll in degrees), or None. The parent is
obj.parent and is stored nowhere else. attach, set_params, detach and every report read it here. A kit_roll
that is not a finite number (written by hand) is roll None: the connection is stated and cannot hold."""
"""The connection a child states, (its socket, the parent's socket, roll in degrees, slide in metres), or None.
The parent is obj.parent and is stored nowhere else. attach, set_params, detach and every report read it here.
A kit_roll or kit_slide that is not a finite number (written by hand) is None: the connection is stated and
cannot hold. An absent kit_slide is 0."""
if SOCKET not in obj:
return None
roll = obj.get(ROLL, 0.0)
return str(obj[SOCKET]), str(obj.get(PARENT_SOCKET, "")), float(roll) if core.finite(roll) else None
roll, slide = obj.get(ROLL, 0.0), obj.get(SLIDE, 0.0)
return str(obj[SOCKET]), str(obj.get(PARENT_SOCKET, "")), float(roll) if core.finite(roll) else None, float(slide) if core.finite(slide) else None
def dof(parent, parent_socket: dict):
"""The DOF kind of a connection on a socket of a part, 'revolute', 'prismatic' or None (rigid): what the
socket's type states in the parent's kit. Nothing else decides it: no part, socket or object name is read."""
return core.load_kit(str(parent.get(KIT, "")))["socketTypes"][parent_socket["type"]].get("dof")
def joint_record(obj) -> dict:
"""The joint record a child's connection states, {limits: (lo, hi) or None, mechanism, compliance}: degrees of
its roll on a revolute joint, metres of its slide on a prismatic one. Every report, the joints report, the
poses and hose read it here. A value written by hand that write_connection would not have written reads None."""
lo, hi, label, spring = obj.get(LIMIT_MIN), obj.get(LIMIT_MAX), obj.get(MECHANISM), None
with contextlib.suppress(ValueError, TypeError):
spring = json.loads(obj.get(COMPLIANCE, "null"))
return {"limits": (float(lo), float(hi)) if core.finite(lo) and core.finite(hi) and lo <= hi else None,
"mechanism": label if isinstance(label, str) and re.fullmatch(LABEL, label) else None,
"compliance": spring if isinstance(spring, dict) and set(spring) == {"hertz", "damping_ratio"} and all(core.finite(v) for v in spring.values()) else None}
def record_refusal(kind, socket_type: str, record: dict) -> str | None:
"""None when a connection of this DOF kind may carry the record, else why not."""
limits, spring = record["limits"], record["compliance"]
if kind is None:
return (f"socket type {socket_type!r} states no dof: the connection is rigid and carries no limits, mechanism or compliance"
if any(value is not None for value in record.values()) else None)
if limits is not None and kind == "revolute" and (limits[1] - limits[0] > TURN or max(abs(limits[0]), abs(limits[1])) > TURN):
return f"limits {limits[0]:.6g} to {limits[1]:.6g}: a revolute joint's span at most {TURN:g} degrees, each end within {TURN:g} of 0"
if limits is not None and kind == "prismatic" and max(abs(limits[0]), abs(limits[1])) > TRAVEL:
return f"limits {limits[0]:.6g} to {limits[1]:.6g}: a prismatic joint's stand within {TRAVEL:g} m of 0"
if spring is not None and kind != "prismatic":
return f"compliance is a prismatic joint's (a slide that settles under load): socket type {socket_type!r} is {kind}"
if spring is not None and limits is None:
return "compliance needs limits: the travel the slide settles within"
if spring is not None and not (0.0 < spring["hertz"] <= HERTZ and 0.0 <= spring["damping_ratio"] <= DAMPING):
return f"compliance {spring}: hertz is over 0 and at most {HERTZ:g}, damping_ratio 0 to {DAMPING:g}"
return None
def attached(obj) -> list:
@ -256,8 +299,8 @@ def mated(parent, parent_part, parent_built, child, child_part, child_built, sta
it: a roll that is not a number, a socket name a part does not have, or sockets core.mate_refusal will not
mate. The parts may be of two kits: they mate when both kits declare the socket's type alike. A closure is
checked here too (how "closing on"), the part it names as the parent."""
if stated[2] is None:
raise Refused(f"{child.name!r} on {parent.name!r}: its {ROLL} is not a number: detach it and attach it again; nothing changed.")
if stated[2] is None or stated[3] is None:
raise Refused(f"{child.name!r} on {parent.name!r}: its {ROLL if stated[2] is None else SLIDE} is not a number: detach it and attach it again; nothing changed.")
try:
sockets = core.joint(parent_part, parent_built, stated[1], child_part, child_built, stated[0])
kits = (parent_part["kit"], child_part["kit"])
@ -276,33 +319,66 @@ 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."""
def write_connection(child, parent, sockets, stated, record=None) -> None:
"""State a connection and seat it: the child's parent, its derived matrix_basis, its three properties and its
joint record. `sockets` is mated()'s answer for `stated`; `record` is the joint record to state (joint_record's
shape), None to keep the one the child states. attach, roll, aim, reach, slide and joint write a connection
here and nowhere else, so what a joint record may be is decided here: before anything is written it refuses a
record its DOF kind may not carry (record_refusal), a slide on a connection that is not prismatic, and a value
with no representative inside the limits (core.within), naming value and limits; the value written is that
representative."""
kind, (socket, parent_socket, roll, slide) = dof(parent, sockets[0]), stated
record, here = joint_record(child) if record is None else record, f"{child.name!r} on {parent.name!r}"
refusal = record_refusal(kind, sockets[0]["type"], record)
if refusal is None and kind != "prismatic" and slide != 0.0:
refusal = f"socket type {sockets[0]['type']!r} is {kind or 'rigid'}: only a prismatic connection slides"
if refusal is None and record["limits"] is not None:
value = roll if kind == "revolute" else slide
inside = core.within(value, *record["limits"], kind == "revolute")
if inside is None:
refusal = (f"its {'roll' if kind == 'revolute' else 'slide'} {value:.6g} is outside the joint's limits "
f"{record['limits'][0]:.6g} to {record['limits'][1]:.6g}")
roll, slide = (inside, slide) if kind == "revolute" else (roll, inside)
if refusal:
raise Refused(f"{here}: {refusal}; nothing changed.")
child.parent = parent
seat(child, core.mate(*sockets, stated[2]))
child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated
seat(child, core.mate(*sockets, roll, slide))
child[SOCKET], child[PARENT_SOCKET], child[ROLL] = socket, parent_socket, roll
lo, hi = record["limits"] or (None, None)
for key, value in ((SLIDE, slide if kind == "prismatic" else None), (LIMIT_MIN, lo), (LIMIT_MAX, hi), (MECHANISM, record["mechanism"]),
(COMPLIANCE, record["compliance"] and json.dumps(record["compliance"], sort_keys=True))):
if value is not None:
child[key] = value
elif key in child:
del child[key]
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
stands within HELD of core.mate. A child moved or re-parented by another action reads holds false until
set_params seats it again."""
set_params seats it again. With it the joint record: dof (the parent socket's type's: revolute, prismatic or
null for rigid), slide, limits, mechanism, compliance, and within, false only for a value written by hand
outside its limits."""
stated = link(obj)
if stated is None:
return None
record = joint_record(obj)
row = {"parent": obj.parent.name if obj.parent else None, "socket": stated[0], "parentSocket": stated[1],
"roll": None if stated[2] is None else round(stated[2], 6), "residual": None, "holds": False}
"roll": None if stated[2] is None else round(stated[2], 6), "residual": None, "holds": False,
"dof": None, "slide": None if stated[3] is None else round(stated[3], 6), "limits": record["limits"] and [round(v, 6) for v in record["limits"]],
"mechanism": record["mechanism"], "compliance": record["compliance"], "within": True}
try:
if obj.parent is None or stated[2] is None:
if obj.parent is None or stated[2] is None or stated[3] is None:
return row
parent_part, parent_built = built_part(obj.parent)
parent_socket, socket = core.joint(parent_part, parent_built, stated[1], part, built, stated[0])
row["dof"] = dof(obj.parent, parent_socket)
except (Refused, core.KitError):
return row
row["residual"] = round(core.residual(obj.parent.matrix_world, parent_socket, obj.matrix_world, socket, stated[2]), 9)
if record["limits"] is not None and row["dof"] is not None:
row["within"] = core.within(stated[2] if row["dof"] == "revolute" else stated[3], *record["limits"], row["dof"] == "revolute") is not None
row["residual"] = round(core.residual(obj.parent.matrix_world, parent_socket, obj.matrix_world, socket, stated[2], stated[3]), 9)
row["holds"] = bool(np.abs(np.array(obj.matrix_parent_inverse) - np.eye(4)).max() <= HELD and row["residual"] <= HELD)
return row
@ -638,18 +714,18 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator):
built = core.build(part, core.resolve_params(part, core.parse_params(self.params), stored))
closing = closure(obj) # a closure this part is an end of must still be one its new sockets may make; where they stand is only reported
if closing is not None and closing[1] is not None:
mated(closing[1], *built_part(closing[1]), obj, part, built, (closing[0], closing[2], 0.0), "closing on")
mated(closing[1], *built_part(closing[1]), obj, part, built, (closing[0], closing[2], 0.0, 0.0), "closing on")
for other in closing_on(obj):
mated(obj, part, built, other, *built_part(other), (closure(other)[0], closure(other)[2], 0.0), "closing on")
mated(obj, part, built, other, *built_part(other), (closure(other)[0], closure(other)[2], 0.0, 0.0), "closing on")
seats, stated = [], link(obj) # every connection this part is an end of, checked against its new sockets before anything is written
if stated is not None:
if obj.parent is None:
raise Refused(f"{obj.name!r} states a connection and has no parent: detach it to clear the connection; nothing changed.")
parent_part, parent_built = built_part(obj.parent)
seats.append((obj, core.mate(*mated(obj.parent, parent_part, parent_built, obj, part, built, stated), stated[2])))
seats.append((obj, core.mate(*mated(obj.parent, parent_part, parent_built, obj, part, built, stated), *stated[2:])))
for child in attached(obj):
child_part, child_built = built_part(child)
seats.append((child, core.mate(*mated(obj, part, built, child, child_part, child_built, link(child)), link(child)[2])))
seats.append((child, core.mate(*mated(obj, part, built, child, child_part, child_built, link(child)), *link(child)[2:])))
try:
old = core.build(part, stored)
except core.KitError: # stored params an edited kit no longer admits: nothing to map faces by
@ -698,11 +774,11 @@ class BROKKR_KITBASH_OT_attach(PolishOperator):
if ancestor == child:
raise Refused(f"{parent.name!r} is below {child.name!r}: attaching {child.name!r} to it would close a loop; nothing changed.")
ancestor = ancestor.parent
stated = (self.socket, self.parent_socket, float(self.roll))
stated = (self.socket, self.parent_socket, float(self.roll), 0.0)
sockets = mated(parent, parent_part, parent_built, child, part, built, stated)
free(parent, self.parent_socket)
free(child, self.socket)
write_connection(child, parent, sockets, stated)
write_connection(child, parent, sockets, stated, {"limits": None, "mechanism": None, "compliance": None}) # a new connection states no joint record: brokkr_kitbash.joint gives it one
context.view_layer.update()
return part_report(child, part, built)
@ -724,18 +800,20 @@ class BROKKR_KITBASH_OT_detach(PolishOperator):
world = obj.matrix_world.copy()
obj.parent = None
obj.matrix_world = world
for key in (SOCKET, PARENT_SOCKET, ROLL, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET):
for key in (SOCKET, PARENT_SOCKET, ROLL, *RECORD, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET):
if key in obj:
del obj[key]
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."""
"""Give an attached part a new roll, slide or joint record where it hangs: its parent and both sockets stay, and
what is attached to it follows. `solve(child, built, sockets, stated, joint)` answers (the roll, the slide, what
to add to the report, the joint record to state or None to keep it), or refuses; `joint` is the record the
connection states with its `dof` and the parent socket's `type`. Refuses a part that states no connection or
has no parent, what mated() refuses and what write_connection does: a value outside the joint's limits. The
report is the part's and, as set_params', every closure in the scene with the part's own first: a pose can open
one, and never seats one."""
child = mesh_object(name)
part, built = built_part(child)
stated = link(child)
@ -745,10 +823,10 @@ def pose(context, name: str, solve) -> dict:
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)
roll, slide, solved, record = solve(child, built, sockets, stated, {**joint_record(child), "dof": dof(child.parent, sockets[0]), "type": sockets[0]["type"]})
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)))
write_connection(child, child.parent, sockets, (stated[0], stated[1], float(roll), float(slide)), record)
context.view_layer.update()
report = {**part_report(child, part, built), **solved}
report["closures"] = scene_closures(context, report, (child,))
@ -774,7 +852,7 @@ class BROKKR_KITBASH_OT_roll(PolishOperator):
@kit_work
def work(self, context):
return pose(context, self.object_name, lambda child, built, sockets, stated: (self.roll, {}))
return pose(context, self.object_name, lambda child, built, sockets, stated, joint: (self.roll, stated[3], {}, None))
class BROKKR_KITBASH_OT_aim(PolishOperator):
@ -791,9 +869,9 @@ class BROKKR_KITBASH_OT_aim(PolishOperator):
@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)}}
def solve(child, built, sockets, stated, joint):
roll, dot = core.aim_roll(child.parent.matrix_world, *sockets, core.AXES[self.axis], unit(self), joint["limits"] if joint["dof"] == "revolute" else None)
return roll, stated[3], {"aimed": {"roll": round(roll, 6), "dot": round(dot, 9)}}, None
return pose(context, self.object_name, solve)
@ -812,15 +890,109 @@ class BROKKR_KITBASH_OT_reach(PolishOperator):
@kit_work
def work(self, context):
def solve(child, built, sockets, stated):
def solve(child, built, sockets, stated, joint):
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)}}
roll, residual = core.reach_roll(child.parent.matrix_world, *sockets, found[0]["matrix"][:3, 3], unit(self), self.height, stated[2],
joint["limits"] if joint["dof"] == "revolute" else None)
return roll, stated[3], {"reached": {"roll": round(roll, 6), "residual": round(residual, 9)}}, None
return pose(context, self.object_name, solve)
class BROKKR_KITBASH_OT_joint(PolishOperator):
"""State the joint record of an attached kit part's connection: its limits, a mechanism label and, on a slide,
its compliance"""
bl_idname = "brokkr_kitbash.joint"
bl_label = "State Kit Joint"
object_name: bpy.props.StringProperty(name="Object", description="An attached part on a revolute or prismatic socket")
record: bpy.props.StringProperty(name="Record", default="{}", description="A JSON object of any of limits ([lo, hi] or null), mechanism (a label or null), "
"compliance ({hertz, damping_ratio} or null); a key left out keeps what is stated, null clears it")
@kit_work
def work(self, context):
try:
given = json.loads(self.record)
except ValueError as error:
raise Refused(f"record must be JSON ({error}); nothing changed.") from None
limits, label, spring = (given.get(key) for key in ("limits", "mechanism", "compliance")) if isinstance(given, dict) else (None, None, None)
if (not isinstance(given, dict) or not set(given) <= {"limits", "mechanism", "compliance"}
or not (limits is None or isinstance(limits, list) and len(limits) == 2 and all(core.finite(v) for v in limits) and limits[0] <= limits[1])
or not (label is None or isinstance(label, str) and re.fullmatch(LABEL, label))
or not (spring is None or isinstance(spring, dict) and set(spring) == {"hertz", "damping_ratio"} and all(core.finite(v) for v in spring.values()))):
raise Refused("record must be a JSON object of any of limits ([lo, hi], lo at most hi, or null), mechanism (1 to 32 of a-z, 0-9 and _, or null) and "
"compliance ({hertz, damping_ratio} or null); nothing changed.")
def solve(child, built, sockets, stated, joint):
if joint["dof"] is None:
raise Refused(f"{child.name!r} on {child.parent.name!r}: socket type {joint['type']!r} states no dof: the connection is rigid and carries no joint record; nothing changed.")
record = {key: joint[key] for key in ("limits", "mechanism", "compliance")}
if "limits" in given:
record["limits"] = limits and (float(limits[0]), float(limits[1]))
if "mechanism" in given:
record["mechanism"] = label
if "compliance" in given:
record["compliance"] = spring and {key: float(spring[key]) for key in ("hertz", "damping_ratio")}
return stated[2], stated[3], {}, record
return pose(context, self.object_name, solve)
class BROKKR_KITBASH_OT_slide(PolishOperator):
"""Slide an attached kit part along its parent socket's normal, in place, on a prismatic connection: its parent
and sockets stay and what hangs from it follows"""
bl_idname = "brokkr_kitbash.slide"
bl_label = "Slide Kit Part"
object_name: bpy.props.StringProperty(name="Object", description="A part attached on a prismatic socket")
slide: bpy.props.FloatProperty(name="Slide", default=0.0, min=-10.0, max=10.0, precision=4,
description="Metres along the parent socket's normal from where the two sockets' origins meet")
@kit_work
def work(self, context):
def solve(child, built, sockets, stated, joint):
if joint["dof"] != "prismatic":
raise Refused(f"{child.name!r} on {child.parent.name!r}: socket type {joint['type']!r} is {joint['dof'] or 'rigid'}: slide poses a prismatic connection"
f"{' (roll, aim and reach turn this one)' if joint['dof'] else ''}; nothing changed.")
return stated[2], self.slide, {}, None
return pose(context, self.object_name, solve)
class BROKKR_KITBASH_OT_joints(PolishOperator):
"""Report the joints of the tree of kit parts under a root: each revolute or prismatic connection with its
parent joint, axis, value, limits, mechanism and compliance, in the root's frame"""
bl_idname = "brokkr_kitbash.joints"
bl_label = "Report Kit Joints"
bl_options = {"REGISTER"}
object_name: bpy.props.StringProperty(name="Object", description="The root: a kit part; the report is of what is attached below it")
@kit_work
def work(self, context):
root, kits, rows, rigid_count = mesh_object(self.object_name), {}, [], 0
built_part(root, kits)
frame = np.linalg.inv(np.array(root.matrix_world, dtype=np.float64))
todo = [(child, None) for child in sorted(attached(root), key=lambda o: o.name, reverse=True)]
while todo: # depth first, children by name: a joint's parent joint is the nearest DOF connection above it, and rigid connections fold into it
child, above = todo.pop()
part, built = built_part(child, kits)
stated = link(child)
parent_socket, _ = mated(child.parent, *built_part(child.parent, kits), child, part, built, stated)
kind = dof(child.parent, parent_socket)
if kind is None:
rigid_count += 1
else:
record, value = joint_record(child), stated[2] if kind == "revolute" else stated[3]
at = frame @ np.array(child.parent.matrix_world, dtype=np.float64) @ parent_socket["matrix"]
limits = record["limits"] and [round(v, 6) for v in record["limits"]]
rows.append({"id": child.name, "parent": above, "part": part["name"], "socket": f"{child.parent.name}:{stated[1]}", "kind": kind,
"axis": [round(float(v), 6) for v in at[:3, 2]], "origin": [round(float(v), 6) for v in at[:3, 3]], "value": round(value, 6),
"limits": limits, "min": limits and round(record["limits"][0] - value, 6), "max": limits and round(record["limits"][1] - value, 6),
"mechanism": record["mechanism"], "compliance": record["compliance"]})
above = child.name
todo += [(below, above) for below in sorted(attached(child), key=lambda o: o.name, reverse=True)]
report = {"schema": "brokkr.joints", "version": 1, "root": root.name, "frame": "the root object's: Blender axes (+Z up), metres", "rigid": rigid_count}
report["joints"] = fitted(report, "joints", rows)
return report
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
@ -841,7 +1013,7 @@ class BROKKR_KITBASH_OT_close(PolishOperator):
raise Refused(f"{obj.name!r} cannot close on itself; nothing changed.")
if closure(obj) is not None:
raise Refused(f"{obj.name!r} already states a closure (its socket {closure(obj)[0]!r}): a part states one, and detach clears it; nothing changed.")
there, here = mated(other, other_part, other_built, obj, part, built, (self.socket, self.other_socket, 0.0), "closing on")
there, here = mated(other, other_part, other_built, obj, part, built, (self.socket, self.other_socket, 0.0, 0.0), "closing on")
free(other, self.other_socket)
free(obj, self.socket)
apart = core.closure_residual(other.matrix_world, there, obj.matrix_world, here)
@ -1542,7 +1714,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
step: bpy.props.FloatProperty(name="Step", default=0.02, min=0.0049, max=0.2, description="Voxel size of the search")
sag: bpy.props.FloatProperty(name="Sag", default=1.0, min=0.0, max=8.0, description="How far the middle of each free span hangs, in outside diameters; 0: taut")
clamps: bpy.props.StringProperty(name="Clamps", default="[]", description="A JSON array of up to 8 {socket: 'Object:socket'}, mount sockets, in order along the hose")
joint: bpy.props.StringProperty(name="Joint", default="", description="Empty, or a JSON object {socket, standoff, range: [lo, hi]}: the pin the hose crosses")
joint: bpy.props.StringProperty(name="Joint", default="", description="Empty, or a JSON object {socket, standoff}: the pin the hose crosses; its roll range is that connection's limits")
# the action table states radius from 0.003 and step from 0.005: a float property rounds those up, so its bounds stand just under
@kit_work
@ -1565,10 +1737,13 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
"use fewer or thinner hoses, a smaller spread, or a larger port; nothing changed.")
clamp_rows, joint = self.rows()
clamps = [self.frame(context, row, f"clamps[{index}]", ("mount",), kits) for index, row in enumerate(clamp_rows)]
pins, pin = self.crossed(start["object"], end["object"], kits), None
(pins, slides), pin = self.crossed(start["object"], end["object"], kits), None
if slides:
raise Refused(f"The hose crosses the slide of {slides[0][0].name!r} on {slides[0][0].parent.name!r} (socket {slides[0][1]['name']!r}): a hose across a prismatic "
"connection is not routed; end it on a part on this side of the slide; nothing changed.")
if joint is None and pins:
raise Refused(f"The hose crosses the pin of {pins[0][0].name!r} on {pins[0][0].parent.name!r} (socket {pins[0][1]['name']!r}): give joint, a socket on that pin's axis, "
"a standoff and the roll range; nothing changed.")
raise Refused(f"The hose crosses the pin of {pins[0][0].name!r} on {pins[0][0].parent.name!r} (socket {pins[0][1]['name']!r}): give joint, a socket on that pin's axis "
"and a standoff; nothing changed.")
if joint is not None and len(pins) != 1:
raise Refused(("joint is given and the hose crosses no pin: its ends are on parts no pivot connection stands between" if not pins else
f"The hose crosses {len(pins)} pins ({', '.join(repr(child.name) + ' on ' + repr(child.parent.name) for child, _, _ in pins)}): a hose crosses one; "
@ -1584,13 +1759,19 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
if off > 1e-6 or lean > 1e-6:
raise Refused(f"joint.socket {on['name']!r} is not on the axis of the pin the hose crosses ({child.name!r} on {child.parent.name!r}, socket {socket['name']!r}): "
f"its origin stands {off:.6g} m off the axis and its z leans {math.degrees(math.asin(min(1.0, lean))):.6g} degrees from it; nothing changed.")
if not joint["range"][0] - 1e-9 <= current <= joint["range"][1] + 1e-9:
raise Refused(f"{child.name!r} stands at roll {current:.6g}, outside joint.range {joint['range']}: the range holds the pose the hose is routed at; nothing changed.")
limits = joint_record(child)["limits"] # the roll range the hose is proven over is the pin's own: its connection's limits
if limits is None:
raise Refused(f"{child.name!r} on {child.parent.name!r}: the pin the hose crosses states no limits: brokkr_kitbash.joint gives it the roll range "
"the hose is proven over; nothing changed.")
if core.within(current, *limits, True) is None:
raise Refused(f"{child.name!r} stands at roll {current:.6g}, outside its joint's limits {limits[0]:.6g} to {limits[1]:.6g}: roll it inside them, or state "
"limits that hold it (brokkr_kitbash.joint); nothing changed.")
current = core.within(current, *limits, True)
sides = [child in self.chain(stop["object"]) for stop in (start, *clamps, end)]
changes = [index for index in range(len(sides) - 1) if sides[index] != sides[index + 1]]
if len(changes) != 1:
raise Refused(f"clamps cross the pin of {child.name!r} {len(changes)} times: list them in order along the hose, those on the start's side of the pin first; nothing changed.")
pin = {"origin": axis[:3, 3], "axis": axis[:3, 2], "current": current, "before": changes[0], "child": child, "child_first": sides[0],
pin = {"origin": axis[:3, 3], "axis": axis[:3, 2], "current": current, "limits": limits, "before": changes[0], "child": child, "child_first": sides[0],
"point": on["matrix"][:3, 3] + on["matrix"][:3, 2] * joint["standoff"]}
rest, moved, through = self.trees(start["depsgraph"], hose, pin and pin["child"], kits)
reach = need + 2.0 * floor + self.step
@ -1700,7 +1881,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
"depsgraph": evaluable(context, obj)[0]}
def rows(self):
"""(the clamps' 'Object:socket' texts, the joint as {socket, standoff, range} or None), each refused by shape."""
"""(the clamps' 'Object:socket' texts, the joint as {socket, standoff} or None), each refused by shape."""
try:
clamps, joint = json.loads(self.clamps or "[]"), json.loads(self.joint) if self.joint else None
except ValueError as error:
@ -1711,29 +1892,28 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
if not isinstance(row, dict) or set(row) != {"socket"} or not isinstance(row["socket"], str):
raise Refused(f"clamps[{index}] must be an object of socket, an 'Object:socket' text; nothing changed.")
if joint is not None:
span = joint.get("range") if isinstance(joint, dict) else None
if (not isinstance(joint, dict) or set(joint) != {"socket", "standoff", "range"} or not isinstance(joint["socket"], str)
or not (core.finite(joint["standoff"]) and 0.0 <= joint["standoff"] <= 10.0)
or not (isinstance(span, list) and len(span) == 2 and all(core.finite(v) and -360.0 <= v <= 360.0 for v in span) and 0.0 <= span[1] - span[0] <= 360.0)):
raise Refused("joint must be an object of socket (an 'Object:socket' text), standoff (0 to 10) and range ([lo, hi] in degrees, lo to hi at most 360, each within 360 of 0); nothing changed.")
if (not isinstance(joint, dict) or set(joint) != {"socket", "standoff"} or not isinstance(joint["socket"], str)
or not (core.finite(joint["standoff"]) and 0.0 <= joint["standoff"] <= 10.0)):
raise Refused("joint must be an object of socket (an 'Object:socket' text) and standoff (0 to 10): the pin's roll range is its connection's limits "
"(brokkr_kitbash.joint); nothing changed.")
return [row["socket"] for row in clamps], joint
def crossed(self, start, end, kits) -> list:
"""The pins between two objects, [(child, the parent's pivot socket, roll)]: a connection is a child's parent
pointer and its kit_parent_socket (link), and it is a pin when that socket is a pivot. Read along both parent
chains up to the first object they share; with none shared, along both whole chains."""
def crossed(self, start, end, kits) -> tuple:
"""(the pins, the slides) between two objects, each [(child, the parent's socket, roll)]: a connection is a
child's parent pointer and its kit_parent_socket (link); it is a pin when that socket's type states dof
revolute in the parent's kit and a slide when it states prismatic. Read along both parent chains up to the
first object they share; with none shared, along both whole chains."""
up, down = self.chain(start), self.chain(end)
shared = [obj for obj in up if obj in down]
between = up[:up.index(shared[0])] + down[:down.index(shared[0])] if shared else up + down
pins = []
found = {"revolute": [], "prismatic": [], None: []}
for child in between:
stated = link(child)
if stated is None or child.parent is None or PART not in child.parent:
continue
socket = [s for s in built_part(child.parent, kits)[1].sockets if s["name"] == stated[1] and s["type"] == "pivot"]
if socket:
pins.append((child, socket[0], stated[2]))
return pins
for socket in (s for s in built_part(child.parent, kits)[1].sockets if s["name"] == stated[1]):
found[dof(child.parent, socket)].append((child, socket, stated[2]))
return found["revolute"], found["prismatic"]
def trees(self, depsgraph, hose, child, kits):
"""(a tree of every mesh the depsgraph evaluates but this hose, the pin's child side and the hoses through
@ -1769,7 +1949,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
ends = [bpy.data.objects.get(text if text in bpy.data.objects else text.rsplit(":", 1)[0]) for text in (stated["start"], stated["end"])]
except (ValueError, TypeError, KeyError, AttributeError):
return False
return None not in ends and any(found[0] == child for found in self.crossed(ends[0], ends[1], kits))
return None not in ends and any(found[0] == child for found in self.crossed(ends[0], ends[1], kits)[0])
@staticmethod
def reader(trees, cap: float):
@ -1829,7 +2009,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
before, after = before / np.linalg.norm(before), after / np.linalg.norm(after)
if pin["child_first"]: # read from the parent's side, as route.passes turns it
before, after = -after, -before
low, high = (v - pin["current"] for v in sized["joint"]["range"])
low, high = (v - pin["current"] for v in pin["limits"])
least[j - 1] = sized["floor"] * math.tan(min(route.sharpest_turn(before, after, pin["axis"], low, high), route.STIFF) / 2.0)
return np.where(clamped, sized["kept"], 0.0), clamped, least
@ -1879,7 +2059,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
if pin is not None:
j, order = tags.index("J"), slice(None, None, -1) if pin["child_first"] else slice(None) # passes reads a polyline from the parent's side
swing = route.passes(points[order], made.t[order], (len(points) - 1 - j) if pin["child_first"] else j, pin["origin"], pin["axis"],
route.rolls_of(sized["joint"]["range"][0], sized["joint"]["range"][1], ROLL_STEP), ROLL_FINEST, pin["current"], sized["far_rest"], sized["far_moved"],
route.rolls_of(pin["limits"][0], pin["limits"][1], ROLL_STEP), ROLL_FINEST, pin["current"], sized["far_rest"], sized["far_moved"],
sized["need"], sized["floor"], sized["exempt"], keep=keep[order])
return made.curve, made, sagged, clearance, swing
@ -1950,6 +2130,7 @@ class BROKKR_KITBASH_OT_report(PolishOperator):
classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report,
BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_roll, BROKKR_KITBASH_OT_aim, BROKKR_KITBASH_OT_reach,
BROKKR_KITBASH_OT_joint, BROKKR_KITBASH_OT_slide, BROKKR_KITBASH_OT_joints,
BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_freeze, BROKKR_KITBASH_OT_thaw,
BROKKR_KITBASH_OT_ribs,
BROKKR_KITBASH_OT_shell, BROKKR_KITBASH_OT_hose)

View file

@ -93,7 +93,7 @@
},
{
"name": "brokkr_kitbash.report",
"doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world 4x4, the connection (parent, sockets, roll, residual, holds) and frozen. faces counts the live mesh; a frozen part adds evaluated {faces}, and dirty (the modifiers shown again by hand, with frozen false). Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.",
"doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world 4x4, the connection (parent, sockets, roll, residual, holds, and its joint record: dof, slide, limits, mechanism, compliance, within) and frozen. faces counts the live mesh; a frozen part adds evaluated {faces}, and dirty (the modifiers shown again by hand, with frozen false). Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.",
"changesScene": false,
"editModeSafe": true,
"result": "brokkr_mesh_polish_result",
@ -109,7 +109,7 @@
},
{
"name": "brokkr_kitbash.attach",
"doc": "Seat a socket of a kit part on a socket of a part of any kit whose socket types agree and parent it there: origins together, normals opposed. Refuses sockets of different types or sizes that do not match, an occupied socket, a child that has a parent, and a loop. Reports the child with its connection.",
"doc": "Seat a socket of a kit part on a socket of a part of any kit whose socket types agree and parent it there: origins together, normals opposed. Refuses sockets of different types or sizes that do not match, an occupied socket, a child that has a parent, and a loop. The connection's DOF is its parent socket's type's (revolute, prismatic or rigid); it starts with no joint record: brokkr_kitbash.joint states one. Reports the child with its connection.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
@ -176,7 +176,7 @@
},
{
"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.",
"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 and, on a revolute joint with limits, a roll with no turn of itself inside them (the roll written is the one inside). 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",
@ -201,7 +201,7 @@
},
{
"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.",
"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. On a revolute joint with limits the roll stays inside them: where the free roll is outside, the end of the limits that points the axis nearer. 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",
@ -254,7 +254,7 @@
},
{
"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.",
"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. On a revolute joint with limits only a roll inside them is taken; with neither inside it refuses, naming both rolls and the limits. 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",
@ -308,6 +308,73 @@
}
]
},
{
"name": "brokkr_kitbash.joint",
"doc": "State the joint record of an attached kit part's connection. The connection's DOF is its parent socket's type's: revolute (its value is the roll, degrees) or prismatic (the slide, metres). record is a JSON object of any of limits ([lo, hi] or null), mechanism (a label of 1 to 32 a-z, 0-9 and _, or null) and compliance ({\"hertz\": over 0 to 30, \"damping_ratio\": 0 to 2} or null: a slide in the load path that settles under load, a record for a runtime, solved by nothing here); a key left out keeps what is stated and null clears it. Refuses a rigid connection naming its socket type, limits that do not hold the value the joint has, revolute limits spanning over 360 degrees or with an end past 360, prismatic limits with an end past 10 m, and compliance on a revolute joint or without limits. Moves nothing but a roll to its turn inside the limits. Reports the part 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": "a part attached on a revolute or prismatic socket"
},
{
"name": "record",
"type": "string",
"required": true,
"minLength": 2,
"maxLength": 400,
"doc": "a JSON object of any of limits, mechanism, compliance"
}
]
},
{
"name": "brokkr_kitbash.slide",
"doc": "Slide an attached kit part along its parent socket's normal, in place, on a prismatic connection (a ram_rod in a ram_barrel's bore: slide 0 is closed, the slide is the extension): its parent and both sockets stay, and what is attached to it follows. Refuses a revolute or rigid connection naming its socket type, and a slide outside the joint's limits. Reports the part 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": "a part attached on a prismatic socket"
},
{
"name": "slide",
"type": "number",
"required": true,
"minimum": -10,
"maximum": 10,
"doc": "metres along the parent socket's normal from where the two sockets' origins meet"
}
]
},
{
"name": "brokkr_kitbash.joints",
"doc": "The joints of the tree of kit parts attached under a root part, as {schema: brokkr.joints, version: 1, root, frame, rigid, joints}. A row per revolute or prismatic connection, depth first with children by name, so a joint's parent row comes before it: id (the child object), parent (the id of the nearest joint above, or null: rigid connections fold into it and are counted in rigid), part, socket ('Object:socket', the parent socket), kind, axis and origin (that socket's z and origin in the root object's frame: Blender axes, +Z up, metres), value (the roll in degrees or the slide in metres now), limits ([lo, hi] or null), min and max (the limits less the value: the travel either way from this pose), mechanism and compliance. Axis, origin and order are derived at each report from the kits and the parent tree; nothing stores them. Rows a receipt cannot carry are counted in jointsOmitted. Refuses a connection that cannot be read. Evaluates no modifier.",
"changesScene": false,
"editModeSafe": true,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "object_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "the root: a kit part"
}
]
},
{
"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.",
@ -800,7 +867,7 @@
},
{
"name": "brokkr_kitbash.hose",
"doc": "Route a bundle of hoses between two sockets, around every mesh Blender evaluates in the scene. start and end are 'Object:socket' on a kit part (a hose or flange socket no narrower than the bundle) or 'Object' alone, an empty whose z the hose leaves along. A leg runs between each pair of waypoints (a fitting's lead end, each clamp, the pin point): it is searched on a voxel grid of its ends' box plus 0.25 m (at most 524288 voxels), pulled taut with room for its bends where a way has it, and the whole polyline is rounded, each corner by the largest arc its measured room allows. That polyline is a seed: one refused for want of straight between its corners is refined in continuous space (vertices dropped, moved and added, each change proven clear), and before a route is refused the legs are searched again on two more grid origins and at half the step. The refusal then names the steps and origins tried and the first seed's refusal, and says this shows no route was found, not that none exists; it says the bundle is too stiff only where that is proven at a port. The innermost hose's bend radius is at least bend outside diameters, and a fitting keeps a straight of 8 radii (a ferrule, then 1.5 outside diameters). The centre line keeps the bundle's half width plus clearance from every other mesh, other hoses included, outside those leads. sag hangs the middle of each free span by that many outside diameters, never by more than half the room measured along the span; a route the sag breaks is made taut instead (sag in the report reads 0). clamps is a JSON array of up to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose: the bundle runs straight over each, along the socket's y, and gets a pad and a strap. A hose may cross one pin (a pivot connection between its ends' parts): joint is then {\"socket\": \"Object:socket\", \"standoff\": metres, \"range\": [lo, hi]}, a socket on that pin's axis whose z runs along it; the hose passes through the point standoff beyond it, so each side's straights move with their own part and only the bend at that point changes. The whole range from lo to hi is measured without posing anything, each side against the other side's parts: a roll every 5 degrees answers for the rolls about it by what a point can move within them, and more are measured between where that falls short; another hose through the same pin is kept clear of where it stands, not across the rolls (follow-up aetheria-release:follow_up:hose-motion-clearance-from-skinning owes that check). Every line is measured so that nothing thinner than a spacing can stand between two readings, whatever the step. The hose is one mesh object, a child of the start's object, and a bake of the scene at the call: after a part moves or rolls, run hose again on its name to rebuild it in place. Where it crosses a pin it is meant to be skinned between the bones on either side; no weights are written. Refuses before it writes anything, naming the leg, corner, point or roll. Reports object, rebuilt, hoses, length, lengthChange (over the range, of the centre line as each roll rounds it), floor, clearance (least beyond the bundle, outside the leads; readings stop at capped), voxels per leg, seed {step, offset, refined} (the grid that gave the route, and whether its polyline was refined), sag per leg in metres, rolls (how many were measured), worstRoll, worstClearance (least over the range, each reading less what its point can move within its roll's bin), faces, volume, nonManifoldEdges and radii {least, corners}.",
"doc": "Route a bundle of hoses between two sockets, around every mesh Blender evaluates in the scene. start and end are 'Object:socket' on a kit part (a hose or flange socket no narrower than the bundle) or 'Object' alone, an empty whose z the hose leaves along. A leg runs between each pair of waypoints (a fitting's lead end, each clamp, the pin point): it is searched on a voxel grid of its ends' box plus 0.25 m (at most 524288 voxels), pulled taut with room for its bends where a way has it, and the whole polyline is rounded, each corner by the largest arc its measured room allows. That polyline is a seed: one refused for want of straight between its corners is refined in continuous space (vertices dropped, moved and added, each change proven clear), and before a route is refused the legs are searched again on two more grid origins and at half the step. The refusal then names the steps and origins tried and the first seed's refusal, and says this shows no route was found, not that none exists; it says the bundle is too stiff only where that is proven at a port. The innermost hose's bend radius is at least bend outside diameters, and a fitting keeps a straight of 8 radii (a ferrule, then 1.5 outside diameters). The centre line keeps the bundle's half width plus clearance from every other mesh, other hoses included, outside those leads. sag hangs the middle of each free span by that many outside diameters, never by more than half the room measured along the span; a route the sag breaks is made taut instead (sag in the report reads 0). clamps is a JSON array of up to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose: the bundle runs straight over each, along the socket's y, and gets a pad and a strap. A hose may cross one pin (a revolute connection between its ends' parts, with limits stated by brokkr_kitbash.joint: they are the roll range lo to hi; a pin without limits and a prismatic connection between the ends are refused): joint is then {\"socket\": \"Object:socket\", \"standoff\": metres}, a socket on that pin's axis whose z runs along it; the hose passes through the point standoff beyond it, so each side's straights move with their own part and only the bend at that point changes. The whole range from lo to hi is measured without posing anything, each side against the other side's parts: a roll every 5 degrees answers for the rolls about it by what a point can move within them, and more are measured between where that falls short; another hose through the same pin is kept clear of where it stands, not across the rolls (follow-up aetheria-release:follow_up:hose-motion-clearance-from-skinning owes that check). Every line is measured so that nothing thinner than a spacing can stand between two readings, whatever the step. The hose is one mesh object, a child of the start's object, and a bake of the scene at the call: after a part moves or rolls, run hose again on its name to rebuild it in place. Where it crosses a pin it is meant to be skinned between the bones on either side; no weights are written. Refuses before it writes anything, naming the leg, corner, point or roll. Reports object, rebuilt, hoses, length, lengthChange (over the range, of the centre line as each roll rounds it), floor, clearance (least beyond the bundle, outside the leads; readings stop at capped), voxels per leg, seed {step, offset, refined} (the grid that gave the route, and whether its polyline was refined), sag per leg in metres, rolls (how many were measured), worstRoll, worstClearance (least over the range, each reading less what its point can move within its roll's bin), faces, volume, nonManifoldEdges and radii {least, corners}.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
@ -898,7 +965,7 @@
"type": "string",
"minLength": 0,
"maxLength": 4000,
"doc": "empty, or a JSON object {\"socket\": \"Object:socket\", \"standoff\": 0 to 10, \"range\": [lo, hi]}: the pin the hose crosses",
"doc": "empty, or a JSON object {\"socket\": \"Object:socket\", \"standoff\": 0 to 10}: the pin the hose crosses; its roll range is that connection's limits",
"default": ""
}
]

View file

@ -303,10 +303,12 @@ def check_kit(document: Any) -> dict:
for name, entry in document["socketTypes"].items():
where = f"{here} socket type {name!r}"
_name(name, where, set())
_keys(entry, where, ("match", "doc"))
_keys(entry, where, ("match", "doc"), ("dof",))
if entry["match"] not in ("equal", "fits"):
raise KitError(f"{where}: match must be 'equal' or 'fits'")
types[name] = {"match": entry["match"], "doc": _text(entry["doc"], f"{where} doc")}
if "dof" in entry and entry["dof"] not in DOFS:
raise KitError(f"{where}: dof must be 'revolute' or 'prismatic' (a type that states none is rigid)")
types[name] = {"match": entry["match"], "doc": _text(entry["doc"], f"{where} doc"), **({"dof": entry["dof"]} if "dof" in entry else {})}
parts, part_names = {}, set()
for index, part in enumerate(document["parts"]):
name = _name(part.get("name") if isinstance(part, dict) else None, f"{here} part {index}", part_names)
@ -1219,19 +1221,44 @@ def surface_frame(point, normal, up, roll_degrees: float = 0.0) -> np.ndarray:
return frame @ _roll(roll_degrees)
def mate(parent_socket: dict, child_socket: dict, roll_degrees: float = 0.0) -> np.ndarray:
"""The child's 4x4 in its parent's frame that seats child_socket on parent_socket: origins together, normals
opposed, the child turned roll_degrees about the parent socket's z (right-handed; at 0 the two ys line up)."""
return parent_socket["matrix"] @ _roll(roll_degrees) @ FLIP @ np.linalg.inv(child_socket["matrix"])
def _slid(metres: float) -> np.ndarray:
move = np.eye(4)
move[2, 3] = metres
return move
def residual(parent_world, parent_socket: dict, child_world, child_socket: dict, roll_degrees: float) -> float:
def mate(parent_socket: dict, child_socket: dict, roll_degrees: float = 0.0, slide: float = 0.0) -> np.ndarray:
"""The child's 4x4 in its parent's frame that seats child_socket on parent_socket: normals opposed, the child
turned roll_degrees about the parent socket's z (right-handed; at 0 the two ys line up) and its socket's origin
`slide` metres along that z from the parent socket's (0: origins together). A turn about z and a move along it
commute, so one connection carries both."""
return parent_socket["matrix"] @ _slid(slide) @ _roll(roll_degrees) @ FLIP @ np.linalg.inv(child_socket["matrix"])
def residual(parent_world, parent_socket: dict, child_world, child_socket: dict, roll_degrees: float, slide: float = 0.0) -> float:
"""How far a child stands from where mate puts it: the largest absolute entry of the difference between the
frame its socket should have in the world and the frame it has."""
wanted = np.asarray(parent_world, dtype=np.float64) @ parent_socket["matrix"] @ _roll(roll_degrees) @ FLIP
wanted = np.asarray(parent_world, dtype=np.float64) @ parent_socket["matrix"] @ _slid(slide) @ _roll(roll_degrees) @ FLIP
return float(np.abs(wanted - np.asarray(child_world, dtype=np.float64) @ child_socket["matrix"]).max())
DOFS = ("revolute", "prismatic") # what a socket type's dof may state: the child turns about the parent socket's z, or slides along it
# How far past an end of its limits a joint's value may stand and still be inside them, as a fraction of the larger
# of 1 and the ends' sizes. A rule: an action's roll and slide are float32 fields and limits are JSON doubles, so a
# value typed as an end of its own limits stands up to 6e-08 of itself off that end; 1e-06 is 17 of those.
LIMIT_SLACK = 1e-6
def within(value: float, lo: float, hi: float, revolute: bool) -> float | None:
"""The representative of a joint's value inside its limits [lo, hi], or None when it has none: the value itself
on a prismatic joint; on a revolute one the value itself when it is inside, else value + 360 k, the least at or
above lo. A value within LIMIT_SLACK of an end is that end."""
slack = LIMIT_SLACK * max(1.0, abs(lo), abs(hi))
if revolute and not lo - slack <= value <= hi + slack:
value += 360.0 * math.ceil((lo - slack - value) / 360.0)
return min(max(value, lo), hi) if lo - slack <= value <= hi + slack else None
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.
@ -1263,26 +1290,36 @@ def _wrapped(degrees: float) -> float:
return 180.0 - (180.0 - degrees) % 360.0
def aim_roll(parent_world, parent_socket: dict, child_socket: dict, axis, direction) -> tuple[float, float]:
def aim_roll(parent_world, parent_socket: dict, child_socket: dict, axis, direction, limits=None) -> 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."""
axis or a direction along the pin (hypot(A, B) at most AIM_FLOOR), which no roll turns. With `limits` (lo, hi)
the roll is its representative inside them (within); when the free roll has none, the end of the limits whose
dot is the larger (the dot is a sinusoid of the roll: over an interval of at most a turn it peaks at its
optimum or at an end; a tie takes lo), and the dot is that end's."""
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)
roll = _wrapped(math.degrees(math.atan2(B, A)))
if limits is None:
return roll, C + math.hypot(A, B)
inside = within(roll, *limits, True)
if inside is not None:
return inside, C + math.hypot(A, B)
return max(((end, A * math.cos(math.radians(end)) + B * math.sin(math.radians(end)) + C) for end in limits), key=lambda found: found[1])
def reach_roll(parent_world, parent_socket: dict, child_socket: dict, point, direction, height: float, current_roll: float) -> tuple[float, float]:
def reach_roll(parent_world, parent_socket: dict, child_socket: dict, point, direction, height: float, current_roll: float, limits=None) -> 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)."""
does). With `limits` (lo, hi) only a root with a representative inside them (within) is taken, as that
representative; with none inside it refuses, naming both roots and the limits."""
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)
@ -1295,6 +1332,12 @@ def reach_roll(parent_world, parent_socket: dict, child_socket: dict, point, dir
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)})
if limits is not None:
inside = [found for found in (within(root, *limits, True) for root in roots) if found is not None]
if not inside:
raise KitError(f"{here}: the rolls that bring the point to {height:.6f} m, {' and '.join(f'{root:.6g}' for root in roots)}, are outside "
f"the joint's limits {limits[0]:.6g} to {limits[1]:.6g}")
roots = inside
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)
@ -1316,7 +1359,7 @@ def mate_refusal(kit_types: dict, parent_socket: dict, child_socket: dict, child
agree as that type's match says ('equal': within 1 percent of the larger; 'fits': the child at most the parent).
kit_types is the socketTypes of the parent's kit. For parts of two kits, child_types is the socketTypes of the
child's and `kits` the two kits' names: socket types are a vocabulary kits share, and the two sockets mate only
when the child's kit declares the type with the same match."""
when the child's kit declares the type with the same match and the same dof."""
p, c = parent_socket, child_socket
both = f"socket {c['name']!r} ({c['type']}, size {c['size']:.6g}) and parent socket {p['name']!r} ({p['type']}, size {p['size']:.6g})"
if p["type"] != c["type"]:
@ -1325,6 +1368,10 @@ def mate_refusal(kit_types: dict, parent_socket: dict, child_socket: dict, child
theirs = child_types.get(c["type"], {}).get("match")
return (f"{both}: kit {kits[0]!r} declares socket type {p['type']!r} with match {kit_types[p['type']]['match']!r} and kit {kits[1]!r} "
f"{'with match ' + repr(theirs) if theirs else 'does not declare it'}; parts of two kits mate by socket types both declare alike")
if child_types is not None and child_types[c["type"]].get("dof") != kit_types[p["type"]].get("dof"):
ours, theirs = (types[p["type"]].get("dof", "none (rigid)") for types in (kit_types, child_types))
return (f"{both}: kit {kits[0]!r} declares socket type {p['type']!r} with dof {ours} and kit {kits[1]!r} with dof {theirs}; "
"parts of two kits mate by socket types both declare alike")
if kit_types[p["type"]]["match"] == "equal":
if abs(p["size"] - c["size"]) > EQUAL * max(p["size"], c["size"]) * (1 + SLACK):
return f"{both} are {p['type']} sockets, which mate at equal sizes (within 1 percent)"

View file

@ -4,7 +4,7 @@
"doc": "Chassis structure: sectioned beams, a truss, a portal, a gusset and a wedge, each a section swept along a path. Metres.",
"socketTypes": {
"mount": {"match": "fits", "doc": "flat seat; size is the free diameter around the socket"},
"pivot": {"match": "equal", "doc": "pin joint; size is the pin diameter"}
"pivot": {"match": "equal", "dof": "revolute", "doc": "pin joint; size is the pin diameter"}
},
"parts": [
{

View file

@ -5,7 +5,8 @@
"socketTypes": {
"flange": {"match": "equal", "doc": "bolted pipe or duct face; size is the bore diameter"},
"mount": {"match": "fits", "doc": "flat seat; size is the free diameter around the socket"},
"pivot": {"match": "equal", "doc": "pin joint; size is the pin diameter"},
"pivot": {"match": "equal", "dof": "revolute", "doc": "pin joint; size is the pin diameter"},
"slide": {"match": "equal", "dof": "prismatic", "doc": "telescoping bore; size is the bore diameter; the child slides along the socket's z"},
"hose": {"match": "fits", "doc": "hose port; size is the widest bundle it takes"}
},
"parts": [
@ -179,6 +180,59 @@
{"name": "port_rod", "type": "hose", "size": "0.4*body_r", "at": ["1.45*body_r", 0, "2.25*body_r+body_len"], "z": "+x", "y": "+z"}
]
},
{
"name": "ram_barrel",
"doc": "The barrel of a tie-rod hydraulic cylinder, the actuator's up to its gland: base eye on a cross pin with a socket on each end face, square caps, barrel, ports, and a bore a ram_rod slides in.",
"params": [
{"name": "body_r", "type": "number", "min": 0.05, "max": 0.12, "default": 0.06, "doc": "barrel radius"},
{"name": "body_len", "type": "number", "min": 0.2, "max": 1.0, "default": 0.4, "doc": "barrel length between caps"},
{"name": "rod_r", "type": "number", "min": 0.01, "max": 0.02, "default": 0.018, "doc": "radius of the rod its gland takes"},
{"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"}
],
"bevel": "0.04*body_r",
"shapes": [
{"shape": "box", "size": ["1.2*body_r", "0.9*body_r", "1.6*body_r"], "at": [0, 0, "0.8*body_r"]},
{"shape": "tube", "r0": "0.45*body_r", "r1": "0.45*body_r", "length": "1.3*body_r", "segments": "segments", "smooth": true, "rot": [-90, 0, 0], "at": [0, "-0.65*body_r", "0.8*body_r"]},
{"shape": "box", "size": ["2.4*body_r", "2.4*body_r", "0.5*body_r"], "at": [0, 0, "1.75*body_r"]},
{"shape": "tube", "r0": "body_r", "r1": "body_r", "length": "body_len+0.2*body_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.9*body_r"]},
{"shape": "box", "size": ["2.4*body_r", "2.4*body_r", "0.5*body_r"], "at": [0, 0, "2.25*body_r+body_len"]},
{"shape": "repeat", "count": 2, "step": ["1.9*body_r", 0, 0], "of":
{"shape": "tube", "r0": "0.12*body_r", "r1": "0.12*body_r", "length": "body_len+1.3*body_r", "segments": 6, "at": ["-0.95*body_r", "-0.95*body_r", "1.35*body_r"]}},
{"shape": "repeat", "count": 2, "step": ["1.9*body_r", 0, 0], "of":
{"shape": "tube", "r0": "0.12*body_r", "r1": "0.12*body_r", "length": "body_len+1.3*body_r", "segments": 6, "at": ["-0.95*body_r", "0.95*body_r", "1.35*body_r"]}},
{"shape": "repeat", "count": 2, "step": [0, 0, "body_len+0.5*body_r"], "of":
{"shape": "tube", "r0": "0.2*body_r", "r1": "0.2*body_r", "length": "0.45*body_r", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": ["body_r", 0, "1.75*body_r"]}},
{"shape": "tube", "r0": "rod_r+0.25*body_r", "r1": "rod_r+0.25*body_r", "length": "0.4*body_r", "segments": "segments", "smooth": true, "at": [0, 0, "2.4*body_r+body_len"]}
],
"sockets": [
{"name": "base", "type": "pivot", "size": "0.9*body_r", "at": [0, "0.65*body_r", "0.8*body_r"], "z": "+y", "y": "+z"},
{"name": "base_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "0.8*body_r"], "z": "-y", "y": "+z"},
{"name": "bore", "type": "slide", "size": "2*rod_r", "at": [0, 0, "2*body_r"], "z": "+z", "y": "+y"},
{"name": "port_cap", "type": "hose", "size": "0.4*body_r", "at": ["1.45*body_r", 0, "1.75*body_r"], "z": "+x", "y": "+z"},
{"name": "port_rod", "type": "hose", "size": "0.4*body_r", "at": ["1.45*body_r", 0, "2.25*body_r+body_len"], "z": "+x", "y": "+z"}
]
},
{
"name": "ram_rod",
"doc": "The rod of a hydraulic cylinder, the actuator's from its gland: a rod from its piston face to a rod eye on a cross pin with a socket on each end face. Its piston slides in a ram_barrel's bore: slide 0 is closed, the slide is the extension.",
"params": [
{"name": "body_r", "type": "number", "min": 0.05, "max": 0.12, "default": 0.06, "doc": "its barrel's radius: sizes the rod eye"},
{"name": "rod_r", "type": "number", "min": 0.01, "max": 0.02, "default": 0.018, "doc": "rod radius"},
{"name": "length", "type": "number", "min": 0.2, "max": 2.0, "default": 0.466, "doc": "piston face to the rod eye's block; its barrel's body_len + 1.1*body_r stands as the actuator does at extension 0"},
{"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"}
],
"bevel": "0.04*body_r",
"shapes": [
{"shape": "tube", "r0": "rod_r", "r1": "rod_r", "length": "length+0.2*body_r", "segments": "segments", "smooth": true, "at": [0, 0, 0]},
{"shape": "box", "size": ["1.2*body_r", "0.9*body_r", "1.4*body_r"], "at": [0, 0, "length+0.7*body_r"]},
{"shape": "tube", "r0": "0.45*body_r", "r1": "0.45*body_r", "length": "1.3*body_r", "segments": "segments", "smooth": true, "rot": [-90, 0, 0], "at": [0, "-0.65*body_r", "length+0.7*body_r"]}
],
"sockets": [
{"name": "piston", "type": "slide", "size": "2*rod_r", "at": [0, 0, 0], "z": "-z", "y": "+y"},
{"name": "rod_end", "type": "pivot", "size": "0.9*body_r", "at": [0, "0.65*body_r", "length+0.7*body_r"], "z": "+y", "y": "+z"},
{"name": "rod_end_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "length+0.7*body_r"], "z": "-y", "y": "+z"}
]
},
{
"name": "pipe_fitting",
"doc": "Flanged tee: a run along +z with a branch along +x at its middle, a reinforced hub and bolted flanges.",

View file

@ -25,8 +25,10 @@ Who owns what:
included: a part's size is its params, and a socket's frame is a rotation and an origin. Set scale to 1 and
resize with `set_params`.
- A connection between two parts belongs to the child: its parent pointer and its `kit_socket`,
`kit_parent_socket` and `kit_roll` properties. Where the child stands is derived from them
("Assembling parts").
`kit_parent_socket` and `kit_roll` properties, and its joint record (`kit_slide`, `kit_min`, `kit_max`,
`kit_mechanism`, `kit_compliance`). Where the child stands is derived from them ("Assembling parts"). The
joint's kind belongs to the kit's socket type and its axis to the parent socket's frame: neither is stored on
the connection.
- A closure, the joint that closes a loop, belongs to the closing part: its `kit_close_socket`, `kit_close_to`
and `kit_close_to_socket` properties. Only `close` writes them and only `detach` clears them. A closure places
nothing: whether it holds is derived at each report.
@ -149,7 +151,8 @@ well under the part's thinnest feature at its smallest params.
**Sockets** are frames. `at` is the origin; `z` is the outward normal (a mating socket faces it), `y` is up (the
roll reference), and x is y cross z; each is one of `+x -x +y -y +z -z` in the part's frame, on different axes.
`size` is a diameter in metres. `type` names one of the kit's `socketTypes`, whose `match` says how sizes are to
be compared when sockets are mated: `equal` (within 1 percent) or `fits` (the child at most the parent). A socket
be compared when sockets are mated: `equal` (within 1 percent) or `fits` (the child at most the parent), and
whose optional `dof` (`revolute` or `prismatic`; absent is rigid) says how a child seated on such a socket moves. A socket
sits on a flat face of the part whose normal is its `z`; `test_kitbash` checks this for every part of a shipped
kit at its default, smallest and largest params and at seeded draws between.
@ -162,20 +165,75 @@ angle: at 0 the two parts line up, side by side. A pin carries a socket on each
**A connection** seats one socket of a child part on one socket of a parent part: the two origins together, the
two normals opposed, and the child turned `roll` degrees about the parent socket's normal (right-handed; at 0 the
two sockets' up axes line up). The child owns it. It is the child's parent pointer, under an identity parent
inverse, and three ID properties on the child: `kit_socket` (its own socket), `kit_parent_socket` and `kit_roll`.
Nothing else stores it: no parent name, no world matrix, no empties. The child's `matrix_basis` is derived,
two sockets' up axes line up). On a prismatic socket the child also stands `slide` metres along that normal. The
child owns it. It is the child's parent pointer, under an identity parent inverse, and three ID properties on the
child: `kit_socket` (its own socket), `kit_parent_socket` and `kit_roll`, with its joint record ("Joint records",
below). Nothing else stores it: no parent name, no world matrix, no empties. The child's `matrix_basis` is
derived,
```text
matrix_basis = S_parent @ Rz(roll) @ FLIP @ inverse(S_child) FLIP = half a turn about y
matrix_basis = S_parent @ T(0, 0, slide) @ 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`, `set_params`,
`roll`, `aim` and `reach` write it; nothing else should.
with `S` each socket's frame in its own part at that part's stored params (`core.mate`); a turn about z and a move
along it commute, so one connection carries both. `attach`, `set_params`, `roll`, `aim`, `reach`, `slide` and
`joint` write it; nothing else should.
**Joint records.** A connection's degree of freedom is its parent socket's type's: a socket type states
`"dof": "revolute"` (the child turns about the socket's z: `pivot`), `"dof": "prismatic"` (it slides along it:
`slide`) or nothing, and is then rigid (`flange`, `mount`, `hose`). No part, socket or object name decides it. A
revolute joint's value is its `kit_roll`, in degrees; a prismatic joint's is its `kit_slide`, in metres, and its
roll is a build angle. Beside the value the child's connection carries a record:
| Property | States | Stated by |
| --- | --- | --- |
| `kit_slide` | metres along the parent socket's z; prismatic only, 0 where the two origins meet | `slide` |
| `kit_min`, `kit_max` | the limits of the value, both or neither: degrees on a revolute joint (a span of at most 360, each end within 360 of 0), metres on a prismatic one (each end within 10 m of 0) | `joint` |
| `kit_mechanism` | a label of 1 to 32 `a-z`, `0-9` and `_`: which mechanism the joint is (`knee`, `shock`) | `joint` |
| `kit_compliance` | `{"hertz", "damping_ratio"}` (hertz over 0 to 30, damping ratio 0 to 2): a slide in the load path that settles and rebounds under load. Prismatic only, and it needs limits, the travel it settles within | `joint` |
Every one of them is written by one function, `write_connection`, which `attach`, `roll`, `aim`, `reach`, `slide`
and `joint` all seat through; `detach` clears them with the connection. So the limits have one check: a value with
no representative inside them is refused before anything is written, naming value and limits, and a roll a turn
away from its limits is written as the roll inside them (limits 150 to 210 and a roll of -170: 190). `aim` inside
limits takes the free roll when the limits hold it and otherwise the end that points the axis nearer; `reach`
takes only a root inside them. A new connection states no record. A value written by hand outside its limits
reads `within: false` in every report and the next pose of that part is refused.
Limits and springs follow Box2D v3's `b2PrismaticJointDef` and Jolt's `SliderConstraintSettings`: the slide's
limits and a spring as a frequency in hertz and a damping ratio sit on the joint itself. Frequency and damping
ratio describe how the strut feels whatever mass it carries; a stiffness in N/m would need the mass the kit does
not know. `kit_compliance` is a record for a runtime: nothing in Brokkr solves it.
Two things a rig needs are not stored, because each is already stated once. The axis is the parent socket's z in
the kit at the parent's stored params: a copy on the connection would go stale at the next `set_params`. The order
is the parent tree. `brokkr_kitbash.joints` derives both at each call and emits them, so a consumer derives
nothing:
```json
{"schema": "brokkr.joints", "version": 1, "root": "Tank", "frame": "the root object's: Blender axes (+Z up), metres",
"rigid": 2, "joints": [
{"id": "Strut", "parent": null, "part": "strut", "socket": "Mount:pivot", "kind": "revolute",
"axis": [0.0, 1.0, 0.0], "origin": [0.436, 0.0, 0.85368], "value": -113.019997, "limits": [-116.02, -40.02],
"min": -3.000003, "max": 72.999997, "mechanism": "knee", "compliance": null},
{"id": "Rod", "parent": "Barrel", "part": "ram_rod", "socket": "Barrel:bore", "kind": "prismatic",
"axis": [0.97429, 0.0, 0.225296], "origin": [1.072572, 0.124, 1.312762], "value": 0.12, "limits": [0.0, 0.3],
"min": -0.12, "max": 0.18, "mechanism": "shock", "compliance": {"damping_ratio": 0.7, "hertz": 4.0}}]}
```
A row per revolute or prismatic connection under the root, depth first with children by name, so a row's parent
comes before it. `parent` is the nearest joint above, not the object the part hangs from: rigid connections fold
into it and are counted in `rigid`. `axis` and `origin` are the parent socket's z and origin in the root object's
frame. `min` and `max` are the limits less the value, the travel either way from the pose the report was taken at,
which is the shape of Aetheria's `ShipJoint` (`Min` and `Max` about rest). What the report gives up: it is the
pose at the call, so rest is whatever the assembly stood at; it carries no meshes or bone names, so a consumer
joins rows to the exported objects by `id`; and `ShipJoint` has no slide and no spring yet
(aetheria-release:question:shipjoint-prismatic-dof), so a prismatic row has no Aetheria reader today.
**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
vocabulary kits share: parts of two kits mate when both kits declare the socket's type with the same `match`
vocabulary kits share: parts of two kits mate when both kits declare the socket's type with the same `match` and
the same `dof`
(`cutters` declares `mount` as `mechanical` does, so a vent seats on a recess floor), and are refused, naming both
kits and the type, when one does not declare it or declares it otherwise. KSP's attach nodes and LDraw's snap
types are connector vocabularies of this kind: global, matched by type and size. `attach` also
@ -666,7 +724,7 @@ evaluation once for every `ribs` call; iterate planes on the cage before it is c
```json
{"action": "brokkr_kitbash.hose", "object_name": "Feed", "start": "ThighRam:port_cap", "end": "ShinRam:port_cap",
"count": 3, "radius": 0.006, "clearance": 0.005,
"joint": "{\"socket\": \"Shin:end_a_back\", \"standoff\": 0.08, \"range\": [-120, 20]}"}
"joint": "{\"socket\": \"Shin:end_a_back\", \"standoff\": 0.08}"}
```
**Ends.** `start` and `end` are `Object:socket` on a kit part, a `hose` socket (an actuator's `port_cap` and
@ -751,9 +809,12 @@ radius above the face, for 2 outside diameters each side, and gets a pad on the
bundle lies flat on the first clamp; its ups are rotation minimising (Wang et al. 2008), so it does not twist
between clamps, and a later clamp's strap follows the bundle as it arrives.
**A pin.** A hose may cross one pin: a pivot connection between its ends' parts, found from their parent chains.
`joint` names a socket on that pin's axis whose z runs along it (the free end face of the pin: a strut's
`end_a_back`), a `standoff` and the pin's roll `range`. The hose passes through the point `standoff` beyond that
**A pin.** A hose may cross one pin: a revolute connection between its ends' parts, found from their parent
chains. `joint` names a socket on that pin's axis whose z runs along it (the free end face of the pin: a strut's
`end_a_back`) and a `standoff`. The roll range the hose is proven over is the pin's own: its connection's limits,
stated once with `brokkr_kitbash.joint` (`{"limits": [-120, 20]}`) and read by every hose across it. A pin with no
limits is refused, naming that action, and so is a prismatic connection between the ends: a hose across a slide
is not routed. The hose passes through the point `standoff` beyond that
socket, on the axis, as a robot's dress pack does: the straights on each side then move with their own part and
only the bend at that point changes with the roll. The whole range is measured without posing anything, not a
list of rolls in it. Each roll from `lo` to `hi` in steps of 5 degrees answers for the rolls nearer it than any
@ -792,7 +853,8 @@ skin weights are `brokkr_rig`'s.
**Refusals**, each before anything is written: a name taken by an object that is no hose; an end or clamp that
names no object, no such socket, or a socket of the wrong type; a bundle wider than a port, naming both sizes; a
part that is scaled or that Blender does not evaluate; a pin crossed with no `joint`, a `joint` with no pin, two
pins, a `joint` socket off the pin's axis, the current roll outside `range`; a search box over 524288 voxels,
pins, a `joint` socket off the pin's axis, a pin with no limits or standing outside them, a slide between the
ends; a search box over 524288 voxels,
naming a step that fits; an end nearer an obstacle than the bundle needs; a bundle proven too stiff to leave a
port; and, once every seed has been tried, no route found, with the first seed's refusal: no way through, a corner
under the floor by what its polyline lacked, a curve not proven to keep the clearance at a named point, or a roll
@ -993,6 +1055,9 @@ Python loop of BVH queries with three rays a sample, and the 13,824-candidate se
| `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.joint` | `object_name`, `record` (a JSON object of any of `limits`: `[lo, hi]` or null; `mechanism`: a label or null; `compliance`: `{hertz, damping_ratio}` or null) | States the joint record of an attached part's connection; a key left out keeps what is stated and null clears it. Refuses a rigid connection naming its socket type, limits that do not hold the value the joint has, revolute limits over a turn or past 360, prismatic limits past 10 m, and compliance on a revolute joint or without limits. Reports the part and `closures` as `roll` does |
| `brokkr_kitbash.slide` | `object_name`, `slide` (metres, -10 to 10) | Slides an attached part along its parent socket's normal on a prismatic connection, where it hangs. Refuses a revolute or rigid connection naming its socket type, and a slide outside the joint's limits. Reports the part and `closures` as `roll` does |
| `brokkr_kitbash.joints` | `object_name` (the root, a kit part) | Reports the joints of the tree attached under the root as `brokkr.joints` version 1: a row per revolute or prismatic connection, parents first, with `id`, `parent`, `part`, `socket`, `kind`, `axis`, `origin`, `value`, `limits`, `min`, `max`, `mechanism` and `compliance`, in the root's frame ("Joint records"). Changes nothing |
| `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; `booleansOmitted` counts rows a receipt had no room for) 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` (with `booleansOmitted`, as `boolean`). |
@ -1001,7 +1066,7 @@ Python loop of BVH queries with three rays a sample, and the 13,824-candidate se
| `brokkr_kitbash.thaw` | `object_name` | Puts the live mesh back, turns every modifier on and removes the frozen mesh; evaluates nothing. Refuses an object that is not frozen or whose held mesh is gone. Reports `object`, `frozen`, `modifiers` and the live mesh's `faces`. |
| `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. |
| `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel`, `count_folds` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `folded` (with `count_folds`, the number of the evaluated wall's inner faces that fold; else null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. |
| `brokkr_kitbash.hose` | `object_name`, `start`, `end`, `count`, `radius`, `spread`, `clearance`, `bend`, `step`, `sag`, `clamps` (a JSON array of up to 8 `{socket}`), `joint` (empty, or a JSON object `{socket, standoff, range}`) | Routes a bundle of hoses between two sockets around every other mesh, over clamps and through a pin's axis across its roll range; on a hose's name, rebuilds it in place. Reports `length`, `lengthChange`, `clearance`, `radii`, `sag`, `voxels`, `seed`, `rolls`, `worstRoll`, `faces`, `nonManifoldEdges`. |
| `brokkr_kitbash.hose` | `object_name`, `start`, `end`, `count`, `radius`, `spread`, `clearance`, `bend`, `step`, `sag`, `clamps` (a JSON array of up to 8 `{socket}`), `joint` (empty, or a JSON object `{socket, standoff}`) | Routes a bundle of hoses between two sockets around every other mesh, over clamps and through a pin's axis across its roll range; on a hose's name, rebuilds it in place. Reports `length`, `lengthChange`, `clearance`, `radii`, `sag`, `voxels`, `seed`, `rolls`, `worstRoll`, `faces`, `nonManifoldEdges`. |
`params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored
value (`set_params`). A value outside its bounds is refused with the bounds in the message.
@ -1047,8 +1112,9 @@ file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the
## The mechanical kit
`kits/mechanical.v0.json`: eleven parts, each along +z, with socket types `flange` (equal), `mount` (fits),
`pivot` (equal) and `hose` (fits: a port takes a bundle no wider than its size).
`kits/mechanical.v0.json`: thirteen parts, each along +z, with socket types `flange` (equal), `mount` (fits),
`pivot` (equal, revolute), `slide` (equal, prismatic: a telescoping bore, sized by its diameter) and `hose` (fits:
a port takes a bundle no wider than its size).
| part | params | sockets |
| --- | --- | --- |
@ -1057,6 +1123,8 @@ file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the
| `ribbed_cylinder` | `radius`, `length`, `ribs`, `rib_depth`, `rib_width`, `segments` | `end_a`, `end_b` (flange) |
| `strut` | `length`, `width`, `thickness`, `segments` | `end_a`, `end_a_back`, `end_b`, `end_b_back` (pivot): the two end faces of the pin at each end |
| `actuator` | `body_r`, `body_len`, `rod_r`, `extension`, `segments` | `base`, `base_back`, `rod_end`, `rod_end_back` (pivot); the rod end's two move with `extension`; `port_cap`, `port_rod` (hose, `0.4*body_r` wide) on the end faces of its two port bosses |
| `ram_barrel` | `body_r`, `body_len`, `rod_r`, `segments` | the actuator up to its gland: `base`, `base_back` (pivot); `bore` (slide, `2*rod_r`) at the closed piston face, its z along the barrel; `port_cap`, `port_rod` (hose) |
| `ram_rod` | `body_r`, `rod_r`, `length`, `segments` | the actuator from its gland: `piston` (slide, `2*rod_r`); `rod_end`, `rod_end_back` (pivot). In a barrel's bore slide 0 is closed and the slide is the extension; a rod of `length` `body_len + 1.1*body_r` stands as the actuator does |
| `pipe_fitting` | `pipe_r`, `run`, `branch`, `flange_r`, `flange_t`, `segments` | `a`, `b`, `c` (flange) |
| `radiator_stack` | `fins`, `fin_w`, `fin_h`, `fin_t`, `pitch`, `segments` | `base` (mount) |
| `vent` | `width`, `height`, `depth`, `slats`, `slat_t`, `tilt` | `back` (mount) |
@ -1088,7 +1156,7 @@ on the other then lie in one plane and can meet at a pin: a braced leg.
## The frame kit
`kits/frame.v0.json`: nine parts of chassis structure, every shell an extrude. Its socket types are `mount` (fits)
and `pivot` (equal), the same two lines as `mechanical`'s, so a frame part seats on a mechanical one and the other
and `pivot` (equal, revolute), the same two lines as `mechanical`'s, so a frame part seats on a mechanical one and the other
way round (`place_part` and `describe` take `kit: "frame"`).
| part | params | what it is | sockets |
@ -1117,7 +1185,7 @@ python -m unittest discover -s surfaces/blender/tests -p "test_kitbash.py" -v
16 seeded draws, and checks that every shell is closed and wound outward, every socket frame is right-handed and
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`.
part of `mechanical` also joins the part and socket list in `test_the_kit_is_the_thirteen_parts_and_five_socket_types`.
`FrameKitTests` holds `frame` to the same (the seat check reads a cap that is not convex, an I section's, as it
reads a convex one), with the truss's shells and chords, the portal's mitres, its web in the frame's plane and its
feet apart, each beam's `w` across x and `h` along y, and a beam seated on a mechanical

View file

@ -1,5 +1,5 @@
"""Live proof, in a background Blender, that the brokkr_kitbash rows are admitted by Brokkr as host actions and that
the mechanical kit goes through run_intent: describe, place_part for all eleven parts, setObjectTransform,
the mechanical kit goes through run_intent: describe, place_part for all thirteen parts, setObjectTransform,
assignMaterial, set_params, report, the refusals, the frame kit's nine parts (placed, a truss re-parameterised, a beam
seated on a mechanical bracket), and exportGltf. Not part of the unittest run: it needs Blender.
@ -93,7 +93,7 @@ try:
kit = core.load_kit("mechanical")
receipt, described = send("brokkr_kitbash.describe")
names = [p["name"] for p in described["parts"]] if described else []
check("describe lists eleven parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 11
check("describe lists thirteen parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 13
and "[truncated]" not in receipt["hostResult"], [names, len(receipt.get("hostResult") or "")])
receipt, one = send("brokkr_kitbash.describe", part="actuator")
check("describe of one part gives its params and its sockets at default params", one and [p["name"] for p in one["parts"]] == ["actuator"]
@ -133,7 +133,7 @@ try:
check(f"place_part {name}: kit, part and every resolved param stored on the object, sockets reported in the part frame", obj is not None
and obj["kit_kit"] == "mechanical" and obj["kit_part"] == name and json.loads(obj["kit_params"]) == reference.params == report["params"]
and report["sockets"] == core.socket_rows(reference.sockets), report)
check("eleven parts are eleven mesh objects", len(bpy.data.objects) == 11 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects))
check("thirteen parts are thirteen mesh objects", len(bpy.data.objects) == 13 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects))
# --- set_params keeps what is not derived --------------------------------------------------------------------------------
reducer = bpy.data.objects["P_reducer"]
@ -252,7 +252,7 @@ try:
check("with the duplicate gone the vent's mesh is its own again and set_params rebuilds it", receipt["status"] == "accepted" and alone
and alone["params"]["slats"] == 9 and len(bpy.data.objects["P_vent"].data.polygons) == len(core.build(kit["parts"]["vent"], {"slats": 9}).counts), receipt["message"])
receipt, whole = send("brokkr_kitbash.report")
check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 11, receipt["message"])
check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 13, receipt["message"])
# --- the frame kit: every shell an extrude, a section swept along a path --------------------------------------------------
frame = core.load_kit("frame")
@ -301,7 +301,7 @@ try:
if glb.is_file():
blob = glb.read_bytes()
meshes = len(json.loads(blob[20:20 + int.from_bytes(blob[12:16], "little")]).get("meshes", []))
check("exportGltf of all eleven parts succeeds", receipt["status"] == "accepted" and meshes == 11, [receipt["message"], meshes])
check("exportGltf of all thirteen parts succeeds", receipt["status"] == "accepted" and meshes == 13, [receipt["message"], meshes])
R["placed"] = {name: {"faces": report["faces"], "shells": report["shells"], "bevel": report["bevel"], "sockets": [s["name"] for s in report["sockets"]]}
for name, report in placed.items() if report}

View file

@ -7,7 +7,7 @@
"detail": null
},
{
"name": "describe lists eleven parts, whole, inside a receipt",
"name": "describe lists thirteen parts, whole, inside a receipt",
"ok": true,
"detail": null
},
@ -121,6 +121,46 @@
"ok": true,
"detail": null
},
{
"name": "place_part ram_barrel: sharp_edge is true on exactly core's sharp edges (0)",
"ok": true,
"detail": null
},
{
"name": "place_part ram_barrel: core's faces, a valid mesh, core's flat faces, at the origin",
"ok": true,
"detail": null
},
{
"name": "place_part ram_barrel: a Bevel of the part's width, 2 segments, angle 30, that evaluates",
"ok": true,
"detail": null
},
{
"name": "place_part ram_barrel: kit, part and every resolved param stored on the object, sockets reported in the part frame",
"ok": true,
"detail": null
},
{
"name": "place_part ram_rod: sharp_edge is true on exactly core's sharp edges (0)",
"ok": true,
"detail": null
},
{
"name": "place_part ram_rod: core's faces, a valid mesh, core's flat faces, at the origin",
"ok": true,
"detail": null
},
{
"name": "place_part ram_rod: a Bevel of the part's width, 2 segments, angle 30, that evaluates",
"ok": true,
"detail": null
},
{
"name": "place_part ram_rod: kit, part and every resolved param stored on the object, sockets reported in the part frame",
"ok": true,
"detail": null
},
{
"name": "place_part pipe_fitting: sharp_edge is true on exactly core's sharp edges (0)",
"ok": true,
@ -242,7 +282,7 @@
"detail": null
},
{
"name": "eleven parts are eleven mesh objects",
"name": "thirteen parts are thirteen mesh objects",
"ok": true,
"detail": null
},
@ -452,7 +492,7 @@
"detail": null
},
{
"name": "exportGltf of all eleven parts succeeds",
"name": "exportGltf of all thirteen parts succeeds",
"ok": true,
"detail": null
}
@ -475,6 +515,9 @@
"brokkr_kitbash.roll",
"brokkr_kitbash.aim",
"brokkr_kitbash.reach",
"brokkr_kitbash.joint",
"brokkr_kitbash.slide",
"brokkr_kitbash.joints",
"brokkr_kitbash.close",
"brokkr_kitbash.boolean",
"brokkr_kitbash.cut",
@ -615,6 +658,28 @@
"port_rod"
]
},
"ram_barrel": {
"faces": 180,
"shells": 12,
"bevel": 0.0024,
"sockets": [
"base",
"base_back",
"bore",
"port_cap",
"port_rod"
]
},
"ram_rod": {
"faces": 58,
"shells": 3,
"bevel": 0.0024,
"sockets": [
"piston",
"rod_end",
"rod_end_back"
]
},
"pipe_fitting": {
"faces": 436,
"shells": 14,

View file

@ -612,7 +612,17 @@
"detail": null
},
{
"name": "refused, scene unchanged: set_params on a dirty frozen part",
"name": "refused, scene unchanged: set_params on a dirty frozen part, named dirty as its report names it",
"ok": true,
"detail": null
},
{
"name": "a frozen part with a modifier shown in renders only reports dirty",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: exportGltf applying modifiers over a frozen part dirty in renders only",
"ok": true,
"detail": null
},
@ -651,6 +661,56 @@
"ok": true,
"detail": null
},
{
"name": "thaw after an export that applied modifiers leaves no frozen mesh behind",
"ok": true,
"detail": null
},
{
"name": "freeze gives the live mesh a fake user and kit_kept, a pointer to the frozen mesh; a save writes both",
"ok": true,
"detail": null
},
{
"name": "deleteObject on a frozen object releases its live mesh: a purge takes it and the frozen mesh",
"ok": true,
"detail": null
},
{
"name": "importGltf drops the kit_* properties a file's extras carry, and says so: the imported object is not frozen and not a part",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: thaw on the imported object",
"ok": true,
"detail": null
},
{
"name": "a frozen object deleted in Blender, by no action: a save writes neither mesh, and a purge takes both",
"ok": true,
"detail": null
},
{
"name": "a kept mesh whose kit_kept was cleared by hand still gives its fake user back at thaw",
"ok": true,
"detail": null
},
{
"name": "a live mesh whose kit_frozen was deleted by hand stays kept through a purge and a save",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: thaw on a frozen part whose kit_frozen was deleted names the kept mesh",
"ok": true,
"detail": null
},
{
"name": "and with kit_frozen pointed back it thaws and the mesh is released",
"ok": true,
"detail": null
},
{
"name": "two cutters share one Boolean modifier above the Bevel, in its collection in the order they came",
"ok": true,

View file

@ -229,7 +229,16 @@ try:
ports = [frame(upper, "port_cap")[:3, 3], frame(lower, "port_cap")[:3, 3]]
check("the actuator's ports sit on its boss faces, facing out", np.allclose(ports[0], [-0.5, -0.2, 0.01], atol=1e-6) and np.allclose(frame(upper, "port_cap")[:3, 2], [1, 0, 0], atol=1e-6)
and others(None).find_nearest(Vector(ports[0]))[3] < 1e-6 and np.allclose(frame(upper, "port_rod")[:3, 3], [-0.5, -0.2, 0.27], atol=1e-6), ports[0].tolist())
JOINT = {"socket": "Shin:end_a_back", "standoff": 0.08, "range": [-20, 20]}
JOINT = {"socket": "Shin:end_a_back", "standoff": 0.08}
def limits(lo, hi):
"""State the knee's limits: the roll range a hose across it is proven over is the pin's own."""
receipt, _ = send("brokkr_kitbash.joint", object_name="Shin", record=json.dumps({"limits": None if lo is None else [lo, hi]}))
return receipt
refused("hose-range-from-pin: a pin with no limits, naming the action that states them", {"object_name": "Feed", "start": "ActT:port_cap", "end": "ActS:port_cap", **BUNDLE, "joint": json.dumps(JOINT)},
"'Shin' on 'Thigh': the pin the hose crosses states no limits: brokkr_kitbash.joint gives it the roll range the hose is proven over")
check("the knee takes its limits", limits(-20, 20)["status"] == "accepted" and (shin["kit_min"], shin["kit_max"]) == (-20.0, 20.0), dict(shin.items()))
FEED = {"object_name": "Feed", "start": "ActT:port_cap", "end": "ActS:port_cap", **BUNDLE, "joint": json.dumps(JOINT)}
state = scene_state()
receipt, report = send("brokkr_kitbash.hose", **FEED)
@ -260,12 +269,14 @@ try:
_, again = send("brokkr_kitbash.hose", **FEED)
check("a rebuild at the same pose reports what the first call did", {**again, "rebuilt": False} == report and len(bpy.data.meshes) == len(state[1]) + 1, again)
check("hose-through-range: the range passes and reports the length's change", report["lengthChange"] is not None and report["lengthChange"] >= 0 and report["worstRoll"] is not None, report)
refused("a range that swings the shin's hose into the thigh's parts, naming the sagged attempt and the taut one", {**FEED, "joint": json.dumps({**JOINT, "range": [-20, 90]})},
limits(-20, 90)
refused("a range that swings the shin's hose into the thigh's parts, naming the sagged attempt and the taut one", FEED,
"sagged: roll 48.59: the hose's child's side reads 0.0269 m from the parts about the pin at [-0.2144, -0.2042, 0.7271], counting the 0.0005933 m it can move against the other side's "
"through the 0.156 degrees either side of it: too near the 0.0266 m the bundle needs to prove it of what stands between two readings; taut: roll 50.78: the hose's child's side reads 0.0264 m")
receipt, _ = send("brokkr_kitbash.hose", **{**FEED, "joint": json.dumps({**JOINT, "range": [-20, 90]})})
receipt, _ = send("brokkr_kitbash.hose", **FEED)
check("the refusal names both attempts, each by its roll and its side", "sagged: roll " in str(receipt["message"]) and "; taut: roll " in str(receipt["message"])
and str(receipt["message"]).count("the hose's child's side reads") == 2, receipt["message"])
limits(-20, 20)
section("thin plate")
# A plate 1 mm thick, 4 cm square, on the thigh, where a point of the shin's side of a single hose stands at roll
# -17.5: between two of the rolls 5 degrees apart. At -20 and at -15 the hose keeps its need from it.
@ -295,8 +306,10 @@ try:
receipt, _ = send("brokkr_kitbash.hose", **SINGLE)
named = [float(part.split(":")[0]) for part in str(receipt["message"]).split("roll ")[1:]]
check("the refusal names a roll between -20 and -15 for each attempt", len(named) >= 1 and all(-20.0 < roll < -15.0 for roll in named), receipt["message"])
receipt, narrow = send("brokkr_kitbash.hose", **{**SINGLE, "joint": json.dumps({**JOINT, "standoff": 0.24, "range": [-10, 20]})})
limits(-10, 20)
receipt, narrow = send("brokkr_kitbash.hose", **SINGLE)
check("short of the plate the same hose passes its range", receipt["status"] == "accepted" and narrow["rolls"] >= 7, receipt["message"])
limits(-20, 20)
for name in ("Thin", "Single"):
gone = bpy.data.objects[name]
mesh = gone.data
@ -451,8 +464,26 @@ try:
bpy.context.view_layer.update()
refused("two pins crossed", {**FEED, "object_name": "New", "end": "Jack:port_cap", "count": 1, "radius": 0.004}, "The hose crosses 2 pins ('Jack' on 'Shin', 'Shin' on 'Thigh'): a hose crosses one")
refused("a joint socket off the crossed pin's axis", {**FEED, "joint": json.dumps({**JOINT, "socket": "Shin:end_b_back"})}, "joint.socket 'Shin:end_b_back' is not on the axis of the pin the hose crosses ('Shin' on 'Thigh', socket 'end_b_back')")
refused("the current roll outside the range", {**FEED, "joint": json.dumps({**JOINT, "range": [30, 60]})}, "'Shin' stands at roll 10, outside joint.range [30, 60]")
refused("a range over a full turn", {**FEED, "joint": json.dumps({**JOINT, "range": [-200, 200]})}, "joint must be an object of socket")
state = scene_state()
receipt = limits(30, 60)
check("limits that exclude the roll the knee stands at are the joint action's to refuse", receipt["status"] != "accepted" and "'Shin' on 'Thigh': its roll 10 is outside the joint's limits 30 to 60" in str(receipt["message"])
and scene_state() == state, receipt["message"])
receipt = limits(-200, 200)
check("and limits over a full turn", receipt["status"] != "accepted" and "a revolute joint's span at most 360 degrees" in str(receipt["message"]) and scene_state() == state, receipt["message"])
shin["kit_min"], shin["kit_max"] = 30.0, 60.0 # by hand: the hose reads the pin's limits and finds the roll outside them
refused("the current roll outside limits written by hand", FEED, "'Shin' stands at roll 10, outside its joint's limits 30 to 60")
shin["kit_min"], shin["kit_max"] = -20.0, 20.0
refused("a joint that states a range of its own", {**FEED, "joint": json.dumps({**JOINT, "range": [-20, 20]})}, "joint must be an object of socket (an 'Object:socket' text) and standoff (0 to 10)")
place("Barrel", "ram_barrel", "body_r=0.0534")
place("Rod", "ram_rod", "body_r=0.0534")
send("brokkr_kitbash.attach", object_name="Barrel", socket="base", parent_name="Shin", parent_socket="end_b_back", roll=90.0)
send("brokkr_kitbash.attach", object_name="Rod", socket="piston", parent_name="Barrel", parent_socket="bore")
rod_tip = bpy.data.objects.new("RodTip", None)
bpy.context.scene.collection.objects.link(rod_tip)
rod_tip.parent = bpy.data.objects["Rod"]
bpy.context.view_layer.update()
refused("hose-range-from-pin: a hose across a slide", {**FEED, "object_name": "New", "start": "Barrel:port_cap", "end": "RodTip", "count": 1, "radius": 0.004, "joint": ""},
"The hose crosses the slide of 'Rod' on 'Barrel' (socket 'bore'): a hose across a prismatic connection is not routed")
refused("a grid past the voxel limit", {**FEED, "step": 0.005}, "voxels at step 0.005, over 524288: a step of ")
lower.scale = (1.0, 1.0, 1.01)
bpy.context.view_layer.update()

View file

@ -6,6 +6,16 @@
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: hose-range-from-pin: a pin with no limits, naming the action that states them",
"ok": true,
"detail": null
},
{
"name": "the knee takes its limits",
"ok": true,
"detail": null
},
{
"name": "hose-behind-armour: three hoses route from the thigh's ram to the shin's, round the plate and through the pin point",
"ok": true,
@ -327,12 +337,27 @@
"detail": null
},
{
"name": "refused, scene unchanged: the current roll outside the range",
"name": "limits that exclude the roll the knee stands at are the joint action's to refuse",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a range over a full turn",
"name": "and limits over a full turn",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: the current roll outside limits written by hand",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a joint that states a range of its own",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: hose-range-from-pin: a hose across a slide",
"ok": true,
"detail": null
},

View file

@ -84,6 +84,14 @@ 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
# The largest difference between a joints row's axis or origin and the parent socket's z or origin read from the scene
# in the root's frame. Shipped worst 4.9e-07 (rows carry 6 decimals); least claimed mutant 3.1 (J11, the rows in the
# world's frame); separation 6.3e6.
JOINT_FRAME = 1.2e-3
# The joint-record readings below use the bounds above: "slid", metres between the rod's piston and the point its slide
# states along the bore's z, against SEATED (shipped 1.4e-07; least claimed mutant J1, the slide applied after FLIP, reads 0.6);
# "limit roll", degrees between a roll solved inside limits and the one expected, against ROLL (shipped
# 2e-05; its mutants J2, J3 and J4 die in test_kitbash's JointRecordTests, where their readings are).
def check(name, ok, detail=None):
@ -309,6 +317,166 @@ try:
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")
# --- joint records ------------------------------------------------------------------------------------------------------
# Below the strut: a barrel on its other pin with a rod in its bore, and a bracket hung by its own pin that carries a
# second bracket rigidly, which carries a strut on its pin. Tank > Mount (rigid) > Strut > {Barrel > Rod, Hinge > Foot (rigid) > Toe, Ram}.
rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")]
check("joint, slide and joints load as host actions after reach", rows[rows.index("brokkr_kitbash.reach") + 1:][:3] == ["brokkr_kitbash.joint", "brokkr_kitbash.slide", "brokkr_kitbash.joints"], rows)
barrel, rod = place("Barrel", "ram_barrel"), place("Rod", "ram_rod")
hinge, foot, toe = place("Hinge", "bracket"), place("Foot", "bracket"), place("Toe", "strut", "width=0.09")
send("brokkr_kitbash.attach", object_name="Barrel", socket="base", parent_name="Strut", parent_socket="end_b_back", roll=25.0)
receipt, report = send("brokkr_kitbash.attach", object_name="Rod", socket="piston", parent_name="Barrel", parent_socket="bore")
send("brokkr_kitbash.attach", object_name="Hinge", socket="pivot", parent_name="Strut", parent_socket="end_a_back", roll=-15.0)
send("brokkr_kitbash.attach", object_name="Foot", socket="mount", parent_name="Hinge", parent_socket="mount", roll=90.0)
send("brokkr_kitbash.attach", object_name="Toe", socket="end_a", parent_name="Foot", parent_socket="pivot", roll=40.0)
found = report and report["connection"]
check("a rod attaches in its barrel's bore: a prismatic connection at slide 0 with no joint record, and no record key written",
receipt["status"] == "accepted" and holds(found, "Barrel", "piston", "bore", 0.0) and found == {**found, "dof": "prismatic", "slide": 0.0, "limits": None, "mechanism": None, "compliance": None, "within": True}
and sorted(k for k in rod.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_parent_socket", "kit_part", "kit_roll", "kit_slide", "kit_socket"]
and connection("Strut")["dof"] == "revolute" and connection("Mount")["dof"] is None and "kit_slide" not in strut.keys() and "kit_slide" not in mount.keys(),
[receipt["message"], found, sorted(rod.keys()), connection("Strut"), connection("Mount")])
def slid(amount):
"""How far the rod's piston stands from the point `amount` along the bore's z, and how far its normal is from opposed."""
a, b = frame(barrel, "bore"), frame(rod, "piston")
return max(float(np.linalg.norm(b[:3, 3] - a[:3, 3] - amount * a[:3, 2])), float(np.abs(a[:3, 2] + b[:3, 2]).max()))
# the record: stated by joint, kept key by key
spring = {"hertz": 4.0, "damping_ratio": 0.7}
receipt, report = send("brokkr_kitbash.joint", object_name="Rod", record=json.dumps({"limits": [0.0, 0.3], "mechanism": "shock", "compliance": spring}))
found = report and report["connection"]
check("joint states a slide's limits, mechanism and compliance, and moves nothing", receipt["status"] == "accepted" and found == {**found, "dof": "prismatic", "slide": 0.0, "limits": [0.0, 0.3],
"mechanism": "shock", "compliance": spring, "within": True, "holds": True} and (rod["kit_min"], rod["kit_max"], rod["kit_mechanism"], json.loads(rod["kit_compliance"])) == (0.0, 0.3, "shock", spring)
and reading("slid", slid(0.0)) < SEATED, [receipt["message"], found, dict(rod.items())])
receipt, report = send("brokkr_kitbash.joint", object_name="Rod", record=json.dumps({"mechanism": None}))
found = report and report["connection"]
check("a key left out keeps what is stated and null clears it", receipt["status"] == "accepted" and found == {**found, "limits": [0.0, 0.3], "mechanism": None, "compliance": spring}
and "kit_mechanism" not in rod.keys(), [receipt["message"], found])
send("brokkr_kitbash.joint", object_name="Rod", record=json.dumps({"mechanism": "shock"}))
# slide
for amount in (0.12, 0.3, 0.0, 0.12):
was, pin = stated(rod), frame(rod, "rod_end")[:3, 3].copy()
receipt, report = send("brokkr_kitbash.slide", object_name="Rod", slide=amount)
off, moved = reading("slid", slid(amount)), float(np.linalg.norm(frame(rod, "rod_end")[:3, 3] - pin))
found = report and report["connection"]
check(f"slide {amount:g} moves the rod along the bore's z where it hangs: its parent, sockets, roll and record as they were, the slide stated and seated",
receipt["status"] == "accepted" and off < SEATED and abs(rod["kit_slide"] - amount) < 1e-6 and found["holds"] is True and found["slide"] == round(rod["kit_slide"], 6)
and {k: v for k, v in stated(rod)[1].items() if k != "kit_slide"} == {k: v for k, v in was[1].items() if k != "kit_slide"} and stated(rod)[0] == "Barrel"
and abs(moved - abs(amount - was[1]["kit_slide"])) < SEATED, [receipt["message"], found, off, moved, dict(rod.items())])
receipt, report = send("brokkr_kitbash.roll", object_name="Rod", roll=90.0)
check("a roll on a prismatic connection is a build angle: it turns the rod in the bore and the slide stays", receipt["status"] == "accepted" and rod["kit_roll"] == 90.0
and abs(rod["kit_slide"] - 0.12) < 1e-6 and reading("slid", slid(0.12)) < SEATED and holds(report["connection"], "Barrel", "piston", "bore", 90.0), [receipt["message"], report and report["connection"]])
receipt, report = send("brokkr_kitbash.set_params", object_name="Barrel", params="body_len=0.5")
check("set_params of the barrel moves its bore and reseats the rod at its slide", receipt["status"] == "accepted" and reading("slid", slid(0.12)) < SEATED
and connection("Rod") == {**connection("Rod"), "holds": True, "slide": 0.12}, [receipt["message"], connection("Rod")])
refused("a slide past the joint's limits, naming value and limits", "brokkr_kitbash.slide", {"object_name": "Rod", "slide": 0.31}, "'Rod' on 'Barrel': its slide 0.31 is outside the joint's limits 0 to 0.3")
refused("a slide under them", "brokkr_kitbash.slide", {"object_name": "Rod", "slide": -0.01}, "its slide -0.01 is outside the joint's limits 0 to 0.3")
refused("a slide of a pin, naming its type", "brokkr_kitbash.slide", {"object_name": "Strut", "slide": 0.1}, "'Strut' on 'Mount': socket type 'pivot' is revolute: slide poses a prismatic connection")
refused("a slide of a rigid connection, naming its type", "brokkr_kitbash.slide", {"object_name": "Mount", "slide": 0.1}, "'Mount' on 'Tank': socket type 'mount' is rigid: slide poses a prismatic connection")
refused("a joint record on a rigid connection, naming its type", "brokkr_kitbash.joint", {"object_name": "Mount", "record": '{"limits": [0, 10]}'},
"'Mount' on 'Tank': socket type 'mount' states no dof: the connection is rigid")
refused("limits that exclude the slide the joint has", "brokkr_kitbash.joint", {"object_name": "Rod", "record": '{"limits": [0.2, 0.3]}'}, "its slide 0.12 is outside the joint's limits 0.2 to 0.3")
refused("prismatic limits past 10 m", "brokkr_kitbash.joint", {"object_name": "Rod", "record": '{"limits": [0, 11]}'}, "a prismatic joint's stand within 10 m of 0")
refused("limits cleared under a compliance", "brokkr_kitbash.joint", {"object_name": "Rod", "record": '{"limits": null}'}, "compliance needs limits")
refused("a compliance out of range", "brokkr_kitbash.joint", {"object_name": "Rod", "record": '{"compliance": {"hertz": 0, "damping_ratio": 0.7}}'}, "hertz is over 0 and at most 30")
refused("a compliance on a pin", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"limits": [-180, 180], "compliance": {"hertz": 4, "damping_ratio": 0.7}}'},
"compliance is a prismatic joint's (a slide that settles under load): socket type 'pivot' is revolute")
refused("revolute limits spanning over a turn", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"limits": [-200, 200]}'}, "a revolute joint's span at most 360 degrees")
refused("a revolute limit past 360", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"limits": [300, 400]}'}, "each end within 360 of 0")
refused("a record that is not the shape", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"limits": [10, -10]}'}, "record must be a JSON object of any of limits")
refused("a record with a key it does not have", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"axis": [0, 0, 1]}'}, "record must be a JSON object of any of limits")
refused("a mechanism that is no label", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"mechanism": "Knee Ram"}'}, "record must be a JSON object of any of limits")
refused("a record that is not JSON", "brokkr_kitbash.joint", {"object_name": "Strut", "record": "{limits}"}, "record must be JSON")
refused("a joint record on a part nobody attached", "brokkr_kitbash.joint", {"object_name": "Spare", "record": "{}"}, "'Spare' is not attached")
# limits on a pin: roll, aim and reach stay inside them
world, z = np.array(mount.matrix_world, dtype=np.float64), np.array([0.0, 0.0, 1.0])
pointing = lambda roll: (world @ core.mate(socket(mount, "pivot"), socket(strut, "end_a"), roll))[:3, :3] @ z # noqa: E731 where the strut's z points at a roll
send("brokkr_kitbash.roll", object_name="Strut", roll=180.0)
refused("limits that exclude the roll the joint has", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"limits": [190, 210]}'}, "'Strut' on 'Mount': its roll 180 is outside the joint's limits 190 to 210")
receipt, report = send("brokkr_kitbash.joint", object_name="Strut", record='{"limits": [150, 210], "mechanism": "knee"}')
check("joint states a pin's limits about the roll it has", receipt["status"] == "accepted" and report["connection"] == {**report["connection"], "roll": 180.0, "limits": [150.0, 210.0], "mechanism": "knee", "within": True}
and (strut["kit_min"], strut["kit_max"]) == (150.0, 210.0) and "kit_slide" not in strut.keys(), [receipt["message"], report and report["connection"]])
refused("a roll with no turn of itself inside the limits, naming value and limits", "brokkr_kitbash.roll", {"object_name": "Strut", "roll": 100.0}, "'Strut' on 'Mount': its roll 100 is outside the joint's limits 150 to 210")
receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=-170.0)
check("a roll a turn away from the limits is written as its representative inside them: -170 as 190", receipt["status"] == "accepted" and strut["kit_roll"] == 190.0
and holds(report["connection"], "Mount", "end_a", "pivot", 190.0) and reading("seated", seated(strut, "end_a", mount, "pivot", 190.0)) < SEATED, [receipt["message"], report and report["connection"]])
send("brokkr_kitbash.roll", object_name="Strut", roll=160.0)
d = pointing(-170.0)
receipt, report = send("brokkr_kitbash.aim", object_name="Strut", axis="+z", direction_x=float(d[0]), direction_y=float(d[1]), direction_z=float(d[2]))
aimed = (report or {}).get("aimed") or {"roll": 1e9, "dot": 1e9}
check("aim solving -170 inside limits 150..210 writes 190", receipt["status"] == "accepted" and reading("limit roll", abs(aimed["roll"] - 190.0)) < ROLL and abs(strut["kit_roll"] - 190.0) < ROLL
and reading("aimed", abs(aimed["dot"] - 1.0)) < AIMED and holds(report["connection"], "Mount", "end_a", "pivot", aimed["roll"]), [receipt["message"], aimed, strut["kit_roll"]])
for free, end in ((100.0, 150.0), (-110.0, 210.0), (127.0, 150.0)):
d = pointing(free)
receipt, report = send("brokkr_kitbash.aim", object_name="Strut", axis="+z", direction_x=float(d[0]), direction_y=float(d[1]), direction_z=float(d[2]))
aimed = (report or {}).get("aimed") or {"roll": 1e9, "dot": 1e9}
read = float(np.array(strut.matrix_world, dtype=np.float64)[:3, :3] @ z @ d)
grid = max(float(pointing(float(r)) @ d) for r in np.arange(150.0, 210.25, 0.25))
check(f"aim at where roll {free:g} points, outside the limits, takes the end that points nearer ({end:g}): no roll inside the limits passes it",
receipt["status"] == "accepted" and aimed["roll"] == end and strut["kit_roll"] == end and reading("aimed", abs(aimed["dot"] - read)) < AIMED
and reading("aimed short", max(grid - read, 0.0)) < AIMED and reading("aimed", abs(read - math.cos(math.radians(free - end)))) < AIMED, [receipt["message"], aimed, read, grid])
A, B, C = core.roll_terms(world, socket(mount, "pivot"), socket(strut, "end_a"), socket(strut, "end_b")["matrix"][:3, 3], 1.0, z)
middle, swing = math.degrees(math.atan2(B, A)), math.hypot(A, B)
near, far, height = middle - 40.0, middle + 40.0, C + math.cos(math.radians(40.0)) * swing # the two rolls that reach this height
send("brokkr_kitbash.joint", object_name="Strut", record='{"limits": null}')
send("brokkr_kitbash.roll", object_name="Strut", roll=round(near + 5.0, 3))
send("brokkr_kitbash.joint", object_name="Strut", record=json.dumps({"limits": [round(near + 2.0, 3), round(far + 10.0, 3)]}))
receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=height)
reached = (report or {}).get("reached") or {"roll": 1e9, "residual": 1e9}
check("reach inside limits that hold only the farther of its two rolls takes that one", receipt["status"] == "accepted" and reading("limit roll", abs(reached["roll"] - far)) < ROLL
and reading("reached", abs(float(frame(strut, "end_b")[:3, 3] @ z) - height)) < REACHED and report["connection"]["within"] is True, [receipt["message"], reached, near, far])
send("brokkr_kitbash.roll", object_name="Strut", roll=round(near + 5.0, 3))
send("brokkr_kitbash.joint", object_name="Strut", record=json.dumps({"limits": [round(near + 2.0, 3), round(far - 2.0, 3)]}))
refused("reach with neither roll inside the limits, naming both and the limits", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": height},
f"are outside the joint's limits {round(near + 2.0, 3):.6g} to {round(far - 2.0, 3):.6g}")
rod["kit_slide"] = 0.5 # by hand, past the limits: every report says so and the next pose is refused
found = connection("Rod")
check("a slide written by hand outside the limits reads within false and does not hold", found == {**found, "slide": 0.5, "within": False, "holds": False}, found)
refused("and a roll of it is refused by the limits", "brokkr_kitbash.roll", {"object_name": "Rod", "roll": 0.0}, "its slide 0.5 is outside the joint's limits 0 to 0.3")
rod["kit_slide"] = 0.12
check("put back, it holds", connection("Rod") == {**connection("Rod"), "slide": 0.12, "within": True, "holds": True}, connection("Rod"))
# --- the joints report --------------------------------------------------------------------------------------------------
send("brokkr_kitbash.joint", object_name="Hinge", record='{"limits": [-90, 20], "mechanism": "ankle"}')
receipt, joints = send("brokkr_kitbash.joints", object_name="Tank")
R["joints"] = joints
table = {row["id"]: row for row in (joints or {}).get("joints", [])}
check("joints reports the tree under the tank: schema, the root's frame, a row per DOF connection depth first with children by name, parents first, rigid ones counted",
receipt["status"] == "accepted" and {k: v for k, v in joints.items() if k != "joints"} == {"schema": "brokkr.joints", "version": 1, "root": "Tank", "frame": "the root object's: Blender axes (+Z up), metres", "rigid": 2}
and [row["id"] for row in joints["joints"]] == ["Strut", "Barrel", "Rod", "Hinge", "Toe", "Ram"], [receipt["message"], joints])
check("a joint's parent is the nearest DOF connection above it, not the object it hangs from: the toe's is the hinge, through the rigid foot; the rod's is the barrel",
{name: row["parent"] for name, row in table.items()} == {"Strut": None, "Barrel": "Strut", "Rod": "Barrel", "Hinge": "Strut", "Toe": "Hinge", "Ram": "Strut"} and toe.parent == foot,
{name: row["parent"] for name, row in table.items()})
check("each row names its part, its parent socket and its kind", {name: (row["part"], row["socket"], row["kind"]) for name, row in table.items()} == {
"Strut": ("strut", "Mount:pivot", "revolute"), "Barrel": ("ram_barrel", "Strut:end_b_back", "revolute"), "Rod": ("ram_rod", "Barrel:bore", "prismatic"),
"Hinge": ("bracket", "Strut:end_a_back", "revolute"), "Toe": ("strut", "Foot:pivot", "revolute"), "Ram": ("actuator", "Strut:end_b", "revolute")}, table)
inverse = np.linalg.inv(np.array(tank.matrix_world, dtype=np.float64))
for name, row in table.items():
owner, _, parent_socket = row["socket"].partition(":")
at = inverse @ frame(bpy.data.objects[owner], parent_socket)
reading("joint frame", max(float(np.abs(at[:3, 2] - row["axis"]).max()), float(np.abs(at[:3, 3] - row["origin"]).max())))
check("axis and origin are the parent socket's z and origin in the root's frame, read from the scene", len(table) == 6 and R["readings"]["joint frame"] < JOINT_FRAME, R["readings"])
value = strut["kit_roll"]
check("value is the roll or slide now, limits are as stated, and min and max are the limits less the value: the travel either way",
table["Rod"] == {**table["Rod"], "value": 0.12, "limits": [0.0, 0.3], "min": -0.12, "max": 0.18, "mechanism": "shock", "compliance": spring}
and table["Hinge"] == {**table["Hinge"], "value": -15.0, "limits": [-90.0, 20.0], "min": -75.0, "max": 35.0, "mechanism": "ankle", "compliance": None}
and table["Strut"] == {**table["Strut"], "value": round(value, 6), "min": round(round(near + 2.0, 3) - value, 6), "max": round(round(far - 2.0, 3) - value, 6), "mechanism": "knee"}
and table["Ram"] == {**table["Ram"], "value": -36.0, "limits": None, "min": None, "max": None, "mechanism": None, "compliance": None}, table)
receipt, below = send("brokkr_kitbash.joints", object_name="Hinge")
check("under another root the rows are in its frame and begin below it", receipt["status"] == "accepted" and [(row["id"], row["parent"]) for row in below["joints"]] == [("Toe", None)] and below["rigid"] == 1
and float(np.abs((np.linalg.inv(np.array(hinge.matrix_world, dtype=np.float64)) @ frame(foot, "pivot"))[:3, 3] - below["joints"][0]["origin"]).max()) < JOINT_FRAME, below)
refused("joints of a mesh that is not a kit part", "brokkr_kitbash.joints", {"object_name": "Plain"}, "'Plain' is not a kit part")
# --- detach clears the record -------------------------------------------------------------------------------------------
receipt, report = send("brokkr_kitbash.detach", object_name="Rod")
check("detach leaves none of the eight connection keys", receipt["status"] == "accepted" and report["connection"] is None and rod.parent is None
and sorted(k for k in rod.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_part"], [receipt["message"], sorted(rod.keys())])
receipt, report = send("brokkr_kitbash.attach", object_name="Rod", socket="piston", parent_name="Barrel", parent_socket="bore")
check("and attached again it states no record", receipt["status"] == "accepted" and report["connection"] == {**report["connection"], "slide": 0.0, "limits": None, "mechanism": None, "compliance": None},
[receipt["message"], report and report["connection"]])
except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file
check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:])

View file

@ -230,6 +230,251 @@
"name": "refused, scene unchanged: an axis that is not one of the six, by the action table",
"ok": true,
"detail": null
},
{
"name": "joint, slide and joints load as host actions after reach",
"ok": true,
"detail": null
},
{
"name": "a rod attaches in its barrel's bore: a prismatic connection at slide 0 with no joint record, and no record key written",
"ok": true,
"detail": null
},
{
"name": "joint states a slide's limits, mechanism and compliance, and moves nothing",
"ok": true,
"detail": null
},
{
"name": "a key left out keeps what is stated and null clears it",
"ok": true,
"detail": null
},
{
"name": "slide 0.12 moves the rod along the bore's z where it hangs: its parent, sockets, roll and record as they were, the slide stated and seated",
"ok": true,
"detail": null
},
{
"name": "slide 0.3 moves the rod along the bore's z where it hangs: its parent, sockets, roll and record as they were, the slide stated and seated",
"ok": true,
"detail": null
},
{
"name": "slide 0 moves the rod along the bore's z where it hangs: its parent, sockets, roll and record as they were, the slide stated and seated",
"ok": true,
"detail": null
},
{
"name": "slide 0.12 moves the rod along the bore's z where it hangs: its parent, sockets, roll and record as they were, the slide stated and seated",
"ok": true,
"detail": null
},
{
"name": "a roll on a prismatic connection is a build angle: it turns the rod in the bore and the slide stays",
"ok": true,
"detail": null
},
{
"name": "set_params of the barrel moves its bore and reseats the rod at its slide",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a slide past the joint's limits, naming value and limits",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a slide under them",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a slide of a pin, naming its type",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a slide of a rigid connection, naming its type",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a joint record on a rigid connection, naming its type",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: limits that exclude the slide the joint has",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: prismatic limits past 10 m",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: limits cleared under a compliance",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a compliance out of range",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a compliance on a pin",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: revolute limits spanning over a turn",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a revolute limit past 360",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a record that is not the shape",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a record with a key it does not have",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a mechanism that is no label",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a record that is not JSON",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a joint record on a part nobody attached",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: limits that exclude the roll the joint has",
"ok": true,
"detail": null
},
{
"name": "joint states a pin's limits about the roll it has",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a roll with no turn of itself inside the limits, naming value and limits",
"ok": true,
"detail": null
},
{
"name": "a roll a turn away from the limits is written as its representative inside them: -170 as 190",
"ok": true,
"detail": null
},
{
"name": "aim solving -170 inside limits 150..210 writes 190",
"ok": true,
"detail": null
},
{
"name": "aim at where roll 100 points, outside the limits, takes the end that points nearer (150): no roll inside the limits passes it",
"ok": true,
"detail": null
},
{
"name": "aim at where roll -110 points, outside the limits, takes the end that points nearer (210): no roll inside the limits passes it",
"ok": true,
"detail": null
},
{
"name": "aim at where roll 127 points, outside the limits, takes the end that points nearer (150): no roll inside the limits passes it",
"ok": true,
"detail": null
},
{
"name": "reach inside limits that hold only the farther of its two rolls takes that one",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: reach with neither roll inside the limits, naming both and the limits",
"ok": true,
"detail": null
},
{
"name": "a slide written by hand outside the limits reads within false and does not hold",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: and a roll of it is refused by the limits",
"ok": true,
"detail": null
},
{
"name": "put back, it holds",
"ok": true,
"detail": null
},
{
"name": "joints reports the tree under the tank: schema, the root's frame, a row per DOF connection depth first with children by name, parents first, rigid ones counted",
"ok": true,
"detail": null
},
{
"name": "a joint's parent is the nearest DOF connection above it, not the object it hangs from: the toe's is the hinge, through the rigid foot; the rod's is the barrel",
"ok": true,
"detail": null
},
{
"name": "each row names its part, its parent socket and its kind",
"ok": true,
"detail": null
},
{
"name": "axis and origin are the parent socket's z and origin in the root's frame, read from the scene",
"ok": true,
"detail": null
},
{
"name": "value is the roll or slide now, limits are as stated, and min and max are the limits less the value: the travel either way",
"ok": true,
"detail": null
},
{
"name": "under another root the rows are in its frame and begin below it",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: joints of a mesh that is not a kit part",
"ok": true,
"detail": null
},
{
"name": "detach leaves none of the eight connection keys",
"ok": true,
"detail": null
},
{
"name": "and attached again it states no record",
"ok": true,
"detail": null
}
],
"hostErrors": [],
@ -238,11 +483,173 @@
"aimed short": 0.0,
"edge reached": 2.6e-08,
"edge typed past": 3.2e-07,
"joint frame": 4e-07,
"limit roll": 2e-05,
"reach other root": 74.0,
"reached": 2.1e-07,
"reached": 2.4e-07,
"roll": 8.4e-06,
"seated": 1.1e-06,
"slid": 1.4e-07,
"turned": 0.55
},
"joints": {
"schema": "brokkr.joints",
"version": 1,
"root": "Tank",
"frame": "the root object's: Blender axes (+Z up), metres",
"rigid": 2,
"joints": [
{
"id": "Strut",
"parent": null,
"part": "strut",
"socket": "Mount:pivot",
"kind": "revolute",
"axis": [
-0.0,
1.0,
0.0
],
"origin": [
0.436,
0.0,
0.85368
],
"value": -113.019997,
"limits": [
-116.02,
-40.02
],
"min": -3.000003,
"max": 72.999997,
"mechanism": "knee",
"compliance": null
},
{
"id": "Barrel",
"parent": "Strut",
"part": "ram_barrel",
"socket": "Strut:end_b_back",
"kind": "revolute",
"axis": [
-0.0,
1.0,
0.0
],
"origin": [
0.154833,
0.085,
1.515425
],
"value": 25.0,
"limits": null,
"min": null,
"max": null,
"mechanism": null,
"compliance": null
},
{
"id": "Rod",
"parent": "Barrel",
"part": "ram_rod",
"socket": "Barrel:bore",
"kind": "prismatic",
"axis": [
0.034551,
-0.0,
0.999403
],
"origin": [
0.157321,
0.124,
1.587382
],
"value": 0.12,
"limits": [
0.0,
0.3
],
"min": -0.12,
"max": 0.18,
"mechanism": "shock",
"compliance": {
"damping_ratio": 0.7,
"hertz": 4.0
}
},
{
"id": "Hinge",
"parent": "Strut",
"part": "bracket",
"socket": "Strut:end_a_back",
"kind": "revolute",
"axis": [
-0.0,
1.0,
0.0
],
"origin": [
0.436,
0.085,
0.85368
],
"value": -15.0,
"limits": [
-90.0,
20.0
],
"min": -75.0,
"max": 35.0,
"mechanism": "ankle",
"compliance": null
},
{
"id": "Toe",
"parent": "Hinge",
"part": "strut",
"socket": "Foot:pivot",
"kind": "revolute",
"axis": [
0.787796,
0.0,
0.615936
],
"origin": [
0.559187,
0.085,
0.696121
],
"value": 40.0,
"limits": null,
"min": null,
"max": null,
"mechanism": null,
"compliance": null
},
{
"id": "Ram",
"parent": "Strut",
"part": "actuator",
"socket": "Strut:end_b",
"kind": "revolute",
"axis": [
0.0,
-1.0,
-0.0
],
"origin": [
0.154833,
-0.0,
1.515425
],
"value": -36.0,
"limits": null,
"min": null,
"max": null,
"mechanism": null,
"compliance": null
}
]
},
"ok": true
}

View file

@ -559,21 +559,24 @@ class ParamTests(unittest.TestCase):
@unittest.skipIf(np is None, "numpy is not installed")
class MechanicalKitTests(unittest.TestCase):
PARTS = ["nozzle", "tank", "ribbed_cylinder", "strut", "actuator", "pipe_fitting", "radiator_stack", "vent", "plate", "reducer", "bracket"]
PARTS = ["nozzle", "tank", "ribbed_cylinder", "strut", "actuator", "ram_barrel", "ram_rod", "pipe_fitting", "radiator_stack", "vent", "plate", "reducer", "bracket"]
@classmethod
def setUpClass(cls):
cls.kit = core.load_kit("mechanical")
def test_the_kit_is_the_eleven_parts_and_four_socket_types(self):
def test_the_kit_is_the_thirteen_parts_and_five_socket_types(self):
self.assertEqual(list(self.kit["parts"]), self.PARTS)
self.assertEqual({k: v["match"] for k, v in self.kit["socketTypes"].items()}, {"flange": "equal", "mount": "fits", "pivot": "equal", "hose": "fits"})
self.assertEqual({k: (v["match"], v.get("dof")) for k, v in self.kit["socketTypes"].items()},
{"flange": ("equal", None), "mount": ("fits", None), "pivot": ("equal", "revolute"), "slide": ("equal", "prismatic"), "hose": ("fits", None)})
self.assertEqual({name: [(s["name"], s["type"]) for s in part["sockets"]] for name, part in self.kit["parts"].items()}, {
"nozzle": [("mount", "flange")],
"tank": [("port_a", "flange"), ("port_b", "flange"), ("saddle", "mount"), ("lug_a", "mount"), ("lug_b", "mount"), ("lug_a_back", "mount"), ("lug_b_back", "mount")],
"ribbed_cylinder": [("end_a", "flange"), ("end_b", "flange")],
"strut": [("end_a", "pivot"), ("end_a_back", "pivot"), ("end_b", "pivot"), ("end_b_back", "pivot")],
"actuator": [("base", "pivot"), ("base_back", "pivot"), ("rod_end", "pivot"), ("rod_end_back", "pivot"), ("port_cap", "hose"), ("port_rod", "hose")],
"ram_barrel": [("base", "pivot"), ("base_back", "pivot"), ("bore", "slide"), ("port_cap", "hose"), ("port_rod", "hose")],
"ram_rod": [("piston", "slide"), ("rod_end", "pivot"), ("rod_end_back", "pivot")],
"pipe_fitting": [("a", "flange"), ("b", "flange"), ("c", "flange")],
"radiator_stack": [("base", "mount")], "vent": [("back", "mount")], "plate": [("back", "mount"), ("front", "mount")],
"reducer": [("big", "flange"), ("small", "flange")], "bracket": [("mount", "mount"), ("pivot", "pivot"), ("pivot_back", "pivot")]})
@ -1409,6 +1412,189 @@ class PoseTests(unittest.TestCase):
core.reach_roll(world, sp, sc, [rng.uniform(-1, 1) for _ in range(3)], (world @ sp["matrix"])[:3, 2], 0.0, 0.0)
@unittest.skipIf(np is None, "numpy is not installed")
class JointRecordTests(unittest.TestCase):
"""What a connection's joint record rests on in core: the socket type's dof, mate and residual with a slide,
within, and aim_roll and reach_roll inside limits. Bounds sit at the geometric mean of the shipped worst reading
and the least claimed mutant's (lodur:ruling:deterministic-bound-margin); a reading that is exact is asserted
equal."""
PAIRS = MateTests.PAIRS
SLIDES = (-0.04, 0.025, 0.3)
SLID = 2.4e-8 # metres from the point `slide` along the parent socket's z. shipped 9.7e-16; least mutant 0.6 (J1); separation 6.2e14
RAM = 1.9e-8 # a socket of barrel and rod against the actuator's. shipped 0, taken as one float step; least mutant 1.6 (J1); separation 7.2e15
BEATEN = 1.2e-8 # how far a roll inside the limits may pass the dot aim reports. shipped 1.1e-16; least mutant 1.26 (J2), J3 reads 1.99; separation 1.1e16
@classmethod
def setUpClass(cls):
cls.kit = core.load_kit("mechanical")
def slide_readings(self):
"""Read from the two world frames, not through core.residual: how far the child socket's origin stands from
the point `slide` along the parent socket's z, the normals, and the residual at the stated slide."""
rng, parts, worst = random.Random("slide"), self.kit["parts"], {"slid": 0.0, "normal": 0.0, "residual": 0.0}
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)
world = np.eye(4)
world[:3, :3] = core._rotation([rng.uniform(-180, 180) for _ in range(3)])
world[:3, 3] = [rng.uniform(-5, 5) for _ in range(3)]
for roll in (0.0, 30.0, -115.0):
self.assertEqual(core.mate(sp, sc, roll, 0.0).tolist(), core.mate(sp, sc, roll).tolist()) # slide 0 is the mate there was
for slide in self.SLIDES:
placed = world @ core.mate(sp, sc, roll, slide)
a, b = world @ sp["matrix"], placed @ sc["matrix"]
worst["slid"] = max(worst["slid"], float(np.linalg.norm(b[:3, 3] - a[:3, 3] - slide * a[:3, 2])))
worst["normal"] = max(worst["normal"], float(np.abs(a[:3, 2] + b[:3, 2]).max()))
worst["residual"] = max(worst["residual"], core.residual(world, sp, placed, sc, roll, slide))
self.assertAlmostEqual(core.residual(world, sp, placed, sc, roll, 0.0), abs(slide) * float(np.abs(a[:3, 2]).max()), places=12) # read at another slide it stands that far off
return worst
def test_a_slide_stands_the_child_along_the_parent_socket_z(self):
"""slide-mates. Mutant J1 (the slide applied after FLIP, so along the child's side of the joint: the child
stands -slide along the parent socket's z)."""
worst = self.slide_readings()
self.assertLess(worst["slid"], self.SLID)
self.assertLess(worst["normal"], MateTests.NORMAL)
self.assertLess(worst["residual"], MateTests.RESIDUAL)
def ram_reading(self):
parts, worst = self.kit["parts"], 0.0
for body_r, body_len, extension in ((0.06, 0.4, 0.0), (0.05, 0.2, 0.15), (0.12, 1.0, 0.8), (0.09, 0.55, 0.31)):
barrel = core.build(parts["ram_barrel"], {"body_r": body_r, "body_len": body_len})
rod = core.build(parts["ram_rod"], {"body_r": body_r, "length": body_len + 1.1 * body_r})
whole = {s["name"]: s["matrix"] for s in core.build(parts["actuator"], {"body_r": body_r, "body_len": body_len, "extension": extension}).sockets}
sp, sc = core.joint(parts["ram_barrel"], barrel, "bore", parts["ram_rod"], rod, "piston")
self.assertIsNone(core.mate_refusal(self.kit["socketTypes"], sp, sc))
placed = core.mate(sp, sc, 0.0, extension)
for socket in barrel.sockets:
if socket["name"] != "bore":
worst = max(worst, float(np.abs(socket["matrix"] - whole[socket["name"]]).max()))
for socket in rod.sockets[1:]:
worst = max(worst, float(np.abs(placed @ socket["matrix"] - whole[socket["name"]]).max()))
return worst
def test_a_rod_in_its_barrel_is_the_actuator_at_that_extension(self):
"""slide-mates, on the kit: ram_rod's piston on ram_barrel's bore at slide e puts every socket where the
actuator has it at extension e. Slide 0 is closed. Mutant J1."""
self.assertEqual([(s["name"], s["type"]) for s in core.build(self.kit["parts"]["ram_barrel"]).sockets],
[("base", "pivot"), ("base_back", "pivot"), ("bore", "slide"), ("port_cap", "hose"), ("port_rod", "hose")])
self.assertEqual([(s["name"], s["type"]) for s in core.build(self.kit["parts"]["ram_rod"]).sockets],
[("piston", "slide"), ("rod_end", "pivot"), ("rod_end_back", "pivot")])
self.assertLess(self.ram_reading(), self.RAM)
def test_a_socket_type_states_its_dof(self):
"""dof-by-type, the format. A type states revolute or prismatic or nothing (rigid); anything else is refused
naming the type."""
doc = document()
doc["socketTypes"] = {"mount": {"match": "fits", "doc": ""}, "pin": {"match": "equal", "doc": "", "dof": "revolute"}, "bore": {"match": "equal", "dof": "prismatic", "doc": ""}}
self.assertEqual({name: entry.get("dof") for name, entry in core.check_kit(doc)["socketTypes"].items()}, {"mount": None, "pin": "revolute", "bore": "prismatic"})
self.assertNotIn("dof", core.check_kit(doc)["socketTypes"]["mount"])
for odd in ("hinge", "", None, ["revolute"], "rigid"):
doc["socketTypes"]["pin"]["dof"] = odd
with self.assertRaisesRegex(core.KitError, r"kit 't' socket type 'pin': dof must be 'revolute' or 'prismatic'"):
core.check_kit(doc)
doc["socketTypes"]["pin"] = {"match": "equal", "doc": "", "axis": "z"}
with self.assertRaisesRegex(core.KitError, r"socket type 'pin' has no key 'axis'"):
core.check_kit(doc)
types = {kit: core.load_kit(kit)["socketTypes"] for kit in ("mechanical", "frame", "cutters")}
self.assertEqual({(kit, name): entry["dof"] for kit, found in types.items() for name, entry in found.items() if "dof" in entry},
{("mechanical", "pivot"): "revolute", ("mechanical", "slide"): "prismatic", ("frame", "pivot"): "revolute"})
self.assertEqual(core.describe(self.kit, "ram_rod")["socketTypes"]["slide"]["dof"], "prismatic")
def test_two_kits_mate_a_type_only_when_its_dof_agrees(self):
"""dof-by-type, across kits. Mutant J6 (mate_refusal ignores dof across kits): a pivot another kit declares
without dof mates."""
types, frame = self.kit["socketTypes"], core.load_kit("frame")["socketTypes"]
socket = lambda name, kind, size: {"name": name, "type": kind, "size": size, "matrix": np.eye(4)} # noqa: E731
self.assertIsNone(core.mate_refusal(frame, socket("p", "pivot", 0.05), socket("c", "pivot", 0.05), types, ("frame", "mechanical")))
self.assertIsNone(core.mate_refusal(types, socket("p", "pivot", 0.05), socket("c", "pivot", 0.05), frame, ("mechanical", "frame")))
rigid = {**types, "pivot": {"match": "equal", "doc": ""}}
self.assertRegex(core.mate_refusal(types, socket("p", "pivot", 0.05), socket("c", "pivot", 0.05), rigid, ("mechanical", "odd")),
r"kit 'mechanical' declares socket type 'pivot' with dof revolute and kit 'odd' with dof none \(rigid\); parts of two kits mate by socket types both declare alike")
self.assertRegex(core.mate_refusal(rigid, socket("p", "pivot", 0.05), socket("c", "pivot", 0.05), types, ("odd", "mechanical")),
r"kit 'odd' declares socket type 'pivot' with dof none \(rigid\) and kit 'mechanical' with dof revolute")
sliding = {**types, "pivot": {"match": "equal", "doc": "", "dof": "prismatic"}}
self.assertIn("with dof revolute and kit 'odd' with dof prismatic", core.mate_refusal(types, socket("p", "pivot", 0.05), socket("c", "pivot", 0.05), sliding, ("mechanical", "odd")))
self.assertIsNone(core.mate_refusal(rigid, socket("p", "pivot", 0.05), socket("c", "pivot", 0.05), None)) # one kit: its own type
def test_within_is_the_value_s_representative_inside_the_limits(self):
"""limits-everywhere, the one rule. Mutant J2 (within without the 360 k shift): -170 has no representative in
150..210."""
self.assertEqual(core.within(190.0, 150.0, 210.0, True), 190.0)
self.assertEqual(core.within(-170.0, 150.0, 210.0, True), 190.0)
self.assertEqual(core.within(550.0, 150.0, 210.0, True), 190.0)
self.assertIsNone(core.within(-170.0, 150.0, 210.0, False))
self.assertIsNone(core.within(100.0, 150.0, 210.0, True))
self.assertIsNone(core.within(-100.0, 150.0, 210.0, True))
self.assertEqual(core.within(180.0, -180.0, 180.0, True), 180.0) # a value inside is itself
self.assertEqual(core.within(-180.0, -180.0, 180.0, True), -180.0)
self.assertEqual(core.within(270.0, -180.0, 180.0, True), -90.0)
self.assertEqual(core.within(-350.0, 0.0, 20.0, True), 10.0)
self.assertEqual(core.within(0.12, 0.0, 0.3, False), 0.12)
self.assertIsNone(core.within(0.31, 0.0, 0.3, False))
self.assertIsNone(core.within(-0.001, 0.0, 0.3, False))
self.assertEqual(core.within(float(np.float32(0.3)), 0.0, 0.3, False), 0.3) # a float32 field's 0.3 is 1.2e-08 over: the end
self.assertEqual(core.within(float(np.float32(-20.1)), -20.1, 90.0, True), -20.1)
self.assertEqual(core.within(-1e-7, 0.0, 0.3, False), 0.0)
self.assertIsNone(core.within(0.3 + 3e-6, 0.0, 0.3, False)) # 3 slacks over
def aim_readings(self):
"""Over PoseTests' joints, each under limits drawn about it: how far a roll on a quarter-degree grid inside
the limits passes the dot aim_roll reports there, and how far the reported dot is from the one read back."""
worst, pose = {"beaten": -math.inf, "read": 0.0, "ends": 0, "cases": 0}, PoseTests()
pose.kit = self.kit
for world, sp, sc, rng in pose.joints("aim-limits"):
for name, axis in core.AXES.items():
if abs(np.array(axis) @ sc["matrix"][:3, 2]) == 1.0:
continue
d, lo = pose.direction(rng), rng.uniform(-360.0, 300.0)
hi = lo + rng.uniform(5.0, min(360.0, 360.0 - lo))
roll, dot = core.aim_roll(world, sp, sc, axis, d, (lo, hi))
turned = lambda r: float(d @ (world @ core.mate(sp, sc, r))[:3, :3] @ np.array(axis)) # noqa: E731
self.assertTrue(lo <= roll <= hi, (roll, lo, hi))
worst["read"] = max(worst["read"], abs(dot - turned(roll)))
worst["beaten"] = max(worst["beaten"], max(turned(float(r)) for r in np.arange(lo, hi, 0.25)) - dot)
worst["ends"] += roll in (lo, hi)
worst["cases"] += 1
return worst
def test_aim_inside_limits_takes_the_best_roll_they_hold(self):
"""limits-everywhere, aim. The free roll's representative when the limits hold one (150..210 and a free roll
of -170: 190), else the end with the larger dot. Mutant J3 (the end nearer the free roll by angle, read along
the line and not round the circle: 100..185 and a free roll of -170 takes 100)."""
ident = {"name": "s", "matrix": np.eye(4)}
toward = lambda roll: (-math.sin(math.radians(roll)), math.cos(math.radians(roll)), 0.0) # noqa: E731 the child's y stands there at that roll
aim = lambda free, limits: tuple(round(v, 9) for v in core.aim_roll(np.eye(4), ident, ident, (0.0, 1.0, 0.0), toward(free), limits)) # noqa: E731
self.assertEqual(aim(-170.0, None), (-170.0, 1.0))
self.assertEqual(aim(-170.0, (150.0, 210.0)), (190.0, 1.0))
self.assertEqual(aim(-170.0, (100.0, 185.0)), (185.0, round(math.cos(math.radians(5.0)), 9)))
self.assertEqual(aim(-170.0, (-90.0, 20.0)), (-90.0, round(math.cos(math.radians(80.0)), 9)))
self.assertEqual(aim(90.0, (-20.0, 200.0)), (90.0, 1.0))
self.assertEqual(aim(0.0, (170.0, 190.0)), (170.0, round(math.cos(math.radians(170.0)), 9))) # a tie takes lo
with self.assertRaisesRegex(core.KitError, "lies along the pin"):
core.aim_roll(np.eye(4), ident, ident, (0.0, 0.0, 1.0), (1.0, 0.0, 0.0), (0.0, 90.0))
worst = self.aim_readings()
self.assertEqual(worst["cases"], 80)
self.assertGreater(worst["ends"], 20) # the limits bind in a share of the cases
self.assertLess(worst["read"], PoseTests.AIMED)
self.assertLess(worst["beaten"], self.BEATEN)
def test_reach_inside_limits_takes_a_root_they_hold(self):
"""limits-everywhere, reach. Mutant J4 (the nearer root whatever the limits)."""
ident = {"name": "s", "matrix": np.eye(4)}
reach = lambda current, limits: 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), 0.5, current, limits)) # noqa: E731
self.assertEqual(reach(0.0, None), (-30.0, 0.0)) # the roots are -30 and -150
self.assertEqual(reach(0.0, (-160.0, -100.0)), (-150.0, 0.0)) # the nearer root is outside
self.assertEqual(reach(0.0, (200.0, 220.0)), (210.0, 0.0)) # as its representative
self.assertEqual(reach(0.0, (-180.0, 180.0)), (-30.0, 0.0)) # both inside: the nearer
self.assertEqual(reach(-170.0, (-180.0, 180.0)), (-150.0, 0.0))
self.assertEqual(reach(300.0, (180.0, 360.0)), (330.0, 0.0))
with self.assertRaisesRegex(core.KitError, r"socket 's' on parent socket 's': the rolls that bring the point to 0\.500000 m, -150 and -30, are outside the joint's limits 0 to 90$"):
reach(0.0, (0.0, 90.0))
with self.assertRaisesRegex(core.KitError, "it reaches -1.000000 m to 1.000000 m"):
core.reach_roll(np.eye(4), ident, ident, (0.0, 1.0, 0.0), (1.0, 0.0, 0.0), 1.5, 0.0, (0.0, 90.0))
@unittest.skipIf(np is None, "numpy is not installed")
class StructureTests(unittest.TestCase):
"""core's sweep, band, crossings, resample and spans: what brokkr_kitbash.ribs builds a frame from. Every reading is
@ -1811,7 +1997,8 @@ class SheetTests(unittest.TestCase):
ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report",
"brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close",
"brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach",
"brokkr_kitbash.joint", "brokkr_kitbash.slide", "brokkr_kitbash.joints", "brokkr_kitbash.close",
"brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.freeze", "brokkr_kitbash.thaw", "brokkr_kitbash.ribs",
"brokkr_kitbash.shell", "brokkr_kitbash.hose"]
@ -1934,7 +2121,8 @@ class OwnershipTests(unittest.TestCase):
r"hide_render|hide_viewport|display_type", # a cutter's visibility is setObjectVisibility's
r"kit_parent_name|kit_parent\b|matrix_world_stored", # obj.parent has no second owner
r"SCREW|\"ARRAY\"|spin\(", # core makes every vertex: no modifier or bmesh op makes kit geometry
r"Kit Boolean |operand_type\s*=\s*[\"']OBJECT") # cutters cut through one collection Boolean per operation, never a modifier each
r"Kit Boolean |operand_type\s*=\s*[\"']OBJECT", # cutters cut through one collection Boolean per operation, never a modifier each
r"kit_axis|kit_order|kit_parent_joint") # a joint's axis is its parent socket's z and its order the parent tree: neither is stored
CORE = r"^import bpy|^from bpy|^import bmesh"
SCHEMAS = r"brokkr\.kit\.v0"
@ -2087,16 +2275,31 @@ class OwnershipTests(unittest.TestCase):
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)."""
and pose (roll, aim, reach, slide and joint) 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). The joint record (kit_slide,
kit_min, kit_max, kit_mechanism, kit_compliance) is written there too and nowhere else: its names are read by
link and joint_record, cleared by detach, and no other function names them; the hose keeps no roll range of
its own, and no DOF kind is read from a socket type's name."""
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("def write_connection(")[1].split("\n\n\n")[0])
self.assertEqual(writes, [" child[SOCKET], child[PARENT_SOCKET], child[ROLL] = socket, parent_socket, roll"])
writer = source.split("def write_connection(")[1].split("\n\n\n")[0]
self.assertIn(writes[0], writer)
record = r"SLIDE|LIMIT_MIN|LIMIT_MAX|MECHANISM|COMPLIANCE|RECORD"
written = rf'\[(?:{record})\](?:, \w+\[\w+\])*\s*=(?!=)|\["kit_(?:slide|min|max|mechanism|compliance)"\]'
self.assertIsNone(re.search(written, source))
self.assertEqual(re.findall(r"[^\n]*\[key\] = [^\n]*", source), [" child[key] = value"])
self.assertIn(" child[key] = value", writer)
named = [body.split("(")[0] for body in re.split(r"\n(?:def|class) ", source)[1:] if re.search(rf"\b(?:{record})\b", body)]
self.assertEqual(named, ["link", "joint_record", "mated", "write_connection", "BROKKR_KITBASH_OT_detach"])
for text in ("child[SLIDE] = slide", "obj[LIMIT_MIN], obj[LIMIT_MAX] = limits", 'obj["kit_compliance"] = text'):
self.assertIsNotNone(re.search(written, text))
self.assertNotIn('"range"', source)
self.assertNotIn('"pivot"', source)
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"):
for name in ("roll", "aim", "reach", "slide", "joint"):
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"]))
@ -2115,7 +2318,7 @@ class OwnershipTests(unittest.TestCase):
assigned = re.findall(rf"[^\n]*\[{keys}\][^\n=]*=(?!=)[^\n]*", source)
self.assertEqual(assigned, [" obj[CLOSE], obj[CLOSE_TO], obj[CLOSE_TO_SOCKET] = self.socket, other, self.other_socket"])
self.assertIn(assigned[0], bodies["close"])
deleted = re.findall(r"[^\n]*\(SOCKET, PARENT_SOCKET, ROLL, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET\)[^\n]*\n[^\n]*\n\s*del obj\[key\]", source)
deleted = re.findall(r"[^\n]*\(SOCKET, PARENT_SOCKET, ROLL, \*RECORD, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET\)[^\n]*\n[^\n]*\n\s*del obj\[key\]", source)
self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 2, True)) # detach's keys, and hold's kit_frozen
self.assertEqual(source.count("CLOSE_TO]"), 1) # the one subscript write above; every read goes through .get
placing = r"matrix_basis|matrix_world\s*=(?!=)|matrix_parent_inverse|\.parent\s*=(?!=)|\bseat\(|\.location|\.rotation"
@ -2126,7 +2329,7 @@ class OwnershipTests(unittest.TestCase):
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',
'obj.modifiers.new("Turn", "SCREW")', 'modifier.operand_type = "OBJECT"')
'obj.modifiers.new("Turn", "SCREW")', 'modifier.operand_type = "OBJECT"', 'child["kit_axis"] = list(axis)')
self.assertIsNotNone(re.search(self.PACKAGE[6], 'obj.modifiers.new("Kit Boolean " + cutter.name, "BOOLEAN")'))
for text in ('obj.modifiers.new("Bolts", "ARRAY")', "bmesh.ops.spin(bm, geom=geom)"):
self.assertIsNotNone(re.search(self.PACKAGE[5], text))