brokkr_kitbash: followers derived from their driver; write_connections writes them with it; joints v2
The record gains follows (kit_follows, kit_follows_driver). write_connections checks every entry before writing any; set_params seats through it, so its direct seat loop goes and a hand-edited out-of-limit roll or stray slide is refused. joint_record reads None for what record_refusal would refuse. pose() refuses a follower and derives a driver's followers (driven: ratio, then loops by core.close_loop, stepped). brokkr_kitbash.follow states and clears; detach clears a loop partner. brokkr.joints version 2: driven, unlimited, after/next, the root's own row (cut kit-follows-2, steps 2 to 4). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
198b79590e
commit
53eac397c7
3 changed files with 461 additions and 93 deletions
|
|
@ -62,8 +62,15 @@ follow-up aetheria-release:follow_up:hose-motion-clearance-from-skinning owes th
|
|||
|
||||
Connections are a tree. A loop (a brace from one branch to another) is closed by a closure: three ID properties
|
||||
on the closing part, kit_close_socket, kit_close_to (a pointer to the other part) and kit_close_to_socket. close
|
||||
writes them, only when the two sockets already meet, and writes nothing else; detach clears them. Nothing here
|
||||
solves a loop: a closure never places a part, and a report says how far its two sockets stand apart.
|
||||
writes them, only when the two sockets already meet, and writes nothing else; detach clears them. A closure never
|
||||
places a part, and a report says how far its two sockets stand apart.
|
||||
|
||||
A connection may follow another: kit_follows on the follower (a ratio k and offset, or a loop) and kit_follows_driver,
|
||||
a pointer to the driver. A follower's kit_roll or kit_slide is then derived: by k x the driver's value + offset, or,
|
||||
for the closing part of a loop and its parent, by solving the two so the closure holds (core.close_loop, over the
|
||||
kit's socket frames at stored params: no pin is stored). pose() derives every follower of a driver in the driver's
|
||||
own action (driven) and write_connections writes them with it, all or none; roll, aim, reach and slide on a follower
|
||||
are refused. A follower has one driver and a driver is never a follower. No Blender driver or constraint is made.
|
||||
"""
|
||||
bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (5, 3, 0),
|
||||
"category": "Object", "description": "Parametric machine parts from kits, with socket frames; agent-callable through Brokkr."}
|
||||
|
|
@ -90,13 +97,14 @@ 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)
|
||||
FOLLOWS, FOLLOWS_DRIVER = "kit_follows", "kit_follows_driver" # on a follower's connection: what its value is derived from, as JSON, and an ID pointer to the driver; write_connections is their one writer
|
||||
RECORD = (SLIDE, LIMIT_MIN, LIMIT_MAX, MECHANISM, COMPLIANCE, FOLLOWS, FOLLOWS_DRIVER)
|
||||
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"
|
||||
HELD = 1e-5 # a connection or a closure holds when its residual is at most this (as RIGID)
|
||||
HELD = core.HELD # a connection or a closure holds when its residual is at most this (as RIGID)
|
||||
BEVEL = "Kit Bevel"
|
||||
CUTTERS = "cutters" # the kit whose parts cut places
|
||||
OPERATIONS = ("DIFFERENCE", "UNION", "INTERSECT") # a target's Boolean modifiers, "Kit " + operation.title(), in the order they are evaluated
|
||||
|
|
@ -115,6 +123,7 @@ HOSE_OFFSETS = ((0.0, 0.0, 0.0), (0.5, 0.5, 0.5), (0.31, 0.67, 0.13)) # of a st
|
|||
HOSE_FINEST = 0.005 # metres: the least step, and the least a refused step is halved to for one more round of seeds
|
||||
HOSE_SEGMENTS = 12 # sides of a hose, a ferrule and a clamp's pad
|
||||
ROLL_STEP = 5.0 # degrees between the rolls of a joint's range that hose measures first: the step an assembly's clearance is read at
|
||||
FOLLOW_SLIDE_STEP = 0.02 # metres a prismatic driver moves between the solves of the loops that follow it, as ROLL_STEP degrees for a revolute one: a rule, 0.044 m is what a 0.5 m crank's pin moves in 5 degrees
|
||||
ROLL_FINEST = 0.3 # degrees: the half width under which a bin of rolls that falls short is refused instead of halved (5 degrees halved 4 times)
|
||||
|
||||
|
||||
|
|
@ -211,23 +220,52 @@ def dof(parent, parent_socket: dict):
|
|||
return core.load_kit(str(parent.get(KIT, "")))["socketTypes"][parent_socket["type"]].get("dof")
|
||||
|
||||
|
||||
def connection_kind(obj) -> tuple:
|
||||
"""(DOF kind, parent socket type) of the connection a child states, from the parent's kit by the socket's name
|
||||
alone (a socket's type is the same at every params), or (None, None) when it cannot be read: no parent, a
|
||||
parent that is no kit part, a socket the part does not have."""
|
||||
try:
|
||||
kit = core.load_kit(str(obj.parent.get(KIT, "")))
|
||||
socket_type = next(s["type"] for s in core.part(kit, str(obj.parent[PART]))["sockets"] if s["name"] == obj.get(PARENT_SOCKET))
|
||||
return kit["socketTypes"][socket_type].get("dof"), socket_type
|
||||
except (AttributeError, KeyError, StopIteration, core.KitError):
|
||||
return None, None
|
||||
|
||||
|
||||
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
|
||||
"""The joint record a child's connection states, {limits: (lo, hi) or None, mechanism, compliance, follows}:
|
||||
degrees of its roll on a revolute joint, metres of its slide on a prismatic one; follows is None or {driver (the
|
||||
object, None once it is gone, as closure's other part), kind 'ratio' | 'loop', k, offset}. Every report, the joints report, the
|
||||
poses and hose read it here. A value written by hand that write_connections would not have written reads None:
|
||||
one that is not of its shape, and one record_refusal refuses for this connection's DOF kind (a compliance on a
|
||||
revolute joint), so no report emits it and the next write clears it."""
|
||||
lo, hi, label, spring, follows = obj.get(LIMIT_MIN), obj.get(LIMIT_MAX), obj.get(MECHANISM), None, 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}
|
||||
with contextlib.suppress(ValueError, TypeError):
|
||||
follows = json.loads(obj.get(FOLLOWS, "null"))
|
||||
ratio = (isinstance(follows, dict) and set(follows) == {"kind", "k", "offset"} and follows["kind"] == "ratio"
|
||||
and core.finite(follows["k"]) and follows["k"] != 0 and core.finite(follows["offset"]))
|
||||
driver = obj.get(FOLLOWS_DRIVER)
|
||||
record = {"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,
|
||||
"follows": {"driver": driver if isinstance(driver, bpy.types.Object) and driver.users_collection else None, "kind": follows["kind"],
|
||||
"k": float(follows["k"]) if ratio else None, "offset": float(follows["offset"]) if ratio else None}
|
||||
if ratio or follows == {"kind": "loop"} else None}
|
||||
kind, socket_type = connection_kind(obj)
|
||||
for field in ("limits", "mechanism", "compliance", "follows"): # limits first: a compliance is read beside the limits that stand
|
||||
alone = {**dict.fromkeys(record), "limits": record["limits"] if field == "compliance" else None, field: record[field]}
|
||||
if record[field] is not None and record_refusal(kind, socket_type, alone) is not None:
|
||||
record[field] = None
|
||||
return record
|
||||
|
||||
|
||||
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"
|
||||
return (f"socket type {socket_type!r} states no dof: the connection is rigid and carries no limits, mechanism, compliance or follows"
|
||||
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"
|
||||
|
|
@ -319,38 +357,221 @@ def seat(child, basis) -> None:
|
|||
child.matrix_basis = Matrix(np.asarray(basis).tolist())
|
||||
|
||||
|
||||
def connection_checks(entries) -> list:
|
||||
"""What write_connections writes for `entries`, each checked: (child, parent, sockets, socket, parent socket,
|
||||
roll, slide, DOF kind, record). An entry is (child, parent, mated()'s sockets for `stated`, stated, the joint
|
||||
record to state or None to keep the one the child states). Refuses, naming the connection, 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 answered is that
|
||||
representative. Writes nothing."""
|
||||
checked = []
|
||||
for child, parent, sockets, stated, record in entries:
|
||||
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.")
|
||||
checked.append((child, parent, sockets, socket, parent_socket, roll, slide, kind, record))
|
||||
return checked
|
||||
|
||||
|
||||
def write_connections(entries) -> None:
|
||||
"""State connections and seat them, all or none: each child's parent, its derived matrix_basis, its three
|
||||
properties and its joint record, kit_follows and its driver pointer with it. Every entry is checked
|
||||
(connection_checks) before any is written, so one refusal leaves every part as it stood. attach, set_params,
|
||||
roll, aim, reach, slide, joint and follow write a connection here and nowhere else, so what a joint record may
|
||||
be, and that a follower's value is written with its driver's, is decided here."""
|
||||
for child, parent, sockets, socket, parent_socket, roll, slide, kind, record in connection_checks(entries):
|
||||
child.parent = parent
|
||||
seat(child, core.mate(*sockets, roll, slide))
|
||||
child[SOCKET], child[PARENT_SOCKET], child[ROLL] = socket, parent_socket, roll
|
||||
(lo, hi), follows = record["limits"] or (None, None), record["follows"]
|
||||
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]
|
||||
for key in (FOLLOWS, FOLLOWS_DRIVER):
|
||||
if key in child and (follows is None or follows["driver"] is None and key == FOLLOWS_DRIVER):
|
||||
del child[key]
|
||||
if follows is not None:
|
||||
child[FOLLOWS] = json.dumps({key: follows[key] for key in ("kind", "k", "offset") if follows[key] is not None}, sort_keys=True)
|
||||
if follows is not None and follows["driver"] is not None:
|
||||
child[FOLLOWS_DRIVER] = follows["driver"]
|
||||
|
||||
|
||||
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, 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]
|
||||
"""write_connections for one connection."""
|
||||
write_connections([(child, parent, sockets, stated, record)])
|
||||
|
||||
|
||||
def followers(driver) -> list:
|
||||
"""The parts whose connection states that it follows `driver`, by name."""
|
||||
return sorted((o for o in bpy.data.objects if o.get(FOLLOWS_DRIVER) == driver and o.users_collection and joint_record(o)["follows"] is not None),
|
||||
key=lambda o: o.name)
|
||||
|
||||
|
||||
def loop_pair(obj, stating=None):
|
||||
"""(the parent follower, the closing follower) of the loop a loop follower is one of, or None when it has no
|
||||
partner. The closing follower states the closure and its parent is the other: both follow one driver as a
|
||||
loop, and the parent follower states no closure (follow and close keep it so)."""
|
||||
def loop_of(o):
|
||||
follows = (stating or {}).get(o) or joint_record(o)["follows"]
|
||||
return follows["driver"] if follows is not None and follows["kind"] == "loop" else None
|
||||
driver = loop_of(obj)
|
||||
if driver is None:
|
||||
return None
|
||||
if CLOSE in obj:
|
||||
return (obj.parent, obj) if obj.parent is not None and CLOSE not in obj.parent and loop_of(obj.parent) == driver else None
|
||||
closing = [child for child in sorted(attached(obj), key=lambda o: o.name) if CLOSE in child and loop_of(child) == driver]
|
||||
return (obj, closing[0]) if closing else None
|
||||
|
||||
|
||||
def driven(driver, sockets, stated, roll: float, slide: float, record, stating=None) -> tuple[list, list]:
|
||||
"""(the entries write_connections takes, [{part, value}]) for a connection given a new value and everything
|
||||
that follows it: the one place a follower's value is derived. `stating` is {part: follows} for followers a
|
||||
follow is about to state. With no follower the entry is the connection's own. With some, the driver steps from
|
||||
its stated value to the new one in ceil(|change| / step) steps (ROLL_STEP degrees, FOLLOW_SLIDE_STEP metres; at
|
||||
least one, so posing a driver where it stands derives its followers again), and each step places ratio followers
|
||||
(k x the driver's value + offset) and then solves each loop (core.close_loop, seeded by the step before) in an
|
||||
order where a loop's base and the part it closes on are placed before it. Worlds are composed from stated mates
|
||||
and the scene's matrices; nothing is written. Only the last step is answered. Refuses a ratio whose driver
|
||||
states no limits, a loop without its partner or its closure, loops that wait on each other, and what close_loop
|
||||
refuses, naming the driver's value and the closing part."""
|
||||
stating, kits = stating or {}, {}
|
||||
own = (driver, driver.parent, sockets, (stated[0], stated[1], roll, slide), record)
|
||||
found = sorted({*followers(driver), *stating}, key=lambda o: o.name)
|
||||
kind = dof(driver.parent, sockets[0])
|
||||
if not found or kind is None:
|
||||
return [own], []
|
||||
*_, roll, slide, _, record = connection_checks([own])[0] # the driver's value as it will be written, or its refusal
|
||||
revolute = kind == "revolute"
|
||||
old, new = (stated[2], roll) if revolute else (stated[3], slide)
|
||||
change = core._wrapped(new - old) if revolute and record["limits"] is None else new - old
|
||||
count = max(1, math.ceil(abs(change) / (ROLL_STEP if revolute else FOLLOW_SLIDE_STEP)))
|
||||
|
||||
def read(obj):
|
||||
part, built = built_part(obj, kits)
|
||||
said = link(obj)
|
||||
if said is None or obj.parent is None:
|
||||
raise Refused(f"{obj.name!r} follows {driver.name!r} and states no connection: brokkr_kitbash.follow with record null clears it; nothing changed.")
|
||||
mates = mated(obj.parent, *built_part(obj.parent, kits), obj, part, built, said)
|
||||
return mates, dof(obj.parent, mates[0]), said, {**joint_record(obj), **({"follows": stating[obj]} if obj in stating else {})}
|
||||
|
||||
links = {obj: read(obj) for obj in found}
|
||||
links[driver] = (sockets, kind, stated, record)
|
||||
ratios, loops = [obj for obj in found if links[obj][3]["follows"]["kind"] == "ratio"], []
|
||||
if ratios and record["limits"] is None:
|
||||
raise Refused(f"{driver.name!r} on {driver.parent.name!r}: {ratios[0].name!r} follows it by ratio, and a ratio's driver states limits (its value is then "
|
||||
"one number, not one of many a turn apart): give it limits with brokkr_kitbash.joint; nothing changed.")
|
||||
for obj in found:
|
||||
if obj in ratios or CLOSE not in obj and loop_pair(obj, stating) is not None:
|
||||
continue
|
||||
pair, closing = loop_pair(obj, stating), closure(obj)
|
||||
if pair is None or closing is None or closing[1] is None:
|
||||
raise Refused(f"{obj.name!r} follows {driver.name!r} as a loop and has no {'partner (a closing part and its parent, both following the driver)' if pair is None else 'part to close on'}: "
|
||||
"brokkr_kitbash.follow with record null clears it; nothing changed.")
|
||||
other_part, other_built = built_part(closing[1], kits)
|
||||
there, here = mated(closing[1], other_part, other_built, obj, *built_part(obj, kits), (closing[0], closing[2], 0.0, 0.0), "closing on")
|
||||
joints = [({**links[o][0][0], "matrix": links[o][0][0]["matrix"] @ core._roll(links[o][2][2])} if links[o][1] == "prismatic" else links[o][0][0],
|
||||
links[o][0][1], links[o][1]) for o in pair]
|
||||
loops.append({"pair": pair, "base": pair[0].parent, "to": closing[1], "there": there, "here": here, "joints": joints,
|
||||
"seed": tuple(links[o][2][2] if links[o][1] == "revolute" else links[o][2][3] for o in pair)})
|
||||
|
||||
def above(obj) -> set:
|
||||
found = set()
|
||||
while obj is not None:
|
||||
found.add(obj)
|
||||
obj = obj.parent
|
||||
return found
|
||||
|
||||
ordered, waiting = [], list(loops) # a loop waits on every loop one of whose pair is its base, the part it closes on, or above either
|
||||
while waiting:
|
||||
ready = [loop for loop in waiting if not any(set(other["pair"]) & (above(loop["base"]) | above(loop["to"])) for other in waiting if other is not loop)]
|
||||
if not ready:
|
||||
raise Refused(f"{driver.name!r}: the loops closing at {', '.join(repr(loop['pair'][1].name) for loop in waiting)} each wait on another: "
|
||||
"a loop's base and the part it closes on are placed before it is solved; nothing changed.")
|
||||
ordered.append(ready[0])
|
||||
waiting.remove(ready[0])
|
||||
values = {}
|
||||
|
||||
def world(obj, memo):
|
||||
if obj not in memo:
|
||||
if obj.parent is None:
|
||||
memo[obj] = np.array(obj.matrix_world, dtype=np.float64)
|
||||
elif obj in values:
|
||||
memo[obj] = world(obj.parent, memo) @ core.mate(*links[obj][0], *values[obj])
|
||||
else: # it moves with its parent as it stands on it
|
||||
memo[obj] = world(obj.parent, memo) @ np.linalg.inv(np.array(obj.parent.matrix_world, dtype=np.float64)) @ np.array(obj.matrix_world, dtype=np.float64)
|
||||
return memo[obj]
|
||||
|
||||
def valued(obj, value):
|
||||
return (value, links[obj][2][3]) if links[obj][1] == "revolute" else (links[obj][2][2], value)
|
||||
|
||||
for step in range(1, count + 1):
|
||||
at = new if step == count else old + change * step / count
|
||||
values = {driver: valued(driver, at)}
|
||||
for obj in ratios:
|
||||
values[obj] = valued(obj, links[obj][3]["follows"]["k"] * at + links[obj][3]["follows"]["offset"])
|
||||
for loop in ordered:
|
||||
memo = {}
|
||||
try:
|
||||
loop["seed"], _ = core.close_loop(world(loop["base"], memo), loop["joints"], loop["here"], world(loop["to"], memo) @ loop["there"]["matrix"], loop["seed"])
|
||||
except core.KitError as error:
|
||||
raise Refused(f"{driver.name!r} at {at:.6g}: the loop {loop['pair'][1].name!r} closes on {loop['to'].name!r} ({loop['pair'][0].name!r} and "
|
||||
f"{loop['pair'][1].name!r} follow): {error}; nothing changed.") from None
|
||||
for obj, value in zip(loop["pair"], loop["seed"]):
|
||||
values[obj] = valued(obj, value)
|
||||
entries, moved = [own], []
|
||||
for obj in (*ratios, *(obj for loop in ordered for obj in loop["pair"])):
|
||||
mates, its_kind, said, its_record = links[obj]
|
||||
value = values[obj][0] if its_kind == "revolute" else values[obj][1]
|
||||
if its_kind == "revolute" and its_record["limits"] is None:
|
||||
value = core._wrapped(value) # a derived roll has no turn to keep
|
||||
entries.append((obj, obj.parent, mates, (said[0], said[1], *valued(obj, value)), its_record))
|
||||
moved.append({"part": obj.name, "value": round(value, 6)})
|
||||
return entries, moved
|
||||
|
||||
|
||||
def follows_report(obj, record: dict, kind, stated) -> dict | None:
|
||||
"""None for a connection that follows nothing, else {driver, kind, k, offset, holds, reason}. A ratio holds when
|
||||
the value stands within HELD of k x the driver's + offset (a roll: of a turn of it); a loop when the closure its
|
||||
closing part states holds. holds is false with a reason when the driver is gone or states no DOF connection.
|
||||
Derived at each report; stored nowhere."""
|
||||
follows = record["follows"]
|
||||
if follows is None:
|
||||
return None
|
||||
driver = follows["driver"]
|
||||
row = {"driver": driver and driver.name, "kind": follows["kind"], "k": follows["k"], "offset": follows["offset"], "holds": False, "reason": None}
|
||||
said, driver_kind = (link(driver), connection_kind(driver)[0]) if driver is not None else (None, None)
|
||||
if driver is None:
|
||||
row["reason"] = "the driver is gone: deleted, or in no collection"
|
||||
elif said is None or driver_kind is None or said[2] is None or said[3] is None:
|
||||
row["reason"] = "the driver states no DOF connection"
|
||||
elif follows["kind"] == "ratio":
|
||||
want = follows["k"] * (said[2] if driver_kind == "revolute" else said[3]) + follows["offset"]
|
||||
off = abs(core._wrapped(stated[2] - want)) if kind == "revolute" else abs(stated[3] - want)
|
||||
if off > HELD:
|
||||
row["reason"] = f"its value stands {off:.6g} from k x the driver's + offset: pose the driver"
|
||||
else:
|
||||
pair = loop_pair(obj)
|
||||
found = closure_report(pair[1], *built_part(pair[1])) if pair is not None else None
|
||||
if found is None:
|
||||
row["reason"] = "its loop has no partner: a closing part and its parent, both following the driver"
|
||||
elif not found["holds"]:
|
||||
row["reason"] = f"the closure {pair[1].name!r} states does not hold ({found['reason']}): pose the driver"
|
||||
row["holds"] = row["reason"] is None
|
||||
return row
|
||||
|
||||
|
||||
def connection_report(obj, part, built):
|
||||
|
|
@ -359,7 +580,7 @@ def connection_report(obj, part, built):
|
|||
stands within HELD of core.mate. A child moved or re-parented by another action reads holds false until
|
||||
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."""
|
||||
outside its limits; and follows (follows_report), null for a connection that follows nothing."""
|
||||
stated = link(obj)
|
||||
if stated is None:
|
||||
return None
|
||||
|
|
@ -367,7 +588,7 @@ def connection_report(obj, part, built):
|
|||
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,
|
||||
"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}
|
||||
"mechanism": record["mechanism"], "compliance": record["compliance"], "within": True, "follows": None}
|
||||
try:
|
||||
if obj.parent is None or stated[2] is None or stated[3] is None:
|
||||
return row
|
||||
|
|
@ -378,6 +599,7 @@ def connection_report(obj, part, built):
|
|||
return row
|
||||
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["follows"] = follows_report(obj, record, row["dof"], stated)
|
||||
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
|
||||
|
|
@ -699,7 +921,9 @@ class BROKKR_KITBASH_OT_place_part(PolishOperator):
|
|||
class BROKKR_KITBASH_OT_set_params(PolishOperator):
|
||||
"""Change params of a placed kit part and rebuild its mesh in place: its modifiers and material slots stay,
|
||||
each shape keeps its faces' material, the Bevel width follows, and its connection and those of the parts
|
||||
attached to it are seated again on the moved sockets; a closure is never seated, only reported"""
|
||||
attached to it are seated again on the moved sockets, through write_connections (a value outside its joint's
|
||||
limits or a stray slide, written by hand, is refused before anything changes); a closure is never seated and a
|
||||
follower never derived again, only reported"""
|
||||
bl_idname = "brokkr_kitbash.set_params"
|
||||
bl_label = "Set Kit Part Params"
|
||||
object_name: bpy.props.StringProperty(name="Object")
|
||||
|
|
@ -717,15 +941,16 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator):
|
|||
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, 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
|
||||
entries, stated = [], link(obj) # every connection this part is an end of, checked against its new sockets and its joint record 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:])))
|
||||
entries.append((obj, obj.parent, mated(obj.parent, parent_part, parent_built, obj, part, built, stated), stated, None))
|
||||
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:])))
|
||||
entries.append((child, obj, mated(obj, part, built, child, child_part, child_built, link(child)), link(child), None))
|
||||
connection_checks(entries)
|
||||
try:
|
||||
old = core.build(part, stored)
|
||||
except core.KitError: # stored params an edited kit no longer admits: nothing to map faces by
|
||||
|
|
@ -738,9 +963,8 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator):
|
|||
obj.data.update()
|
||||
sync_bevel(obj, built.bevel)
|
||||
obj[PARAMS] = json.dumps(built.params)
|
||||
for seated, basis in seats: # deeper descendants follow through parenting: their sockets did not move
|
||||
seat(seated, basis)
|
||||
if seats:
|
||||
write_connections(entries) # deeper descendants follow through parenting: their sockets did not move
|
||||
if entries:
|
||||
context.view_layer.update()
|
||||
report = part_report(obj, part, built)
|
||||
report["closures"] = scene_closures(context, report, (obj,))
|
||||
|
|
@ -778,14 +1002,15 @@ class BROKKR_KITBASH_OT_attach(PolishOperator):
|
|||
sockets = mated(parent, parent_part, parent_built, child, part, built, stated)
|
||||
free(parent, self.parent_socket)
|
||||
free(child, self.socket)
|
||||
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
|
||||
write_connection(child, parent, sockets, stated, dict.fromkeys(("limits", "mechanism", "compliance", "follows"))) # a new connection states no joint record: brokkr_kitbash.joint and follow give it one
|
||||
context.view_layer.update()
|
||||
return part_report(child, part, built)
|
||||
|
||||
|
||||
class BROKKR_KITBASH_OT_detach(PolishOperator):
|
||||
"""Clear a kit part's connection and the closure it states: it stays where it stands in the world, loses its
|
||||
parent, and the parts attached to it stay attached to it"""
|
||||
parent, and the parts attached to it stay attached to it. A loop follower's partner stops following with it; a
|
||||
driver's followers keep their statements and report that the driver states no DOF connection"""
|
||||
bl_idname = "brokkr_kitbash.detach"
|
||||
bl_label = "Detach Kit Part"
|
||||
object_name: bpy.props.StringProperty(name="Object")
|
||||
|
|
@ -796,6 +1021,7 @@ class BROKKR_KITBASH_OT_detach(PolishOperator):
|
|||
if SOCKET not in obj and CLOSE not in obj:
|
||||
raise Refused(f"{obj.name!r} is not attached (it has no {SOCKET} property) and states no closure; nothing changed.")
|
||||
part, built = built_part(obj)
|
||||
pair = loop_pair(obj) # a loop follower's partner follows nothing once the loop is gone
|
||||
if SOCKET in obj:
|
||||
world = obj.matrix_world.copy()
|
||||
obj.parent = None
|
||||
|
|
@ -803,17 +1029,24 @@ class BROKKR_KITBASH_OT_detach(PolishOperator):
|
|||
for key in (SOCKET, PARENT_SOCKET, ROLL, *RECORD, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET):
|
||||
if key in obj:
|
||||
del obj[key]
|
||||
for other in pair or ():
|
||||
for key in (FOLLOWS, FOLLOWS_DRIVER):
|
||||
if key in other:
|
||||
del other[key]
|
||||
return part_report(obj, part, built)
|
||||
|
||||
|
||||
def pose(context, name: str, solve) -> dict:
|
||||
def pose(context, name: str, solve, keeps: bool = False) -> dict:
|
||||
"""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."""
|
||||
has no parent, what mated() refuses and what write_connections does: a value outside the joint's limits. A
|
||||
follower's value is derived: it is refused here, naming its driver, unless the solve `keeps` the value (joint's).
|
||||
A driver's followers are derived with it (driven) and written with it in one write_connections: one of them
|
||||
outside its own limits, or a loop that cannot close, refuses the pose with nothing changed. The report is the
|
||||
part's with followers, [{part, value}] in the order written, and, as set_params', every closure in the scene
|
||||
with the part's own first: a pose can open one, and seats none but those of the loops that follow it."""
|
||||
child = mesh_object(name)
|
||||
part, built = built_part(child)
|
||||
stated = link(child)
|
||||
|
|
@ -822,13 +1055,18 @@ def pose(context, name: str, solve) -> dict:
|
|||
if child.parent is None:
|
||||
raise Refused(f"{child.name!r} states a connection and has no parent: detach it to clear the connection; nothing changed.")
|
||||
sockets = mated(child.parent, *built_part(child.parent), child, part, built, stated)
|
||||
follows = joint_record(child)["follows"]
|
||||
if follows is not None and not keeps:
|
||||
raise Refused(f"{child.name!r} follows {repr(follows['driver'].name) if follows['driver'] else 'a driver that is gone'} ({follows['kind']}): its value is derived. "
|
||||
"Pose the driver, or clear the statement with brokkr_kitbash.follow and record null; nothing changed.")
|
||||
try:
|
||||
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), float(slide)), record)
|
||||
entries, moved = driven(child, sockets, stated, float(roll), float(slide), record)
|
||||
write_connections(entries)
|
||||
context.view_layer.update()
|
||||
report = {**part_report(child, part, built), **solved}
|
||||
report = {**part_report(child, part, built), **solved, "followers": moved}
|
||||
report["closures"] = scene_closures(context, report, (child,))
|
||||
return report
|
||||
|
||||
|
|
@ -902,7 +1140,7 @@ class BROKKR_KITBASH_OT_reach(PolishOperator):
|
|||
|
||||
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"""
|
||||
its compliance. A follower keeps its derived value; a driver's followers are derived again"""
|
||||
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")
|
||||
|
|
@ -926,7 +1164,7 @@ class BROKKR_KITBASH_OT_joint(PolishOperator):
|
|||
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")}
|
||||
record = {key: joint[key] for key in ("limits", "mechanism", "compliance", "follows")}
|
||||
if "limits" in given:
|
||||
record["limits"] = limits and (float(limits[0]), float(limits[1]))
|
||||
if "mechanism" in given:
|
||||
|
|
@ -934,7 +1172,7 @@ class BROKKR_KITBASH_OT_joint(PolishOperator):
|
|||
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)
|
||||
return pose(context, self.object_name, solve, keeps=True)
|
||||
|
||||
|
||||
class BROKKR_KITBASH_OT_slide(PolishOperator):
|
||||
|
|
@ -958,38 +1196,137 @@ class BROKKR_KITBASH_OT_slide(PolishOperator):
|
|||
|
||||
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"""
|
||||
parent joint, axis, value, limits, mechanism, compliance and what drives it, 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")
|
||||
object_name: bpy.props.StringProperty(name="Object", description="The root: a kit part; the report is of its own joint, when it states one, and of what is attached below it")
|
||||
after: bpy.props.StringProperty(name="After", description="Empty, or the id of a row: the report carries the rows after it (the `next` of the report before)")
|
||||
|
||||
@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)]
|
||||
todo = [(root, None)]
|
||||
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
|
||||
if child != root or link(child) is not None and child.parent is not None and PART in child.parent: # the root's own joint comes first, parent null
|
||||
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 += child != root
|
||||
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, follows = record["limits"] and [round(v, 6) for v in record["limits"]], record["follows"]
|
||||
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"],
|
||||
"driven": follows and {"by": follows["driver"] and follows["driver"].name, "kind": follows["kind"], "k": follows["k"], "offset": follows["offset"]}})
|
||||
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 = {"schema": "brokkr.joints", "version": 2, "root": root.name, "frame": "the root object's: Blender axes (+Z up), metres", "rigid": rigid_count,
|
||||
"unlimited": [row["id"] for row in rows if row["limits"] is None and row["driven"] is None], "next": "x" * 63}
|
||||
if self.after:
|
||||
ids = [row["id"] for row in rows]
|
||||
if self.after not in ids:
|
||||
raise Refused(f"after {self.after!r} is not the id of a joint under {root.name!r}: it is the `next` of the report before, or empty.")
|
||||
rows = rows[ids.index(self.after) + 1:]
|
||||
report["joints"] = fitted(report, "joints", rows)
|
||||
report["next"] = report["joints"][-1]["id"] if "jointsOmitted" in report and report["joints"] else None
|
||||
return report
|
||||
|
||||
|
||||
class BROKKR_KITBASH_OT_follow(PolishOperator):
|
||||
"""State that an attached kit part's joint follows another's: its value is derived from the driver's, by a ratio
|
||||
or by closing the loop its closure states, whenever the driver is posed"""
|
||||
bl_idname = "brokkr_kitbash.follow"
|
||||
bl_label = "Follow Kit Joint"
|
||||
object_name: bpy.props.StringProperty(name="Object", description="The follower: a part attached on a revolute or prismatic socket; for a loop, the part that states the closure")
|
||||
record: bpy.props.StringProperty(name="Record", default="null", description='{"driver": name, "kind": "ratio", "k": number, "offset": number}, '
|
||||
'{"driver": name, "kind": "loop"}, or null to clear')
|
||||
|
||||
@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
|
||||
ratio = isinstance(given, dict) and set(given) == {"driver", "kind", "k", "offset"} and given["kind"] == "ratio"
|
||||
if not (given is None or isinstance(given, dict) and isinstance(given.get("driver"), str) and (
|
||||
ratio and core.finite(given["k"]) and given["k"] != 0 and core.finite(given["offset"]) or set(given) == {"driver", "kind"} and given["kind"] == "loop")):
|
||||
raise Refused('record must be {"driver": name, "kind": "ratio", "k": a number that is not 0, "offset": a number}, {"driver": name, "kind": "loop"}, '
|
||||
"or null to clear; nothing changed.")
|
||||
obj = mesh_object(self.object_name)
|
||||
part, built = built_part(obj)
|
||||
|
||||
def connection(o, what):
|
||||
"""(sockets, stated, DOF kind) of the DOF connection a part states, or the refusal that names what it is here."""
|
||||
said = link(o)
|
||||
if said is None or o.parent is None:
|
||||
raise Refused(f"{o.name!r} ({what}) is not attached: attach gives it a connection; nothing changed.")
|
||||
mates = mated(o.parent, *built_part(o.parent), o, *built_part(o), said)
|
||||
if dof(o.parent, mates[0]) is None:
|
||||
raise Refused(f"{o.name!r} ({what}) on {o.parent.name!r}: socket type {mates[0]['type']!r} states no dof: the connection is rigid, "
|
||||
"and only a revolute or prismatic connection follows or drives; nothing changed.")
|
||||
return mates, said, dof(o.parent, mates[0])
|
||||
|
||||
sockets, stated, _ = connection(obj, "the follower")
|
||||
current = joint_record(obj)["follows"]
|
||||
if given is None:
|
||||
if current is None:
|
||||
raise Refused(f"{obj.name!r} follows nothing; nothing changed.")
|
||||
cleared = loop_pair(obj) or (obj,)
|
||||
write_connections([(o, o.parent, connection(o, "a follower")[0], link(o), {**joint_record(o), "follows": None}) for o in cleared])
|
||||
context.view_layer.update()
|
||||
return {**part_report(obj, part, built), "cleared": [o.name for o in cleared]}
|
||||
driver = mesh_object(given["driver"])
|
||||
pair = (obj,) if ratio else (obj.parent, obj)
|
||||
if not ratio:
|
||||
connection(obj.parent, "the follower's parent: a loop's two unknowns are the closing part's joint and its parent's")
|
||||
closing = closure(obj)
|
||||
if not ratio and (closing is None or closing[1] is None or not closure_report(obj, part, built)["holds"]):
|
||||
raise Refused(f"{obj.name!r} states no closure that holds: a loop follower is the part that states the closure (brokkr_kitbash.close, where the "
|
||||
"two sockets meet), and its joint and its parent's are solved to keep it; nothing changed.")
|
||||
if not ratio and CLOSE in obj.parent:
|
||||
raise Refused(f"{obj.parent.name!r}, the parent of {obj.name!r}, states a closure itself: a loop's parent follower states none; nothing changed.")
|
||||
driver_sockets, driver_stated, _ = connection(driver, "the driver")
|
||||
if joint_record(driver)["follows"] is not None:
|
||||
raise Refused(f"{driver.name!r} is itself a follower: a driver is never a follower (one joint, one driver); nothing changed.")
|
||||
for o in pair:
|
||||
below = driver
|
||||
while below is not None and below != o:
|
||||
below = below.parent
|
||||
if below == o:
|
||||
raise Refused(f"{driver.name!r} is {'the follower itself' if driver == o else 'below ' + repr(o.name)}: a follower's driver is neither it nor below it; nothing changed.")
|
||||
if joint_record(o)["follows"] is not None:
|
||||
raise Refused(f"{o.name!r} already follows: clear it first (brokkr_kitbash.follow with record null); nothing changed.")
|
||||
if followers(o):
|
||||
raise Refused(f"{o.name!r} drives {followers(o)[0].name!r}: a driver is never a follower (one joint, one driver); nothing changed.")
|
||||
if ratio and joint_record(driver)["limits"] is None:
|
||||
raise Refused(f"{driver.name!r} states no limits: a ratio's driver states them (its value is then one number, not one of many a turn apart); "
|
||||
"brokkr_kitbash.joint gives it limits; nothing changed.")
|
||||
if not ratio:
|
||||
moving = {driver, *followers(driver)} # what moves when the driver is posed: it, what follows it, and what hangs from either
|
||||
|
||||
def moves(o) -> bool:
|
||||
while o is not None and o not in moving:
|
||||
o = o.parent
|
||||
return o is not None
|
||||
ends = (obj.parent.parent, closing[1])
|
||||
if moves(ends[0]) == moves(ends[1]):
|
||||
raise Refused(f"the loop's two ends, {ends[0].name!r} (the base) and {ends[1].name!r} (closed on), {'both move' if moves(ends[0]) else 'neither moves'} with "
|
||||
f"{driver.name!r}: exactly one of them is the driver, follows it, or hangs from one that does; nothing changed.")
|
||||
follows = {"driver": driver, "kind": given["kind"], "k": float(given["k"]) if ratio else None, "offset": float(given["offset"]) if ratio else None}
|
||||
entries, moved = driven(driver, driver_sockets, driver_stated, driver_stated[2], driver_stated[3], None, {o: follows for o in pair})
|
||||
write_connections(entries)
|
||||
context.view_layer.update()
|
||||
report = {**part_report(obj, part, built), "followers": moved}
|
||||
report["closures"] = scene_closures(context, report, (obj,))
|
||||
return report
|
||||
|
||||
|
||||
|
|
@ -1013,6 +1350,8 @@ 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.")
|
||||
if (joint_record(obj)["follows"] or {}).get("kind") == "loop":
|
||||
raise Refused(f"{obj.name!r} follows as the parent of a loop: the closing part of a loop states its closure, and its parent states none; nothing changed.")
|
||||
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)
|
||||
|
|
@ -2134,7 +2473,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_joint, BROKKR_KITBASH_OT_slide, BROKKR_KITBASH_OT_joints, BROKKR_KITBASH_OT_follow,
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -445,7 +445,8 @@ try:
|
|||
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}
|
||||
receipt["status"] == "accepted" and {k: v for k, v in joints.items() if k != "joints"} == {"schema": "brokkr.joints", "version": 2, "root": "Tank", "frame": "the root object's: Blender axes (+Z up), metres", "rigid": 2,
|
||||
"unlimited": ["Barrel", "Toe", "Ram"], "next": None}
|
||||
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,
|
||||
|
|
@ -466,8 +467,9 @@ try:
|
|||
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)
|
||||
check("under another root the rows are in its frame and begin with the root's own joint, parent null", receipt["status"] == "accepted"
|
||||
and [(row["id"], row["parent"]) for row in below["joints"]] == [("Hinge", None), ("Toe", "Hinge")] and below["rigid"] == 1 and below["unlimited"] == ["Toe"]
|
||||
and float(np.abs((np.linalg.inv(np.array(hinge.matrix_world, dtype=np.float64)) @ frame(foot, "pivot"))[:3, 3] - below["joints"][1]["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 -------------------------------------------------------------------------------------------
|
||||
|
|
|
|||
|
|
@ -2439,6 +2439,30 @@ class OwnershipTests(unittest.TestCase):
|
|||
for path in schemas:
|
||||
self.assertIsNone(re.search(self.SCHEMAS, path.read_text(encoding="utf-8", errors="replace")), path.name)
|
||||
|
||||
def test_a_follower_has_one_writer_and_one_place_it_is_derived(self):
|
||||
"""The negative patterns of cut kit-follows-2: kit_follows and its driver pointer are written only inside
|
||||
write_connections; set_params seats through it, its checks before the mesh is rebuilt; no linkage record is
|
||||
stored and no Blender driver or constraint is made; close_loop is called from driven alone."""
|
||||
source = self.sources()["__init__.py"]
|
||||
writer = source.split("\ndef write_connections(")[1].split("\n\n\n")[0]
|
||||
writes = r"\[FOLLOWS(?:_DRIVER)?\] ="
|
||||
self.assertEqual(re.findall(writes, source), re.findall(writes, writer))
|
||||
self.assertEqual(len(re.findall(writes, writer)), 2)
|
||||
for name, text in self.sources().items():
|
||||
self.assertIsNone(re.search("kit_" "drive" r"\b", text), name)
|
||||
self.assertIsNone(re.search(r"seat\(seated|driver_add\(|constraints\.new\(", source))
|
||||
self.assertEqual(source.count("seat("), 5) # its def, write_connections, and a cutter's, a ribs' and a hose's own frames
|
||||
body = source.split("class BROKKR_KITBASH_OT_set_params(")[1].split("class BROKKR_KITBASH_OT_")[0]
|
||||
self.assertLess(body.index("connection_checks(entries)"), body.index("clear_geometry()"))
|
||||
self.assertLess(body.index("clear_geometry()"), body.index("write_connections(entries)"))
|
||||
self.assertEqual(source.count("core.close_loop("), 1)
|
||||
self.assertIn("core.close_loop(", source.split("\ndef driven(")[1].split("\n\n\n")[0])
|
||||
self.assertEqual(source.count("write_connections(["), 2) # write_connection, and follow clearing a statement
|
||||
pose = source.split("\ndef pose(")[1].split("\n\n\n")[0]
|
||||
self.assertLess(pose.index("if follows is not None and not keeps:"), pose.index("= solve(child"))
|
||||
self.assertEqual(source.count("keeps=True"), 1)
|
||||
self.assertIn("keeps=True", source.split("class BROKKR_KITBASH_OT_joint(")[1].split("class BROKKR_KITBASH_OT_")[0])
|
||||
|
||||
def test_only_cut_boolean_and_ribs_evaluate_a_modifier_stack(self):
|
||||
"""An Exact Boolean costs from tenths of a second to seconds: report, attach, detach and set_params read stored
|
||||
state only, and cut evaluates its target with the Booleans off."""
|
||||
|
|
@ -2574,23 +2598,26 @@ class OwnershipTests(unittest.TestCase):
|
|||
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] = socket, parent_socket, roll"])
|
||||
writer = 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_connections(")[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)
|
||||
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"])
|
||||
self.assertEqual(named, ["link", "joint_record", "mated", "write_connections", "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))
|
||||
self.assertEqual((callers, source.count("write_connection(")), (["attach"], 2)) # its def, which is write_connections for one, and attach
|
||||
callers = [name for name, body in bodies.items() if "write_connections(" in body]
|
||||
self.assertEqual((callers, source.count("write_connections("), source.split("def pose(")[1].split("\n\n\n")[0].count("write_connections(entries)")),
|
||||
(["set_params", "follow"], 6, 1)) # its def, write_connection, set_params, pose, and follow stating and clearing
|
||||
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"]))
|
||||
|
|
@ -2617,7 +2644,7 @@ class OwnershipTests(unittest.TestCase):
|
|||
self.assertIsNone(re.search(placing, bodies["close"]))
|
||||
for text in ("child.matrix_basis = basis", "obj.matrix_world = world", "obj.parent = other", "seat(obj, basis)"):
|
||||
self.assertIsNotNone(re.search(placing, text))
|
||||
self.assertIsNotNone(re.search(placing, source.split("def write_connection(")[1].split("\n\n\n")[0]))
|
||||
self.assertIsNotNone(re.search(placing, source.split("def write_connections(")[1].split("\n\n\n")[0]))
|
||||
|
||||
def test_the_patterns_bite(self):
|
||||
planted = ("value = eval(text)", "from brokkr_bridge import x", 'modifier.solver = "MANIFOLD"', "cutter.hide_render = True", 'obj["kit_parent"] = parent.name',
|
||||
|
|
|
|||
Loading…
Reference in a new issue