diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 5d8da04..4b1ada6 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -110,11 +110,12 @@ def built_part(obj): 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.""" + 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.""" 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 0.0 + return str(obj[SOCKET]), str(obj.get(PARENT_SOCKET, "")), float(roll) if core.finite(roll) else None def attached(obj) -> list: @@ -124,7 +125,10 @@ def attached(obj) -> list: def mated(parent, parent_part, parent_built, child, child_part, child_built, stated): """(parent socket, child socket) of the connection `stated` between two built parts, or a refusal that names - it: parts of two kits, a socket name a part does not have, or sockets core.mate_refusal will not mate.""" + it: a roll that is not a number, parts of two kits, a socket name a part does not have, or sockets + core.mate_refusal will not mate.""" + 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.") try: sockets = core.joint(parent_part, parent_built, stated[1], child_part, child_built, stated[0]) refusal = core.mate_refusal(core.load_kit(parent_part["kit"])["socketTypes"], *sockets) @@ -143,15 +147,16 @@ def seat(child, basis) -> None: 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 part - of the same kit, both sockets exist, 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.""" + of the same kit, 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.""" stated = link(obj) if stated is None: return None row = {"parent": obj.parent.name if obj.parent else None, "socket": stated[0], "parentSocket": stated[1], - "roll": round(stated[2], 6), "residual": None, "holds": False} + "roll": None if stated[2] is None else round(stated[2], 6), "residual": None, "holds": False} try: - if obj.parent is None: + if obj.parent is None or stated[2] 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]) @@ -412,6 +417,10 @@ class BROKKR_KITBASH_OT_apply(PolishOperator): baked = bpy.data.meshes.new_from_object(evaluated, preserve_all_data_layers=True, depsgraph=depsgraph) while len(baked.materials) > slots and baked.materials[len(baked.materials) - 1] is None: baked.materials.pop() # a Boolean gives a part that had no material slot one empty slot + index = np.zeros(len(baked.polygons), dtype=np.int32) + baked.polygons.foreach_get("material_index", index) + if (index < 0).any(): # faces from a cutter's empty slot: slot 0, as faces from a cutter with no material + baked.polygons.foreach_set("material_index", np.maximum(index, 0)) old, name = obj.data, obj.data.name obj.data = baked obj.modifiers.clear() diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 2bb8481..a9f342e 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -1,15 +1,17 @@ """Live proof, in a background Blender, of brokkr_kitbash assembly through run_intent: attach and its refusals, -set_params seating a part and the parts attached to it again, drift and how it is cleared, detach, boolean (Exact, -self-intersection on, above the Bevel) on two targets, and apply. Not part of the unittest run: it needs Blender. +set_params seating a part and the parts attached to it again, drift and how it is cleared, a roll that is not a +number, detach, boolean (Exact, self-intersection on, above the Bevel), and apply with its material slots. Not part +of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_assembly.py -- Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses without them). is an absolute path; writes .result.json and exits 1 when a check failed. -An Exact Boolean costs about a second a part and evaluation, so only two parts are ever cut here (the tank and -one plate). Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the geometric mean of the shipped -worst reading and the least claimed mutant's, both written beside it; the result file carries the readings. +An Exact Boolean costs a few tenths of a second a part and evaluation (docs/kitbash.md), so few parts are cut +here: the tank, a tee and three plates. Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the +geometric mean of the shipped worst reading and the least claimed mutant's, both written beside it; the result file +carries the readings. """ import importlib.util import json @@ -69,9 +71,14 @@ ROLL = 2.2e-2 # Largest entry of matrix_world after detach minus before. Shipped worst 1.5e-08; least claimed mutant 2.9 # (A10, detach drops the world matrix); separation 1.9e8. KEPT = 2.1e-4 -# Cubic metres left of the 1.8 m tank (its 20 shells as one solid) with a 0.3 m box cut from its wall. Shipped -# 0.2539; least claimed mutant 0.0079 (A11, self-intersection off: overlapping shells cancel); separation 32. -CUT = 0.045 +# Cubic metres left of the 1.8 m tank (its 6 shells as one solid) with a 0.3 m box cut through its lower cradle, the +# pad, a strap and the barrel's wall, where four shells overlap. Shipped 0.2508; least claimed mutant 0.0060 (K15, self- +# intersection off: overlapping shells cancel); separation 6.5 each side. A box through the barrel alone no longer +# tells the two apart: the barrel is one shell. +CUT = 0.039 +# Metres an attached child is moved to read holds false. HELD is a rule, 1e-5; least claimed mutant 1e-2 (K12); +# the geometric mean of the two, separation 32 each side. +NUDGE = 3.2e-4 def check(name, ok, detail=None): @@ -137,7 +144,7 @@ def held(report): def scene_state(): return {o.name: (o.parent and o.parent.name, np.round(np.array(o.matrix_basis), 6).tolist(), np.round(np.array(o.matrix_parent_inverse), 6).tolist(), - {k: o[k] for k in sorted(o.keys()) if k.startswith("kit_")}, [(m.name, m.type) for m in o.modifiers], + {k: repr(o[k]) for k in sorted(o.keys()) if k.startswith("kit_")}, [(m.name, m.type) for m in o.modifiers], o.data.name if o.type == "MESH" else None, len(o.data.polygons) if o.type == "MESH" else None, [s.material and s.material.name for s in o.material_slots], o.hide_render) for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes) @@ -298,6 +305,27 @@ check("a parent inverse that is not the identity does not hold, wherever the chi send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") check("and set_params on the parent writes the identity back", holds("Nozzle", "Tee", "mount", "c", 37.0)[0] and np.array_equal(np.array(nozzle.matrix_parent_inverse), np.eye(4)), connection("Nozzle")) +push = np.array(tee.matrix_world)[:3, :3].T @ [NUDGE, 0.0, 0.0] # NUDGE along the world's x, in the tee's frame +send("setObjectTransform", targetObjectName="Nozzle", location=(np.array(nozzle.matrix_basis)[:3, 3] + push).tolist()) +found = connection("Nozzle") or {} +check("a child moved by NUDGE does not hold, and its residual is the move", found.get("holds") is False + and abs(reading("nudged", found.get("residual") or 0.0) - NUDGE) < 0.1 * NUDGE, found) +send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") +check("and set_params on its parent seats it again", holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) +for written in (float("nan"), "x"): # a kit_roll nobody's attach wrote + nozzle["kit_roll"] = written + found = connection("Nozzle") or {} + check(f"a kit_roll of {written!r} reports roll null and does not hold", found.get("roll", 0.0) is None and found.get("holds") is False + and found.get("residual", 0.0) is None and found.get("parent") == "Tee", found) + refused(f"set_params on a child whose kit_roll is {written!r}", "brokkr_kitbash.set_params", {"object_name": "Nozzle", "params": "exit_r=0.3"}, + "'Nozzle' on 'Tee': its kit_roll is not a number: detach it and attach it again") + refused(f"set_params on the parent of a child whose kit_roll is {written!r}", "brokkr_kitbash.set_params", {"object_name": "Tee", "params": "run=0.6"}, + "'Nozzle' on 'Tee': its kit_roll is not a number") +receipt, report = send("brokkr_kitbash.detach", object_name="Nozzle") +check("detach clears a roll that is not a number", receipt["status"] == "accepted" and nozzle.parent is None and report and report["connection"] is None + and "kit_roll" not in nozzle, [receipt["message"], dict(nozzle.items())]) +receipt, report = send("brokkr_kitbash.attach", object_name="Nozzle", socket="mount", parent_name="Tee", parent_socket="c", roll=37.0) +check("and the nozzle attaches again", receipt["status"] == "accepted" and held(report) and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) send("setObjectParent", targetObjectName="Spare", parentObjectName="") found = connection("Spare") check("setObjectParent clearing an attached child's parent shows as a connection with no parent", found and found == {**found, "parent": None, "holds": False, "residual": None}, found) @@ -325,9 +353,9 @@ check("the freed tee attaches by another socket to the tank's other port", holds send("assignMaterial", targetObjectName="Tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35]) send("assignMaterial", targetObjectName="Tank", materialName="Strap Steel", color=[0.2, 0.2, 0.2]) tank_built = core.build(kit["parts"]["tank"], json.loads(tank["kit_params"])) -STRAPS = sorted(set(tank_built.shape.tolist()))[-1] +STRAPS = 1 # the tank's second shape: the repeat of two straps tank.data.polygons.foreach_set("material_index", np.where(tank_built.shape == STRAPS, 1, 0).astype(np.int32)) -side = np.array(tank.matrix_world) @ [0.24, 0.0, 0.9, 1.0] # on the barrel's wall, halfway along +side = np.array(tank.matrix_world) @ [0.0, -0.22, 0.4564, 1.0] # under the barrel at the lower cradle: cradle, pad, strap and wall send("createObject", objectType="MESH", name="Box", location=side[:3].tolist(), size=0.3) box = bpy.data.objects["Box"] box_was = (box.hide_render, box.hide_viewport, len(box.data.polygons), [m.name for m in box.modifiers], box.parent) @@ -340,7 +368,8 @@ check("boolean adds a Boolean modifier above the Bevel: Exact, self-intersection [receipt["message"], [m.name for m in tank.modifiers]]) shown, shown_slots = evaluated(tank) check("boolean reports the evaluated mesh, with less volume than the uncut tank and no non-manifold edge", cut and cut["evaluated"] == shown - and CUT < cut["evaluated"]["volume"] < raw["volume"] - 0.005 and cut["evaluated"]["nonManifoldEdges"] == 0 + and CUT < reading("cut", cut["evaluated"]["volume"]) < raw["volume"] - 0.005 and cut["evaluated"]["nonManifoldEdges"] == 0 + and int(np.count_nonzero(tank_built.shape == STRAPS)) == 2 * 4 * 24 and cut["booleans"] == [{"cutter": "Box", "operation": "DIFFERENCE"}] and cut["faces"] == len(tank.data.polygons) == raw["faces"], [cut and cut["evaluated"], shown, raw]) R["tank"] = {"raw": raw, "cut": cut and cut["evaluated"]} @@ -437,6 +466,39 @@ big = place("Big", "vent", "width=0.8; height=0.6") refused("a part larger than the seat", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Plate", "parent_socket": "back"}, "are mount sockets, where the child fits the parent: it is larger") +# --- a tee is one solid under the Boolean ----------------------------------------------------------------------------------------- +place("Cross", "pipe_fitting", location=[0.0, -6.0, 0.0]) # pipe_r 0.05, the default +send("createObject", objectType="MESH", name="Bar", location=[0.0, -6.0, 0.0], size=1.0) +send("setObjectTransform", targetObjectName="Bar", scale=[0.3, 3.0, 0.3]) +receipt, cut = send("brokkr_kitbash.boolean", object_name="Cross", cutter="Bar") +R["tee"] = cut and cut["evaluated"] +check("a tee with a box cut from it has no non-manifold edge: its branch hub is narrower than its run hub", receipt["status"] == "accepted" and cut + and cut["evaluated"]["nonManifoldEdges"] == 0 and 0.004 < cut["evaluated"]["volume"] < 0.008, [receipt["message"], cut and cut["evaluated"]]) + +# --- apply and empty material slots ----------------------------------------------------------------------------------------------- +keeper = place("Keeper", "plate", location=[0.0, -9.0, 0.0]) +send("assignMaterial", targetObjectName="Keeper", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) +keeper.data.materials.append(None) # an empty last slot the part was given +send("createObject", objectType="MESH", name="Bare", location=[0.1, -9.0, 0.0], size=0.1) +send("brokkr_kitbash.boolean", object_name="Keeper", cutter="Bare") +receipt, baked = send("brokkr_kitbash.apply", object_name="Keeper") +check("apply keeps a part's own empty last slot when the cutter has no material", receipt["status"] == "accepted" + and [m and m.name for m in keeper.data.materials] == ["Plate Paint", None] and len(keeper.material_slots) == 2, + [receipt["message"], [m and m.name for m in keeper.data.materials]]) +gapped = place("Gapped", "plate", location=[0.0, -12.0, 0.0]) +send("assignMaterial", targetObjectName="Gapped", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) +send("createObject", objectType="MESH", name="Gap", location=[0.1, -12.0, 0.0], size=0.1) +gap = bpy.data.objects["Gap"] +gap.data.materials.append(None) # the cutter's faces are in an empty first slot +gap.data.materials.append(bpy.data.materials["Boss Brass"]) +send("brokkr_kitbash.boolean", object_name="Gapped", cutter="Gap") +receipt, baked = send("brokkr_kitbash.apply", object_name="Gapped") +used = np.zeros(len(gapped.data.polygons), dtype=np.int32) +gapped.data.polygons.foreach_get("material_index", used) +check("apply leaves no face outside the material slots when a cutter's first slot is empty", receipt["status"] == "accepted" and len(used) > 44 + and used.min() >= 0 and used.max() < len(gapped.data.materials) and not gapped.data.validate_material_indices() and not gapped.data.validate(verbose=False), + [receipt["message"], int(used.min()), int(used.max()), [m and m.name for m in gapped.data.materials]]) + R["ok"] = all(c["ok"] for c in R["checks"]) R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json index 3be8cda..e51d21b 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.result.json +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -171,6 +171,56 @@ "ok": true, "detail": null }, + { + "name": "a child moved by NUDGE does not hold, and its residual is the move", + "ok": true, + "detail": null + }, + { + "name": "and set_params on its parent seats it again", + "ok": true, + "detail": null + }, + { + "name": "a kit_roll of nan reports roll null and does not hold", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a child whose kit_roll is nan", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on the parent of a child whose kit_roll is nan", + "ok": true, + "detail": null + }, + { + "name": "a kit_roll of 'x' reports roll null and does not hold", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a child whose kit_roll is 'x'", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on the parent of a child whose kit_roll is 'x'", + "ok": true, + "detail": null + }, + { + "name": "detach clears a roll that is not a number", + "ok": true, + "detail": null + }, + { + "name": "and the nozzle attaches again", + "ok": true, + "detail": null + }, { "name": "setObjectParent clearing an attached child's parent shows as a connection with no parent", "ok": true, @@ -330,24 +380,41 @@ "name": "refused, scene unchanged: a part larger than the seat", "ok": true, "detail": null + }, + { + "name": "a tee with a box cut from it has no non-manifold edge: its branch hub is narrower than its run hub", + "ok": true, + "detail": null + }, + { + "name": "apply keeps a part's own empty last slot when the cutter has no material", + "ok": true, + "detail": null + }, + { + "name": "apply leaves no face outside the material slots when a cutter's first slot is empty", + "ok": true, + "detail": null } ], "hostErrors": [], "readings": { "carried": 2.7e-07, + "cut": 0.25, "kept": 1.5e-08, + "nudged": 0.00032, "roll": 6.3e-06, "seated": 1.5e-07 }, "tank": { "raw": { - "faces": 740, - "volume": 0.264901065, + "faces": 764, + "volume": 0.264485537, "nonManifoldEdges": 0 }, "cut": { - "faces": 2337, - "volume": 0.25387923, + "faces": 2250, + "volume": 0.250847643, "nonManifoldEdges": 0 } }, @@ -368,5 +435,10 @@ "nonManifoldEdges": 0 } }, + "tee": { + "faces": 1661, + "volume": 0.006031088, + "nonManifoldEdges": 0 + }, "ok": true } \ No newline at end of file