diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index d339078..96aeb51 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -71,6 +71,7 @@ bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), import contextlib import json import math +import re import bmesh import bpy @@ -88,6 +89,10 @@ from . import core, route KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" SOCKET, PARENT_SOCKET, ROLL = "kit_socket", "kit_parent_socket", "kit_roll" +SLIDE, LIMIT_MIN, LIMIT_MAX, MECHANISM, COMPLIANCE = "kit_slide", "kit_min", "kit_max", "kit_mechanism", "kit_compliance" # a connection's joint record; write_connection is its one writer +RECORD = (SLIDE, LIMIT_MIN, LIMIT_MAX, MECHANISM, COMPLIANCE) +LABEL = r"[a-z0-9_]{1,32}" # a mechanism label +TURN, TRAVEL, HERTZ, DAMPING = 360.0, 10.0, 30.0, 2.0 # what a joint record may state: degrees a revolute joint's limits span and stand from 0, metres a prismatic one's stand from 0, a compliance's hertz and damping ratio FROZEN = "kit_frozen" # on a frozen object: an ID pointer to its live mesh; its presence is the frozen state. hold writes it and nothing else does KEPT = "kit_kept" # on a live mesh a frozen object holds: an ID pointer to that object's frozen mesh, beside the fake user that keeps the live mesh through a purge. hold writes both CLOSE, CLOSE_TO, CLOSE_TO_SOCKET = "kit_close_socket", "kit_close_to", "kit_close_to_socket" @@ -190,13 +195,51 @@ def built_part(obj, kits=None): def link(obj): - """The connection a child states, (its socket, the parent's socket, roll in degrees), or None. The parent is - obj.parent and is stored nowhere else. attach, set_params, detach and every report read it here. A kit_roll - that is not a finite number (written by hand) is roll None: the connection is stated and cannot hold.""" + """The connection a child states, (its socket, the parent's socket, roll in degrees, slide in metres), or None. + The parent is obj.parent and is stored nowhere else. attach, set_params, detach and every report read it here. + A kit_roll or kit_slide that is not a finite number (written by hand) is None: the connection is stated and + cannot hold. An absent kit_slide is 0.""" if SOCKET not in obj: return None - roll = obj.get(ROLL, 0.0) - return str(obj[SOCKET]), str(obj.get(PARENT_SOCKET, "")), float(roll) if core.finite(roll) else None + roll, slide = obj.get(ROLL, 0.0), obj.get(SLIDE, 0.0) + return str(obj[SOCKET]), str(obj.get(PARENT_SOCKET, "")), float(roll) if core.finite(roll) else None, float(slide) if core.finite(slide) else None + + +def dof(parent, parent_socket: dict): + """The DOF kind of a connection on a socket of a part, 'revolute', 'prismatic' or None (rigid): what the + socket's type states in the parent's kit. Nothing else decides it: no part, socket or object name is read.""" + return core.load_kit(str(parent.get(KIT, "")))["socketTypes"][parent_socket["type"]].get("dof") + + +def joint_record(obj) -> dict: + """The joint record a child's connection states, {limits: (lo, hi) or None, mechanism, compliance}: degrees of + its roll on a revolute joint, metres of its slide on a prismatic one. Every report, the joints report, the + poses and hose read it here. A value written by hand that write_connection would not have written reads None.""" + lo, hi, label, spring = obj.get(LIMIT_MIN), obj.get(LIMIT_MAX), obj.get(MECHANISM), None + with contextlib.suppress(ValueError, TypeError): + spring = json.loads(obj.get(COMPLIANCE, "null")) + return {"limits": (float(lo), float(hi)) if core.finite(lo) and core.finite(hi) and lo <= hi else None, + "mechanism": label if isinstance(label, str) and re.fullmatch(LABEL, label) else None, + "compliance": spring if isinstance(spring, dict) and set(spring) == {"hertz", "damping_ratio"} and all(core.finite(v) for v in spring.values()) else None} + + +def record_refusal(kind, socket_type: str, record: dict) -> str | None: + """None when a connection of this DOF kind may carry the record, else why not.""" + limits, spring = record["limits"], record["compliance"] + if kind is None: + return (f"socket type {socket_type!r} states no dof: the connection is rigid and carries no limits, mechanism or compliance" + if any(value is not None for value in record.values()) else None) + if limits is not None and kind == "revolute" and (limits[1] - limits[0] > TURN or max(abs(limits[0]), abs(limits[1])) > TURN): + return f"limits {limits[0]:.6g} to {limits[1]:.6g}: a revolute joint's span at most {TURN:g} degrees, each end within {TURN:g} of 0" + if limits is not None and kind == "prismatic" and max(abs(limits[0]), abs(limits[1])) > TRAVEL: + return f"limits {limits[0]:.6g} to {limits[1]:.6g}: a prismatic joint's stand within {TRAVEL:g} m of 0" + if spring is not None and kind != "prismatic": + return f"compliance is a prismatic joint's (a slide that settles under load): socket type {socket_type!r} is {kind}" + if spring is not None and limits is None: + return "compliance needs limits: the travel the slide settles within" + if spring is not None and not (0.0 < spring["hertz"] <= HERTZ and 0.0 <= spring["damping_ratio"] <= DAMPING): + return f"compliance {spring}: hertz is over 0 and at most {HERTZ:g}, damping_ratio 0 to {DAMPING:g}" + return None def attached(obj) -> list: @@ -256,8 +299,8 @@ def mated(parent, parent_part, parent_built, child, child_part, child_built, sta it: a roll that is not a number, a socket name a part does not have, or sockets core.mate_refusal will not mate. The parts may be of two kits: they mate when both kits declare the socket's type alike. A closure is checked here too (how "closing on"), the part it names as the parent.""" - if stated[2] is None: - raise Refused(f"{child.name!r} on {parent.name!r}: its {ROLL} is not a number: detach it and attach it again; nothing changed.") + if stated[2] is None or stated[3] is None: + raise Refused(f"{child.name!r} on {parent.name!r}: its {ROLL if stated[2] is None else SLIDE} is not a number: detach it and attach it again; nothing changed.") try: sockets = core.joint(parent_part, parent_built, stated[1], child_part, child_built, stated[0]) kits = (parent_part["kit"], child_part["kit"]) @@ -276,33 +319,66 @@ def seat(child, basis) -> None: child.matrix_basis = Matrix(np.asarray(basis).tolist()) -def write_connection(child, parent, sockets, stated) -> None: - """State a connection and seat it: the child's parent, its derived matrix_basis and its three properties. - `sockets` is mated()'s answer for `stated`. attach, roll, aim and reach write a connection here and nowhere - else.""" +def write_connection(child, parent, sockets, stated, record=None) -> None: + """State a connection and seat it: the child's parent, its derived matrix_basis, its three properties and its + joint record. `sockets` is mated()'s answer for `stated`; `record` is the joint record to state (joint_record's + shape), None to keep the one the child states. attach, roll, aim, reach, slide and joint write a connection + here and nowhere else, so what a joint record may be is decided here: before anything is written it refuses a + record its DOF kind may not carry (record_refusal), a slide on a connection that is not prismatic, and a value + with no representative inside the limits (core.within), naming value and limits; the value written is that + representative.""" + kind, (socket, parent_socket, roll, slide) = dof(parent, sockets[0]), stated + record, here = joint_record(child) if record is None else record, f"{child.name!r} on {parent.name!r}" + refusal = record_refusal(kind, sockets[0]["type"], record) + if refusal is None and kind != "prismatic" and slide != 0.0: + refusal = f"socket type {sockets[0]['type']!r} is {kind or 'rigid'}: only a prismatic connection slides" + if refusal is None and record["limits"] is not None: + value = roll if kind == "revolute" else slide + inside = core.within(value, *record["limits"], kind == "revolute") + if inside is None: + refusal = (f"its {'roll' if kind == 'revolute' else 'slide'} {value:.6g} is outside the joint's limits " + f"{record['limits'][0]:.6g} to {record['limits'][1]:.6g}") + roll, slide = (inside, slide) if kind == "revolute" else (roll, inside) + if refusal: + raise Refused(f"{here}: {refusal}; nothing changed.") child.parent = parent - seat(child, core.mate(*sockets, stated[2])) - child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated + seat(child, core.mate(*sockets, roll, slide)) + child[SOCKET], child[PARENT_SOCKET], child[ROLL] = socket, parent_socket, roll + lo, hi = record["limits"] or (None, None) + for key, value in ((SLIDE, slide if kind == "prismatic" else None), (LIMIT_MIN, lo), (LIMIT_MAX, hi), (MECHANISM, record["mechanism"]), + (COMPLIANCE, record["compliance"] and json.dumps(record["compliance"], sort_keys=True))): + if value is not None: + child[key] = value + elif key in child: + del child[key] def connection_report(obj, part, built): """None for a part that states no connection, else what it states and whether it holds: the parent is a kit part, both sockets exist, the roll is a number, the parent inverse is the identity and the child stands within HELD of core.mate. A child moved or re-parented by another action reads holds false until - set_params seats it again.""" + set_params seats it again. With it the joint record: dof (the parent socket's type's: revolute, prismatic or + null for rigid), slide, limits, mechanism, compliance, and within, false only for a value written by hand + outside its limits.""" stated = link(obj) if stated is None: return None + record = joint_record(obj) row = {"parent": obj.parent.name if obj.parent else None, "socket": stated[0], "parentSocket": stated[1], - "roll": None if stated[2] is None else round(stated[2], 6), "residual": None, "holds": False} + "roll": None if stated[2] is None else round(stated[2], 6), "residual": None, "holds": False, + "dof": None, "slide": None if stated[3] is None else round(stated[3], 6), "limits": record["limits"] and [round(v, 6) for v in record["limits"]], + "mechanism": record["mechanism"], "compliance": record["compliance"], "within": True} try: - if obj.parent is None or stated[2] is None: + if obj.parent is None or stated[2] is None or stated[3] is None: return row parent_part, parent_built = built_part(obj.parent) parent_socket, socket = core.joint(parent_part, parent_built, stated[1], part, built, stated[0]) + row["dof"] = dof(obj.parent, parent_socket) except (Refused, core.KitError): return row - row["residual"] = round(core.residual(obj.parent.matrix_world, parent_socket, obj.matrix_world, socket, stated[2]), 9) + if record["limits"] is not None and row["dof"] is not None: + row["within"] = core.within(stated[2] if row["dof"] == "revolute" else stated[3], *record["limits"], row["dof"] == "revolute") is not None + row["residual"] = round(core.residual(obj.parent.matrix_world, parent_socket, obj.matrix_world, socket, stated[2], stated[3]), 9) row["holds"] = bool(np.abs(np.array(obj.matrix_parent_inverse) - np.eye(4)).max() <= HELD and row["residual"] <= HELD) return row @@ -638,18 +714,18 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): built = core.build(part, core.resolve_params(part, core.parse_params(self.params), stored)) closing = closure(obj) # a closure this part is an end of must still be one its new sockets may make; where they stand is only reported if closing is not None and closing[1] is not None: - mated(closing[1], *built_part(closing[1]), obj, part, built, (closing[0], closing[2], 0.0), "closing on") + mated(closing[1], *built_part(closing[1]), obj, part, built, (closing[0], closing[2], 0.0, 0.0), "closing on") for other in closing_on(obj): - mated(obj, part, built, other, *built_part(other), (closure(other)[0], closure(other)[2], 0.0), "closing on") + mated(obj, part, built, other, *built_part(other), (closure(other)[0], closure(other)[2], 0.0, 0.0), "closing on") seats, stated = [], link(obj) # every connection this part is an end of, checked against its new sockets before anything is written if stated is not None: if obj.parent is None: raise Refused(f"{obj.name!r} states a connection and has no parent: detach it to clear the connection; nothing changed.") parent_part, parent_built = built_part(obj.parent) - seats.append((obj, core.mate(*mated(obj.parent, parent_part, parent_built, obj, part, built, stated), stated[2]))) + seats.append((obj, core.mate(*mated(obj.parent, parent_part, parent_built, obj, part, built, stated), *stated[2:]))) for child in attached(obj): child_part, child_built = built_part(child) - seats.append((child, core.mate(*mated(obj, part, built, child, child_part, child_built, link(child)), link(child)[2]))) + seats.append((child, core.mate(*mated(obj, part, built, child, child_part, child_built, link(child)), *link(child)[2:]))) try: old = core.build(part, stored) except core.KitError: # stored params an edited kit no longer admits: nothing to map faces by @@ -698,11 +774,11 @@ class BROKKR_KITBASH_OT_attach(PolishOperator): if ancestor == child: raise Refused(f"{parent.name!r} is below {child.name!r}: attaching {child.name!r} to it would close a loop; nothing changed.") ancestor = ancestor.parent - stated = (self.socket, self.parent_socket, float(self.roll)) + stated = (self.socket, self.parent_socket, float(self.roll), 0.0) sockets = mated(parent, parent_part, parent_built, child, part, built, stated) free(parent, self.parent_socket) free(child, self.socket) - write_connection(child, parent, sockets, stated) + write_connection(child, parent, sockets, stated, {"limits": None, "mechanism": None, "compliance": None}) # a new connection states no joint record: brokkr_kitbash.joint gives it one context.view_layer.update() return part_report(child, part, built) @@ -724,18 +800,20 @@ class BROKKR_KITBASH_OT_detach(PolishOperator): world = obj.matrix_world.copy() obj.parent = None obj.matrix_world = world - for key in (SOCKET, PARENT_SOCKET, ROLL, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET): + for key in (SOCKET, PARENT_SOCKET, ROLL, *RECORD, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET): if key in obj: del obj[key] return part_report(obj, part, built) def pose(context, name: str, solve) -> dict: - """Give an attached part a new roll where it hangs: its parent and both sockets stay, and what is attached to - it follows. `solve(child, built, sockets, stated)` answers (the roll, what to add to the report), or refuses. - Refuses a part that states no connection or has no parent, and what mated() refuses. The report is the part's - and, as set_params', every closure in the scene with the part's own first: a roll can open one, and never - seats one.""" + """Give an attached part a new roll, slide or joint record where it hangs: its parent and both sockets stay, and + what is attached to it follows. `solve(child, built, sockets, stated, joint)` answers (the roll, the slide, what + to add to the report, the joint record to state or None to keep it), or refuses; `joint` is the record the + connection states with its `dof` and the parent socket's `type`. Refuses a part that states no connection or + has no parent, what mated() refuses and what write_connection does: a value outside the joint's limits. The + report is the part's and, as set_params', every closure in the scene with the part's own first: a pose can open + one, and never seats one.""" child = mesh_object(name) part, built = built_part(child) stated = link(child) @@ -745,10 +823,10 @@ def pose(context, name: str, solve) -> dict: raise Refused(f"{child.name!r} states a connection and has no parent: detach it to clear the connection; nothing changed.") sockets = mated(child.parent, *built_part(child.parent), child, part, built, stated) try: - roll, solved = solve(child, built, sockets, stated) + roll, slide, solved, record = solve(child, built, sockets, stated, {**joint_record(child), "dof": dof(child.parent, sockets[0]), "type": sockets[0]["type"]}) except core.KitError as error: raise Refused(f"{child.name!r} on {child.parent.name!r}: {error}; nothing changed.") from None - write_connection(child, child.parent, sockets, (stated[0], stated[1], float(roll))) + write_connection(child, child.parent, sockets, (stated[0], stated[1], float(roll), float(slide)), record) context.view_layer.update() report = {**part_report(child, part, built), **solved} report["closures"] = scene_closures(context, report, (child,)) @@ -774,7 +852,7 @@ class BROKKR_KITBASH_OT_roll(PolishOperator): @kit_work def work(self, context): - return pose(context, self.object_name, lambda child, built, sockets, stated: (self.roll, {})) + return pose(context, self.object_name, lambda child, built, sockets, stated, joint: (self.roll, stated[3], {}, None)) class BROKKR_KITBASH_OT_aim(PolishOperator): @@ -791,9 +869,9 @@ class BROKKR_KITBASH_OT_aim(PolishOperator): @kit_work def work(self, context): - def solve(child, built, sockets, stated): - roll, dot = core.aim_roll(child.parent.matrix_world, *sockets, core.AXES[self.axis], unit(self)) - return roll, {"aimed": {"roll": round(roll, 6), "dot": round(dot, 9)}} + def solve(child, built, sockets, stated, joint): + roll, dot = core.aim_roll(child.parent.matrix_world, *sockets, core.AXES[self.axis], unit(self), joint["limits"] if joint["dof"] == "revolute" else None) + return roll, stated[3], {"aimed": {"roll": round(roll, 6), "dot": round(dot, 9)}}, None return pose(context, self.object_name, solve) @@ -812,15 +890,109 @@ class BROKKR_KITBASH_OT_reach(PolishOperator): @kit_work def work(self, context): - def solve(child, built, sockets, stated): + def solve(child, built, sockets, stated, joint): found = [s for s in built.sockets if s["name"] == self.socket] if not found: raise Refused(f"{child.name!r} has no socket {self.socket!r}; its sockets: {', '.join(s['name'] for s in built.sockets)}; nothing changed.") - roll, residual = core.reach_roll(child.parent.matrix_world, *sockets, found[0]["matrix"][:3, 3], unit(self), self.height, stated[2]) - return roll, {"reached": {"roll": round(roll, 6), "residual": round(residual, 9)}} + roll, residual = core.reach_roll(child.parent.matrix_world, *sockets, found[0]["matrix"][:3, 3], unit(self), self.height, stated[2], + joint["limits"] if joint["dof"] == "revolute" else None) + return roll, stated[3], {"reached": {"roll": round(roll, 6), "residual": round(residual, 9)}}, None return pose(context, self.object_name, solve) +class BROKKR_KITBASH_OT_joint(PolishOperator): + """State the joint record of an attached kit part's connection: its limits, a mechanism label and, on a slide, + its compliance""" + bl_idname = "brokkr_kitbash.joint" + bl_label = "State Kit Joint" + object_name: bpy.props.StringProperty(name="Object", description="An attached part on a revolute or prismatic socket") + record: bpy.props.StringProperty(name="Record", default="{}", description="A JSON object of any of limits ([lo, hi] or null), mechanism (a label or null), " + "compliance ({hertz, damping_ratio} or null); a key left out keeps what is stated, null clears it") + + @kit_work + def work(self, context): + try: + given = json.loads(self.record) + except ValueError as error: + raise Refused(f"record must be JSON ({error}); nothing changed.") from None + limits, label, spring = (given.get(key) for key in ("limits", "mechanism", "compliance")) if isinstance(given, dict) else (None, None, None) + if (not isinstance(given, dict) or not set(given) <= {"limits", "mechanism", "compliance"} + or not (limits is None or isinstance(limits, list) and len(limits) == 2 and all(core.finite(v) for v in limits) and limits[0] <= limits[1]) + or not (label is None or isinstance(label, str) and re.fullmatch(LABEL, label)) + or not (spring is None or isinstance(spring, dict) and set(spring) == {"hertz", "damping_ratio"} and all(core.finite(v) for v in spring.values()))): + raise Refused("record must be a JSON object of any of limits ([lo, hi], lo at most hi, or null), mechanism (1 to 32 of a-z, 0-9 and _, or null) and " + "compliance ({hertz, damping_ratio} or null); nothing changed.") + + def solve(child, built, sockets, stated, joint): + if joint["dof"] is None: + raise Refused(f"{child.name!r} on {child.parent.name!r}: socket type {joint['type']!r} states no dof: the connection is rigid and carries no joint record; nothing changed.") + record = {key: joint[key] for key in ("limits", "mechanism", "compliance")} + if "limits" in given: + record["limits"] = limits and (float(limits[0]), float(limits[1])) + if "mechanism" in given: + record["mechanism"] = label + if "compliance" in given: + record["compliance"] = spring and {key: float(spring[key]) for key in ("hertz", "damping_ratio")} + return stated[2], stated[3], {}, record + return pose(context, self.object_name, solve) + + +class BROKKR_KITBASH_OT_slide(PolishOperator): + """Slide an attached kit part along its parent socket's normal, in place, on a prismatic connection: its parent + and sockets stay and what hangs from it follows""" + bl_idname = "brokkr_kitbash.slide" + bl_label = "Slide Kit Part" + object_name: bpy.props.StringProperty(name="Object", description="A part attached on a prismatic socket") + slide: bpy.props.FloatProperty(name="Slide", default=0.0, min=-10.0, max=10.0, precision=4, + description="Metres along the parent socket's normal from where the two sockets' origins meet") + + @kit_work + def work(self, context): + def solve(child, built, sockets, stated, joint): + if joint["dof"] != "prismatic": + raise Refused(f"{child.name!r} on {child.parent.name!r}: socket type {joint['type']!r} is {joint['dof'] or 'rigid'}: slide poses a prismatic connection" + f"{' (roll, aim and reach turn this one)' if joint['dof'] else ''}; nothing changed.") + return stated[2], self.slide, {}, None + return pose(context, self.object_name, solve) + + +class BROKKR_KITBASH_OT_joints(PolishOperator): + """Report the joints of the tree of kit parts under a root: each revolute or prismatic connection with its + parent joint, axis, value, limits, mechanism and compliance, in the root's frame""" + bl_idname = "brokkr_kitbash.joints" + bl_label = "Report Kit Joints" + bl_options = {"REGISTER"} + object_name: bpy.props.StringProperty(name="Object", description="The root: a kit part; the report is of what is attached below it") + + @kit_work + def work(self, context): + root, kits, rows, rigid_count = mesh_object(self.object_name), {}, [], 0 + built_part(root, kits) + frame = np.linalg.inv(np.array(root.matrix_world, dtype=np.float64)) + todo = [(child, None) for child in sorted(attached(root), key=lambda o: o.name, reverse=True)] + while todo: # depth first, children by name: a joint's parent joint is the nearest DOF connection above it, and rigid connections fold into it + child, above = todo.pop() + part, built = built_part(child, kits) + stated = link(child) + parent_socket, _ = mated(child.parent, *built_part(child.parent, kits), child, part, built, stated) + kind = dof(child.parent, parent_socket) + if kind is None: + rigid_count += 1 + else: + record, value = joint_record(child), stated[2] if kind == "revolute" else stated[3] + at = frame @ np.array(child.parent.matrix_world, dtype=np.float64) @ parent_socket["matrix"] + limits = record["limits"] and [round(v, 6) for v in record["limits"]] + rows.append({"id": child.name, "parent": above, "part": part["name"], "socket": f"{child.parent.name}:{stated[1]}", "kind": kind, + "axis": [round(float(v), 6) for v in at[:3, 2]], "origin": [round(float(v), 6) for v in at[:3, 3]], "value": round(value, 6), + "limits": limits, "min": limits and round(record["limits"][0] - value, 6), "max": limits and round(record["limits"][1] - value, 6), + "mechanism": record["mechanism"], "compliance": record["compliance"]}) + above = child.name + todo += [(below, above) for below in sorted(attached(child), key=lambda o: o.name, reverse=True)] + report = {"schema": "brokkr.joints", "version": 1, "root": root.name, "frame": "the root object's: Blender axes (+Z up), metres", "rigid": rigid_count} + report["joints"] = fitted(report, "joints", rows) + return report + + class BROKKR_KITBASH_OT_close(PolishOperator): """State that a socket of a kit part meets a socket of another part, of its kit or of any kit whose socket types agree, closing a loop the tree of connections cannot: accepted only when the two already meet, origins together and normals opposed, and it @@ -841,7 +1013,7 @@ class BROKKR_KITBASH_OT_close(PolishOperator): raise Refused(f"{obj.name!r} cannot close on itself; nothing changed.") if closure(obj) is not None: raise Refused(f"{obj.name!r} already states a closure (its socket {closure(obj)[0]!r}): a part states one, and detach clears it; nothing changed.") - there, here = mated(other, other_part, other_built, obj, part, built, (self.socket, self.other_socket, 0.0), "closing on") + there, here = mated(other, other_part, other_built, obj, part, built, (self.socket, self.other_socket, 0.0, 0.0), "closing on") free(other, self.other_socket) free(obj, self.socket) apart = core.closure_residual(other.matrix_world, there, obj.matrix_world, here) @@ -1542,7 +1714,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): step: bpy.props.FloatProperty(name="Step", default=0.02, min=0.0049, max=0.2, description="Voxel size of the search") sag: bpy.props.FloatProperty(name="Sag", default=1.0, min=0.0, max=8.0, description="How far the middle of each free span hangs, in outside diameters; 0: taut") clamps: bpy.props.StringProperty(name="Clamps", default="[]", description="A JSON array of up to 8 {socket: 'Object:socket'}, mount sockets, in order along the hose") - joint: bpy.props.StringProperty(name="Joint", default="", description="Empty, or a JSON object {socket, standoff, range: [lo, hi]}: the pin the hose crosses") + joint: bpy.props.StringProperty(name="Joint", default="", description="Empty, or a JSON object {socket, standoff}: the pin the hose crosses; its roll range is that connection's limits") # the action table states radius from 0.003 and step from 0.005: a float property rounds those up, so its bounds stand just under @kit_work @@ -1565,10 +1737,13 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): "use fewer or thinner hoses, a smaller spread, or a larger port; nothing changed.") clamp_rows, joint = self.rows() clamps = [self.frame(context, row, f"clamps[{index}]", ("mount",), kits) for index, row in enumerate(clamp_rows)] - pins, pin = self.crossed(start["object"], end["object"], kits), None + (pins, slides), pin = self.crossed(start["object"], end["object"], kits), None + if slides: + raise Refused(f"The hose crosses the slide of {slides[0][0].name!r} on {slides[0][0].parent.name!r} (socket {slides[0][1]['name']!r}): a hose across a prismatic " + "connection is not routed; end it on a part on this side of the slide; nothing changed.") if joint is None and pins: - raise Refused(f"The hose crosses the pin of {pins[0][0].name!r} on {pins[0][0].parent.name!r} (socket {pins[0][1]['name']!r}): give joint, a socket on that pin's axis, " - "a standoff and the roll range; nothing changed.") + raise Refused(f"The hose crosses the pin of {pins[0][0].name!r} on {pins[0][0].parent.name!r} (socket {pins[0][1]['name']!r}): give joint, a socket on that pin's axis " + "and a standoff; nothing changed.") if joint is not None and len(pins) != 1: raise Refused(("joint is given and the hose crosses no pin: its ends are on parts no pivot connection stands between" if not pins else f"The hose crosses {len(pins)} pins ({', '.join(repr(child.name) + ' on ' + repr(child.parent.name) for child, _, _ in pins)}): a hose crosses one; " @@ -1584,13 +1759,19 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): if off > 1e-6 or lean > 1e-6: raise Refused(f"joint.socket {on['name']!r} is not on the axis of the pin the hose crosses ({child.name!r} on {child.parent.name!r}, socket {socket['name']!r}): " f"its origin stands {off:.6g} m off the axis and its z leans {math.degrees(math.asin(min(1.0, lean))):.6g} degrees from it; nothing changed.") - if not joint["range"][0] - 1e-9 <= current <= joint["range"][1] + 1e-9: - raise Refused(f"{child.name!r} stands at roll {current:.6g}, outside joint.range {joint['range']}: the range holds the pose the hose is routed at; nothing changed.") + limits = joint_record(child)["limits"] # the roll range the hose is proven over is the pin's own: its connection's limits + if limits is None: + raise Refused(f"{child.name!r} on {child.parent.name!r}: the pin the hose crosses states no limits: brokkr_kitbash.joint gives it the roll range " + "the hose is proven over; nothing changed.") + if core.within(current, *limits, True) is None: + raise Refused(f"{child.name!r} stands at roll {current:.6g}, outside its joint's limits {limits[0]:.6g} to {limits[1]:.6g}: roll it inside them, or state " + "limits that hold it (brokkr_kitbash.joint); nothing changed.") + current = core.within(current, *limits, True) sides = [child in self.chain(stop["object"]) for stop in (start, *clamps, end)] changes = [index for index in range(len(sides) - 1) if sides[index] != sides[index + 1]] if len(changes) != 1: raise Refused(f"clamps cross the pin of {child.name!r} {len(changes)} times: list them in order along the hose, those on the start's side of the pin first; nothing changed.") - pin = {"origin": axis[:3, 3], "axis": axis[:3, 2], "current": current, "before": changes[0], "child": child, "child_first": sides[0], + pin = {"origin": axis[:3, 3], "axis": axis[:3, 2], "current": current, "limits": limits, "before": changes[0], "child": child, "child_first": sides[0], "point": on["matrix"][:3, 3] + on["matrix"][:3, 2] * joint["standoff"]} rest, moved, through = self.trees(start["depsgraph"], hose, pin and pin["child"], kits) reach = need + 2.0 * floor + self.step @@ -1700,7 +1881,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): "depsgraph": evaluable(context, obj)[0]} def rows(self): - """(the clamps' 'Object:socket' texts, the joint as {socket, standoff, range} or None), each refused by shape.""" + """(the clamps' 'Object:socket' texts, the joint as {socket, standoff} or None), each refused by shape.""" try: clamps, joint = json.loads(self.clamps or "[]"), json.loads(self.joint) if self.joint else None except ValueError as error: @@ -1711,29 +1892,28 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): if not isinstance(row, dict) or set(row) != {"socket"} or not isinstance(row["socket"], str): raise Refused(f"clamps[{index}] must be an object of socket, an 'Object:socket' text; nothing changed.") if joint is not None: - span = joint.get("range") if isinstance(joint, dict) else None - if (not isinstance(joint, dict) or set(joint) != {"socket", "standoff", "range"} or not isinstance(joint["socket"], str) - or not (core.finite(joint["standoff"]) and 0.0 <= joint["standoff"] <= 10.0) - or not (isinstance(span, list) and len(span) == 2 and all(core.finite(v) and -360.0 <= v <= 360.0 for v in span) and 0.0 <= span[1] - span[0] <= 360.0)): - raise Refused("joint must be an object of socket (an 'Object:socket' text), standoff (0 to 10) and range ([lo, hi] in degrees, lo to hi at most 360, each within 360 of 0); nothing changed.") + if (not isinstance(joint, dict) or set(joint) != {"socket", "standoff"} or not isinstance(joint["socket"], str) + or not (core.finite(joint["standoff"]) and 0.0 <= joint["standoff"] <= 10.0)): + raise Refused("joint must be an object of socket (an 'Object:socket' text) and standoff (0 to 10): the pin's roll range is its connection's limits " + "(brokkr_kitbash.joint); nothing changed.") return [row["socket"] for row in clamps], joint - def crossed(self, start, end, kits) -> list: - """The pins between two objects, [(child, the parent's pivot socket, roll)]: a connection is a child's parent - pointer and its kit_parent_socket (link), and it is a pin when that socket is a pivot. Read along both parent - chains up to the first object they share; with none shared, along both whole chains.""" + def crossed(self, start, end, kits) -> tuple: + """(the pins, the slides) between two objects, each [(child, the parent's socket, roll)]: a connection is a + child's parent pointer and its kit_parent_socket (link); it is a pin when that socket's type states dof + revolute in the parent's kit and a slide when it states prismatic. Read along both parent chains up to the + first object they share; with none shared, along both whole chains.""" up, down = self.chain(start), self.chain(end) shared = [obj for obj in up if obj in down] between = up[:up.index(shared[0])] + down[:down.index(shared[0])] if shared else up + down - pins = [] + found = {"revolute": [], "prismatic": [], None: []} for child in between: stated = link(child) if stated is None or child.parent is None or PART not in child.parent: continue - socket = [s for s in built_part(child.parent, kits)[1].sockets if s["name"] == stated[1] and s["type"] == "pivot"] - if socket: - pins.append((child, socket[0], stated[2])) - return pins + for socket in (s for s in built_part(child.parent, kits)[1].sockets if s["name"] == stated[1]): + found[dof(child.parent, socket)].append((child, socket, stated[2])) + return found["revolute"], found["prismatic"] def trees(self, depsgraph, hose, child, kits): """(a tree of every mesh the depsgraph evaluates but this hose, the pin's child side and the hoses through @@ -1829,7 +2009,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): before, after = before / np.linalg.norm(before), after / np.linalg.norm(after) if pin["child_first"]: # read from the parent's side, as route.passes turns it before, after = -after, -before - low, high = (v - pin["current"] for v in sized["joint"]["range"]) + low, high = (v - pin["current"] for v in pin["limits"]) least[j - 1] = sized["floor"] * math.tan(min(route.sharpest_turn(before, after, pin["axis"], low, high), route.STIFF) / 2.0) return np.where(clamped, sized["kept"], 0.0), clamped, least @@ -1879,7 +2059,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): if pin is not None: j, order = tags.index("J"), slice(None, None, -1) if pin["child_first"] else slice(None) # passes reads a polyline from the parent's side swing = route.passes(points[order], made.t[order], (len(points) - 1 - j) if pin["child_first"] else j, pin["origin"], pin["axis"], - route.rolls_of(sized["joint"]["range"][0], sized["joint"]["range"][1], ROLL_STEP), ROLL_FINEST, pin["current"], sized["far_rest"], sized["far_moved"], + route.rolls_of(pin["limits"][0], pin["limits"][1], ROLL_STEP), ROLL_FINEST, pin["current"], sized["far_rest"], sized["far_moved"], sized["need"], sized["floor"], sized["exempt"], keep=keep[order]) return made.curve, made, sagged, clearance, swing @@ -1950,6 +2130,7 @@ class BROKKR_KITBASH_OT_report(PolishOperator): classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report, BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_roll, BROKKR_KITBASH_OT_aim, BROKKR_KITBASH_OT_reach, + BROKKR_KITBASH_OT_joint, BROKKR_KITBASH_OT_slide, BROKKR_KITBASH_OT_joints, BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_freeze, BROKKR_KITBASH_OT_thaw, BROKKR_KITBASH_OT_ribs, BROKKR_KITBASH_OT_shell, BROKKR_KITBASH_OT_hose) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 4ea390e..e0d6282 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -93,7 +93,7 @@ }, { "name": "brokkr_kitbash.report", - "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world 4x4, the connection (parent, sockets, roll, residual, holds) and frozen. faces counts the live mesh; a frozen part adds evaluated {faces}, and dirty (the modifiers shown again by hand, with frozen false). Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.", + "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world 4x4, the connection (parent, sockets, roll, residual, holds, and its joint record: dof, slide, limits, mechanism, compliance, within) and frozen. faces counts the live mesh; a frozen part adds evaluated {faces}, and dirty (the modifiers shown again by hand, with frozen false). Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.", "changesScene": false, "editModeSafe": true, "result": "brokkr_mesh_polish_result", @@ -109,7 +109,7 @@ }, { "name": "brokkr_kitbash.attach", - "doc": "Seat a socket of a kit part on a socket of a part of any kit whose socket types agree and parent it there: origins together, normals opposed. Refuses sockets of different types or sizes that do not match, an occupied socket, a child that has a parent, and a loop. Reports the child with its connection.", + "doc": "Seat a socket of a kit part on a socket of a part of any kit whose socket types agree and parent it there: origins together, normals opposed. Refuses sockets of different types or sizes that do not match, an occupied socket, a child that has a parent, and a loop. The connection's DOF is its parent socket's type's (revolute, prismatic or rigid); it starts with no joint record: brokkr_kitbash.joint states one. Reports the child with its connection.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -176,7 +176,7 @@ }, { "name": "brokkr_kitbash.roll", - "doc": "Turn an attached kit part to a roll about its parent socket's normal, in place: its parent and both sockets stay, and what is attached to it follows. Refuses a part that is not attached. Reports the part and closures, every closure in the scene as {part, to, holds}, its own first: a roll can open one and never seats one.", + "doc": "Turn an attached kit part to a roll about its parent socket's normal, in place: its parent and both sockets stay, and what is attached to it follows. Refuses a part that is not attached and, on a revolute joint with limits, a roll with no turn of itself inside them (the roll written is the one inside). Reports the part and closures, every closure in the scene as {part, to, holds}, its own first: a roll can open one and never seats one.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -201,7 +201,7 @@ }, { "name": "brokkr_kitbash.aim", - "doc": "Turn an attached kit part about its pin until one of its own axes points as near a world direction as the pin lets it. The roll is solved exactly, not searched. Refuses an axis or a direction that lies along the pin (within about 0.06 degrees), and a zero direction. Reports the part, aimed: {roll, dot} (dot 1 when the axis reaches the direction) and closures as roll does.", + "doc": "Turn an attached kit part about its pin until one of its own axes points as near a world direction as the pin lets it. The roll is solved exactly, not searched. On a revolute joint with limits the roll stays inside them: where the free roll is outside, the end of the limits that points the axis nearer. Refuses an axis or a direction that lies along the pin (within about 0.06 degrees), and a zero direction. Reports the part, aimed: {roll, dot} (dot 1 when the axis reaches the direction) and closures as roll does.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -254,7 +254,7 @@ }, { "name": "brokkr_kitbash.reach", - "doc": "Turn an attached kit part about its pin until one of its sockets' origins stands at a height along a world direction (by default world z): of the two rolls that do it, the one nearer the roll it has. Solved exactly. Refuses a height the socket cannot reach, naming the range it can (either end of the range is taken), and a socket that lies on the pin. Reports the part, reached: {roll, residual} and closures as roll does.", + "doc": "Turn an attached kit part about its pin until one of its sockets' origins stands at a height along a world direction (by default world z): of the two rolls that do it, the one nearer the roll it has. Solved exactly. On a revolute joint with limits only a roll inside them is taken; with neither inside it refuses, naming both rolls and the limits. Refuses a height the socket cannot reach, naming the range it can (either end of the range is taken), and a socket that lies on the pin. Reports the part, reached: {roll, residual} and closures as roll does.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -308,6 +308,73 @@ } ] }, + { + "name": "brokkr_kitbash.joint", + "doc": "State the joint record of an attached kit part's connection. The connection's DOF is its parent socket's type's: revolute (its value is the roll, degrees) or prismatic (the slide, metres). record is a JSON object of any of limits ([lo, hi] or null), mechanism (a label of 1 to 32 a-z, 0-9 and _, or null) and compliance ({\"hertz\": over 0 to 30, \"damping_ratio\": 0 to 2} or null: a slide in the load path that settles under load, a record for a runtime, solved by nothing here); a key left out keeps what is stated and null clears it. Refuses a rigid connection naming its socket type, limits that do not hold the value the joint has, revolute limits spanning over 360 degrees or with an end past 360, prismatic limits with an end past 10 m, and compliance on a revolute joint or without limits. Moves nothing but a roll to its turn inside the limits. Reports the part and closures as roll does.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "a part attached on a revolute or prismatic socket" + }, + { + "name": "record", + "type": "string", + "required": true, + "minLength": 2, + "maxLength": 400, + "doc": "a JSON object of any of limits, mechanism, compliance" + } + ] + }, + { + "name": "brokkr_kitbash.slide", + "doc": "Slide an attached kit part along its parent socket's normal, in place, on a prismatic connection (a ram_rod in a ram_barrel's bore: slide 0 is closed, the slide is the extension): its parent and both sockets stay, and what is attached to it follows. Refuses a revolute or rigid connection naming its socket type, and a slide outside the joint's limits. Reports the part and closures as roll does.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "a part attached on a prismatic socket" + }, + { + "name": "slide", + "type": "number", + "required": true, + "minimum": -10, + "maximum": 10, + "doc": "metres along the parent socket's normal from where the two sockets' origins meet" + } + ] + }, + { + "name": "brokkr_kitbash.joints", + "doc": "The joints of the tree of kit parts attached under a root part, as {schema: brokkr.joints, version: 1, root, frame, rigid, joints}. A row per revolute or prismatic connection, depth first with children by name, so a joint's parent row comes before it: id (the child object), parent (the id of the nearest joint above, or null: rigid connections fold into it and are counted in rigid), part, socket ('Object:socket', the parent socket), kind, axis and origin (that socket's z and origin in the root object's frame: Blender axes, +Z up, metres), value (the roll in degrees or the slide in metres now), limits ([lo, hi] or null), min and max (the limits less the value: the travel either way from this pose), mechanism and compliance. Axis, origin and order are derived at each report from the kits and the parent tree; nothing stores them. Rows a receipt cannot carry are counted in jointsOmitted. Refuses a connection that cannot be read. Evaluates no modifier.", + "changesScene": false, + "editModeSafe": true, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the root: a kit part" + } + ] + }, { "name": "brokkr_kitbash.close", "doc": "Close a loop: state that a socket of a kit part meets a socket of a part of any kit whose socket types agree, where attach cannot (the part already has its parent). Accepted only when the two sockets already meet, origins together and normals opposed, any roll; it moves nothing. Attach the parts with the rolls that make them meet first; brokkr_kitbash.report shows the closure and whether it holds.", @@ -800,7 +867,7 @@ }, { "name": "brokkr_kitbash.hose", - "doc": "Route a bundle of hoses between two sockets, around every mesh Blender evaluates in the scene. start and end are 'Object:socket' on a kit part (a hose or flange socket no narrower than the bundle) or 'Object' alone, an empty whose z the hose leaves along. A leg runs between each pair of waypoints (a fitting's lead end, each clamp, the pin point): it is searched on a voxel grid of its ends' box plus 0.25 m (at most 524288 voxels), pulled taut with room for its bends where a way has it, and the whole polyline is rounded, each corner by the largest arc its measured room allows. That polyline is a seed: one refused for want of straight between its corners is refined in continuous space (vertices dropped, moved and added, each change proven clear), and before a route is refused the legs are searched again on two more grid origins and at half the step. The refusal then names the steps and origins tried and the first seed's refusal, and says this shows no route was found, not that none exists; it says the bundle is too stiff only where that is proven at a port. The innermost hose's bend radius is at least bend outside diameters, and a fitting keeps a straight of 8 radii (a ferrule, then 1.5 outside diameters). The centre line keeps the bundle's half width plus clearance from every other mesh, other hoses included, outside those leads. sag hangs the middle of each free span by that many outside diameters, never by more than half the room measured along the span; a route the sag breaks is made taut instead (sag in the report reads 0). clamps is a JSON array of up to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose: the bundle runs straight over each, along the socket's y, and gets a pad and a strap. A hose may cross one pin (a pivot connection between its ends' parts): joint is then {\"socket\": \"Object:socket\", \"standoff\": metres, \"range\": [lo, hi]}, a socket on that pin's axis whose z runs along it; the hose passes through the point standoff beyond it, so each side's straights move with their own part and only the bend at that point changes. The whole range from lo to hi is measured without posing anything, each side against the other side's parts: a roll every 5 degrees answers for the rolls about it by what a point can move within them, and more are measured between where that falls short; another hose through the same pin is kept clear of where it stands, not across the rolls (follow-up aetheria-release:follow_up:hose-motion-clearance-from-skinning owes that check). Every line is measured so that nothing thinner than a spacing can stand between two readings, whatever the step. The hose is one mesh object, a child of the start's object, and a bake of the scene at the call: after a part moves or rolls, run hose again on its name to rebuild it in place. Where it crosses a pin it is meant to be skinned between the bones on either side; no weights are written. Refuses before it writes anything, naming the leg, corner, point or roll. Reports object, rebuilt, hoses, length, lengthChange (over the range, of the centre line as each roll rounds it), floor, clearance (least beyond the bundle, outside the leads; readings stop at capped), voxels per leg, seed {step, offset, refined} (the grid that gave the route, and whether its polyline was refined), sag per leg in metres, rolls (how many were measured), worstRoll, worstClearance (least over the range, each reading less what its point can move within its roll's bin), faces, volume, nonManifoldEdges and radii {least, corners}.", + "doc": "Route a bundle of hoses between two sockets, around every mesh Blender evaluates in the scene. start and end are 'Object:socket' on a kit part (a hose or flange socket no narrower than the bundle) or 'Object' alone, an empty whose z the hose leaves along. A leg runs between each pair of waypoints (a fitting's lead end, each clamp, the pin point): it is searched on a voxel grid of its ends' box plus 0.25 m (at most 524288 voxels), pulled taut with room for its bends where a way has it, and the whole polyline is rounded, each corner by the largest arc its measured room allows. That polyline is a seed: one refused for want of straight between its corners is refined in continuous space (vertices dropped, moved and added, each change proven clear), and before a route is refused the legs are searched again on two more grid origins and at half the step. The refusal then names the steps and origins tried and the first seed's refusal, and says this shows no route was found, not that none exists; it says the bundle is too stiff only where that is proven at a port. The innermost hose's bend radius is at least bend outside diameters, and a fitting keeps a straight of 8 radii (a ferrule, then 1.5 outside diameters). The centre line keeps the bundle's half width plus clearance from every other mesh, other hoses included, outside those leads. sag hangs the middle of each free span by that many outside diameters, never by more than half the room measured along the span; a route the sag breaks is made taut instead (sag in the report reads 0). clamps is a JSON array of up to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose: the bundle runs straight over each, along the socket's y, and gets a pad and a strap. A hose may cross one pin (a revolute connection between its ends' parts, with limits stated by brokkr_kitbash.joint: they are the roll range lo to hi; a pin without limits and a prismatic connection between the ends are refused): joint is then {\"socket\": \"Object:socket\", \"standoff\": metres}, a socket on that pin's axis whose z runs along it; the hose passes through the point standoff beyond it, so each side's straights move with their own part and only the bend at that point changes. The whole range from lo to hi is measured without posing anything, each side against the other side's parts: a roll every 5 degrees answers for the rolls about it by what a point can move within them, and more are measured between where that falls short; another hose through the same pin is kept clear of where it stands, not across the rolls (follow-up aetheria-release:follow_up:hose-motion-clearance-from-skinning owes that check). Every line is measured so that nothing thinner than a spacing can stand between two readings, whatever the step. The hose is one mesh object, a child of the start's object, and a bake of the scene at the call: after a part moves or rolls, run hose again on its name to rebuild it in place. Where it crosses a pin it is meant to be skinned between the bones on either side; no weights are written. Refuses before it writes anything, naming the leg, corner, point or roll. Reports object, rebuilt, hoses, length, lengthChange (over the range, of the centre line as each roll rounds it), floor, clearance (least beyond the bundle, outside the leads; readings stop at capped), voxels per leg, seed {step, offset, refined} (the grid that gave the route, and whether its polyline was refined), sag per leg in metres, rolls (how many were measured), worstRoll, worstClearance (least over the range, each reading less what its point can move within its roll's bin), faces, volume, nonManifoldEdges and radii {least, corners}.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -898,7 +965,7 @@ "type": "string", "minLength": 0, "maxLength": 4000, - "doc": "empty, or a JSON object {\"socket\": \"Object:socket\", \"standoff\": 0 to 10, \"range\": [lo, hi]}: the pin the hose crosses", + "doc": "empty, or a JSON object {\"socket\": \"Object:socket\", \"standoff\": 0 to 10}: the pin the hose crosses; its roll range is that connection's limits", "default": "" } ] diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 626f77a..82e4d10 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1997,7 +1997,8 @@ class SheetTests(unittest.TestCase): ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", - "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close", + "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", + "brokkr_kitbash.joint", "brokkr_kitbash.slide", "brokkr_kitbash.joints", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.freeze", "brokkr_kitbash.thaw", "brokkr_kitbash.ribs", "brokkr_kitbash.shell", "brokkr_kitbash.hose"] @@ -2120,7 +2121,8 @@ class OwnershipTests(unittest.TestCase): r"hide_render|hide_viewport|display_type", # a cutter's visibility is setObjectVisibility's r"kit_parent_name|kit_parent\b|matrix_world_stored", # obj.parent has no second owner r"SCREW|\"ARRAY\"|spin\(", # core makes every vertex: no modifier or bmesh op makes kit geometry - r"Kit Boolean |operand_type\s*=\s*[\"']OBJECT") # cutters cut through one collection Boolean per operation, never a modifier each + r"Kit Boolean |operand_type\s*=\s*[\"']OBJECT", # cutters cut through one collection Boolean per operation, never a modifier each + r"kit_axis|kit_order|kit_parent_joint") # a joint's axis is its parent socket's z and its order the parent tree: neither is stored CORE = r"^import bpy|^from bpy|^import bmesh" SCHEMAS = r"brokkr\.kit\.v0" @@ -2273,16 +2275,31 @@ class OwnershipTests(unittest.TestCase): def test_only_write_connection_writes_the_roll(self): """one-writer. kit_roll is the one statement of a connection's roll, and write_connection its one writer: attach - and pose (roll, aim and reach) call it; set_params and the reports read the roll and never write it back. - Mutant R7 (attach keeps its own inline write beside write_connection).""" + and pose (roll, aim, reach, slide and joint) call it; set_params and the reports read the roll and never write + it back. Mutant R7 (attach keeps its own inline write beside write_connection). The joint record (kit_slide, + kit_min, kit_max, kit_mechanism, kit_compliance) is written there too and nowhere else: its names are read by + link and joint_record, cleared by detach, and no other function names them; the hose keeps no roll range of + its own, and no DOF kind is read from a socket type's name.""" source = self.sources()["__init__.py"] writes = re.findall(r'[^\n]*(?:\[ROLL\]|\["kit_roll"\])\s*=(?!=)[^\n]*', source) - self.assertEqual(writes, [" child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated"]) - self.assertIn(writes[0], source.split("def write_connection(")[1].split("\n\n\n")[0]) + self.assertEqual(writes, [" child[SOCKET], child[PARENT_SOCKET], child[ROLL] = socket, parent_socket, roll"]) + writer = source.split("def write_connection(")[1].split("\n\n\n")[0] + self.assertIn(writes[0], writer) + record = r"SLIDE|LIMIT_MIN|LIMIT_MAX|MECHANISM|COMPLIANCE|RECORD" + written = rf'\[(?:{record})\](?:, \w+\[\w+\])*\s*=(?!=)|\["kit_(?:slide|min|max|mechanism|compliance)"\]' + self.assertIsNone(re.search(written, source)) + self.assertEqual(re.findall(r"[^\n]*\[key\] = [^\n]*", source), [" child[key] = value"]) + self.assertIn(" child[key] = value", writer) + named = [body.split("(")[0] for body in re.split(r"\n(?:def|class) ", source)[1:] if re.search(rf"\b(?:{record})\b", body)] + self.assertEqual(named, ["link", "joint_record", "mated", "write_connection", "BROKKR_KITBASH_OT_detach"]) + for text in ("child[SLIDE] = slide", "obj[LIMIT_MIN], obj[LIMIT_MAX] = limits", 'obj["kit_compliance"] = text'): + self.assertIsNotNone(re.search(written, text)) + self.assertNotIn('"range"', source) + self.assertNotIn('"pivot"', source) bodies = {body.split("(")[0]: body.split("\n\n\n")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:]} callers = [name for name, body in bodies.items() if "write_connection(" in body] self.assertEqual((callers, source.count("write_connection("), source.split("def pose(")[1].split("\n\n\n")[0].count("write_connection(")), (["attach"], 3, 1)) - for name in ("roll", "aim", "reach"): + for name in ("roll", "aim", "reach", "slide", "joint"): self.assertEqual((bodies[name].count("pose(context, self.object_name, "), bool(re.search(r"\.parent\s*=(?!=)|\bseat\(|matrix_basis", bodies[name]))), (1, False), name) self.assertIsNone(re.search(r"\.parent\s*=(?!=)|\bseat\(|matrix_basis", bodies["attach"])) @@ -2301,7 +2318,7 @@ class OwnershipTests(unittest.TestCase): assigned = re.findall(rf"[^\n]*\[{keys}\][^\n=]*=(?!=)[^\n]*", source) self.assertEqual(assigned, [" obj[CLOSE], obj[CLOSE_TO], obj[CLOSE_TO_SOCKET] = self.socket, other, self.other_socket"]) self.assertIn(assigned[0], bodies["close"]) - deleted = re.findall(r"[^\n]*\(SOCKET, PARENT_SOCKET, ROLL, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET\)[^\n]*\n[^\n]*\n\s*del obj\[key\]", source) + deleted = re.findall(r"[^\n]*\(SOCKET, PARENT_SOCKET, ROLL, \*RECORD, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET\)[^\n]*\n[^\n]*\n\s*del obj\[key\]", source) self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 2, True)) # detach's keys, and hold's kit_frozen self.assertEqual(source.count("CLOSE_TO]"), 1) # the one subscript write above; every read goes through .get placing = r"matrix_basis|matrix_world\s*=(?!=)|matrix_parent_inverse|\.parent\s*=(?!=)|\bseat\(|\.location|\.rotation" @@ -2312,7 +2329,7 @@ class OwnershipTests(unittest.TestCase): def test_the_patterns_bite(self): planted = ("value = eval(text)", "from brokkr_bridge import x", 'modifier.solver = "MANIFOLD"', "cutter.hide_render = True", 'obj["kit_parent"] = parent.name', - 'obj.modifiers.new("Turn", "SCREW")', 'modifier.operand_type = "OBJECT"') + 'obj.modifiers.new("Turn", "SCREW")', 'modifier.operand_type = "OBJECT"', 'child["kit_axis"] = list(axis)') self.assertIsNotNone(re.search(self.PACKAGE[6], 'obj.modifiers.new("Kit Boolean " + cutter.name, "BOOLEAN")')) for text in ('obj.modifiers.new("Bolts", "ARRAY")', "bmesh.ops.spin(bm, geom=geom)"): self.assertIsNotNone(re.search(self.PACKAGE[5], text))