brokkr_kitbash.ram: a ram and linkage solver across a hinge: direct, four-bar, bell crank (cut kit-ram-core) #34

Merged
eureka merged 14 commits from nibu/kit-ram-core into main 2026-12-02 21:04:28 +00:00
7 changed files with 3059 additions and 1 deletions

View file

@ -0,0 +1,790 @@
"""Rams and linkages across a one-axis hinge: numpy and the standard library only, and nothing from the package, so
a rig, a runtime or a test loads this file alone. Signed, the mesh oracle, asks for Blender's BVH tree when one is
made and not before.
A Mechanism is the record of one hinge's drive: the hinge (pivot, unit axis, lo and hi in degrees, positive
right-handed about the axis), a kind, and pins, each in its own body's rest frame (the pose at angle 0, where
every body's frame is the parent's).
direct the ram runs from a on the parent to b on the child.
four_bar a rocker pinned on the parent at `rocker` (R) carries the pin p; a coupler joins p to c on the child;
the ram runs from a on the parent to d on the rocker, and d is p (the excavator bucket linkage).
bell_crank the same loop with d elsewhere on the rocker.
Every pose quantity is a pure function of (record, angle): pose() holds no solve state. The loop is solved in the
plane across the axis; a pin's coordinate along the axis only says where its member stands: the rocker bars at R's,
the coupler bar at c's, the ram at a's plus each of `offsets`.
pose(m, degrees) every body's rotation, the ram's base and eye, L, dL/dtheta, per angle
length(m, degrees) pin-to-pin ram length
barrel_length(m, ram) the barrel the range's shorter end leaves room for
extension(m, ram, degrees) rod extension from closed
fit(m, ram, ...) the gates over the range: assembly, stroke, arm, load, clearance
clearance(m, ram, degrees, distance) the clearance gate's reading at any angles, per member and part
search(kind, hinge, ram, seats, ...) the best of a seat grid, or the tally and the nearest miss
record(m, ram), from_record the JSON record a rig or runtime drives from
swept(fit, body, ...) points of the swept ram's surface in a body's rest frame
Signed(shells, cap) the distance oracle over closed meshes, signed by three rays
Clearance. The record names the mechanism's `parts`, each a piece of one body (part -> the body whose rest frame
it turns with: a thigh's core, the bracket that carries the rocker's pivot, a link's plates, a pin), and `touch`:
for each member of MEMBERS[kind], zones (part, pin, radius, depth). Every member meets every part. A zone lowers
what the member's samples keep from one part, and only within `radius` of the axis of `pin`, one of the member's
own (RIDES), measured across the hinge axis: there a sample may come as near the part as -depth and no nearer.
depth is 0 for what is stacked beside the member on the pin (a plate, the bracket or horn the pin stands in: the
member's axis stays outside it, so a pin whose place along the axis is inside the part it claims to stand beside
is refused), the pin's radius for the pin through the member's eye, half the thickness for the member's own plate
or clevis. Beyond the radius the pair is checked like any other; nothing is exempt by a name, a length or the
member's own body. Every body of the kind owns at least one part, or the gate refuses.
A zone is bounded by its member. Its radius and its depth are finite and no more than the member's length from pin
to pin (a bar's between its pins; the ram's at the most its pins allow), which the record refuses by its pins
alone; its depth is no more than the member's eye on that pin (Ram.eye: e_a at the base, e_b at the rod's eye,
link_r on a bar), which from_record and the gate refuse, a world's answer included. Between two samples of which
either is in a zone, the gate does not trust the spacing: it halves the segment until the readings at its ends
prove it holds -depth throughout (see _between), so a part of any thickness that the axis crosses there is read.
The oracle is distance(part, points) -> distances, points (N, 3) in the rest frame of the part's body. A distance
is signed: negative inside the part, by any depth. The oracle may cap what it returns at Ram.reach(spacing),
outside a part only: a point inside reads negative however deep it lies. An oracle that cannot tell inside from
outside (a nearest-surface query on an open mesh) raises instead of answering; nan is refused here. It never reads
more than the true distance: the gate's proof between samples is that a distance changes by no more than the way
between two points.
A RamError of a gate (assembly, stroke, toggle, arm, load, clash) names the angle and the pin; one of the record
or of a call (an unknown kind, a range, a grid over the limit, a version) names the pin or the field it refuses.
"""
import math
from dataclasses import dataclass, field, fields, replace
import numpy as np
KINDS = ("direct", "four_bar", "bell_crank")
BODIES = {"direct": ("parent", "child"), "four_bar": ("parent", "child", "rocker", "coupler"),
"bell_crank": ("parent", "child", "rocker", "coupler")}
PINS = {"direct": ("a", "b"), "four_bar": ("a", "rocker", "p", "c", "d"), "bell_crank": ("a", "rocker", "p", "c", "d")}
MEMBERS = {"direct": ("barrel", "rod"), "four_bar": ("barrel", "rod", "rocker", "coupler"),
"bell_crank": ("barrel", "rod", "rocker", "coupler", "rocker arm")}
EYE = {"direct": "b", "four_bar": "d", "bell_crank": "d"} # the pin the rod's eye rides
RIDES = {kind: {"barrel": ("a", EYE[kind]), "rod": ("a", EYE[kind]), "rocker": ("rocker", "p"), "coupler": ("p", "c"), "rocker arm": ("rocker", "d")}
for kind in KINDS} # member -> the pins at its start and its end
GATES = ("assembly", "stroke", "toggle", "arm", "load", "clash")
SCHEMA, VERSION = "brokkr.ram", 1
ZONE = ("part", "pin", "radius", "depth") # a zone of `touch`, as the record writes it
COMPLIANCE = ("stiffness", "damping", "travel") # reserved: a load-path ram's settle, solved by a later version
BAND = 1e-9 # the loop is refused within this of a dead centre of the rocker and coupler
FINE = 64 # in a zone a segment between samples is halved down to spacing / FINE
RAYS = ((0.5377, 0.6211, 0.5701), (-0.7071, 0.2903, 0.6447), (0.1873, -0.8011, -0.5684)) # Signed's, in order
class RamError(ValueError):
"""A refusal: the mechanism kind, the gate, the angle and the pin it failed at. `fit` holds the readings when
the gates got far enough to take them."""
def __init__(self, kind, gate, message, angle=None, pin=None, fit=None):
where = (f" at {angle:g} deg" if angle is not None else "") + (f" (pin {pin})" if pin else "")
super().__init__(f"{kind} ram: {gate}{where}: {message}")
self.kind, self.gate, self.angle, self.pin, self.fit = kind, gate, angle, pin, fit
def _number(kind, name, value, least=None):
"""A record's number: an int or a float, finite, never a bool, a string or null; above `least` when given."""
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
raise RamError(kind, "record", f"a finite number, got {value!r}", pin=name)
if least is not None and not value > least:
raise RamError(kind, "record", f"a number greater than {least:g}, got {value!r}", pin=name)
return float(value)
@dataclass
class Ram:
"""A ram's proportions. Lengths default from the bore radius. Every one is a finite number and the bore is
greater than 0, or the ram is refused naming the field (as the ram of `any` kind: a ram knows none)."""
bore: float
rod: float = None # rod radius
barrel_r: float = None # barrel outer radius
e_a: float = None # base pin centre to the barrel's back end
e_b: float = None # rod eye centre to the rod's shoulder (what stays out of the barrel, closed)
gland: float = None # piston and gland: barrel length that is not stroke
over: float = None # spare travel at each end of the stroke
tail: float = 0.0 # trunnion mount: barrel behind the base pin (replaces e_a)
min_arm: float = None # least effective arm |dL/dtheta|, length per radian
gap: float = None # least clearance to a body
link_r: float = None # half thickness of a rocker or coupler bar
max_load: float = 3.0 # greatest coupler pin load per unit ram force
def __post_init__(self):
b = self.bore = _number("any", "bore", self.bore, 0.0)
for name, value in (("rod", 0.5 * b), ("barrel_r", 1.25 * b), ("e_a", 1.7 * b), ("e_b", 1.7 * b), ("gland", 1.3 * b),
("over", 0.2 * b), ("min_arm", 1.5 * b), ("gap", 0.15 * b), ("link_r", 0.7 * b)):
if getattr(self, name) is None:
setattr(self, name, value)
for f in fields(self):
setattr(self, f.name, _number("any", f.name, getattr(self, f.name)))
@property
def back(self):
"""Signed distance from the base pin to the barrel's back end along the ram (negative: behind the pin)."""
return -self.tail if self.tail > 0 else self.e_a
def spacing(self, spacing=None):
return self.barrel_r if spacing is None else float(spacing)
def eye(self, member, pin):
"""The radius of a member's eye on one of its pins: the most a zone's depth lets its axis into a part."""
if member in ("barrel", "rod"):
return self.e_a if pin == "a" else self.e_b
return self.link_r
def reach(self, spacing=None):
"""The greatest distance the clearance gate asks of any member: what a distance oracle may cap at."""
return max(self.barrel_r, self.rod, self.link_r) + self.gap + self.spacing(spacing) / 2
def _flat(v, n):
"""v without its part along the unit axis n."""
return v - n * (v @ n)[..., None]
def _rot(v, n, t):
"""v (..., 3) turned about the unit axis n by t radians (Rodrigues); t broadcasts over v's leading shape."""
t = np.asarray(t, dtype=float)[..., None]
return v * np.cos(t) + np.cross(n, v) * np.sin(t) + n * (v @ n)[..., None] * (1.0 - np.cos(t))
def _angle(v0, v, n):
"""Signed angle about n from v0 to v, both across n."""
return np.arctan2(np.cross(v0, v) @ n, v @ v0)
@dataclass
class Mechanism:
kind: str
pivot: np.ndarray
axis: np.ndarray
lo: float
hi: float
a: np.ndarray
b: np.ndarray = None
rocker: np.ndarray = None
p: np.ndarray = None
c: np.ndarray = None
d: np.ndarray = None
offsets: tuple = (0.0,)
parts: dict = field(default_factory=dict) # part -> the body it turns with
touch: dict = field(default_factory=dict) # member -> zones (part, pin, radius, depth)
def __post_init__(self):
if self.kind not in KINDS:
raise RamError(str(self.kind), "record", f"kind is one of {', '.join(KINDS)}")
for name in ("pivot", "axis", "a", "b", "rocker", "p", "c", "d"):
value = getattr(self, name)
if value is not None:
value = np.array(value, dtype=float)
if value.shape != (3,) or not np.isfinite(value).all():
raise RamError(self.kind, "record", "three finite numbers", pin=name)
setattr(self, name, value)
if abs(np.linalg.norm(self.axis) - 1.0) > 1e-6:
raise RamError(self.kind, "record", f"the axis is a unit vector, length {np.linalg.norm(self.axis):.6f}", pin="axis")
self.lo, self.hi = float(self.lo), float(self.hi)
if not self.lo < self.hi or self.hi - self.lo > 360.0:
raise RamError(self.kind, "record", f"lo < hi and hi - lo <= 360, got {self.lo:g}..{self.hi:g}", angle=self.lo)
self.offsets = tuple(float(o) for o in self.offsets)
if not self.offsets:
raise RamError(self.kind, "record", "at least one offset: where the ram stands along the axis from a", pin="a")
self.parts = {str(part): body for part, body in dict(self.parts).items()}
for part, body in self.parts.items():
if body not in BODIES[self.kind]:
raise RamError(self.kind, "record", f"part {part!r} turns with {body!r}; this kind has {', '.join(BODIES[self.kind])}")
for name in ("a", "b", "rocker", "p", "c", "d"):
needed, given = name in PINS[self.kind], getattr(self, name) is not None
if needed != given:
raise RamError(self.kind, "record", "this kind needs the pin" if needed else "this kind has no such pin", pin=name)
touch = {}
for member, zones in dict(self.touch).items():
if member not in MEMBERS[self.kind]:
raise RamError(self.kind, "record", f"touch names {member!r}; this kind's members are {', '.join(MEMBERS[self.kind])}")
touch[member] = []
for zone in zones:
if isinstance(zone, (str, dict)) or len(zone) != 4:
raise RamError(self.kind, "record", f"{member}'s zone is (part, pin, radius, depth), got {zone!r}")
part, pin, radius, depth = zone
if part not in self.parts:
raise RamError(self.kind, "record", f"{member} may touch {part!r}, which is no part of the record")
if pin not in RIDES[self.kind][member]:
raise RamError(self.kind, "record", f"{member} may touch {part!r} about a pin it rides ({', '.join(RIDES[self.kind][member])}), not {pin!r}", pin=str(pin))
radius, depth = _number(self.kind, f"{member} {part} radius", radius, 0.0), _number(self.kind, f"{member} {part} depth", depth)
if depth < 0.0:
raise RamError(self.kind, "record", f"a depth of 0 or more, got {depth!r}", pin=f"{member} {part} depth")
span = _span(self, member)
for name, value in (("radius", radius), ("depth", depth)):
if value > span:
raise RamError(self.kind, "record", f"a zone no wider or deeper than its member: {member} is at most {span:.4f} from pin to pin, got {value!r}",
pin=f"{member} {part} {name}")
touch[member].append((part, pin, radius, depth))
touch[member] = tuple(touch[member])
self.touch = touch
if self.kind == "direct":
return
n = self.axis
apart = float(np.linalg.norm(self.d - self.p))
if self.kind == "four_bar" and apart > 0.0:
raise RamError(self.kind, "record", f"a four-bar's ram eye is the rocker's coupler pin; d is {apart:.4f} from p", pin="d")
if self.kind == "bell_crank" and apart == 0.0:
raise RamError(self.kind, "record", "a bell crank's ram eye stands off the coupler pin; d on p is a four_bar", pin="d")
self.lr = float(np.linalg.norm(_flat(self.p - self.rocker, n)))
self.lc = float(np.linalg.norm(_flat(self.p - self.c, n)))
side = float(n @ np.cross(_flat(self.c - self.rocker, n), _flat(self.p - self.rocker, n)))
if min(self.lr, self.lc) < BAND or abs(side) < BAND:
raise RamError(self.kind, "assembly", "the rest pose is a dead centre: R, p and c are in line", pin="p")
self.branch = 1.0 if side > 0 else -1.0 # which side of R -> c the pin p keeps, through the whole range
def _span(m, member):
"""The most a member measures from pin to pin, by the pins alone: a bar's length across the axis; for the ram's
two, the base's and the eye's distances from the centre the eye turns about, added."""
if member in ("barrel", "rod"):
centre, eye = m.pivot if m.kind == "direct" else m.rocker, getattr(m, EYE[m.kind])
return float(np.linalg.norm(m.a - centre) + np.linalg.norm(eye - centre))
start, end = RIDES[m.kind][member]
return float(np.linalg.norm(_flat(getattr(m, end) - getattr(m, start), m.axis)))
def _eyes(m, ram):
"""Refuse a zone deeper than its member's eye on its pin."""
for member, zones in m.touch.items():
for part, pin, _, depth in zones:
if depth > ram.eye(member, pin):
raise RamError(m.kind, "record", f"a zone no deeper than its member's eye: {member}'s on {pin} is {ram.eye(member, pin):.4f}, got {depth!r}",
pin=f"{member} {part} depth")
@dataclass
class Pose:
degrees: np.ndarray # (S,)
base: np.ndarray # (S, 3) ram base pin, parent frame, at offset 0
eye: np.ndarray # (S, 3) ram eye
u: np.ndarray # (S, 3) unit vector base -> eye
L: np.ndarray # (S,) pin to pin
dL: np.ndarray # (S,) dL/dtheta, length per radian: the effective arm, signed
phi: np.ndarray = None # (S,) rocker angle from rest, radians, in (-pi, pi]
psi: np.ndarray = None # (S,) coupler angle from rest
dphi: np.ndarray = None # (S,) dphi/dtheta
P: np.ndarray = None # (S, 3) the rocker's coupler pin
C: np.ndarray = None # (S, 3) the child's coupler pin
load: np.ndarray = None # (S,) coupler pin load per unit ram force
mu_c: np.ndarray = None # (S,) transmission angle at c, degrees, folded to 0..90
mu_p: np.ndarray = None # (S,) transmission angle at p
def pose(m, degrees):
"""The mechanism at each of `degrees` (a number or an array): a pure function of the record and the angle."""
deg = np.atleast_1d(np.asarray(degrees, dtype=float))
t, n, O = np.radians(deg), m.axis, m.pivot
if m.kind == "direct":
eye = O + _rot(m.b - O, n, t)
base = np.broadcast_to(m.a, eye.shape)
L = np.linalg.norm(eye - base, axis=1)
u = (eye - base) / np.maximum(L, 1e-12)[:, None]
return Pose(deg, base, eye, u, L, (np.cross(n, eye - O) * u).sum(axis=1))
R = m.rocker
C = O + _rot(m.c - O, n, t)
g = _flat(C - R, n)
dist = np.linalg.norm(g, axis=1)
lo, hi = abs(m.lr - m.lc) + BAND, m.lr + m.lc - BAND
bad = (dist <= lo) | (dist >= hi)
if bad.any():
i = int(np.argmax(bad))
raise RamError(m.kind, "assembly", f"|c - R| is {dist[i]:.4f}, outside ({lo:.4f}, {hi:.4f}): the rocker ({m.lr:.4f}) and coupler "
f"({m.lc:.4f}) cannot close the loop, or reach a dead centre where the branch would change", angle=float(deg[i]), pin="c")
x = (m.lr * m.lr - m.lc * m.lc + dist * dist) / (2.0 * dist)
h = np.sqrt(np.maximum(m.lr * m.lr - x * x, 0.0))
across = g / dist[:, None]
v = across * x[:, None] + m.branch * np.cross(n, across) * h[:, None] # p - R across the axis
phi = _angle(_flat(m.p - R, n), v, n)
P = R + _rot(m.p - R, n, phi)
eye = R + _rot(m.d - R, n, phi)
w = _flat(P - C, n) # the coupler, c -> p
k = w / np.linalg.norm(w, axis=1)[:, None]
psi = _angle(_flat(m.p - m.c, n), w, n)
# the coupler's two ends move equally along it
dphi = (np.cross(n, C - O) * k).sum(axis=1) / (np.cross(n, P - R) * k).sum(axis=1)
base = np.broadcast_to(m.a, eye.shape)
L = np.linalg.norm(eye - base, axis=1)
u = (eye - base) / np.maximum(L, 1e-12)[:, None]
dL = (np.cross(n, eye - R) * u).sum(axis=1) * dphi
crank, link = _flat(O - C, n), _flat(R - P, n)
moment = np.abs(np.cross(-crank, k) @ n)
load = np.abs(dL) / np.maximum(moment, 1e-12)
mu_c = np.degrees(np.arcsin(np.clip(moment / np.linalg.norm(crank, axis=1), 0.0, 1.0)))
mu_p = np.degrees(np.arcsin(np.clip(np.abs(np.cross(link, k) @ n) / np.linalg.norm(link, axis=1), 0.0, 1.0)))
return Pose(deg, base, eye, u, L, dL, phi, psi, dphi, P, C, load, mu_c, mu_p)
def length(m, degrees):
"""Pin-to-pin ram length at each angle."""
return pose(m, degrees).L
def barrel_length(m, ram):
"""The barrel the mechanism leaves room for: the ram's length at the shorter end of the range, less the
overtravel, the base clevis (or nothing, on a trunnion) and the eye. L runs one way over a range that fits
(the toggle gate), so that end is the least. Derived, never stored: a record holds the pins and the ram."""
return _barrel(ram, pose(m, (m.lo, m.hi)).L)
def _barrel(ram, ends):
return float(min(ends[0], ends[-1])) - ram.over - ram.back - ram.e_b
def extension(m, ram, degrees):
"""Rod extension from closed at each angle: L - (back + barrel + e_b)."""
return pose(m, degrees).L - (ram.back + barrel_length(m, ram) + ram.e_b)
def _members(m, ram, barrel, p):
"""(member, label, start (S, 3), end (S, 3), radius, (pin at start, pin at end)) of every member in the parent
frame, each from pin to pin: the barrel from its back end, the rod to the eye, a bar between its pins."""
n, rides = m.axis, RIDES[m.kind]
for off in m.offsets:
base, tip = p.base + off * n, p.eye + off * n
front = base + p.u * (ram.back + max(barrel, 1e-6))
yield "barrel", f"barrel[{off:g}]", base + p.u * ram.back, front, ram.barrel_r, rides["barrel"]
yield "rod", f"rod[{off:g}]", front, tip, ram.rod, rides["rod"]
if m.kind == "direct":
return
R = np.broadcast_to(m.rocker, p.P.shape)
yield "rocker", "rocker", R, p.P - n * ((p.P - R) @ n)[:, None], ram.link_r, rides["rocker"]
yield "coupler", "coupler", p.P - n * ((p.P - p.C) @ n)[:, None], p.C, ram.link_r, rides["coupler"]
if m.kind == "bell_crank":
yield "rocker arm", "rocker arm", R, p.eye - n * ((p.eye - R) @ n)[:, None], ram.link_r, rides["rocker arm"]
def _into(m, p, body, pts):
"""Parent-frame points (S, N, 3) carried into a body's rest frame at each angle."""
n = m.axis
if body == "parent":
return pts
if body == "child":
return m.pivot + _rot(pts - m.pivot, n, -np.radians(p.degrees)[:, None])
if body == "rocker":
return m.rocker + _rot(pts - m.rocker, n, -p.phi[:, None])
return m.p + _rot(pts - p.P[:, None, :], n, -p.psi[:, None])
@dataclass
class Clearance:
margin: np.ndarray # (S,) the least margin of any checked pair at each angle
where: tuple # (angle, member label, part, pin) of the least: the pin is the member's nearer one
pairs: dict # (member label, part) -> (least margin, angle) of every pair: every member, every part
allowed: list # (member label, part) of every pair a zone of the record's `touch` lets near a pin
def clearance(m, ram, degrees, distance, spacing=None):
"""The clearance gate's reading. A member is clear where margin >= 0: each sample of its axis, taken at most
`spacing` apart (default barrel_r), is at least radius + gap + spacing / 2 from every part, measured in the
rest frame of the part's body at that angle. A sample is at most spacing / 2 from any point of the axis, so
the member's surface keeps the gap. Every member meets every part of the record. Inside a zone of `touch`
(within its radius of its pin's axis, across the hinge axis) a sample keeps -depth from the zone's part
instead: the margin there is the distance plus the depth, and the segment to the next sample is proved to
hold -depth throughout (_between). Two zones of one pair that both reach a sample let it the deeper."""
return _clearance(m, ram, barrel_length(m, ram), pose(m, degrees), distance, spacing)
def _between(kind, distance, part, pts, got, keep, zoned, floor):
"""(S,) the least margin found between samples, inf where none is: for each segment between consecutive samples
of which either is in a zone, whether the axis holds -depth (the deeper of its ends') all along it. A distance
changes by no more than the way between two points, so along a segment it is at least (g(a) + g(b) - |ab|) / 2;
where that does not prove the segment it is halved, the midpoint read (its margin is counted), down to `floor`.
A segment still unproved at the floor against a part the axis is held outside (depth 0) reads that bound, so
it is refused: the part is within floor / 2 of the axis there, crossed or touched. Against a part the axis may
enter, the samples' readings stand: a burial is read to floor / 2."""
out = np.full(len(pts), math.inf)
pair = zoned[:, :-1] | zoned[:, 1:]
row = np.nonzero(pair)[0]
a, b, ga, gb = pts[:, :-1][pair], pts[:, 1:][pair], got[:, :-1][pair], got[:, 1:][pair]
hold = np.minimum(keep[:, :-1], keep[:, 1:])[pair]
while len(row):
span = np.linalg.norm(b - a, axis=1)
bound = (ga + gb - span) / 2.0
unproved = (bound < hold) & (np.minimum(ga, gb) >= hold) # an end under its hold is already refused
touched = unproved & (span <= floor) & (hold == 0.0)
np.minimum.at(out, row[touched], bound[touched])
go = unproved & (span > floor)
if not go.any():
break
a, b, ga, gb, hold, row = (x[go] for x in (a, b, ga, gb, hold, row))
mid = (a + b) / 2.0
gm = np.asarray(distance(part, mid), dtype=float)
if np.isnan(gm).any():
raise RamError(kind, "oracle", f"the distance oracle answered nan for part {part!r}")
np.minimum.at(out, row, gm - hold)
a, b, ga, gb = np.concatenate([a, mid]), np.concatenate([mid, b]), np.concatenate([ga, gm]), np.concatenate([gm, gb])
hold, row = np.concatenate([hold, hold]), np.concatenate([row, row])
return out
def _clearance(m, ram, barrel, p, distance, spacing):
_eyes(m, ram)
for body in BODIES[m.kind]:
if body not in m.parts.values():
raise RamError(m.kind, "record", f"no part turns with body {body}: the clearance gate would pass it unseen")
step = ram.spacing(spacing)
out = Clearance(np.full(len(p.degrees), math.inf), None, {}, [])
least = math.inf
at = {"a": p.base, EYE[m.kind]: p.eye, "rocker": m.rocker, "p": p.P, "c": p.C} # each pin over the angles, parent frame
for member, label, start, end, radius, pins in _members(m, ram, barrel, p):
count = max(int(math.ceil(float(np.linalg.norm(end - start, axis=1).max()) / step)) + 1, 2)
pts = start[:, None, :] + (end - start)[:, None, :] * np.linspace(0.0, 1.0, count)[None, :, None]
need = radius + ram.gap + step / 2.0
seen = {}
for part, body in m.parts.items():
if body not in seen:
seen[body] = _into(m, p, body, pts).reshape(-1, 3)
got = np.asarray(distance(part, seen[body]), dtype=float).reshape(len(p.degrees), count)
if np.isnan(got).any():
raise RamError(m.kind, "oracle", f"the distance oracle answered nan for part {part!r}")
keep = np.full(got.shape, need) # what each sample keeps from the part
zoned = np.zeros(got.shape, dtype=bool)
zones = [zone for zone in m.touch.get(member, ()) if zone[0] == part]
for _, pin, reach, depth in zones:
across = np.linalg.norm(_flat(pts - np.broadcast_to(at[pin], start.shape)[:, None, :], m.axis), axis=2)
keep = np.where(across <= reach, np.minimum(keep, -depth), keep)
zoned |= across <= reach
over = got - keep
row = over.min(axis=1)
if zones:
out.allowed.append((label, part))
row = np.minimum(row, _between(m.kind, distance, part, seen[body].reshape(len(p.degrees), count, 3), got, keep, zoned, step / FINE))
out.margin = np.minimum(out.margin, row)
i = int(np.argmin(row))
out.pairs[(label, part)] = (float(row[i]), float(p.degrees[i]))
if row[i] < least:
least = float(row[i])
out.where = (float(p.degrees[i]), label, part, pins[int(np.argmin(over[i])) * 2 >= count])
return out
@dataclass
class Fit:
m: Mechanism
ram: Ram
why: list # (gate, angle, pin, message) of every gate that failed; empty when it fits
degrees: np.ndarray
l_min: float
l_max: float
travel: float # L_max - L_min
barrel: float # barrel length: barrel_length(m, ram)
closed: float # pin to pin with the rod home: back + barrel + e_b
stroke: float # travel the barrel holds
spare: float # stroke - (travel + 2 over): negative when the stroke does not fit
arm_min: float # least |dL/dtheta|
arm_at: float # the angle of it
arm_sign: int # 0 when dL/dtheta changes sign (a dead centre inside the range)
swing: float = 0.0 # the rocker's travel, degrees
load_max: float = 0.0 # greatest coupler pin load per unit ram force
mu_c: float = None # least transmission angle at c, degrees: reported, never gated
mu_p: float = None # least transmission angle at p
clear_min: float = math.inf # least clearance beyond what the gate asks; inf with no oracle
clear_at: tuple = None # (angle, member, part, pin) of it
pairs: dict = field(default_factory=dict) # (member, part) -> (least margin, angle) of every pair
allowed: list = field(default_factory=list) # (member, part) of every pair a zone of `touch` lets near a pin
table: list = field(default_factory=list) # (angle, L, dL/dtheta, clearance margin) per step
@property
def ok(self):
return not self.why
def error(self):
gate, angle, pin, message = self.why[0]
return RamError(self.m.kind, gate, message, angle=angle, pin=pin, fit=self)
def report(self):
"""One line for a log or a sheet."""
state = "OK" if self.ok else "NO (" + "; ".join(f"{g}: {msg}" for g, _, _, msg in self.why) + ")"
links = "" if self.m.kind == "direct" else f", rocker swing {self.swing:.1f}, pin load <= {self.load_max:.2f}, transmission >= {min(self.mu_c, self.mu_p):.1f} deg"
return (f"{state}: L {self.l_min:.3f}..{self.l_max:.3f}, barrel {self.barrel:.3f}, stroke {self.stroke:.3f} for travel {self.travel:.3f} "
f"(spare {self.spare:+.3f}), arm >= {self.arm_min:.3f}{links}, clear {self.clear_min:+.3f}")
def _fit(m, ram, steps=25, distance=None, spacing=None, clear=True):
"""Every gate's reading; raises only where the loop does not assemble or a bell crank's eye crowds its pin."""
if m.kind == "bell_crank" and np.linalg.norm(m.d - m.p) < 2.0 * ram.bore:
raise RamError(m.kind, "pins", f"the ram eye stands at least 2 bore ({2.0 * ram.bore:.4f}) from the coupler pin; d is {np.linalg.norm(m.d - m.p):.4f} from p", pin="d")
if (m.kind != "direct") and not (m.lo <= 0.0 <= m.hi):
pose(m, np.linspace(0.0, m.lo if m.lo > 0.0 else m.hi, steps)) # the branch is carried from rest: no dead centre on the way
p = pose(m, np.linspace(m.lo, m.hi, steps))
l_min, l_max = float(p.L.min()), float(p.L.max())
eye = EYE[m.kind]
travel = l_max - l_min
barrel = _barrel(ram, p.L) # the samples' ends are lo and hi: barrel_length's own two angles
stroke = barrel - ram.gland
spare = stroke - (travel + 2.0 * ram.over)
i = int(np.argmin(np.abs(p.dL)))
arm_min, arm_at = float(abs(p.dL[i])), float(p.degrees[i])
signs = set(np.sign(p.dL[np.abs(p.dL) > 1e-9]).tolist())
arm_sign = int(signs.pop()) if len(signs) == 1 else 0
f = Fit(m, ram, [], p.degrees, l_min, l_max, travel, barrel, ram.back + barrel + ram.e_b, stroke, spare, arm_min, arm_at, arm_sign)
if barrel <= ram.gland or spare < -1e-9:
f.why.append(("stroke", float(p.degrees[int(np.argmin(p.L))]), eye, f"travel {travel:.3f} needs {travel + 3.0 * ram.over + ram.gland + ram.back + ram.e_b:.3f} closed, L_min is {l_min:.3f}"))
if arm_sign == 0:
flip = np.nonzero(np.sign(p.dL[1:]) != np.sign(p.dL[:-1]))[0]
f.why.append(("toggle", float(p.degrees[flip[0] + 1]) if len(flip) else arm_at, eye, "dL/dtheta changes sign: a dead centre inside the range"))
elif arm_min < ram.min_arm:
f.why.append(("arm", arm_at, eye, f"least effective arm {arm_min:.3f} under {ram.min_arm:.3f}"))
if m.kind != "direct":
phi = np.degrees(np.unwrap(p.phi))
j = int(np.argmax(p.load))
f.swing, f.load_max = float(phi.max() - phi.min()), float(p.load[j])
f.mu_c, f.mu_p = float(p.mu_c.min()), float(p.mu_p.min())
if f.load_max > ram.max_load:
f.why.append(("load", float(p.degrees[j]), "c", f"coupler pin load {f.load_max:.2f} x the ram force, over {ram.max_load:.2f}"))
margin = np.full(steps, math.inf)
if distance is not None and clear:
c = _clearance(m, ram, barrel, p, distance, spacing)
margin, f.clear_at, f.pairs, f.allowed = c.margin, c.where, c.pairs, c.allowed
f.clear_min = float(margin.min())
if f.clear_min < 0.0:
angle, member, part, pin = f.clear_at
f.why.append(("clash", angle, pin, f"{member} is {-f.clear_min:.3f} inside the clearance of part {part!r} ({m.parts[part]})"))
f.table = [tuple(row) for row in np.stack([p.degrees, p.L, p.dL, margin], axis=1).tolist()]
return f
def fit(m, ram, steps=25, distance=None, spacing=None):
"""Check one mechanism from lo to hi. Gates, in order, each over all steps at once: assembly; stroke; effective
arm (one sign, and at least min_arm); coupler pin load (linkages); clearance, when a distance oracle is given
(see clearance: the record's parts say what it meets, its touch how near a pin).
Returns the Fit; a failed gate raises RamError, its `fit` holding the readings."""
f = _fit(m, ram, steps, distance, spacing)
if not f.ok:
raise f.error()
return f
@dataclass
class Search:
best: Fit # the winner, or the nearest miss when none fits
found: bool
tried: int
fits: int # candidates that pass every gate but clearance
tally: dict # gate -> candidates it failed (a candidate can fail several)
seat: dict # the winner's or nearest miss's pins
def report(self):
head = f"{self.fits} of {self.tried} candidates pass the gates before clearance" if self.found else f"no candidate of {self.tried} fits"
reasons = ", ".join(f"{k} {v}" for k, v in sorted(self.tally.items()))
return f"{head}{' (failed: ' + reasons + ')' if reasons else ''}; {'best' if self.found else 'nearest'}: {self.best.report() if self.best else 'none assembles'}"
def _polar(n, centre, toward, radii, step):
"""Points about `centre` across the axis n: each radius, every `step` degrees from the direction `toward`."""
e = _flat(np.asarray(toward, dtype=float) - centre, n)
if np.linalg.norm(e) < 1e-9:
e = _flat(np.array([0.0, 0.0, 1.0]) if abs(n[2]) < 0.9 else np.array([1.0, 0.0, 0.0]), n)
e = e / np.linalg.norm(e)
return [centre + r * _rot(e, n, math.radians(turn)) for r in radii for turn in range(0, 360, step)]
def candidates(kind, hinge, seats):
"""The pins of every candidate of a seat grid. direct: seats['a'] x seats['b']. Linkages: seats['rocker'] x
seats['c'] x p on a polar grid about R (lengths seats['link'] = (lo, hi, n), every 15 degrees) x seats['a'],
and for a bell crank x d on a polar grid about R (seats['d'] = (lo, hi, n), every 30 degrees). The ram's eye
(d, and a four-bar's p) stands at a's place along the axis, so the ram runs across it."""
n = np.asarray(hinge["axis"], dtype=float)
if kind == "direct":
return [{"a": a, "b": b} for a in seats["a"] for b in seats["b"]]
out = []
for R in seats["rocker"]:
R = np.asarray(R, dtype=float)
for c in seats["c"]:
for p in _polar(n, R, c, np.linspace(*seats["link"]), 15):
eyes = [p] if kind == "four_bar" else _polar(n, R, p, np.linspace(*seats["d"]), 30)
for a in seats["a"]:
a = np.asarray(a, dtype=float)
for d in eyes:
d = d - n * ((d - a) @ n)
out.append({"a": a, "rocker": R, "p": d if kind == "four_bar" else p, "c": c, "d": d})
return out
def search(kind, hinge, ram, seats, world=None, limit=20000, steps=25, spacing=None):
"""Seat a mechanism from a grid (see candidates). hinge = {pivot, axis, lo, hi, offsets (optional)}. Best
first: every gate but clearance over all candidates, then clearance in order of least arm, greatest first;
the first clear one wins. world(m) -> (parts, touch, distance) builds a candidate's own parts, the brackets
and links its pins place among them, and the oracle that answers for them: a linkage's links are the
candidate's, so no one oracle serves a grid. What it returns is read as a record's: anything but the three,
a part on no body of the kind, a zone that is not (part, pin the member rides, radius, depth) or one wider or
deeper than its member is refused. A grid past `limit` candidates is refused naming the count. A
miss returns the tally and the nearest miss (the least total shortfall: stroke, arm, load excess,
clearance)."""
pins = candidates(kind, hinge, seats)
if len(pins) > limit:
raise RamError(kind, "search", f"{len(pins)} candidates, over the limit of {limit}: thin the seat grid")
tally, passed, miss = {}, [], None
def missed(f, seat):
nonlocal miss
for gate in {g for g, _, _, _ in f.why}:
tally[gate] = tally.get(gate, 0) + 1
short = (max(-f.spare, 0.0) + max(ram.min_arm - f.arm_min, 0.0) + (ram.min_arm if f.arm_sign == 0 else 0.0)
+ max(f.load_max - ram.max_load, 0.0) + (max(-f.clear_min, 0.0) if f.clear_min < math.inf else 0.0))
if miss is None or short < miss[0]:
miss = (short, f, seat)
for seat in pins:
try:
m = Mechanism(kind, hinge["pivot"], hinge["axis"], hinge["lo"], hinge["hi"], offsets=hinge.get("offsets", (0.0,)), **seat)
f = _fit(m, ram, steps, clear=False)
except RamError as refusal:
tally[refusal.gate] = tally.get(refusal.gate, 0) + 1
continue
if f.ok:
passed.append((f, seat))
else:
missed(f, seat)
passed.sort(key=lambda entry: -entry[0].arm_min)
for f, seat in passed:
if world is None:
return Search(f, True, len(pins), len(passed), tally, seat)
made = world(f.m)
if not isinstance(made, tuple) or len(made) != 3 or not callable(made[2]):
raise RamError(kind, "search", f"world(m) returns (parts, touch, distance), got {type(made).__name__}")
parts, touch, distance = made
f = _fit(replace(f.m, parts=parts, touch=touch), ram, steps, distance, spacing)
if f.ok:
return Search(f, True, len(pins), len(passed), tally, seat)
missed(f, seat)
return Search(miss[1] if miss else None, False, len(pins), len(passed), tally, miss[2] if miss else None)
def record(m, ram):
"""The mechanism record: plain JSON types, everything a rig or runtime needs to drive the ram from the hinge
angle (from_record, then length or extension). It holds what is authored and nothing derived from it: barrel,
closed length and link lengths come from the pins and the ram. `compliance` is reserved for a load-path ram's
settle (COMPLIANCE: stiffness, damping, travel); version 1 writes it null and solves none."""
return {"schema": SCHEMA, "version": VERSION, "kind": m.kind,
"hinge": {"pivot": m.pivot.tolist(), "axis": m.axis.tolist(), "lo": m.lo, "hi": m.hi},
"pins": {name: getattr(m, name).tolist() for name in PINS[m.kind]}, "offsets": list(m.offsets),
"ram": {f.name: getattr(ram, f.name) for f in fields(Ram)},
"parts": dict(m.parts), "compliance": None,
"touch": {member: [dict(zip(ZONE, zone)) for zone in zones] for member, zones in m.touch.items()}}
def from_record(data):
"""(Mechanism, Ram) of a record. A record of another schema or version (the integer 1: not 1.0, not true), with
a key this version does not know or without one it does, with a compliance block, or with a value that is not
its field's type (a finite number, three of them, a name), or with a zone wider or deeper than its member is
refused whole, as a RamError naming the field: nothing is read past and dropped."""
if not isinstance(data, dict):
raise RamError("None", "record", f"a record is an object, got {type(data).__name__}")
kind, version = str(data.get("kind")), data.get("version")
if data.get("schema") != SCHEMA or type(version) is not int or version != VERSION:
raise RamError(kind, "record", f"this reader reads {SCHEMA} version {VERSION}; the record is {data.get('schema')} version {version!r}")
if kind not in KINDS:
raise RamError(kind, "record", f"kind is one of {', '.join(KINDS)}")
def keys(name, given, known):
if not isinstance(given, dict):
raise RamError(kind, "record", f"an object, got {type(given).__name__}", pin=name)
if set(given) != set(known):
raise RamError(kind, "record", f"the {name}'s keys are not version {VERSION}'s: unknown {sorted(set(given) - set(known), key=str)}, missing {sorted(set(known) - set(given))}")
def point(name, value):
if not isinstance(value, list) or len(value) != 3:
raise RamError(kind, "record", f"three finite numbers, got {value!r}", pin=name)
return [_number(kind, name, x) for x in value]
keys("record", data, ("schema", "version", "kind", "hinge", "pins", "offsets", "ram", "parts", "touch", "compliance"))
hinge, pins, ram = data["hinge"], data["pins"], data["ram"]
keys("hinge", hinge, ("pivot", "axis", "lo", "hi"))
keys("pins", pins, PINS[kind])
keys("ram", ram, [f.name for f in fields(Ram)])
if data["compliance"] is not None:
raise RamError(kind, "record", f"a compliance block ({', '.join(COMPLIANCE)}) is a later version's: version {VERSION} solves none and will not drop it")
for name, value in ram.items():
_number(kind, name, value, 0.0 if name == "bore" else None)
if not isinstance(data["offsets"], list):
raise RamError(kind, "record", f"a list of numbers, got {data['offsets']!r}", pin="offsets")
if not isinstance(data["parts"], dict) or not all(isinstance(body, str) for body in data["parts"].values()):
raise RamError(kind, "record", "an object of part: body", pin="parts")
if not isinstance(data["touch"], dict):
raise RamError(kind, "record", "an object of member: zones", pin="touch")
touch = {}
for member, zones in data["touch"].items():
if not isinstance(zones, list):
raise RamError(kind, "record", f"{member}'s zones are a list, got {zones!r}", pin="touch")
for zone in zones:
keys(f"{member} zone", zone, ZONE)
touch[member] = [tuple(zone[key] for key in ZONE) for zone in zones]
m = Mechanism(kind, point("pivot", hinge["pivot"]), point("axis", hinge["axis"]), _number(kind, "lo", hinge["lo"]), _number(kind, "hi", hinge["hi"]),
offsets=tuple(_number(kind, "offsets", o) for o in data["offsets"]), parts=data["parts"], touch=touch,
**{name: point(name, value) for name, value in pins.items()})
ram = Ram(**ram)
_eyes(m, ram)
return m, ram
def swept(f, body, margin=0.0, steps=13, around=8):
"""Points on the swept ram's surface in a body's rest frame, the barrel radius grown by `margin`, a trunnion's
tail included: what a recess in that body must clear (their hull or bounding box)."""
m, ram = f.m, f.ram
if body not in BODIES[m.kind]:
raise RamError(m.kind, "swept", f"no body {body!r}; this kind has {', '.join(BODIES[m.kind])}")
p = pose(m, np.linspace(m.lo, m.hi, steps))
side = np.cross(p.u, m.axis)
side = side / np.linalg.norm(side, axis=1)[:, None]
up = np.cross(side, p.u)
turn = np.linspace(0.0, 2.0 * math.pi, around, endpoint=False)
ring = (ram.barrel_r + margin) * (np.cos(turn)[None, :, None] * side[:, None, :] + np.sin(turn)[None, :, None] * up[:, None, :])
pts = []
for off in m.offsets:
for centre in (p.base + off * m.axis + p.u * min(ram.back, 0.0), p.eye + off * m.axis):
pts.append(centre[:, None, :] + ring)
return _into(m, p, body, np.concatenate(pts, axis=1)).reshape(-1, 3)
class Signed:
"""The distance oracle over closed meshes: distance(part, points) is the nearest face's distance, negative
where the point is inside one of the part's shells (its depth below the nearest face), capped at `cap` outside
only. shells: part -> [(vertices (N, 3), faces)], each shell closed, in the rest frame of the part's body.
Inside is the crossing parity of `rays` of RAYS, by majority: one ray that runs through an edge or a vertex
miscounts, and a sample then reads inside a plate it stands clear of. An unknown part raises. Needs Blender's
mathutils (BVHTree)."""
def __init__(self, shells, cap=None, rays=3):
from mathutils import Vector
from mathutils.bvhtree import BVHTree
self.cap, self.asked, self.vector = cap, 0, Vector
self.rays = [Vector(ray).normalized() for ray in RAYS[:rays]]
self.trees = {part: [(BVHTree.FromPolygons(np.asarray(v, dtype=float).tolist(), [tuple(face) for face in f], epsilon=0.0),
np.min(v, axis=0), np.max(v, axis=0)) for v, f in made] for part, made in shells.items()}
@staticmethod
def crossings(tree, v, ray):
count, o = 0, v
for _ in range(64):
loc = tree.ray_cast(o, ray)[0]
if loc is None:
break
count, o = count + 1, loc + ray * 1e-6
return count
def inside(self, tree, v):
return 2 * sum(self.crossings(tree, v, ray) % 2 for ray in self.rays) > len(self.rays)
def __call__(self, part, pts):
pts = np.asarray(pts, dtype=float)
self.asked += len(pts)
out = np.full(len(pts), math.inf if self.cap is None else self.cap)
for tree, lo, hi in self.trees[part]:
boxed = ((pts >= lo) & (pts <= hi)).all(axis=1)
for i, p in enumerate(pts):
v = self.vector(p)
if boxed[i] and self.inside(tree, v):
out[i] = min(out[i], -tree.find_nearest(v)[3])
continue
hit = tree.find_nearest(v, self.cap) if self.cap else tree.find_nearest(v)
if hit[0] is not None and hit[3] < out[i]:
out[i] = hit[3]
return out

View file

@ -777,6 +777,154 @@ field. Nothing in a kit is run as Python. Division by zero, a result that is not
or `segments` that is not whole are refused when the part is built, naming the expression; so is a shape whose
vertices overflow.
## Rams and linkages
`brokkr_kitbash/ram.py` owns the motion of a ram across one hinge. It is numpy and the standard library, imports
nothing from the package, and no action calls it yet: a rig or a runtime loads the file alone. Its input is a
mechanism record: the hinge (pivot, unit axis, `lo` and `hi` in degrees, positive right-handed about the axis like
a pin joint's roll), a kind, and pins, each in its own body's rest frame.
| kind | pins | the ram runs |
| --- | --- | --- |
| `direct` | `a` on the parent, `b` on the child | `a` to `b` |
| `four_bar` | `a`; `rocker` (R), the rocker's pivot on the parent; `p` on the rocker; `c` on the child; `d` = `p` | `a` to `p`: the excavator bucket linkage, a coupler from `p` to `c` turning the child |
| `bell_crank` | the same, `d` elsewhere on the rocker, at least 2 bore from `p` | `a` to `d` |
Everything is a function of the record and the hinge angle: `pose` gives each body's rotation, the ram's base and
eye, its pin-to-pin length L and dL/dtheta; `length` and `extension` (L less the closed length) are what a rig
drives a rod from. Nothing stores a rocker angle or an extension. The loop is solved in the plane across the axis:
`p` lies where the rocker's circle about R meets the coupler's about `c`, on the side of R -> `c` it has at rest,
so an angle gives the same pose whatever was asked before it. A pin's coordinate along the axis says only where
its member stands: the rocker bars at R's, the coupler at `c`'s, the ram at `a`'s plus each of `offsets` (twins).
Rates are closed form: for a linkage dphi/dtheta = (axis x (c - O)) . k / ((axis x (p - R)) . k), k along the
coupler, and dL/dtheta = (axis x (d - R)) . u x dphi/dtheta, u along the ram.
`fit` runs the gates over the range, in this order. A failed gate is a `RamError` naming the kind, the gate, the
angle and the pin, with the readings attached; a refusal of the record or of a call (an unknown kind, a range, a
grid over the limit, a version) names the pin or the field it refuses.
- **assembly**: the rocker and coupler close the loop at every step, and on the way from rest when the range does
not hold 0; within 1e-9 of a dead centre is refused, since the branch would change there. Names `c`.
- **stroke**: the barrel holds the travel, the overtravel at both ends and the gland. Names the angle of the
shortest length and the eye's pin.
- **toggle**, **arm**: dL/dtheta keeps one sign, and |dL/dtheta| (the effective arm: hinge torque per unit ram
force) stays at or above `min_arm`. Name the eye's pin.
- **load** (linkages): the coupler's pin load per unit ram force, |dL/dtheta| over the coupler's moment arm about
the hinge, stays at or under `max_load` (3). Names `c`.
- **clash**: clearance, when a distance oracle is given. Names the member, the part, and the member's nearer pin.
The barrel is derived, never stored: `barrel_length` is the length at the shorter end of the range less the
overtravel, the base clevis and the eye, and `fit` reads it from its own two end samples.
Transmission angles at `c` and `p` are reported and not gated. Over the R-3 knee's 125 degrees the best least
transmission angle of 200,000 sampled four-bars was 21.9 degrees, under the 30 to 40 a textbook asks; a gate there
would have refused every one of them. What a poor angle costs is pin load, and that is the gate.
### Clearance: parts, and zones about a member's pins
The record names the mechanism's `parts`, each a piece of one body (part -> parent, child, rocker or coupler: the
body whose rest frame it turns with), and `touch`: for each member (`barrel`, `rod`, `rocker`, `coupler`, and a
bell crank's `rocker arm`), zones `(part, pin, radius, depth)`. Every member meets every part. A zone changes what
the member's samples keep from one part, and only within `radius` of the axis of `pin`, measured across the hinge
axis; the pin is one the member rides (the ram `a` and its eye, the rocker its pivot and `p`, the coupler `p` and
`c`, the arm the pivot and `d`). Inside the zone a sample may come as near the part as `-depth`; beyond it the
pair is checked like any other. Nothing is exempt by a name, by a length cut from a member's end, or by the
member's own body: the barrel runs from its back end, the rod to the eye, a bar from pin to pin. Every body of the
kind owns at least one part, or the gate refuses the record.
A zone's radius is the eye's radius plus a margin: the pin's, collar's or cheek's radius plus what the member
keeps (radius, gap, half the spacing). Its depth says how the member stands to the part there. 0 is beside it: a
plate stacked on the pin, the bracket or horn the pin stands in. The member's axis then stays outside the part, so
a pin whose place along the axis is inside what it claims to stand beside is refused: the gate does not take the
record's x on trust. The pin's radius is for the pin through the member's eye, half the plate's thickness for the
member's own plate, which is zoned about both of the member's pins. Two plates stacked on a pin cross like
scissors; the zone that lets one link by the other's plate reaches as far as the two part, (half width + what a
link keeps) / sin of the least angle they cross at, and no further than the link is long. Two zones of one pair
that both reach a sample let it the deeper of the two.
A zone is bounded by its member. Its radius and its depth are finite and no more than the member's length from pin
to pin: a bar's length between its pins, and for the barrel and the rod the base's and the eye's distances from
the centre the eye turns about, added. A `Mechanism` refuses a zone past that from its pins alone. Its depth is
also no more than the member's eye on that pin (`Ram.eye`: `e_a` at the base, `e_b` at the rod's eye, `link_r` on
a bar), which `from_record` and the gate refuse, so a world's answer is held to it as well. The record holds no
plate widths, so the radius has no tighter bound than the length.
Between two samples of which either is in a zone the gate does not rely on the spacing. A distance changes by no
more than the way between two points, so along a segment it is at least (g(a) + g(b) - length) / 2. Where that
does not show the segment keeps `-depth`, the gate halves it and reads the midpoint, down to spacing / 64. A
segment still unproved there against a part the axis is held outside (depth 0) is refused: the part is within
spacing / 128 of the axis, crossed or touched, whatever its thickness. Against a part the axis may enter, the
samples' readings stand, so a burial is read to spacing / 128. This asks of the oracle that it never reads more
than the true distance.
What it gives up: inside a zone the gate holds only the member's axis `depth` from the part, not its surface a
gap from it, so a link may graze the plate it scissors with anywhere within the stated radius. The members are
round bars; a plate's flat sides are not modelled, which is why stacked plates need a zone at all. The proof
between samples costs oracle calls: a depth stated with no slack over the burial (a bar's own plates at `link_r`)
is halved to the floor along the whole zone. And it is along the axis at each checked angle; between two angles
nothing is proved.
The oracle is `distance(part, points) -> distances`, `points` in the rest frame of the part's body. Each member is
sampled along its axis at most `spacing` apart (default the barrel's radius) and carried into each body's rest
frame at each angle; a sample is clear at radius + gap + spacing / 2 or more, which keeps the gap for the surface
between samples. A distance is signed: negative inside a part, by any depth. The oracle may cap what it returns at
`Ram.reach(spacing)`, outside a part only; a point inside reads negative however deep it lies. An oracle that
cannot tell inside from outside raises instead of answering (a nearest-surface query alone reads 0.13 at the
centre of the R-3 thigh's core, and reads clear when capped); nan is refused. `Fit.pairs` holds the least margin
and its angle for every pair, `Fit.allowed` the pairs a zone lets near a pin.
`search` seats a mechanism from a grid (ram seats; for linkages rocker pivots, child pins, `p` on a polar grid
about R, and `d` about R for a bell crank, the eye standing at `a`'s place along the axis), refuses a grid over
`limit` candidates naming the count, runs every gate but clearance on all of them, then clearance in order of
least arm; a miss returns the tally by gate and the nearest miss. Clearance takes `world(m) -> (parts, touch,
distance)`: a linkage's brackets and links are the candidate's own, so each candidate that reaches the gate is met
with the parts its own pins place. What `world` returns is read as a record's: anything but the three, a part on
no body of the kind, a zone that is not a part, a pin the member rides, a radius and a depth, or a zone wider or
deeper than its member is refused.
`swept` gives the ram's swept surface in any body's frame, for a recess.
### The record
`record` and `from_record` carry a mechanism as JSON: `schema` (`brokkr.ram`), `version` (1), `kind`, `hinge`,
`pins`, `offsets`, `ram`, `parts`, `touch` (member -> zones, each `{part, pin, radius, depth}`), and `compliance`.
It holds what is authored; barrel, closed length and link lengths are derived by the reader. `compliance` is
reserved for a load-path ram's settle (stiffness, damping, travel); version 1 writes it null and solves none. A
record of another schema or version (the integer 1: 1.0 and true are not it), with a key version 1 does not know or
without one it does (at the top, in `ram`, `hinge`, `pins` or a zone), with a compliance block, or with a value
that is not its field's (a finite number, the bore over 0, three numbers for a point), or with a zone wider or
deeper than its member is refused whole, as a
`RamError` that names the field: a reader never reads past what it cannot solve. A `Ram` built by hand refuses the
same numbers.
### Readings on the R-3 knee
Bore 0.042, range 0..-125. The kinematic rows are tests/test_ram.py's. The clearance rows are
`tests/live/ram_knee.py`'s, Blender 5.3 (`ram_knee.result.json` is the last run): the knee as closed meshes the
test generates (thigh with its front plate, shin with caps and armour, the bracket that carries R, the horn that
carries `c`, twin link plates stacked 5 mm apart at x 0.31..0.345 and 0.35..0.385, pins through the knee's width,
collars at the eye and a base clevis whose foot runs 0.01 into the thigh; 12 parts) and the package's signed BVH
oracle, `ram.Signed(shells, cap)`: the nearest face for the depth, the crossing parity of three rays, by majority,
for the side. One ray that runs through an edge or a vertex miscounts and signs a sample inside a plate it stands
clear of. `tests/fixtures/ram_rays.json` holds the ray count: the rocker plates as the joint library builds them
and 24 points between the plates, each on the first ray short of an edge or a vertex. One ray signs all 24
inside; three sign none. Three rays are not a proof: of 146 such points one ray missigned, two rays missigned 16.
| drive | reading |
| --- | --- |
| direct, the joint library's seats, 0..-62 | fits (analytic thigh and shin) |
| direct, 2,000 seat pairs behind the knee | none fits (analytic thigh and shin) |
| four-bar behind the knee | passes every gate before clearance: rocker swing 70.5, L 0.722..1.168, arm 0.096..0.265, pin load 1.61, transmission 16.5. Refused on the meshes: the barrel and the rod against the shin's body (the barrel 0.122 inside its clearance, 49 steps), a body the ram is not pinned to |
| bell crank in front of the knee | fits on the meshes, the plates on either side: rocker swing 105.7, L 0.659..1.038, arm 0.091..0.215, pin load 1.13, transmission 13.8. 60 pairs, 20 of them with a zone. Over 251 steps, uncapped, the least margin of a pair with no zone is 0.034 (the rocker and the eye's pin at -125), then 0.039 (the rod and the rocker's pivot pin at -125) and 0.042 (the coupler and the bracket at 0). With `touch` empty the same gate refuses 19 pairs, each one a zoned pair; each stated zone takes in the least zone that lets its pair. A zone cut to half its radius refuses its pair |
| the same, a link's x moved | the rocker at x 0.25 (inside the bracket's 0.13..0.35) is refused 0.054 inside the bracket; the coupler at 0.25 (inside the horn's 0.23..0.31) 0.020 inside the horn |
| bell-crank search on the meshes | 13,824 candidates, each world built from the candidate's pins: 78 pass the gates before clearance, 21 of them are refused on their own parts, the 22nd fits (arm 0.090, swing 99.9, pin load 0.73) and holds at 251 steps |
Cost on Starfire, Python 3.13, 100 repetitions paired and interleaved: one candidate's gates before clearance at
49 steps took 0.79 ms median on the bell crank; its clearance against the analytic parts (50 pairs) took 42 ms
(5th to 95th percentile 38 to 57) over 97,875 points, of which 23,520 are the samples and the rest the halving in
zones (the own plates, stated with no slack, to the floor); the samples alone took 11 ms. A search without a world ran 1.6 to 1.8 ms a candidate over 3,456, so `limit`
(20,000) is 30 to 40 s. On the meshes the bell crank's 60 pairs at 49 steps took 1.95 to 2.12 s capped (two runs), in a
Python loop of BVH queries with three rays a sample, and the 13,824-candidate search with its 22 worlds 43 s (one run).
## The actions
| action | fields | what it does |

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,435 @@
"""Live proof, in a background Blender, of brokkr_kitbash/ram.py's clearance gate on meshes: the R-3 knee (thigh,
shin, the bracket and horn, a bell crank's or a four-bar's plates, pins and clevises), every piece a closed mesh this
file generates, each a named part of a body, and the gate answered by the package's signed BVH oracle (ram.Signed)
over them. Not part of the unittest run: it needs Blender (mathutils' BVHTree).
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/ram_knee.py -- <out>
Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses
without them). <out> is an absolute path; writes <out>.result.json and <out>.r3_<angle>.png (the bell crank at 0,
-62.5 and -125) and exits 1 when a check failed.
The oracle is ram.Signed, three rays by majority. Its ray count is held by tests/fixtures/ram_rays.json: the rocker
plates as Imagination's jointlib builds them and points between the plates that stand on the first ray short of an
edge or a vertex. One ray reads them inside a plate they stand clear of; the oracle as it is made reads none inside.
A clearance verdict is a sign, the gate's own. FLAT follows lodur:ruling:deterministic-bound-margin. The checks run
inside one try: an uncaught error is a failed check that names its section, and the result file is always written.
"""
import importlib.util
import json
import math
import os
import sys
import time
import traceback
from dataclasses import replace
from pathlib import Path
import bmesh
import bpy
import numpy as np
from mathutils import Matrix, Vector
SURFACE = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(SURFACE / "tools"))
import private_dirs # noqa: E402
_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
if _refused:
raise SystemExit(_refused)
OUT = sys.argv[sys.argv.index("--") + 1]
if not Path(OUT).is_absolute():
raise SystemExit(f"{OUT!r} is not an absolute path")
spec = importlib.util.spec_from_file_location("brokkr_kitbash_ram", SURFACE / "brokkr_kitbash" / "ram.py")
R = importlib.util.module_from_spec(spec) # ram.py as the unit tests load it
sys.modules[spec.name] = R
spec.loader.exec_module(R)
Signed = R.Signed
RES = {"blender": bpy.app.version_string, "checks": [], "readings": {}}
SECTION = ["setup"]
# Metres between the oracle's reading and 0.0225, on a grid a plate's thickness off a rocker plate's face. Shipped
# worst 1.3e-08 (float32 faces); least claimed mutant 0.045 (a sample signed inside reads -0.0225); the geometric mean.
FLAT = 2.4e-5
BORE, PIN, AXLE = 0.042, 0.026, 0.028
SLAB_C, SLAB_R = (0.31, 0.345), (0.35, 0.385) # the twin link plates along the axis: the coupler's inside the rocker's
X_C, X_R = 0.5 * sum(SLAB_C), 0.5 * sum(SLAB_R)
HALF = 0.5 * (SLAB_R[1] - SLAB_R[0]) # half a plate's thickness
W_ROCKER, W_COUPLER, W_ARM, W_HORN, W_BRACKET, COLLAR = 0.045, 0.04, 0.04, 0.05, 0.055, 0.05
CHEEK = (0.03, 0.05) # a clevis's cheeks, either side of the ram's eye
SLACK = 0.001 # a zone's depth over the burial it lets: a float32 face reads a burial to 1e-8
# P2's seats, (y, z): the deep four-bar behind the knee and the bell crank in front of it
DEEP = {"a": (-0.45, 1.15), "rocker": (-0.2320142211320173, 0.4604939911625098), "p": (-0.43650046730511183, -0.017951928782268284),
"c": (0.06881023105761902, -0.3143743967236484), "d": (-0.43650046730511183, -0.017951928782268284)}
CRANK = {"a": (0.45, 1.15), "rocker": (0.3171126791600819, 0.3216537818398838), "p": (0.7282866960904424, 0.43261578669776135),
"c": (0.34929485118682846, 0.14862538079826304), "d": (0.48651463351122515, 0.49166254003196397)}
ROOTS = {"bell_crank": {"horn": (0.10, -0.40), "bracket": (0.10, 0.55)}, "four_bar": {"horn": (0.0, -0.42), "bracket": (-0.10, 0.55)}}
THIGH_FRONT, EMBED = 0.14, 0.01 # the thigh core's faces stand at y +-0.14; a foot runs this far into it
def check(name, ok, detail=None):
RES["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail})
def prism(outline, x0, x1):
"""A closed shell: the convex (y, z) outline, counter-clockwise seen from +x, run from x0 to x1."""
x0, x1 = min(x0, x1), max(x0, x1)
n = len(outline)
verts = [(x, y, z) for x in (x0, x1) for y, z in outline]
faces = [tuple(range(n - 1, -1, -1)), tuple(range(n, 2 * n))] + [(k, (k + 1) % n, n + (k + 1) % n, n + k) for k in range(n)]
return np.array(verts, dtype=float), faces
def box(centre, size):
(cx, cy, cz), (sx, sy, sz) = centre, size
return prism([(cy - sy / 2, cz - sz / 2), (cy + sy / 2, cz - sz / 2), (cy + sy / 2, cz + sz / 2), (cy - sy / 2, cz + sz / 2)], cx - sx / 2, cx + sx / 2)
def disc(at, r, x0, x1, n=32):
return prism([(at[0] + r * math.cos(2 * math.pi * k / n), at[1] + r * math.sin(2 * math.pi * k / n)) for k in range(n)], x0, x1)
def bar(p, q, w, x0, x1, n=10):
"""A link plate: the stadium of half width w about the segment p -> q."""
p, q = np.array(p, float), np.array(q, float)
base = math.atan2(*((q - p) / np.linalg.norm(q - p))[::-1])
pts = [(c[0] + w * math.cos(a0 + math.pi * k / n), c[1] + w * math.sin(a0 + math.pi * k / n)) for c, a0 in ((q, base - math.pi / 2), (p, base + math.pi / 2)) for k in range(n + 1)]
return prism(pts, x0, x1)
def knee(kind, pn, links=True):
"""part -> [shell], part -> body: the knee at rest (angle 0, every frame the parent's)."""
shells, front = {}, kind == "bell_crank"
def add(part, *made):
shells.setdefault(part, []).extend(made)
r, gap, cheek = 0.25, 0.22, 0.07
half = gap / 2 + cheek
add("parent.body", box((0, 0, 0.725), (0.26, 2 * THIGH_FRONT, 0.85)), box((0, 0.185, 0.725), (0.34, 0.06, 0.77)), box((0, 0, 0.2), (gap - 0.03, 0.24, 0.4)),
disc((0, 0), 0.9 * r, -(gap - 0.03) / 2, (gap - 0.03) / 2))
outline = [(r * math.cos(math.radians(a)), r * math.sin(math.radians(a))) for a in range(0, 181, 15)] + [(-0.12, -0.95), (0.12, -0.95)]
add("child.body", box((0, 0, -0.72), (gap, 0.22, 0.46)), box((0, 0.15, -0.62), (2 * half + 0.06, 0.06, 0.58)))
Rk, P, C, A, D = (pn[k] for k in ("rocker", "p", "c", "a", "d"))
for s in (-1, 1):
add("child.body", prism(outline, s * gap / 2, s * half), disc((0, 0), 0.19, s * half, s * (half + 0.025)), box((s * (half + 0.03), 0.0, -0.62), (0.045, 0.2, 0.5)))
add("child.horn", bar(ROOTS[kind]["horn"], C, W_HORN, s * (half + 0.05), s * SLAB_C[0]))
add("parent.bracket", bar(ROOTS[kind]["bracket"], Rk, W_BRACKET, s * 0.13, s * SLAB_R[0]))
# the base clevis: cheeks about the pin and a foot that runs into the thigh's core, toward it
toward = -1.0 if front else 1.0
foot = (A[0] + toward * 0.2, A[1])
add("parent.seat", bar(A, foot, 1.7 * BORE, s * CHEEK[0], s * CHEEK[1]))
if links:
add("rocker.plate", bar(Rk, P, W_ROCKER, s * SLAB_R[0], s * SLAB_R[1]))
add("coupler.plate", bar(P, C, W_COUPLER, s * SLAB_C[0], s * SLAB_C[1]))
add("rocker.seat", disc(D, COLLAR, s * CHEEK[0], s * CHEEK[1])) # the eye's collars on its pin
if front:
add("rocker.plate", bar(Rk, D, W_ARM, s * SLAB_R[0], s * SLAB_R[1]))
face = toward * (THIGH_FRONT - EMBED)
add("parent.seat", box((0, 0.5 * (face + foot[0]), A[1]), (2 * CHEEK[1], abs(foot[0] - face), 3.4 * BORE)))
if links:
add("rocker.pin.R", disc(Rk, AXLE, -SLAB_R[1] - 0.015, SLAB_R[1] + 0.015))
add("rocker.pin.p", disc(P, PIN, -SLAB_R[1] - 0.015, SLAB_R[1] + 0.015))
add("coupler.pin.c", disc(C, PIN, -SLAB_C[1] - 0.015, SLAB_C[1] + 0.015))
if front:
add("rocker.pin.d", disc(D, PIN, -SLAB_R[1] - 0.015, SLAB_R[1] + 0.015))
return shells, {part: {"parent": "parent", "child": "child", "rocker": "rocker", "coupler": "coupler"}[part.split(".")[0]] for part in shells}
def near(ram, member):
return {"barrel": ram.barrel_r, "rod": ram.rod}.get(member, ram.link_r) + ram.gap + ram.spacing() / 2
def parting(ram, w, degrees):
"""How far from a pin a link parts from a plate of half width w that stands beside it on the pin, a plate's
thickness off along the axis, the two crossing at `degrees` at the least: where the link's axis is what a link
keeps from the plate's edge, and never less than the plate's round end."""
lateral = math.sqrt(near(ram, "rocker") ** 2 - HALF ** 2)
return max((w + lateral) / math.sin(math.radians(min(degrees, 90.0))), w + near(ram, "rocker"))
def crossing(m, kind):
"""The least angle, over the range, at which the rocker, the rocker arm and the coupler cross what stands beside
them: the bracket's bar at the pivot, the horn's at c (seen from the shin), each other at p."""
p, n = R.pose(m, np.linspace(m.lo, m.hi, 126)), m.axis
def least(a, b):
a, b = R._flat(a, n), R._flat(np.broadcast_to(b, a.shape), n)
return float(np.degrees(np.arccos(np.clip((a * b).sum(axis=1) / (np.linalg.norm(a, axis=1) * np.linalg.norm(b, axis=1)), -1.0, 1.0))).min())
root = {key: np.array((0.0, *value)) for key, value in ROOTS[kind].items()}
seen = R._into(m, p, "child", p.P[:, None, :])[:, 0, :]
return {"rocker": least(p.P - m.rocker, root["bracket"] - m.rocker), "rocker arm": least(p.eye - m.rocker, root["bracket"] - m.rocker),
"coupler": least(seen - m.c, root["horn"] - m.c), "p": float(p.mu_p.min())}
def zones(m, ram, parts):
"""Each member's zones. About a pin: the pin's, collar's or cheek's radius plus what the member keeps, as deep as
the pin where it runs through the member's eye and 0 beside a collar, a cheek, the bracket or the horn; a link's
own plate about both its pins, each a little over half its length (a zone is no wider than its member), half
the plate's thickness deep; a plate beside a link as far as the two part. A depth that is not 0 is stated SLACK
over the burial."""
kind, link, at = m.kind, near(ram, "rocker"), crossing(m, m.kind)
PIN, AXLE, HALF = (value + SLACK for value in (globals()["PIN"], globals()["AXLE"], globals()["HALF"]))
reach = {"pin": globals()["PIN"] + link, "axle": globals()["AXLE"] + link}
eye = "rocker.pin.d" if kind == "bell_crank" else "rocker.pin.p"
def own(part, a, b, span):
return [(part, a, 0.51 * span, HALF), (part, b, 0.51 * span, HALF)]
def parts_at(member, w, degrees): # never wider than the member: two that cross at a few degrees part beyond its length
return min(parting(ram, w, degrees), R._span(m, member))
touch = {member: [("parent.seat", "a", 1.7 * BORE + near(ram, member), 0.0), ("rocker.seat", "d", COLLAR + near(ram, member), 0.0),
(eye, "d", globals()["PIN"] + near(ram, member), PIN if member == "rod" else 0.0)] for member in ("barrel", "rod")}
pivot = [("parent.bracket", "rocker", None, 0.0), ("rocker.pin.R", "rocker", reach["axle"], AXLE)]
touch["rocker"] = pivot + [("rocker.pin.p", "p", reach["pin"], PIN), *own("rocker.plate", "rocker", "p", m.lr), ("coupler.plate", "p", parts_at("rocker", W_COUPLER, at["p"]), 0.0)]
touch["coupler"] = [("child.horn", "c", parts_at("coupler", W_HORN, at["coupler"]), 0.0), ("coupler.pin.c", "c", reach["pin"], PIN), ("rocker.pin.p", "p", reach["pin"], PIN),
*own("coupler.plate", "p", "c", m.lc), ("rocker.plate", "p", parts_at("coupler", W_ROCKER, at["p"]), 0.0)]
if kind == "bell_crank":
touch["rocker arm"] = pivot + [("rocker.pin.d", "d", reach["pin"], PIN), *own("rocker.plate", "rocker", "d", R._span(m, "rocker arm"))]
for member in ("rocker", "rocker arm"):
if member in touch:
touch[member][0] = ("parent.bracket", "rocker", parts_at(member, W_BRACKET, at[member]), 0.0)
return {member: [zone for zone in given if zone[0] in parts] for member, given in touch.items()}
def pins3(pn, side=1.0, **moved):
at = {"a": 0.0, "p": 0.0, "d": 0.0, "rocker": side * X_R, "c": side * X_C, **moved}
return {k: (at[k], float(pn[k][0]), float(pn[k][1])) for k in pn}
def needs(m, ram, parts, distance, steps=49):
"""(member, part) -> (pin, radius, depth): for every pair refused with nothing let, the least zone that lets it."""
p = R.pose(m, np.linspace(m.lo, m.hi, steps))
at = {"a": p.base, R.EYE[m.kind]: p.eye, "rocker": m.rocker, "p": p.P, "c": p.C}
step, out = ram.spacing(), {}
for member, label, start, end, radius, pins in R._members(m, ram, R.barrel_length(m, ram), p):
count = max(int(math.ceil(float(np.linalg.norm(end - start, axis=1).max()) / step)) + 1, 2)
pts = start[:, None, :] + (end - start)[:, None, :] * np.linspace(0.0, 1.0, count)[None, :, None]
for part, body in parts.items():
got = distance(part, R._into(m, p, body, pts).reshape(-1, 3)).reshape(len(p.degrees), count)
bad = got < radius + ram.gap + step / 2
if bad.any():
best = None
for pin in pins:
across = np.linalg.norm(R._flat(pts - np.broadcast_to(at[pin], start.shape)[:, None, :], m.axis), axis=2)
reach = float(across[bad].max())
if best is None or reach < best[1]:
best = (pin, reach, max(-float(got[across <= reach].min()), 0.0))
out[(label, part)] = best
return out
def refused(f):
return sorted((pair, round(reading[0], 4), reading[1]) for pair, reading in f.pairs.items() if reading[0] < 0.0)
def label(member):
return member + "[0]" if member in ("barrel", "rod") else member
def hinge4(pivot, degrees):
return Matrix.Translation(Vector(pivot)) @ Matrix.Rotation(math.radians(degrees), 4, "X") @ Matrix.Translation(-Vector(pivot))
def render(m, ram, f, shells, parts):
"""The bell crank at 0, -62.5 and -125, each piece coloured by its part, the ram as the gate holds it."""
scene = bpy.context.scene
colour = {"horn": (0.95, 0.45, 0.1, 1), "bracket": (0.15, 0.45, 0.9, 1), "plate": (0.75, 0.75, 0.78, 1), "seat": (0.55, 0.3, 0.6, 1), "pin": (0.9, 0.9, 0.3, 1)}
objects = []
for part, made in shells.items():
for k, (verts, faces) in enumerate(made):
me = bpy.data.meshes.new(f"{part}.{k}")
me.from_pydata(verts.tolist(), [], faces)
o = bpy.data.objects.new(me.name, me)
scene.collection.objects.link(o)
o.color = colour.get(part.split(".")[1], (0.33, 0.38, 0.24, 1) if parts[part] == "child" else (0.3, 0.32, 0.36, 1))
objects.append((o, parts[part]))
def tube(name, r, col):
me, bm = bpy.data.meshes.new(name), bmesh.new()
bmesh.ops.create_cone(bm, cap_ends=True, segments=24, radius1=r, radius2=r, depth=1.0)
bmesh.ops.translate(bm, verts=bm.verts[:], vec=(0, 0, 0.5))
bm.to_mesh(me)
bm.free()
o = bpy.data.objects.new(name, me)
scene.collection.objects.link(o)
o.color = col
return o
barrel, rod = tube("ram.barrel", ram.barrel_r, (0.85, 0.15, 0.12, 1)), tube("ram.rod", ram.rod, (0.95, 0.95, 0.95, 1))
scene.render.engine = "BLENDER_WORKBENCH"
scene.display.shading.light, scene.display.shading.color_type = "STUDIO", "OBJECT"
scene.display.shading.show_shadows = scene.display.shading.show_cavity = True
scene.render.resolution_x, scene.render.resolution_y, scene.render.film_transparent = 1400, 1500, False
scene.world = bpy.data.worlds.new("w")
scene.world.color = (0.82, 0.83, 0.85)
cam = bpy.data.objects.new("cam", bpy.data.cameras.new("cam"))
scene.collection.objects.link(cam)
cam.data.type, cam.data.ortho_scale = "ORTHO", 2.75
target = Vector((0.0, 0.1, 0.12))
cam.location = target + Vector((0.72, 0.62, 0.22)).normalized() * 8.0
cam.rotation_euler = (target - cam.location).to_track_quat("-Z", "Y").to_euler()
scene.camera = cam
made = []
for angle in (0.0, -62.5, -125.0):
p = R.pose(m, angle)
T = {"parent": Matrix.Identity(4), "child": hinge4((0, 0, 0), angle), "rocker": hinge4(m.rocker, math.degrees(p.phi[0])),
"coupler": Matrix.Translation(Vector(p.P[0] - m.p)) @ hinge4(m.p, math.degrees(p.psi[0]))}
for o, body in objects:
o.matrix_world = T[body]
u, base = Vector(p.u[0]), Vector(p.base[0])
frame = u.to_track_quat("Z", "Y").to_matrix().to_4x4()
barrel.matrix_world = Matrix.Translation(base + u * ram.back) @ frame @ Matrix.Diagonal((1, 1, f.barrel, 1))
rod.matrix_world = Matrix.Translation(base + u * (ram.back + f.barrel)) @ frame @ Matrix.Diagonal((1, 1, float(p.L[0]) - ram.back - f.barrel, 1))
scene.render.filepath = f"{OUT}.r3_{abs(angle):g}".replace(".5", "p5") + ".png"
bpy.ops.render.render(write_still=True)
made.append(scene.render.filepath)
return made
try:
bpy.ops.wm.read_factory_settings(use_empty=True)
ram = R.Ram(BORE)
HINGE = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), -125.0, 0.0)
SECTION[0] = "oracle"
shells, parts = knee("bell_crank", CRANK)
rows = []
for name, part, point, depth in (("the thigh core's centre", "parent.body", (0.0, 0.0, 0.7), -0.13), ("0.02 inside the thigh's wall", "parent.body", (0.11, 0.0, 0.7), -0.02),
("the shin's leg centre", "child.body", (0.0, 0.0, -0.7), -0.11), ("0.125 off the thigh's plate", "parent.body", (0.0, 0.34, 0.7), 0.125)):
capped, free = (float(Signed(shells, cap)(part, np.array([point]))[0]) for cap in (ram.reach(), None))
rows.append((name, capped, free, abs(free - depth) < FLAT and capped == (free if depth < 0 else min(free, ram.reach()))))
check("inside-is-negative: a point inside a part reads its depth, negative, capped or not; a cap changes only what is outside", all(row[3] for row in rows), rows)
# a grid a plate's thickness off the rocker plates' inner face, over the knee: every point is 0.0225 or more from the
# plates and none is inside; where the plate is under the point the reading is the 0.0225
ys, zs = np.meshgrid(np.linspace(0.1, 0.9, 96), np.linspace(0.1, 0.7, 72))
plane = np.stack([np.full(ys.size, X_C), ys.ravel(), zs.ravel()], axis=1)
three, one = Signed(shells)("rocker.plate", plane), Signed(shells, rays=1)("rocker.plate", plane)
def off(a, b): # each grid point's distance from the segment a -> b, across the axis
a, b = np.array(a), np.array(b)
t = np.clip(((plane[:, 1:] - a) @ (b - a)) / ((b - a) @ (b - a)), 0.0, 1.0)
return np.linalg.norm(plane[:, 1:] - a - t[:, None] * (b - a), axis=1)
under = (off(CRANK["rocker"], CRANK["p"]) < W_ROCKER - 0.005) | (off(CRANK["rocker"], CRANK["d"]) < W_ARM - 0.005)
RES["readings"]["FLAT"] = float(np.abs(three[under] - (SLAB_R[0] - X_C)).max())
RES["readings"]["one ray: samples signed inside, of %d" % len(plane)] = int((one < 0).sum())
check("three-rays: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225",
(three >= SLAB_R[0] - X_C - FLAT).all() and under.sum() > 500 and RES["readings"]["FLAT"] < FLAT, [float(three.min()), int(under.sum()), RES["readings"]["FLAT"]])
# against shells whose inside is known in closed form: a box and a disc, random points, each ray's edges and vertices among them
rng = np.random.default_rng(7)
cloud = rng.uniform((-0.2, -0.2, 0.2), (0.2, 0.2, 1.25), (4000, 3))
core = Signed({"core": [box((0, 0, 0.725), (0.26, 0.28, 0.85))]})("core", cloud)
exact = np.maximum.reduce([np.abs(cloud[:, 0]) - 0.13, np.abs(cloud[:, 1]) - 0.14, np.abs(cloud[:, 2] - 0.725) - 0.425])
check("three-rays: 4000 random points about a box are signed as the box signs them", ((core < 0) == (exact < 0)).all(), int(((core < 0) != (exact < 0)).sum()))
# the ray count: the jointlib rocker plates, and points between them aimed along the first ray at an edge or a vertex
fixture = json.loads((SURFACE / "tests" / "fixtures" / "ram_rays.json").read_text(encoding="utf-8"))
plates, aimed = {"plates": [(np.array(fixture["verts"]), fixture["faces"])]}, np.array(fixture["points"])
made, single = Signed(plates)("plates", aimed), Signed(plates, rays=1)("plates", aimed)
RES["readings"]["jointlib plates: points one ray signs inside, of %d" % len(aimed)] = int((single < 0).sum())
RES["readings"]["jointlib plates: points the oracle signs inside"] = int((made < 0).sum())
# one ray reads all 24 inside; the oracle as made reads none. The bound on one ray's count is the geometric mean of 1 and 24
check("ray-count: between the jointlib rocker plates, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray",
(np.abs(aimed[:, 0]) < 0.349).all() and (made > 0).all() and (single < 0).sum() >= 5, [int((made < 0).sum()), int((single < 0).sum())])
SECTION[0] = "seat"
seat = np.concatenate([v for v, _ in shells["parent.seat"]])
deepest = float(Signed(shells)("parent.body", seat).min())
RES["readings"]["the base clevis's foot inside the thigh"] = deepest
check("the base clevis is seated: its foot runs 0.01 into the thigh's core, through the front plate", abs(deepest + EMBED) < FLAT, deepest)
SECTION[0] = "bell crank"
winner = None
for side in (1.0, -1.0):
m = R.Mechanism("bell_crank", *HINGE, **pins3(CRANK, side), parts=parts)
touch = zones(m, ram, parts)
m = replace(m, touch=touch)
zoned = {(label(member), zone[0]) for member, given in touch.items() for zone in given}
t0 = time.perf_counter()
f = R._fit(m, ram, steps=49, distance=Signed(shells, ram.reach()))
seconds = time.perf_counter() - t0
check(f"bell-crank-clears-on-meshes (side {side:+.0f}): over 0..-125 at 49 steps every member is clear of every part, 5 x {len(parts)} pairs, beside its pins by the record's zones",
f.ok and len(f.pairs) == 5 * len(parts) and set(f.allowed) == zoned, [f.report(), refused(f)])
fine = R._fit(m, ram, steps=251, distance=Signed(shells))
check(f"bell-crank-clears-on-meshes (side {side:+.0f}): and at 251 steps with the oracle uncapped", fine.ok, [fine.report(), refused(fine)])
bare = R._fit(replace(m, touch={}), ram, steps=49, distance=Signed(shells, ram.reach()))
need = needs(m, ram, parts, Signed(shells))
stated = {}
for member, given in touch.items():
for zone in given:
stated.setdefault((label(member), zone[0]), []).append(zone)
def takes(given, pin, radius, depth): # one zone about the pin, or zones about both of the member's pins that meet
return all(zone[3] >= depth for zone in given) and (any(zone[1] == pin and zone[2] >= radius for zone in given)
or (len({zone[1] for zone in given}) == 2 and sum(zone[2] for zone in given) >= radius))
slack = {pair: takes(stated[pair], *least) for pair, least in need.items() if pair in stated}
check(f"zones (side {side:+.0f}): with nothing let the gate refuses, and only pairs the record zones; each stated zone takes in the least that lets its pair",
{pair for pair, _, _ in refused(bare)} == set(need) and set(need) <= zoned and all(slack.values()), [refused(bare), sorted(set(need) - zoned), [k for k, v in slack.items() if not v]])
if side > 0:
winner = (m, f)
def free(fit): # the least margin of the pairs no zone lets: a zoned pair's is its depth's slack at the pin
return min(reading[0] for pair, reading in fit.pairs.items() if pair not in zoned)
RES["readings"].update({"bell crank: least margin of a pair with no zone, 251 steps uncapped": free(fine),
"bell crank: least margin of a zoned pair, 251 steps uncapped": min(reading[0] for pair, reading in fine.pairs.items() if pair in zoned),
"bell crank: pairs": len(f.pairs), "bell crank: zoned pairs": len(f.allowed), "bell crank: pairs refused with nothing let": len(refused(bare)),
"bell crank: seconds, 49 steps capped": seconds})
RES["zones"] = {f"{pair[0]} | {pair[1]}": {"stated": [list(zone[1:]) for zone in stated[pair]], "least": [pin, round(radius, 4), round(depth, 4)]} for pair, (pin, radius, depth) in sorted(need.items()) if pair in stated}
RES["least pairs"] = sorted((round(v[0], 4), v[1], k[0], k[1]) for k, v in fine.pairs.items() if k not in zoned)[:8]
SECTION[0] = "zones end"
m, f = winner
for member, part in (("rocker", "parent.bracket"), ("coupler", "child.horn"), ("rod", "rocker.pin.d")):
short = {**m.touch, member: tuple((p_, pin, 0.5 * radius, depth) if p_ == part else (p_, pin, radius, depth) for p_, pin, radius, depth in m.touch[member])}
got = R._fit(replace(m, touch=short), ram, steps=49, distance=Signed(shells, ram.reach()))
check(f"a zone ends at its radius: {member}'s about {part} cut to half, that pair alone is refused", [pair for pair, _, _ in refused(got)] == [(label(member), part)], refused(got))
SECTION[0] = "moved x"
# Soul's let_hide probes: a link's place along the axis moved from beside the bracket or horn into it
for name, moved, expect in (("the rocker at x 0.25, inside the bracket's 0.13..0.35", {"rocker": 0.25}, {("rocker", "parent.bracket"), ("rocker arm", "parent.bracket")}),
("the coupler at x 0.25, inside the horn's 0.23..0.31", {"c": 0.25}, {("coupler", "child.horn")}),
("both", {"rocker": 0.25, "c": 0.25}, {("rocker", "parent.bracket"), ("rocker arm", "parent.bracket"), ("coupler", "child.horn")})):
mm = R.Mechanism("bell_crank", *HINGE, **pins3(CRANK, 1.0, **moved), parts=parts, touch=m.touch)
got = R._fit(mm, ram, steps=49, distance=Signed(shells, ram.reach()))
inside = {pair: reading for pair, reading, _ in refused(got)}
RES["readings"]["moved x: " + name] = min(inside.values()) if inside else 0.0
check(f"a pin stood inside what it stands beside is refused: {name}", not got.ok and expect <= set(inside) and all(inside[pair] < -0.015 for pair in expect), refused(got))
SECTION[0] = "four bar"
shells4, parts4 = knee("four_bar", DEEP)
m4 = R.Mechanism("four_bar", *HINGE, **pins3(DEEP), parts=parts4)
m4 = replace(m4, touch=zones(m4, ram, parts4))
f4 = R._fit(m4, ram, steps=49, distance=Signed(shells4, ram.reach()))
hit = {pair: reading for pair, reading, _ in refused(f4)}
RES["readings"]["four bar: barrel inside the shin's clearance"] = hit.get(("barrel[0]", "child.body"), 0.0)
check("third-body: the deep four-bar's ram is refused on the shin, which folds into it", not f4.ok and {("barrel[0]", "child.body"), ("rod[0]", "child.body")} <= set(hit) and f4.clear_at[2] == "child.body", refused(f4))
SECTION[0] = "search"
seats = {"rocker": [(X_R, *CRANK["rocker"]), (X_R, CRANK["rocker"][0] - 0.07, CRANK["rocker"][1] + 0.03)], "c": [(X_C, *CRANK["c"]), (X_C, CRANK["c"][0] - 0.05, CRANK["c"][1] + 0.03)],
"a": [(0.0, *CRANK["a"]), (0.0, 0.4, 1.0)], "link": (0.35, 0.5, 3), "d": (0.2, 0.26, 2)}
built = []
def world(mech):
made, bodies = knee("bell_crank", {k: (float(getattr(mech, k)[1]), float(getattr(mech, k)[2])) for k in CRANK})
built.append(mech)
return bodies, zones(mech, ram, bodies), Signed(made, ram.reach())
t0 = time.perf_counter()
s = R.search("bell_crank", {"pivot": HINGE[0], "axis": HINGE[1], "lo": -125, "hi": 0}, ram, seats, world=world, steps=49)
RES["readings"].update({"search: seconds": time.perf_counter() - t0, "search: candidates": s.tried, "search: pass the gates before clearance": s.fits,
"search: worlds built": len(built), "search: refused on their own parts": s.tally.get("clash", 0)})
RES["search"] = {"report": s.report(), "seat": {k: np.round(v, 4).tolist() for k, v in (s.seat or {}).items()}, "tally": s.tally}
again = R._fit(s.best.m, ram, steps=251, distance=world(s.best.m)[2]) if s.found else None
check("search-holds-candidate-links: a seat grid about the probe's bell crank, each candidate met with the meshes its own pins place, runs to a fit that holds at 251 steps",
s.found and s.best.ok and len(built) - 1 == s.tally.get("clash", 0) + 1 and again.ok and len(s.best.pairs) == 5 * len(parts), [s.report(), refused(again) if again else None])
SECTION[0] = "render"
RES["renders"] = render(winner[0], ram, winner[1], shells, parts)
check("the bell crank is drawn at 0, -62.5 and -125", all(Path(path).is_file() for path in RES["renders"]), RES["renders"])
except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file
check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-8:])
finally:
RES["ok"] = all(c["ok"] for c in RES["checks"])
RES["readings"] = {name: (float(f"{value:.3g}") if isinstance(value, float) else value) for name, value in sorted(RES["readings"].items())}
Path(OUT + ".result.json").write_text(json.dumps(RES, indent=1, default=str), encoding="utf-8")
for c in RES["checks"]:
print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True)
print("READINGS", RES["readings"], flush=True)
sys.exit(0 if RES["ok"] else 1)

View file

@ -0,0 +1,504 @@
{
"blender": "5.3.0",
"checks": [
{
"name": "inside-is-negative: a point inside a part reads its depth, negative, capped or not; a cap changes only what is outside",
"ok": true,
"detail": null
},
{
"name": "three-rays: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225",
"ok": true,
"detail": null
},
{
"name": "three-rays: 4000 random points about a box are signed as the box signs them",
"ok": true,
"detail": null
},
{
"name": "ray-count: between the jointlib rocker plates, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray",
"ok": true,
"detail": null
},
{
"name": "the base clevis is seated: its foot runs 0.01 into the thigh's core, through the front plate",
"ok": true,
"detail": null
},
{
"name": "bell-crank-clears-on-meshes (side +1): over 0..-125 at 49 steps every member is clear of every part, 5 x 12 pairs, beside its pins by the record's zones",
"ok": true,
"detail": null
},
{
"name": "bell-crank-clears-on-meshes (side +1): and at 251 steps with the oracle uncapped",
"ok": true,
"detail": null
},
{
"name": "zones (side +1): with nothing let the gate refuses, and only pairs the record zones; each stated zone takes in the least that lets its pair",
"ok": true,
"detail": null
},
{
"name": "bell-crank-clears-on-meshes (side -1): over 0..-125 at 49 steps every member is clear of every part, 5 x 12 pairs, beside its pins by the record's zones",
"ok": true,
"detail": null
},
{
"name": "bell-crank-clears-on-meshes (side -1): and at 251 steps with the oracle uncapped",
"ok": true,
"detail": null
},
{
"name": "zones (side -1): with nothing let the gate refuses, and only pairs the record zones; each stated zone takes in the least that lets its pair",
"ok": true,
"detail": null
},
{
"name": "a zone ends at its radius: rocker's about parent.bracket cut to half, that pair alone is refused",
"ok": true,
"detail": null
},
{
"name": "a zone ends at its radius: coupler's about child.horn cut to half, that pair alone is refused",
"ok": true,
"detail": null
},
{
"name": "a zone ends at its radius: rod's about rocker.pin.d cut to half, that pair alone is refused",
"ok": true,
"detail": null
},
{
"name": "a pin stood inside what it stands beside is refused: the rocker at x 0.25, inside the bracket's 0.13..0.35",
"ok": true,
"detail": null
},
{
"name": "a pin stood inside what it stands beside is refused: the coupler at x 0.25, inside the horn's 0.23..0.31",
"ok": true,
"detail": null
},
{
"name": "a pin stood inside what it stands beside is refused: both",
"ok": true,
"detail": null
},
{
"name": "third-body: the deep four-bar's ram is refused on the shin, which folds into it",
"ok": true,
"detail": null
},
{
"name": "search-holds-candidate-links: a seat grid about the probe's bell crank, each candidate met with the meshes its own pins place, runs to a fit that holds at 251 steps",
"ok": true,
"detail": null
},
{
"name": "the bell crank is drawn at 0, -62.5 and -125",
"ok": true,
"detail": null
}
],
"readings": {
"FLAT": 8.34e-09,
"bell crank: least margin of a pair with no zone, 251 steps uncapped": 0.0336,
"bell crank: least margin of a zoned pair, 251 steps uncapped": 0.000118,
"bell crank: pairs": 60,
"bell crank: pairs refused with nothing let": 19,
"bell crank: seconds, 49 steps capped": 2.12,
"bell crank: zoned pairs": 20,
"four bar: barrel inside the shin's clearance": -0.122,
"jointlib plates: points one ray signs inside, of 24": 24,
"jointlib plates: points the oracle signs inside": 0,
"moved x: both": -0.0543,
"moved x: the coupler at x 0.25, inside the horn's 0.23..0.31": -0.02,
"moved x: the rocker at x 0.25, inside the bracket's 0.13..0.35": -0.0543,
"one ray: samples signed inside, of 6912": 0,
"search: candidates": 13824,
"search: pass the gates before clearance": 78,
"search: refused on their own parts": 21,
"search: seconds": 43.3,
"search: worlds built": 22,
"the base clevis's foot inside the thigh": -0.01
},
"zones": {
"barrel[0] | parent.seat": {
"stated": [
[
"a",
0.15645000000000003,
0.0
]
],
"least": [
"a",
0.1222,
0.0
]
},
"barrel[0] | rocker.pin.d": {
"stated": [
[
"d",
0.11105000000000001,
0.0
]
],
"least": [
"d",
0.1108,
0.0
]
},
"barrel[0] | rocker.seat": {
"stated": [
[
"d",
0.13505,
0.0
]
],
"least": [
"d",
0.1263,
0.0
]
},
"coupler | child.horn": {
"stated": [
[
"c",
0.11195,
0.0
]
],
"least": [
"c",
0.0947,
0.0
]
},
"coupler | coupler.pin.c": {
"stated": [
[
"c",
0.08795,
0.027
]
],
"least": [
"c",
0.0474,
0.0259
]
},
"coupler | coupler.plate": {
"stated": [
[
"p",
0.24152975906703586,
0.018500000000000016
],
[
"c",
0.24152975906703586,
0.018500000000000016
]
],
"least": [
"p",
0.4736,
0.0175
]
},
"coupler | rocker.pin.p": {
"stated": [
[
"p",
0.08795,
0.027
]
],
"least": [
"p",
0.0474,
0.0259
]
},
"coupler | rocker.plate": {
"stated": [
[
"p",
0.2818973893266964,
0.0
]
],
"least": [
"p",
0.2368,
0.0
]
},
"rocker | coupler.plate": {
"stated": [
[
"p",
0.26840002998268986,
0.0
]
],
"least": [
"p",
0.2366,
0.0
]
},
"rocker | parent.bracket": {
"stated": [
[
"rocker",
0.11695,
0.0
]
],
"least": [
"rocker",
0.0946,
0.0
]
},
"rocker | rocker.pin.R": {
"stated": [
[
"rocker",
0.08995,
0.029
]
],
"least": [
"rocker",
0.0473,
0.0279
]
},
"rocker | rocker.pin.p": {
"stated": [
[
"p",
0.08795,
0.027
]
],
"least": [
"p",
0.0473,
0.0259
]
},
"rocker | rocker.plate": {
"stated": [
[
"rocker",
0.2172005150345214,
0.018500000000000016
],
[
"p",
0.2172005150345214,
0.018500000000000016
]
],
"least": [
"rocker",
0.4259,
0.0175
]
},
"rocker arm | parent.bracket": {
"stated": [
[
"rocker",
0.11695,
0.0
]
],
"least": [
"rocker",
0.096,
0.0
]
},
"rocker arm | rocker.pin.R": {
"stated": [
[
"rocker",
0.08995,
0.029
]
],
"least": [
"rocker",
0.048,
0.0279
]
},
"rocker arm | rocker.pin.d": {
"stated": [
[
"d",
0.08795,
0.027
]
],
"least": [
"d",
0.048,
0.0259
]
},
"rocker arm | rocker.plate": {
"stated": [
[
"rocker",
0.12240000000000001,
0.018500000000000016
],
[
"d",
0.12240000000000001,
0.018500000000000016
]
],
"least": [
"rocker",
0.24,
0.0175
]
},
"rod[0] | rocker.pin.d": {
"stated": [
[
"d",
0.07955,
0.027
]
],
"least": [
"d",
0.0794,
0.0259
]
},
"rod[0] | rocker.seat": {
"stated": [
[
"d",
0.10355,
0.0
]
],
"least": [
"d",
0.0938,
0.0
]
}
},
"least pairs": [
[
0.0336,
-125.0,
"rocker",
"rocker.pin.d"
],
[
0.0393,
-125.0,
"rod[0]",
"rocker.pin.R"
],
[
0.0417,
0.0,
"coupler",
"parent.bracket"
],
[
0.0579,
0.0,
"rocker arm",
"coupler.plate"
],
[
0.0687,
0.0,
"coupler",
"rocker.pin.R"
],
[
0.0766,
0.0,
"rocker",
"child.horn"
],
[
0.0766,
0.0,
"rocker arm",
"child.horn"
],
[
0.0808,
-125.0,
"coupler",
"child.body"
]
],
"search": {
"report": "78 of 13824 candidates pass the gates before clearance (failed: arm 1406, assembly 4800, clash 21, load 1355, stroke 1160, toggle 7352); best: OK: L 0.664..0.968, barrel 0.513, stroke 0.458 for travel 0.304 (spare +0.137), arm >= 0.090, rocker swing 99.9, pin load <= 0.73, transmission >= 17.3 deg, clear +0.000",
"seat": {
"a": [
0.0,
0.45,
1.15
],
"rocker": [
0.3675,
0.3171,
0.3217
],
"p": [
0.3675,
0.7683,
0.5372
],
"c": [
0.3275,
0.3493,
0.1486
],
"d": [
0.0,
0.4303,
0.4866
]
},
"tally": {
"assembly": 4800,
"toggle": 7352,
"arm": 1406,
"stroke": 1160,
"load": 1355,
"clash": 21
}
},
"renders": [
"F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_0.png",
"F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_62p5.png",
"F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_125.png"
],
"ok": true
}

View file

@ -1941,7 +1941,7 @@ class OwnershipTests(unittest.TestCase):
return {p.name: p.read_text(encoding="utf-8") for p in sorted((SURFACE / "brokkr_kitbash").rglob("*")) if p.suffix in (".py", ".json")}
def test_no_pattern_matches(self):
self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "frame.v0.json", "mechanical.v0.json", "route.py"])
self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "frame.v0.json", "mechanical.v0.json", "ram.py", "route.py"])
for pattern in self.PACKAGE:
for name, text in self.sources().items():
if pattern is self.PACKAGE[2] and name == "__init__.py":

File diff suppressed because it is too large Load diff