From 8767699767e81e0c8927a612a0afc52f9442141b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:22:03 +0100 Subject: [PATCH 1/5] brokkr_kitbash: cut apply and kit_baked (cut kit-freeze, 1 of 2) apply's class, action row, docs and tests go, with BAKED and report's baked key. A destructive bake removed the stack and the collections that say what cuts a part; freeze and thaw replace it in the next commit. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 64 ++----------- .../brokkr_kitbash/brokkr_actions.json | 20 +--- surfaces/blender/docs/kitbash.md | 27 ++---- .../blender/tests/live/kitbash_assembly.py | 91 +------------------ surfaces/blender/tests/live/kitbash_shell.py | 21 +---- surfaces/blender/tests/test_kitbash.py | 14 +-- 6 files changed, 30 insertions(+), 207 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 299d1e6..3616982 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -10,15 +10,14 @@ WindowManager.brokkr_mesh_polish_result, as the polish operators do. What a placed part is lives on its object as three ID properties: kit_kit, kit_part and kit_params. The mesh is derived from them (set_params rebuilds it), and socket frames are derived again at every report: nothing else in the scene stores them. Two things would give a part a second owner and are refused: a mesh datablock shared with -another object (set_params, apply), and a world transform that scales, mirrors or shears (a part's size is its +another object (set_params), and a world transform that scales, mirrors or shears (a part's size is its params). A connection belongs to the child: its parent pointer (under an identity parent inverse) and three more ID properties, kit_socket, kit_parent_socket and kit_roll. Its matrix_basis is derived from them and both parts' params by core.mate; attach and set_params write it, and a report says how far the child stands from it. write_connection is the one writer of a connection. roll, aim and reach rewrite an attached part's roll through it, -in place: roll states the roll, aim and reach solve it in closed form (core.aim_roll, core.reach_roll). kit_baked -says apply replaced the mesh with the evaluated one: the params then only place the part's sockets. Placing a +in place: roll states the roll, aim and reach solve it in closed form (core.aim_roll, core.reach_roll). Placing a loose part, hiding a cutter, materials and export are Brokkr's own rows (setObjectTransform, setObjectVisibility, assignMaterial, exportGltf). @@ -33,7 +32,7 @@ identity parent inverse: its matrix_basis is the recess frame and its params the the cutter object moves the cut and its floor socket together, and nothing else stores either. Machinery attaches to a floor socket with the ordinary attach. Blender evaluates a changed target after every action, so each cut costs one Boolean evaluation; cut_many places many cutters for one. Every action that evaluates an object (boolean, cut, -cut_many, apply) first refuses one Blender does not evaluate (evaluable). A report's list that would not fit a +cut_many) first refuses one Blender does not evaluate (evaluable). A report's list that would not fit a receipt is trimmed by fitted, the rows left off counted beside it: the scene keeps what they would have said. ribs derives the frame under an armor cage from the cage: ribs behind the plate along plane sections, stopped where @@ -86,7 +85,7 @@ except ImportError as error: # register() says so; the classes below only need from . import core, route KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" -SOCKET, PARENT_SOCKET, ROLL, BAKED = "kit_socket", "kit_parent_socket", "kit_roll", "kit_baked" +SOCKET, PARENT_SOCKET, ROLL = "kit_socket", "kit_parent_socket", "kit_roll" 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) BEVEL = "Kit Bevel" @@ -181,7 +180,7 @@ def kit_part_of(obj, kits=None): def built_part(obj, kits=None): - """(part, the part built at the object's stored params): where its sockets are, baked or not.""" + """(part, the part built at the object's stored params): where its sockets are.""" part, stored = kit_part_of(obj, kits) return part, core.build(part, stored) @@ -353,8 +352,7 @@ def part_report(obj, part, built) -> dict: return {"object": obj.name, "kit": part["kit"], "part": part["name"], "params": built.params, "faces": len(obj.data.polygons), "shells": built.shell_count, "bevel": round(built.bevel, 6), "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world)), - "connection": connection_report(obj, part, built), "closure": closure_report(obj, part, built), - "baked": bool(obj.get(BAKED, False))} + "connection": connection_report(obj, part, built), "closure": closure_report(obj, part, built)} def own_mesh(obj, doing: str) -> None: @@ -402,14 +400,14 @@ def uncut(target, cutter) -> None: def evaluated_of(context, obj): """(depsgraph, obj with its modifier stack evaluated). An Exact Boolean costs from a few tenths of a second (a - kit part) to a few seconds (a subdivided shell), so only cut, boolean and apply call this; no report does.""" + kit part) to a few seconds (a subdivided shell), so only boolean and ribs call this; no report does.""" depsgraph = context.evaluated_depsgraph_get() return depsgraph, obj.evaluated_get(depsgraph) def evaluable(context, obj): """evaluated_of, for an object Blender evaluates: refuses one the evaluated depsgraph does not hold, which has no - evaluated mesh to cast at, cut or bake. Membership of the depsgraph is the test, whatever keeps the object out + evaluated mesh to cast at or cut. Membership of the depsgraph is the test, whatever keeps the object out of it. Every action that evaluates calls this before its first write.""" depsgraph, evaluated = evaluated_of(context, obj) if not evaluated.is_evaluated: @@ -558,9 +556,6 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): def work(self, context): obj = mesh_object(self.object_name) part, stored = kit_part_of(obj) - if obj.get(BAKED): - raise Refused(f"{obj.name!r} is baked: apply replaced its mesh, and its params now only place its sockets. " - "place_part a new part to change them; nothing changed.") own_mesh(obj, "rebuilding") 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 @@ -879,45 +874,6 @@ class BROKKR_KITBASH_OT_cut_many(PolishOperator): return report -class BROKKR_KITBASH_OT_apply(PolishOperator): - """Bake a kit part: its mesh becomes its evaluated mesh (Booleans and Bevel applied), every modifier goes with - the collections its Booleans held, its material slots stay, and it is marked baked; its sockets and connections - stay as they are, and so do the cutter objects""" - bl_idname = "brokkr_kitbash.apply" - bl_label = "Apply Kit Part" - object_name: bpy.props.StringProperty(name="Object") - - @kit_work - def work(self, context): - obj = mesh_object(self.object_name) - evaluable(context, obj) - part, built = built_part(obj) - own_mesh(obj, "baking") - if not obj.modifiers: - raise Refused(f"{obj.name!r} has no modifiers to apply; nothing changed.") - cutters, slots = [row["cutter"] for row in booleans(obj)], len(obj.data.materials) - depsgraph, evaluated = evaluated_of(context, obj) - 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 - held = [found for found in (operation_collection(obj, operation) for operation in OPERATIONS) if found is not None] - obj.data = baked - obj.modifiers.clear() - for collection in held: # a collection another object's modifier still reads (a copied part) stays - if collection.users == 0: - bpy.data.collections.remove(collection) - if old.users == 0: - bpy.data.meshes.remove(old) - baked.name = name - obj[BAKED] = True - return {**part_report(obj, part, built), **measured(baked), "cutters": cutters} - - RIBS = "kit_ribs" # on a ribs object: the request that derived it, as JSON; nothing reads it to decide geometry SAMPLES_LIMIT = 20000 # section points in one ribs: every chain's length over step, summed SHELL_MODIFIERS = ("SOLIDIFY", "BEVEL", "BOOLEAN") # what makes a designed surface a cut plate: off, the cage shows the surface @@ -1833,7 +1789,7 @@ class BROKKR_KITBASH_OT_describe(PolishOperator): class BROKKR_KITBASH_OT_report(PolishOperator): """Report placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world frame, - the connection and the closure and whether each holds, and whether the part is baked""" + the connection and the closure and whether each holds""" bl_idname = "brokkr_kitbash.report" bl_label = "Report Kit Parts" bl_options = {"REGISTER"} @@ -1848,7 +1804,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_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_apply, BROKKR_KITBASH_OT_ribs, + BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, 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 3ea95e9..2fc918f 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -45,7 +45,7 @@ }, { "name": "brokkr_kitbash.set_params", - "doc": "Change params of a placed kit part and rebuild its mesh in place; modifiers and materials stay, and its connection and the parts attached to it are seated again. Refuses a change that breaks a connection, a baked part, a mesh another object shares and a scaled part. Reports as place_part.", + "doc": "Change params of a placed kit part and rebuild its mesh in place; modifiers and materials stay, and its connection and the parts attached to it are seated again. Refuses a change that breaks a connection, a mesh another object shares and a scaled part. Reports as place_part.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -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 baked. 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). Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.", "changesScene": false, "editModeSafe": true, "result": "brokkr_mesh_polish_result", @@ -551,22 +551,6 @@ } ] }, - { - "name": "brokkr_kitbash.apply", - "doc": "Bake a kit part: its mesh becomes its evaluated mesh, every modifier goes, material slots stay, and it is marked baked (set_params then refuses it). Sockets and connections stay. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate.", - "changesScene": true, - "editModeSafe": false, - "result": "brokkr_mesh_polish_result", - "fields": [ - { - "name": "object_name", - "type": "string", - "required": true, - "minLength": 1, - "maxLength": 63 - } - ] - }, { "name": "brokkr_kitbash.ribs", "doc": "Derive the frame under an armor cage from the cage itself, so it fits the armor by construction: a rib along each plane's section of the cage's surface, set the standoff behind the plate's inner face (along the plate's normal, at any tilt of the plane and any curvature of the wall: its edge is cut from the inner face offset inward, then measured against the plate) and reaching depth inward, clipped inside a crease tighter than that; lightening holes through the ribs; posts that stand the plate off them; longerons through the ribs. The plate's two faces are read from the cage's one Solidify as it evaluates, whatever its thickness mode. A rib stops where the plate is open (a port cut through it), runs behind an opening shorter than bridge (a panel break) and under a recess: openings are read from the cage as it is cut, so cut first. Inward is the side the cage's normals face away from. Makes one mesh object, a child of the cage, baked at this call: after the cage or its cuts change, delete it and run ribs again (its kit_ribs property keeps the request). Every plane and longeron is checked before anything is written. Reports ribs, thickness, sections [{plane, chains, pieces, length, open}], posts, holes, longerons [{index, stations}], faces, volume and nonManifoldEdges.", diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 157b805..8e789ba 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -30,8 +30,7 @@ Who owns what: - A closure, the joint that closes a loop, belongs to the closing part: its `kit_close_socket`, `kit_close_to` and `kit_close_to_socket` properties. Only `close` writes them and only `detach` clears them. A closure places nothing: whether it holds is derived at each report. -- A boolean belongs to its Boolean modifier on the part that is cut. `kit_baked` says `apply` replaced the part's - mesh with the evaluated one. +- A boolean belongs to its Boolean modifier on the part that is cut. ## A part, end to end @@ -318,22 +317,12 @@ took 1.89 s through the collection modifier, 12.6 s with a Boolean modifier for eight cutters joined into one mesh (medians of five interleaved evaluations, Blender 5.3 on Starfire; an earlier probe with raw cutters read 2.04, 14.7 and 1.94 s). All three give the same faces and volume. The cost is the target's, hardly the cutters': one cutter on that shell already costs 1.4 s. The target pays it each time it is -evaluated, and Blender evaluates it after every action that changes it or a cutter. `apply` a kit part when its -shape is settled; a mesh that is not a kit part is baked by `exportGltf` with `applyModifiers`. `boolean` +evaluated, and Blender evaluates it after every action that changes it or a cutter. `boolean` evaluates the target once and reports `evaluated: {faces, volume, nonManifoldEdges}`; `report` never evaluates a modifier. The cutter is any other mesh object and is not changed: hide it with `setObjectVisibility`. A cutter with no material leaves the target's material slots as they are; a cutter that has materials brings them, after the target's own, on the faces it makes. -**`apply`** bakes a kit part: its mesh becomes the evaluated mesh (booleans and bevel applied), every modifier -goes with the collections its Booleans held, and `kit_baked` is set. The cutter objects stay: a cutter placed by -`cut` keeps its floor socket and what is attached to it. The material slots are the part's own (an empty one it had included), followed by any -a cutter brought; faces a cutter made from an empty slot of its own take the part's first slot. A baked part -keeps `kit_kit`, `kit_part`, `kit_params` and its connections: its sockets are still derived from the params, -so what is attached to it stays attached and new parts can attach to it, and it can be cut and baked again. -`set_params` refuses it, since the params no longer make the mesh. `exportGltf` with `applyModifiers` already -exports the evaluated mesh; `apply` is for a baked `.blend`. - ## Making a shell `shell` makes an armor plate the way one is modelled by hand: fit a sparse subdivision cage, crease the edges that @@ -430,7 +419,7 @@ medians of three interleaved calls in the live suite (Blender 5.3 on Starfire). are twisted, and the Boolean, which cuts quads into triangles, can read the wall as passing through itself and leave edges with four faces. On the Seraph's cap that began at 0.91 of the thickness at which the first face folds (0.0301 against 0.033), on the left cap and not on its mirror, the right; on its breast plate at 0.91 as -well (0.032 against 0.035). Read `nonManifoldEdges` after cutting (`boolean`, `apply`, or a count on the evaluated +well (0.032 against 0.035). Read `nonManifoldEdges` after cutting (`boolean`, or a count on the evaluated mesh), and keep `thickness` clear of the first folding one with a thinner wall, fewer `levels` or wider facets at the corner. @@ -504,7 +493,7 @@ attaching a part to a floor) costs an evaluation again while the target is visib more cutters than fit (about 150 of long names), the rows left off the end are counted in `booleansOmitted`. The scene keeps every cutter; the target's `Kit` modifier collections list them. -`cut`, `cut_many`, `boolean` and `apply` evaluate their object, and refuse one Blender does not evaluate in the +`cut`, `cut_many` and `boolean` evaluate their object, and refuse one Blender does not evaluate in the view layer: an object disabled in viewports that nothing evaluated depends on, or one whose collections no view layer shows. A disabled object that an evaluated object needs (a parent of one, a cutter of one) is evaluated all the same, and is cut. @@ -931,8 +920,8 @@ Python loop of BVH queries with three rays a sample, and the 13,824-candidate se | --- | --- | --- | | `brokkr_kitbash.describe` | `kit` (default `mechanical`), `part` (default: all) | Parts with their params (type, min, max, default, doc) and sockets in the part frame at default params. Changes nothing. | | `brokkr_kitbash.place_part` | `kit`, `part`, `object_name`, `params` | A new mesh object at the origin: the part's mesh, a `Kit Bevel` modifier when the part has a bevel, and the three ID properties. Refuses a name an object already has. | -| `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: modifiers and material slots stay, and the Bevel width follows. Per-face materials are carried by shape: each shape of the part keeps the material most of its faces had, whatever the new face count. Seats the part and the parts attached to it again; refuses a change that breaks a connection or a closure's mate, and a baked part. Reports the part and `closures`, every closure in the scene as `{part, to, holds}`: its own first, then the broken, then the rest; rows that would not fit a receipt are left off the end and counted in `closuresOmitted`. Each closure in the scene adds a few milliseconds (both its parts are built again to find their sockets). | -| `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, each socket's world frame, `connection`, `closure` and `baked`. Changes nothing and evaluates no modifier. | +| `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: modifiers and material slots stay, and the Bevel width follows. Per-face materials are carried by shape: each shape of the part keeps the material most of its faces had, whatever the new face count. Seats the part and the parts attached to it again; refuses a change that breaks a connection or a closure's mate. Reports the part and `closures`, every closure in the scene as `{part, to, holds}`: its own first, then the broken, then the rest; rows that would not fit a receipt are left off the end and counted in `closuresOmitted`. Each closure in the scene adds a few milliseconds (both its parts are built again to find their sockets). | +| `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, each socket's world frame, `connection` and `closure`. Changes nothing and evaluates no modifier. | | `brokkr_kitbash.attach` | `object_name` (the child), `socket`, `parent_name`, `parent_socket`, `roll` (degrees, -360 to 360, default 0) | Seats the child's socket on the parent's and parents it there; the two parts are of one kit or of two whose socket types agree. Reports the child. | | `brokkr_kitbash.detach` | `object_name` | Clears the part's connection and the closure it states; it stays where it stands. Refuses a part that has neither. | | `brokkr_kitbash.roll` | `object_name`, `roll` (degrees, -360 to 360) | Turns an attached part to that roll where it hangs. Refuses a part that is not attached. Reports the part and `closures` as `set_params` does. | @@ -942,7 +931,6 @@ Python loop of BVH queries with three rays a sample, and the 13,824-candidate se | `brokkr_kitbash.boolean` | `object_name` (any mesh), `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds the cutter to the collection of the target's one live Exact Boolean for the operation, above the Bevel. Refuses a cutter that is the target, is not a mesh, or already cuts it, and a scaled target. Reports the part (or `object` for a mesh that is not one), `booleans: [{cutter, operation}]` (difference, union, intersect; each in the order added; `booleansOmitted` counts rows a receipt had no room for) and `evaluated`. | | `brokkr_kitbash.cut` | `object_name` (any mesh), `cutter_name`, `part` (`box`, `cyl`, `slot`, `slab`), `params`, `origin_x/y/z`, `direction_x/y/z`, `up_x/y/z` (default 0, 0, 1), `roll` (degrees, default 0), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans` (with `booleansOmitted`, as `boolean`). | | `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans` (with `booleansOmitted`, as `boolean`). | -| `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | | `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | | `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel`, `count_folds` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `folded` (with `count_folds`, the number of the evaluated wall's inner faces that fold; else null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | | `brokkr_kitbash.hose` | `object_name`, `start`, `end`, `count`, `radius`, `spread`, `clearance`, `bend`, `step`, `sag`, `clamps` (a JSON array of up to 8 `{socket}`), `joint` (empty, or a JSON object `{socket, standoff, range}`) | Routes a bundle of hoses between two sockets around every other mesh, over clamps and through a pin's axis across its roll range; on a hose's name, rebuilds it in place. Reports `length`, `lengthChange`, `clearance`, `radii`, `sag`, `voxels`, `seed`, `rolls`, `worstRoll`, `faces`, `nonManifoldEdges`. | @@ -979,7 +967,6 @@ assembly by its root: an attached part is placed by its connection. {"action": "createObject", "objectType": "MESH", "name": "Cutter", "location": [0.3, 0.6, 0], "size": 0.2}, {"action": "brokkr_kitbash.boolean", "object_name": "Tank", "cutter": "Cutter"}, {"action": "setObjectVisibility", "targetObjectName": "Cutter", "visible": false}, - {"action": "brokkr_kitbash.apply", "object_name": "Tank"}, {"action": "brokkr_kitbash.report", "object_name": "Nozzle"}, {"action": "exportGltf", "filepath": "engine.glb", "selection": ["Tank", "Tee", "Nozzle"]} ]} @@ -1070,6 +1057,6 @@ frame `cut` gives a cutter. `MateTests` covers the mate arithmetic and what may `PoseTests` the closed-form rolls. The operators are exercised in a real Blender by `tests/live/kitbash.py` (placing and re-parameterising, and the frame kit: its nine parts placed, the truss re-parameterised, a beam seated on a bracket), `tests/live/kitbash_assembly.py` (attach, detach, -`set_params` on assemblies, a braced leg closed by `close`, boolean and apply), `tests/live/kitbash_shell.py` +`set_params` on assemblies, a braced leg closed by `close` and boolean), `tests/live/kitbash_shell.py` (`cut` and `cut_many` on a cage that is not a kit part, a part on a cutter's floor, the three Boolean modifiers, an object in no collection) and `tests/live/kitbash_pose.py` (roll, aim and reach). diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 33b580e..4371f5f 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -1,6 +1,6 @@ """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, a braced leg closed by close and what set_params, -attach and detach then do, drift and how it is cleared, a roll that is not a number, detach, boolean (one Exact Boolean modifier per operation over a collection of cutters, self-intersection on, above the Bevel), and apply with its material slots. Not part +attach and detach then do, drift and how it is cleared, a roll that is not a number, detach, boolean (one Exact Boolean modifier per operation over a collection of cutters, self-intersection on, above the Bevel). 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 -- @@ -199,8 +199,7 @@ try: radiator = place("Radiator", "radiator_stack", location=[0.0, 10.0, 0.0]) send("createObject", objectType="MESH", name="Plain", location=[0.0, 12.0, 0.0], size=0.3) receipt, report = send("brokkr_kitbash.report", object_name="Tank") - check("a part nobody attached reports connection null and baked false", report and report["parts"][0]["connection"] is None - and report["parts"][0]["baked"] is False, report) + check("a part nobody attached reports connection null", report and report["parts"][0]["connection"] is None, report) receipt, report = send("brokkr_kitbash.attach", object_name="Nozzle", socket="mount", parent_name="Tee", parent_socket="c", roll=37.0) check("attach parents the nozzle to the tee under an identity parent inverse and stores the three properties", receipt["status"] == "accepted" @@ -599,36 +598,6 @@ try: and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], report["params"]).counts) != raw["faces"] and CUT < resized["volume"] < measure(tank.data)["volume"] - 0.005 and holds("Tee", "Tank", "b", "port_a", 180.0)[0], [receipt["message"], resized]) - # --- apply ------------------------------------------------------------------------------------------------------------------------ - refused("apply on a mesh that is not a kit part", "brokkr_kitbash.apply", {"object_name": "Plain"}, "'Plain' is not a kit part") - slots = [s.material and s.material.name for s in tank.material_slots] - shown, shown_slots = evaluated(tank) - index = np.zeros(len(tank.data.polygons), dtype=np.int32) - tank.data.polygons.foreach_get("material_index", index) - mesh_name, meshes, collections = tank.data.name, len(bpy.data.meshes), len(bpy.data.collections) - sockets_before = send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["sockets"] - receipt, baked = send("brokkr_kitbash.apply", object_name="Tank") - after = np.zeros(len(tank.data.polygons), dtype=np.int32) - tank.data.polygons.foreach_get("material_index", after) - check("apply makes the evaluated mesh the tank's mesh: the same faces and volume, no modifiers, one mesh datablock of the old name", - receipt["status"] == "accepted" and baked and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown == measure(tank.data) - and len(tank.modifiers) == 0 and tank.data.name == mesh_name and len(bpy.data.meshes) == meshes and baked["cutters"] == ["Box"] - and len(bpy.data.collections) == collections - 1 and "Tank difference" not in bpy.data.collections and "Box" in bpy.context.scene.objects, [receipt["message"], baked, shown]) - check("apply keeps the material slots exactly, and faces of both materials", slots == shown_slots == ["Tank Paint", "Strap Steel"] - and [s.material and s.material.name for s in tank.material_slots] == slots and [m and m.name for m in tank.data.materials] == slots - and index.max() == 1 and sorted(set(after.tolist())) == [0, 1], [slots, [m and m.name for m in tank.data.materials], sorted(set(after.tolist()))]) - check("apply marks the part baked and keeps what it is", tank.get("kit_baked") is True and baked and baked["baked"] is True and tank["kit_part"] == "tank" - and json.loads(tank["kit_params"])["segments"] == 16, dict(tank.items())) - refused("set_params on a baked part", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"}, "'Tank' is baked") - refused("apply on a baked part with no modifiers left", "brokkr_kitbash.apply", {"object_name": "Tank"}, "'Tank' has no modifiers to apply") - receipt, report = send("brokkr_kitbash.report", object_name="Tank") - check("a baked part still reports its sockets where its params put them, and what is attached to it still holds", report and report["parts"][0]["baked"] is True - and report["parts"][0]["sockets"] == sockets_before and report["parts"][0]["faces"] == baked["faces"] and holds("Tee", "Tank", "b", "port_a", 180.0)[0] - and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], report) - receipt, report = send("brokkr_kitbash.attach", object_name="Radiator", socket="base", parent_name="Tank", parent_socket="saddle") - check("a new part attaches to a baked one", receipt["status"] == "accepted" and held(report) - and reading("seated", seated(radiator, "base", tank, "saddle", 0.0)) < SEATED, receipt["message"]) - # --- the second target: a plate with no material slot, cut twice ---------------------------------------------------------------------- plate = place("Plate", "plate", location=[0.0, -3.0, 0.0]) send("createObject", objectType="MESH", name="Slot", location=[0.1, -3.0, 0.0], size=0.1) @@ -643,33 +612,9 @@ try: and all(m.use_self and m.solver == "EXACT" for m in plate.modifiers if m.type == "BOOLEAN"), [[m.name for m in plate.modifiers], first and first["evaluated"], second and second["evaluated"]]) R["plate"] = {"raw": measure(plate.data), "slot": first and first["evaluated"], "slotAndHole": second and second["evaluated"]} - twin = plate.copy() - twin.name = "Plate_twin" - bpy.context.scene.collection.objects.link(twin) - refused("apply on a mesh a linked duplicate shares", "brokkr_kitbash.apply", {"object_name": "Plate"}, "shares its mesh 'Plate' with 1 other user(s): baking it") - bpy.data.objects.remove(twin) - shown, shown_slots = evaluated(plate) - receipt, baked = send("brokkr_kitbash.apply", object_name="Plate") - check("apply on a part with no material slot leaves it with none (Blender's Boolean shows it with one empty slot)", receipt["status"] == "accepted" - and shown_slots == [None] and len(plate.data.materials) == 0 and len(plate.material_slots) == 0 and baked["cutters"] == ["Slot", "Hole"] - and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown, [shown_slots, len(plate.data.materials), len(plate.material_slots), baked]) - send("assignMaterial", targetObjectName="Plate", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) - send("createObject", objectType="MESH", name="Boss", location=[0.0, -3.0, 0.1], size=0.06) - send("assignMaterial", targetObjectName="Boss", materialName="Boss Brass", color=[0.6, 0.5, 0.2]) - send("setObjectTransform", targetObjectName="Boss", location=[0.0, -3.0, 0.02]) - receipt, third = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Boss", operation="UNION") - shown, shown_slots = evaluated(plate) - receipt, baked = send("brokkr_kitbash.apply", object_name="Plate") - used = np.zeros(len(plate.data.polygons), dtype=np.int32) - plate.data.polygons.foreach_get("material_index", used) - check("a baked part is cut and baked again; a cutter that has a material brings it after the part's own slots, on the faces it made", - receipt["status"] == "accepted" and third["booleans"] == [{"cutter": "Boss", "operation": "UNION"}] and third["baked"] is True - and third["evaluated"]["volume"] > R["plate"]["slotAndHole"]["volume"] and shown_slots == ["Plate Paint", "Boss Brass"] - and [m and m.name for m in plate.data.materials] == ["Plate Paint", "Boss Brass"] and sorted(set(used.tolist())) == [0, 1] - and len(plate.modifiers) == 0, [third and third["evaluated"], shown_slots, [m and m.name for m in plate.data.materials], sorted(set(used.tolist()))]) vent = place("Vent", "vent", "width=0.2; height=0.15") receipt, report = send("brokkr_kitbash.attach", object_name="Vent", socket="back", parent_name="Plate", parent_socket="front") - check("a vent that fits attaches to the baked plate's front", receipt["status"] == "accepted" and held(report) + check("a vent that fits attaches to the cut plate's front", receipt["status"] == "accepted" and held(report) and reading("seated", seated(vent, "back", plate, "front", 0.0)) < SEATED, receipt["message"]) refused("a loop of two", "brokkr_kitbash.attach", {"object_name": "Plate", "socket": "back", "parent_name": "Vent", "parent_socket": "back"}, "'Vent' is below 'Plate'") @@ -686,36 +631,6 @@ try: 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"]) - gap.data.polygons[0].material_index = gap.data.polygons[1].material_index = 1 # two of its faces are brass; the rest stay in the empty slot - 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]]) - names = [m and m.name for m in gapped.data.materials] - brass = [p.index for p in gapped.data.polygons if "Boss Brass" in names and p.material_index == names.index("Boss Brass")] - far = [p.index for p in gapped.data.polygons if (gapped.matrix_world @ p.center).x < -0.05] # the plate's half the cutter does not reach - check("and each face keeps its own slot: the cutter's brass faces are brass, the faces from its empty slot and the plate's own are the plate's paint", - names[0] == "Plate Paint" and 0 < len(brass) < len(used) and far and all(used[i] == 0 for i in far) - and all(abs((gapped.matrix_world @ gapped.data.polygons[i].center).x - 0.1) < 0.051 for i in brass), [names, len(brass), len(far), sorted(set(used.tolist()))]) except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) diff --git a/surfaces/blender/tests/live/kitbash_shell.py b/surfaces/blender/tests/live/kitbash_shell.py index d5f8e20..02f2c66 100644 --- a/surfaces/blender/tests/live/kitbash_shell.py +++ b/surfaces/blender/tests/live/kitbash_shell.py @@ -259,7 +259,7 @@ try: check("the evaluated cage stays a closed wall and loses volume with each cut", all(falls) and len(falls) == 4, R["cage"]) receipt, report = send("brokkr_kitbash.report", object_name="") check("report lists the cutters as kit parts and not the cage", report and [p["object"] for p in report["parts"]] == sorted(c[0] for c in CUTS) - and all(p["connection"] is None and p["baked"] is False for p in report["parts"]), report and [p["object"] for p in report["parts"]]) + and all(p["connection"] is None for p in report["parts"]), report and [p["object"] for p in report["parts"]]) # --- cut-casts-the-uncut-surface -------------------------------------------------------------------------------------------- section('cut-casts-the-uncut-surface') @@ -398,23 +398,6 @@ try: receipt["status"] == "accepted" and stack(plate) == ["Kit Difference", "Kit Union", "Kit Intersect", "Kit Bevel"] and report["booleans"] == [{"cutter": "Hole", "operation": "DIFFERENCE"}, {"cutter": "Boss", "operation": "UNION"}, {"cutter": "Keep", "operation": "INTERSECT"}] and report["evaluated"]["nonManifoldEdges"] == 0 and report["kit"] == "mechanical", [stack(plate), report and report["booleans"]]) - collections = len(bpy.data.collections) - receipt, baked = send("brokkr_kitbash.apply", object_name="Plate") - check("apply removes the three collections its modifiers held and leaves every cutter in the scene", receipt["status"] == "accepted" - and baked["cutters"] == ["Hole", "Boss", "Keep"] and len(bpy.data.collections) == collections - 3 and len(plate.modifiers) == 0 - and all(name in bpy.context.scene.objects for name in ("Hole", "Boss", "Keep")), [receipt["message"], [c.name for c in bpy.data.collections]]) - refused("apply on the cage, which is not a kit part", "brokkr_kitbash.apply", {"object_name": "Cage"}, "'Cage' is not a kit part") - twin = place("Twin", "plate", location=[0.0, -15.0, 0.0]) - send("createObject", objectType="MESH", name="TwinHole", location=[0.0, -15.0, 0.0], size=0.05) - send("brokkr_kitbash.boolean", object_name="Twin", cutter="TwinHole") - copied = twin.copy() # a copied part: its own mesh, and a Kit Difference modifier that reads the same collection - copied.data = twin.data.copy() - bpy.context.scene.collection.objects.link(copied) - receipt, baked = send("brokkr_kitbash.apply", object_name="Twin") - kept = bpy.data.collections.get("Twin difference") - check("M6: apply keeps a collection a copied part's modifier still reads", receipt["status"] == "accepted" and len(twin.modifiers) == 0 and kept is not None - and copied.modifiers["Kit Difference"].collection == kept and [o.name for o in kept.objects] == ["TwinHole"], [receipt["message"], [c.name for c in bpy.data.collections]]) - # --- cut-refusals ----------------------------------------------------------------------------------------------------------- section('cut-refusals') RAY = {"object_name": "Cage", "cutter_name": "New", "part": "box", "origin_x": 3.0, "origin_y": 0.0, "origin_z": 0.1, "direction_x": -1.0, "direction_y": 0.0, "direction_z": 0.0} @@ -471,8 +454,6 @@ try: refused(f"cut_many on a target {why}", "brokkr_kitbash.cut_many", {"object_name": name, "cuts": json.dumps([{"name": "Unseen", "part": "box", "origin": [0.1, 0.1, 3.0], "direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]}])}, NOT) refused(f"boolean on a target {why}", "brokkr_kitbash.boolean", {"object_name": name, "cutter": "Sheet"}, NOT) - refused("apply on a part disabled in viewports", "brokkr_kitbash.apply", {"object_name": "Plate"}, "Blender does not evaluate 'Plate' in this view layer") - refused("apply on a part in a collection outside the view layer", "brokkr_kitbash.apply", {"object_name": "Loose"}, "Blender does not evaluate 'Loose' in this view layer") veil.hide_viewport = plate.hide_viewport = False bpy.context.view_layer.update() diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 6b5da5f..0ade179 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1812,7 +1812,7 @@ 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.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", "brokkr_kitbash.ribs", + "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.ribs", "brokkr_kitbash.shell", "brokkr_kitbash.hose"] @@ -1859,7 +1859,7 @@ class HostFileTests(unittest.TestCase): self.assertEqual(at.validate(boolean, host)["operation"], "DIFFERENCE") for bad in ({**attach, "roll": 360.5}, {**attach, "socket": "a b"}, {**attach, "parent_socket": ""}, {**attach, "matrix": [1, 0, 0]}, {**boolean, "operation": "SLICE"}, {**boolean, "solver": "EXACT"}, {**boolean, "cutter": ""}, - {**envelope, "action": "brokkr_kitbash.apply"}, {**envelope, "action": "brokkr_kitbash.detach", "object_name": "x" * 64}, + {**envelope, "action": "brokkr_kitbash.detach", "object_name": "x" * 64}, {**close, "socket": "end b"}, {**close, "other_socket": "x" * 33}, {**close, "other_name": ""}, {**close, "roll": 10}, {k: v for k, v in close.items() if k != "other_socket"}): with self.assertRaises(at.IntentInvalid, msg=str(bad)): @@ -1958,25 +1958,25 @@ 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_only_cut_boolean_and_apply_evaluate_a_modifier_stack(self): + 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.""" source = self.sources()["__init__.py"] self.assertEqual(source.count("evaluated_get("), 1) self.assertIn("evaluated_get(", source.split("def evaluated_of(")[1].split("\n\n\n")[0]) bodies = {body.split("(")[0]: body.split("\n\n\n")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:]} - self.assertEqual([name for name, body in bodies.items() if "evaluated_of(" in body], ["boolean", "apply", "ribs"]) - self.assertEqual(source.count("evaluated_of("), 7) # its def, evaluable, boolean, apply, and ribs for the designed surface, for the plate's two faces and for its holes + self.assertEqual([name for name, body in bodies.items() if "evaluated_of(" in body], ["boolean", "ribs"]) + self.assertEqual(source.count("evaluated_of("), 6) # its def, evaluable, boolean, and ribs for the designed surface, for the plate's two faces and for its holes self.assertIn("evaluated_of(", source.split("def evaluable(")[1].split("\n\n\n")[0]) place = source.split("def place_cutters(")[1].split("\n\n\n")[0] # cut and cut_many place through it: one evaluation, with the Booleans off self.assertEqual((place.count("evaluable("), place.count("evaluated_of(")), (1, 0)) self.assertLess(place.index("modifier.show_viewport = False"), place.index("evaluable(")) self.assertLess(place.index("evaluable("), place.index("modifier.show_viewport = True")) # unevaluable-target: every action that evaluates refuses an object Blender does not evaluate before its first write - for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["apply"], "bpy.data.meshes.new_from_object("), + for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["ribs"], "show_viewport = False"), (bodies["shell"], "clear_geometry()")): self.assertLess(body.index("evaluable("), body.index(first_write)) - self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply", "ribs", "shell", "hose"]) + self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "ribs", "shell", "hose"]) ribs = bodies["ribs"] # every refusal before the ribs object is written, and the cage's modifiers shown again whatever happened self.assertLess(ribs.rindex("raise Refused("), ribs.index("mesh = bpy.data.meshes.new(self.ribs_name)")) self.assertLess(ribs.index("finally:"), ribs.index("modifier.show_viewport = True")) -- 2.47.3 From 6ea92025553d8ba65d526a479785313c20886bec Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:33:29 +0100 Subject: [PATCH 2/5] brokkr_kitbash.freeze and thaw: a cut object carries its evaluated mesh, its live mesh held in kit_frozen, its stack kept and off (cut kit-freeze, 2 of 2) Blender re-evaluates every live collection Boolean after any datablock removal, hide or mesh read in the scene. freeze swaps in the evaluated mesh and turns every modifier off; thaw is its one undo. live() refuses a frozen object in set_params, boolean, cut, cut_many, ribs, a shell or hose rebuild and freeze. Live: three cut tanks frozen cost 0.0022 of what they cost live when an orphan mesh is removed (mutant F1, modifiers left on: 1.5; bound 0.057). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 96 ++++++++- .../brokkr_kitbash/brokkr_actions.json | 36 +++- .../blender/tests/live/kitbash.result.json | 3 +- .../blender/tests/live/kitbash_assembly.py | 182 +++++++++++++++++- .../tests/live/kitbash_assembly.result.json | 143 ++++++++++++-- surfaces/blender/tests/live/kitbash_shell.py | 53 +++++ .../tests/live/kitbash_shell.result.json | 55 +++++- surfaces/blender/tests/test_kitbash.py | 19 +- 8 files changed, 546 insertions(+), 41 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 3616982..3ff8135 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -1,5 +1,5 @@ """Kitbash parts: place parametric machine parts from a kit, mate them socket to socket, cut them and any other -mesh, and bake them. +mesh, and freeze them. A host add-on for Brokkr beside brokkr_mesh_polish and brokkr_rig (it imports the polish package's operator base, Refused and mesh_object, and nothing from Brokkr): brokkr_actions.json beside this file lists the operators agents @@ -17,7 +17,9 @@ A connection belongs to the child: its parent pointer (under an identity parent properties, kit_socket, kit_parent_socket and kit_roll. Its matrix_basis is derived from them and both parts' params by core.mate; attach and set_params write it, and a report says how far the child stands from it. write_connection is the one writer of a connection. roll, aim and reach rewrite an attached part's roll through it, -in place: roll states the roll, aim and reach solve it in closed form (core.aim_roll, core.reach_roll). Placing a +in place: roll states the roll, aim and reach solve it in closed form (core.aim_roll, core.reach_roll). kit_frozen +is the frozen state: freeze holds the live mesh there while the object carries its evaluated one with every modifier +off, and thaw is its one undo. Placing a loose part, hiding a cutter, materials and export are Brokkr's own rows (setObjectTransform, setObjectVisibility, assignMaterial, exportGltf). @@ -32,7 +34,7 @@ identity parent inverse: its matrix_basis is the recess frame and its params the the cutter object moves the cut and its floor socket together, and nothing else stores either. Machinery attaches to a floor socket with the ordinary attach. Blender evaluates a changed target after every action, so each cut costs one Boolean evaluation; cut_many places many cutters for one. Every action that evaluates an object (boolean, cut, -cut_many) first refuses one Blender does not evaluate (evaluable). A report's list that would not fit a +cut_many, freeze) first refuses one Blender does not evaluate (evaluable). A report's list that would not fit a receipt is trimmed by fitted, the rows left off counted beside it: the scene keeps what they would have said. ribs derives the frame under an armor cage from the cage: ribs behind the plate along plane sections, stopped where @@ -86,6 +88,7 @@ from . import core, route KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" SOCKET, PARENT_SOCKET, ROLL = "kit_socket", "kit_parent_socket", "kit_roll" +FROZEN = "kit_frozen" # on a frozen object: an ID pointer to its live mesh; its presence is the frozen state, freeze sets it and thaw deletes it 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) BEVEL = "Kit Bevel" @@ -352,7 +355,15 @@ def part_report(obj, part, built) -> dict: return {"object": obj.name, "kit": part["kit"], "part": part["name"], "params": built.params, "faces": len(obj.data.polygons), "shells": built.shell_count, "bevel": round(built.bevel, 6), "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world)), - "connection": connection_report(obj, part, built), "closure": closure_report(obj, part, built)} + "connection": connection_report(obj, part, built), "closure": closure_report(obj, part, built), + "frozen": FROZEN in obj} + + +def live(obj, doing: str) -> None: + """Refuses a frozen object: its mesh is its frozen evaluation and its modifiers are off, so a write would land on + a mesh thaw discards, or under a stack nothing evaluates.""" + if FROZEN in obj: + raise Refused(f"{obj.name!r} is frozen, and {doing} it needs its live mesh and modifiers: thaw it first; nothing changed.") def own_mesh(obj, doing: str) -> None: @@ -400,14 +411,14 @@ def uncut(target, cutter) -> None: def evaluated_of(context, obj): """(depsgraph, obj with its modifier stack evaluated). An Exact Boolean costs from a few tenths of a second (a - kit part) to a few seconds (a subdivided shell), so only boolean and ribs call this; no report does.""" + kit part) to a few seconds (a subdivided shell), so only boolean, freeze (through evaluable) and ribs call this; no report does.""" depsgraph = context.evaluated_depsgraph_get() return depsgraph, obj.evaluated_get(depsgraph) def evaluable(context, obj): """evaluated_of, for an object Blender evaluates: refuses one the evaluated depsgraph does not hold, which has no - evaluated mesh to cast at or cut. Membership of the depsgraph is the test, whatever keeps the object out + evaluated mesh to cast at, cut or freeze. Membership of the depsgraph is the test, whatever keeps the object out of it. Every action that evaluates calls this before its first write.""" depsgraph, evaluated = evaluated_of(context, obj) if not evaluated.is_evaluated: @@ -470,6 +481,7 @@ def place_cutters(context, target, specs) -> list: first did, and no Boolean is evaluated here. Blender evaluates the changed target once after the action, however many cutters it placed.""" rigid(target) + live(target, "cutting") kit, made, names = core.load_kit(CUTTERS), [], set() for spec in specs: name = spec["name"] @@ -556,6 +568,7 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): def work(self, context): obj = mesh_object(self.object_name) part, stored = kit_part_of(obj) + live(obj, "setting params of") own_mesh(obj, "rebuilding") 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 @@ -792,6 +805,7 @@ class BROKKR_KITBASH_OT_boolean(PolishOperator): raise Refused(f"{obj.name!r} cannot cut itself; nothing changed.") report = part_report(obj, *built_part(obj)) if PART in obj else {"object": obj.name} rigid(obj) + live(obj, "cutting") uncut(obj, cutter) evaluable(context, obj) operation_collection(obj, self.operation, True).objects.link(cutter) @@ -874,6 +888,68 @@ class BROKKR_KITBASH_OT_cut_many(PolishOperator): return report +class BROKKR_KITBASH_OT_freeze(PolishOperator): + """Freeze a mesh object that has modifiers, a kit part or any other: its mesh becomes its evaluated mesh, its live + mesh is held by its kit_frozen property, and every modifier stays in the stack, off in viewports and renders, with + its collections; Blender then evaluates no Boolean for it until thaw""" + bl_idname = "brokkr_kitbash.freeze" + bl_label = "Freeze Cut Object" + object_name: bpy.props.StringProperty(name="Object", description="A mesh with modifiers: a kit part, a shell or any mesh") + + @kit_work + def work(self, context): + obj = mesh_object(self.object_name) + live(obj, "freezing") + if not obj.modifiers: + raise Refused(f"{obj.name!r} has no modifiers to freeze; nothing changed.") + off = [modifier.name for modifier in obj.modifiers if not (modifier.show_viewport and modifier.show_render)] + if off: + raise Refused(f"{obj.name!r} has {', '.join(off)} off in viewports or renders, and thaw turns every modifier on: " + "it would not give this stack back. Show them, or remove them; nothing changed.") + report = part_report(obj, *built_part(obj)) if PART in obj else {"object": obj.name} + depsgraph, evaluated = evaluable(context, obj) + slots = len(obj.data.materials) + frozen = bpy.data.meshes.new_from_object(evaluated, preserve_all_data_layers=True, depsgraph=depsgraph) + while len(frozen.materials) > slots and frozen.materials[len(frozen.materials) - 1] is None: + frozen.materials.pop() # a Boolean gives a part that had no material slot one empty slot + index = np.zeros(len(frozen.polygons), dtype=np.int32) + frozen.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 + frozen.polygons.foreach_set("material_index", np.maximum(index, 0)) + frozen.name = f"{obj.name} frozen" + obj[FROZEN] = obj.data + obj.data = frozen + for modifier in obj.modifiers: + modifier.show_viewport = modifier.show_render = False + report.update(frozen=True, **measured(frozen), modifiers=[modifier.name for modifier in obj.modifiers]) + report["booleans"] = fitted(report, "booleans", booleans(obj)) + return report + + +class BROKKR_KITBASH_OT_thaw(PolishOperator): + """Thaw a frozen object: its live mesh comes back from kit_frozen, every modifier is turned on, and the frozen mesh + goes; evaluates nothing itself (Blender evaluates the object once afterwards)""" + bl_idname = "brokkr_kitbash.thaw" + bl_label = "Thaw Frozen Object" + object_name: bpy.props.StringProperty(name="Object", description="A frozen mesh object") + + @kit_work + def work(self, context): + obj = mesh_object(self.object_name) + if FROZEN not in obj: + raise Refused(f"{obj.name!r} is not frozen; nothing changed.") + held, frozen = obj[FROZEN], obj.data + if not isinstance(held, bpy.types.Mesh): + raise Refused(f"{obj.name!r} is frozen and the live mesh its {FROZEN} held is gone: there is nothing to thaw to; nothing changed.") + obj.data = held + del obj[FROZEN] + for modifier in obj.modifiers: + modifier.show_viewport = modifier.show_render = True + if frozen.users == 0: + bpy.data.meshes.remove(frozen) + return {"object": obj.name, "frozen": False, "modifiers": [modifier.name for modifier in obj.modifiers], "faces": len(held.polygons)} + + RIBS = "kit_ribs" # on a ribs object: the request that derived it, as JSON; nothing reads it to decide geometry SAMPLES_LIMIT = 20000 # section points in one ribs: every chain's length over step, summed SHELL_MODIFIERS = ("SOLIDIFY", "BEVEL", "BOOLEAN") # what makes a designed surface a cut plate: off, the cage shows the surface @@ -985,6 +1061,7 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): def work(self, context): cage = mesh_object(self.object_name) rigid(cage) + live(cage, "deriving ribs from") depsgraph, _ = evaluable(context, cage) if not 1 <= len(self.ribs_name) <= 63 or self.ribs_name in bpy.data.objects: raise Refused(f"ribs_name {self.ribs_name!r} must be 1 to 63 characters and no object's name; nothing changed.") @@ -1292,6 +1369,7 @@ class BROKKR_KITBASH_OT_shell(PolishOperator): if obj.type != "MESH" or SHELL not in obj: raise Refused(f"An object named {obj.name!r} exists and is no shell (it carries no {SHELL}): shell rebuilds only what shell made; nothing changed.") rigid(obj) + live(obj, "rebuilding") own_mesh(obj, "rebuilding") if self.count_folds: unseen = [modifier.name for modifier in obj.modifiers if modifier.name in (SUBSURF, SOLIDIFY) and not modifier.show_viewport] @@ -1408,6 +1486,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): if hose is not None: if hose.type != "MESH" or HOSE not in hose: raise Refused(f"An object named {hose.name!r} exists and is no hose (it carries no {HOSE}): hose rebuilds only what hose made; nothing changed.") + live(hose, "rebuilding") own_mesh(hose, "rebuilding") sizes = route.bundle(self.count, self.radius, self.spread, self.clearance, self.bend) r, need, floor, lead, half_width = self.radius, sizes["need"], sizes["floor"], sizes["lead"], sizes["envelope"] - self.radius @@ -1789,7 +1868,7 @@ class BROKKR_KITBASH_OT_describe(PolishOperator): class BROKKR_KITBASH_OT_report(PolishOperator): """Report placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world frame, - the connection and the closure and whether each holds""" + the connection and the closure and whether each holds, and whether the part is frozen""" bl_idname = "brokkr_kitbash.report" bl_label = "Report Kit Parts" bl_options = {"REGISTER"} @@ -1804,7 +1883,8 @@ 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_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_ribs, + 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 2fc918f..17a3d57 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -45,7 +45,7 @@ }, { "name": "brokkr_kitbash.set_params", - "doc": "Change params of a placed kit part and rebuild its mesh in place; modifiers and materials stay, and its connection and the parts attached to it are seated again. Refuses a change that breaks a connection, a mesh another object shares and a scaled part. Reports as place_part.", + "doc": "Change params of a placed kit part and rebuild its mesh in place; modifiers and materials stay, and its connection and the parts attached to it are seated again. Refuses a change that breaks a connection, a frozen part, a mesh another object shares and a scaled part. Reports as place_part.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -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). 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 frozen. Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.", "changesScene": false, "editModeSafe": true, "result": "brokkr_mesh_polish_result", @@ -551,6 +551,38 @@ } ] }, + { + "name": "brokkr_kitbash.freeze", + "doc": "Freeze a mesh object that has modifiers (a kit part, a shell or any mesh) when its cuts are settled: its mesh becomes its evaluated mesh, its live mesh is held by its kit_frozen property, and every modifier stays in the stack, turned off, with its collections and cutters. Blender re-evaluates a live collection Boolean after any removal, hide or mesh read anywhere in the scene; a frozen object costs nothing there. Sockets, connections and report rows stay. set_params, boolean, cut, cut_many, ribs and a shell or hose rebuild refuse a frozen object: thaw it first. Refuses a frozen object, one with no modifiers, one with a modifier already off (named) and one Blender does not evaluate. Reports object (or the part), frozen, faces, volume, nonManifoldEdges, modifiers and booleans.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + } + ] + }, + { + "name": "brokkr_kitbash.thaw", + "doc": "Thaw a frozen object: its live mesh comes back, every modifier is turned on, and the frozen mesh is removed. Evaluates nothing; Blender evaluates the object once afterwards. Refuses an object that is not frozen or whose held mesh is gone. Reports object, frozen false, modifiers and the live mesh's faces.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + } + ] + }, { "name": "brokkr_kitbash.ribs", "doc": "Derive the frame under an armor cage from the cage itself, so it fits the armor by construction: a rib along each plane's section of the cage's surface, set the standoff behind the plate's inner face (along the plate's normal, at any tilt of the plane and any curvature of the wall: its edge is cut from the inner face offset inward, then measured against the plate) and reaching depth inward, clipped inside a crease tighter than that; lightening holes through the ribs; posts that stand the plate off them; longerons through the ribs. The plate's two faces are read from the cage's one Solidify as it evaluates, whatever its thickness mode. A rib stops where the plate is open (a port cut through it), runs behind an opening shorter than bridge (a panel break) and under a recess: openings are read from the cage as it is cut, so cut first. Inward is the side the cage's normals face away from. Makes one mesh object, a child of the cage, baked at this call: after the cage or its cuts change, delete it and run ribs again (its kit_ribs property keeps the request). Every plane and longeron is checked before anything is written. Reports ribs, thickness, sections [{plane, chains, pieces, length, open}], posts, holes, longerons [{index, stations}], faces, volume and nonManifoldEdges.", diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index 9a852d1..1f4ba39 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -479,7 +479,8 @@ "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", - "brokkr_kitbash.apply", + "brokkr_kitbash.freeze", + "brokkr_kitbash.thaw", "brokkr_kitbash.ribs", "brokkr_kitbash.shell", "brokkr_kitbash.hose" diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 4371f5f..d0b66c4 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -1,6 +1,6 @@ """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, a braced leg closed by close and what set_params, -attach and detach then do, drift and how it is cleared, a roll that is not a number, detach, boolean (one Exact Boolean modifier per operation over a collection of cutters, self-intersection on, above the Bevel). Not part +attach and detach then do, drift and how it is cleared, a roll that is not a number, detach, boolean (one Exact Boolean modifier per operation over a collection of cutters, self-intersection on, above the Bevel), and freeze and thaw: the frozen shape, the round trip, the refusals, and what a frozen part costs. 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 -- @@ -21,6 +21,7 @@ import math import os import re import sys +import time import traceback import tempfile import types @@ -85,6 +86,12 @@ KEPT = 2.1e-4 # 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 +# Seconds the scene's update takes after an orphan mesh is removed with three cut tanks frozen, over the same with them +# live (medians of three, interleaved; every other Boolean in the scene frozen first). Shipped 0.0022 (0.0023 s over 1.05 s); least +# claimed mutant 1.5 (F1, freeze leaves the modifiers on: the Booleans run again, on the frozen mesh); the +# geometric mean, separation 26 each side. A ratio of two times read in one process: what other work +# on the machine does to it is far under the separation. +FROZEN_COST = 0.057 # 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 @@ -178,6 +185,10 @@ def measure(mesh): return row +def stack(obj): + return [m.name for m in obj.modifiers] + + def evaluated(obj): """(faces, volume, non-manifold edges, material slot names) of the object with its modifiers, read here and not through the add-on.""" shown = obj.evaluated_get(bpy.context.evaluated_depsgraph_get()) @@ -598,6 +609,71 @@ try: and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], report["params"]).counts) != raw["faces"] and CUT < resized["volume"] < measure(tank.data)["volume"] - 0.005 and holds("Tee", "Tank", "b", "port_a", 180.0)[0], [receipt["message"], resized]) + # --- freeze and thaw ---------------------------------------------------------------------------------------------------------- + THAW = "thaw it first" + refused("freeze on a mesh with no modifiers", "brokkr_kitbash.freeze", {"object_name": "Plain"}, "'Plain' has no modifiers to freeze") + refused("thaw on a live part", "brokkr_kitbash.thaw", {"object_name": "Tank"}, "'Tank' is not frozen") + tank.modifiers["Kit Bevel"].show_render = False + refused("freeze on a part with a modifier already off names it", "brokkr_kitbash.freeze", {"object_name": "Tank"}, "'Tank' has Kit Bevel off in viewports or renders") + tank.modifiers["Kit Bevel"].show_render = True + slots = [s.material and s.material.name for s in tank.material_slots] + shown, shown_slots = evaluated(tank) + index = np.zeros(len(tank.data.polygons), dtype=np.int32) + tank.data.polygons.foreach_get("material_index", index) + mesh_name, live_faces, meshes, collections = tank.data.name, len(tank.data.polygons), len(bpy.data.meshes), len(bpy.data.collections) + sockets_before = send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["sockets"] + receipt, frozen = send("brokkr_kitbash.freeze", object_name="Tank") + after = np.zeros(len(tank.data.polygons), dtype=np.int32) + tank.data.polygons.foreach_get("material_index", after) + facts = frozen and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} + check("freeze makes the evaluated mesh the tank's mesh: the same faces, volume and non-manifold edges, and the tank still evaluates to them", + receipt["status"] == "accepted" and facts == shown == measure(tank.data) == evaluated(tank)[0] and tank.data.name == "Tank frozen" + and len(bpy.data.meshes) == meshes + 1, [receipt["message"], facts, shown]) + check("freeze holds the live mesh in kit_frozen and keeps the stack, off, with its collection and cutter", frozen and frozen["frozen"] is True + and tank["kit_frozen"].name == mesh_name and len(tank["kit_frozen"].polygons) == live_faces and stack(tank) == frozen["modifiers"] == ["Kit Difference", "Kit Bevel"] + and not any(m.show_viewport or m.show_render for m in tank.modifiers) and tank.modifiers["Kit Difference"].collection.objects[:] == [box] + and frozen["booleans"] == [{"cutter": "Box", "operation": "DIFFERENCE"}] and len(bpy.data.collections) == collections and "Box" in bpy.context.scene.objects, + [frozen, [(m.name, m.show_viewport, m.show_render) for m in tank.modifiers]]) + check("freeze keeps the material slots exactly, and faces of both materials", slots == shown_slots == ["Tank Paint", "Strap Steel"] + and [s.material and s.material.name for s in tank.material_slots] == slots and [m and m.name for m in tank.data.materials] == slots + and index.max() == 1 and sorted(set(after.tolist())) == [0, 1], [slots, [m and m.name for m in tank.data.materials], sorted(set(after.tolist()))]) + check("a frozen part keeps what it is", frozen and tank["kit_part"] == "tank" and json.loads(tank["kit_params"])["segments"] == 16 and frozen["part"] == "tank", dict(tank.items())) + RAY = {"origin": [0.0, 0.0, 3.0], "direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]} + refused("set_params on a frozen part", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"}, THAW) + refused("boolean on a frozen part", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Plain"}, THAW) + refused("cut on a frozen part", "brokkr_kitbash.cut", {"object_name": "Tank", "cutter_name": "Late", "part": "box", "origin_x": 0.0, "origin_y": 0.0, "origin_z": 3.0, + "direction_x": 0.0, "direction_y": 0.0, "direction_z": -1.0, "up_y": 1.0, "up_z": 0.0}, THAW) + refused("cut_many on a frozen part", "brokkr_kitbash.cut_many", {"object_name": "Tank", "cuts": json.dumps([{"name": "Late", "part": "box", **RAY}])}, THAW) + refused("freeze on a frozen part", "brokkr_kitbash.freeze", {"object_name": "Tank"}, THAW) + receipt, report = send("brokkr_kitbash.report", object_name="Tank") + check("a frozen part still reports its sockets where its params put them, and what is attached to it still holds", report and report["parts"][0]["frozen"] is True + and report["parts"][0]["sockets"] == sockets_before and report["parts"][0]["faces"] == frozen["faces"] and holds("Tee", "Tank", "b", "port_a", 180.0)[0] + and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], report) + receipt, report = send("brokkr_kitbash.attach", object_name="Radiator", socket="base", parent_name="Tank", parent_socket="saddle") + check("a new part attaches to a frozen one", receipt["status"] == "accepted" and held(report) + and reading("seated", seated(radiator, "base", tank, "saddle", 0.0)) < SEATED, receipt["message"]) + receipt, chilled = send("brokkr_kitbash.freeze", object_name="Tee") + receipt, report = send("brokkr_kitbash.roll", object_name="Tee", roll=90.0) + check("a frozen child rolls where it hangs on a frozen parent, and what hangs on it follows", receipt["status"] == "accepted" and chilled and chilled["frozen"] is True + and holds("Tee", "Tank", "b", "port_a", 90.0)[0] and reading("seated", seated(tee, "b", tank, "port_a", 90.0)) < SEATED + and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], [receipt["message"], connection("Tee")]) + send("brokkr_kitbash.roll", object_name="Tee", roll=180.0) + bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True) + check("the held live mesh survives a purge of orphans", bpy.data.meshes.get(mesh_name) is not None and tank["kit_frozen"] == bpy.data.meshes[mesh_name] + and len(tank["kit_frozen"].polygons) == live_faces, sorted(m.name for m in bpy.data.meshes)) + for name in ("Tee", "Tank"): + receipt, thawed = send("brokkr_kitbash.thaw", object_name=name) + check("thaw puts the live mesh back, turns every modifier on and removes the frozen mesh", receipt["status"] == "accepted" and tank.data.name == mesh_name and "kit_frozen" not in tank + and thawed == {"object": "Tank", "frozen": False, "modifiers": ["Kit Difference", "Kit Bevel"], "faces": live_faces} and stack(tank) == ["Kit Difference", "Kit Bevel"] + and all(m.show_viewport and m.show_render for m in tank.modifiers) and "Tank frozen" not in bpy.data.meshes and "kit_frozen" not in tee + and len(bpy.data.collections) == collections, [receipt["message"], thawed, sorted(m.name for m in bpy.data.meshes)]) + check("the thawed tank evaluates to what it did before freeze, and reports frozen false", evaluated(tank)[0] == shown + and send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["frozen"] is False, [evaluated(tank)[0], shown]) + lost = place("Lost", "plate", location=[0.0, -24.0, 0.0]) + send("brokkr_kitbash.freeze", object_name="Lost") + bpy.data.meshes.remove(lost["kit_frozen"]) + refused("thaw on a frozen part whose held mesh was removed", "brokkr_kitbash.thaw", {"object_name": "Lost"}, "the live mesh its kit_frozen held is gone") + # --- the second target: a plate with no material slot, cut twice ---------------------------------------------------------------------- plate = place("Plate", "plate", location=[0.0, -3.0, 0.0]) send("createObject", objectType="MESH", name="Slot", location=[0.1, -3.0, 0.0], size=0.1) @@ -612,9 +688,35 @@ try: and all(m.use_self and m.solver == "EXACT" for m in plate.modifiers if m.type == "BOOLEAN"), [[m.name for m in plate.modifiers], first and first["evaluated"], second and second["evaluated"]]) R["plate"] = {"raw": measure(plate.data), "slot": first and first["evaluated"], "slotAndHole": second and second["evaluated"]} + twin = plate.copy() # a linked duplicate: it shares the live mesh, and keeps it + twin.name = "Plate_twin" + bpy.context.scene.collection.objects.link(twin) + shown, shown_slots = evaluated(plate) + receipt, frozen = send("brokkr_kitbash.freeze", object_name="Plate") + check("freeze on a part with no material slot leaves the frozen mesh with none (Blender's Boolean shows it with one empty slot); a linked duplicate keeps the live mesh", + receipt["status"] == "accepted" and shown_slots == [None] and len(plate.data.materials) == 0 and len(plate.material_slots) == 0 + and frozen["booleans"] == second["booleans"] and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown + and twin.data.name == "Plate" and plate["kit_frozen"] == twin.data and all(m.show_viewport for m in twin.modifiers), + [shown_slots, len(plate.data.materials), len(plate.material_slots), frozen]) + bpy.data.objects.remove(twin) + send("brokkr_kitbash.thaw", object_name="Plate") + send("assignMaterial", targetObjectName="Plate", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) + send("createObject", objectType="MESH", name="Boss", location=[0.0, -3.0, 0.1], size=0.06) + send("assignMaterial", targetObjectName="Boss", materialName="Boss Brass", color=[0.6, 0.5, 0.2]) + send("setObjectTransform", targetObjectName="Boss", location=[0.0, -3.0, 0.02]) + receipt, third = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Boss", operation="UNION") + shown, shown_slots = evaluated(plate) + receipt, frozen = send("brokkr_kitbash.freeze", object_name="Plate") + used = np.zeros(len(plate.data.polygons), dtype=np.int32) + plate.data.polygons.foreach_get("material_index", used) + check("a thawed part is cut and frozen again; a cutter that has a material brings it after the part's own slots, on the faces it made", + receipt["status"] == "accepted" and third["booleans"][-1] == {"cutter": "Boss", "operation": "UNION"} and third["frozen"] is False and frozen["frozen"] is True + and third["evaluated"]["volume"] > R["plate"]["slotAndHole"]["volume"] and shown_slots == ["Plate Paint", "Boss Brass"] + and [m and m.name for m in plate.data.materials] == ["Plate Paint", "Boss Brass"] and sorted(set(used.tolist())) == [0, 1] + and stack(plate) == ["Kit Difference", "Kit Union", "Kit Bevel"], [third and third["evaluated"], shown_slots, [m and m.name for m in plate.data.materials], sorted(set(used.tolist()))]) vent = place("Vent", "vent", "width=0.2; height=0.15") receipt, report = send("brokkr_kitbash.attach", object_name="Vent", socket="back", parent_name="Plate", parent_socket="front") - check("a vent that fits attaches to the cut plate's front", receipt["status"] == "accepted" and held(report) + check("a vent that fits attaches to the frozen plate's front", receipt["status"] == "accepted" and held(report) and reading("seated", seated(vent, "back", plate, "front", 0.0)) < SEATED, receipt["message"]) refused("a loop of two", "brokkr_kitbash.attach", {"object_name": "Plate", "socket": "back", "parent_name": "Vent", "parent_socket": "back"}, "'Vent' is below 'Plate'") @@ -631,6 +733,82 @@ try: 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"]]) + # --- freeze 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, frozen = send("brokkr_kitbash.freeze", object_name="Keeper") + check("freeze keeps a part's own empty last slot when the cutter has no material", receipt["status"] == "accepted" and keeper.data.name == "Keeper frozen" + 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"]) + gap.data.polygons[0].material_index = gap.data.polygons[1].material_index = 1 # two of its faces are brass; the rest stay in the empty slot + send("brokkr_kitbash.boolean", object_name="Gapped", cutter="Gap") + receipt, frozen = send("brokkr_kitbash.freeze", object_name="Gapped") + used = np.zeros(len(gapped.data.polygons), dtype=np.int32) + gapped.data.polygons.foreach_get("material_index", used) + check("freeze 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]]) + names = [m and m.name for m in gapped.data.materials] + brass = [p.index for p in gapped.data.polygons if "Boss Brass" in names and p.material_index == names.index("Boss Brass")] + far = [p.index for p in gapped.data.polygons if (gapped.matrix_world @ p.center).x < -0.05] # the plate's half the cutter does not reach + check("and each face keeps its own slot: the cutter's brass faces are brass, the faces from its empty slot and the plate's own are the plate's paint", + names[0] == "Plate Paint" and 0 < len(brass) < len(used) and far and all(used[i] == 0 for i in far) + and all(abs((gapped.matrix_world @ gapped.data.polygons[i].center).x - 0.1) < 0.051 for i in brass), [names, len(brass), len(far), sorted(set(used.tolist()))]) + + # --- a frozen part is cheap ------------------------------------------------------------------------------------------------------- + # Blender re-evaluates every live collection Boolean in the scene after any datablock is removed (docs/kitbash.md). Every + # other cut object is frozen first, so the update timed here evaluates the three tanks' Booleans or none. + for obj in [o for o in bpy.context.scene.objects if o.type == "MESH" and any(m.type == "BOOLEAN" and m.show_viewport for m in o.modifiers)]: + send("brokkr_kitbash.freeze", object_name=obj.name) + tanks = [] + for n in range(3): + tanks.append(place(f"Cold{n}", "tank", location=[6.0, 3.0 * n, 0.0])) + send("createObject", objectType="MESH", name=f"ColdBox{n}", location=[6.3, 3.0 * n, 0.0], size=0.3) + send("brokkr_kitbash.boolean", object_name=f"Cold{n}", cutter=f"ColdBox{n}") + SEEN = [] + + def seen(scene, depsgraph): + SEEN.extend(u.id.original.name for u in depsgraph.updates if isinstance(u.id, bpy.types.Object) and u.is_updated_geometry + and u.id.original.type == "MESH" and any(m.type == "BOOLEAN" and m.show_viewport for m in u.id.original.modifiers)) + + def orphan_removed(): + """(seconds the scene's update takes after an orphan mesh is removed, the objects with a shown Boolean it re-evaluated)""" + mesh = bpy.data.meshes.new("Orphan") + bpy.context.view_layer.update() + SEEN.clear() + start = time.perf_counter() + bpy.data.meshes.remove(mesh) + bpy.context.view_layer.update() + return time.perf_counter() - start, sorted(set(SEEN)) + + bpy.app.handlers.depsgraph_update_post.append(seen) + costs = {"live": [], "frozen": []} + for _ in range(3): + bpy.context.view_layer.update() + costs["live"].append(orphan_removed()) + for obj in tanks: + send("brokkr_kitbash.freeze", object_name=obj.name) + bpy.context.view_layer.update() + costs["frozen"].append(orphan_removed()) + for obj in tanks: + send("brokkr_kitbash.thaw", object_name=obj.name) + bpy.app.handlers.depsgraph_update_post.remove(seen) + medians = {state: sorted(seconds for seconds, _ in rows)[1] for state, rows in costs.items()} + R["frozenCost"] = {"liveSeconds": round(medians["live"], 4), "frozenSeconds": round(medians["frozen"], 5), + "live": [[round(s, 4), names] for s, names in costs["live"]], "frozen": [[round(s, 5), names] for s, names in costs["frozen"]]} + check("removing an orphan mesh re-evaluates the three live cut tanks, and none of them frozen", all(names == ["Cold0", "Cold1", "Cold2"] for _, names in costs["live"]) + and all(names == [] for _, names in costs["frozen"]), R["frozenCost"]) + check("and the update with them frozen costs under the bound of what it costs with them live", + reading("frozenCost", medians["frozen"] / medians["live"]) < FROZEN_COST, R["frozenCost"]) except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json index f7be6b4..db1ffde 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.result.json +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -7,7 +7,7 @@ "detail": null }, { - "name": "a part nobody attached reports connection null and baked false", + "name": "a part nobody attached reports connection null", "ok": true, "detail": null }, @@ -497,42 +497,97 @@ "detail": null }, { - "name": "refused, scene unchanged: apply on a mesh that is not a kit part", + "name": "refused, scene unchanged: freeze on a mesh with no modifiers", "ok": true, "detail": null }, { - "name": "apply makes the evaluated mesh the tank's mesh: the same faces and volume, no modifiers, one mesh datablock of the old name", + "name": "refused, scene unchanged: thaw on a live part", "ok": true, "detail": null }, { - "name": "apply keeps the material slots exactly, and faces of both materials", + "name": "refused, scene unchanged: freeze on a part with a modifier already off names it", "ok": true, "detail": null }, { - "name": "apply marks the part baked and keeps what it is", + "name": "freeze makes the evaluated mesh the tank's mesh: the same faces, volume and non-manifold edges, and the tank still evaluates to them", "ok": true, "detail": null }, { - "name": "refused, scene unchanged: set_params on a baked part", + "name": "freeze holds the live mesh in kit_frozen and keeps the stack, off, with its collection and cutter", "ok": true, "detail": null }, { - "name": "refused, scene unchanged: apply on a baked part with no modifiers left", + "name": "freeze keeps the material slots exactly, and faces of both materials", "ok": true, "detail": null }, { - "name": "a baked part still reports its sockets where its params put them, and what is attached to it still holds", + "name": "a frozen part keeps what it is", "ok": true, "detail": null }, { - "name": "a new part attaches to a baked one", + "name": "refused, scene unchanged: set_params on a frozen part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: boolean on a frozen part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut on a frozen part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many on a frozen part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: freeze on a frozen part", + "ok": true, + "detail": null + }, + { + "name": "a frozen part still reports its sockets where its params put them, and what is attached to it still holds", + "ok": true, + "detail": null + }, + { + "name": "a new part attaches to a frozen one", + "ok": true, + "detail": null + }, + { + "name": "a frozen child rolls where it hangs on a frozen parent, and what hangs on it follows", + "ok": true, + "detail": null + }, + { + "name": "the held live mesh survives a purge of orphans", + "ok": true, + "detail": null + }, + { + "name": "thaw puts the live mesh back, turns every modifier on and removes the frozen mesh", + "ok": true, + "detail": null + }, + { + "name": "the thawed tank evaluates to what it did before freeze, and reports frozen false", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: thaw on a frozen part whose held mesh was removed", "ok": true, "detail": null }, @@ -542,22 +597,17 @@ "detail": null }, { - "name": "refused, scene unchanged: apply on a mesh a linked duplicate shares", + "name": "freeze on a part with no material slot leaves the frozen mesh with none (Blender's Boolean shows it with one empty slot); a linked duplicate keeps the live mesh", "ok": true, "detail": null }, { - "name": "apply on a part with no material slot leaves it with none (Blender's Boolean shows it with one empty slot)", + "name": "a thawed part is cut and frozen again; a cutter that has a material brings it after the part's own slots, on the faces it made", "ok": true, "detail": null }, { - "name": "a baked part is cut and baked again; a cutter that has a material brings it after the part's own slots, on the faces it made", - "ok": true, - "detail": null - }, - { - "name": "a vent that fits attaches to the baked plate's front", + "name": "a vent that fits attaches to the frozen plate's front", "ok": true, "detail": null }, @@ -577,12 +627,12 @@ "detail": null }, { - "name": "apply keeps a part's own empty last slot when the cutter has no material", + "name": "freeze 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", + "name": "freeze leaves no face outside the material slots when a cutter's first slot is empty", "ok": true, "detail": null }, @@ -590,6 +640,16 @@ "name": "and each face keeps its own slot: the cutter's brass faces are brass, the faces from its empty slot and the plate's own are the plate's paint", "ok": true, "detail": null + }, + { + "name": "removing an orphan mesh re-evaluates the three live cut tanks, and none of them frozen", + "ok": true, + "detail": null + }, + { + "name": "and the update with them frozen costs under the bound of what it costs with them live", + "ok": true, + "detail": null } ], "hostErrors": [], @@ -598,6 +658,7 @@ "close nudged": 0.00032, "closed": 3.9e-07, "cut": 0.25, + "frozenCost": 0.0016, "kept": 6e-08, "nudged": 0.00032, "roll": 6.6e-06, @@ -637,5 +698,49 @@ "volume": 0.006031088, "nonManifoldEdges": 0 }, + "frozenCost": { + "liveSeconds": 1.0356, + "frozenSeconds": 0.00168, + "live": [ + [ + 1.0412, + [ + "Cold0", + "Cold1", + "Cold2" + ] + ], + [ + 1.0356, + [ + "Cold0", + "Cold1", + "Cold2" + ] + ], + [ + 0.9348, + [ + "Cold0", + "Cold1", + "Cold2" + ] + ] + ], + "frozen": [ + [ + 0.00168, + [] + ], + [ + 0.00264, + [] + ], + [ + 0.00165, + [] + ] + ] + }, "ok": true } \ No newline at end of file diff --git a/surfaces/blender/tests/live/kitbash_shell.py b/surfaces/blender/tests/live/kitbash_shell.py index 02f2c66..c5eed48 100644 --- a/surfaces/blender/tests/live/kitbash_shell.py +++ b/surfaces/blender/tests/live/kitbash_shell.py @@ -398,6 +398,57 @@ try: receipt["status"] == "accepted" and stack(plate) == ["Kit Difference", "Kit Union", "Kit Intersect", "Kit Bevel"] and report["booleans"] == [{"cutter": "Hole", "operation": "DIFFERENCE"}, {"cutter": "Boss", "operation": "UNION"}, {"cutter": "Keep", "operation": "INTERSECT"}] and report["evaluated"]["nonManifoldEdges"] == 0 and report["kit"] == "mechanical", [stack(plate), report and report["booleans"]]) + THAW = "thaw it first" + shown, cage_shown, collections = evaluated(plate)[0], evaluated(cage)[0], len(bpy.data.collections) + receipt, frozen = send("brokkr_kitbash.freeze", object_name="Plate") + check("freeze keeps the three modifiers, off, the three collections they read and every cutter in the scene", receipt["status"] == "accepted" + and frozen["booleans"] == report["booleans"] and len(bpy.data.collections) == collections and frozen["modifiers"] == stack(plate) == ["Kit Difference", "Kit Union", "Kit Intersect", "Kit Bevel"] + and not any(m.show_viewport or m.show_render for m in plate.modifiers) and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown == evaluated(plate)[0] + and all(name in bpy.context.scene.objects for name in ("Hole", "Boss", "Keep")), [receipt["message"], frozen, shown]) + cage_stack, cage_mesh = stack(cage), cage.data.name + receipt, frozen = send("brokkr_kitbash.freeze", object_name="Cage") + check("freeze takes the cage, which is not a kit part: its evaluated wall, its stack off, its cutters still its children", receipt["status"] == "accepted" and frozen["object"] == "Cage" + and "kit" not in frozen and frozen["frozen"] is True and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} == cage_shown == evaluated(cage)[0] + and frozen["modifiers"] == stack(cage) == cage_stack and not any(m.show_viewport or m.show_render for m in cage.modifiers) and cage.data.name == "Cage frozen" + and bpy.data.objects["Bay"].parent == cage and len(bpy.data.collections) == collections, [receipt["message"], frozen and frozen["modifiers"], cage_shown]) + refused("ribs from a frozen cage", "brokkr_kitbash.ribs", {"object_name": "Cage", "ribs_name": "ColdRibs", "planes": json.dumps([{"origin": [0.0, 0.0, 0.5], "normal": [0.0, 0.0, 1.0]}])}, THAW) + refused("cut on a frozen cage", "brokkr_kitbash.cut", {"object_name": "Cage", "cutter_name": "Late", "part": "box", "origin_x": 3.0, "origin_y": 0.0, "origin_z": 0.1, + "direction_x": -1.0, "direction_y": 0.0, "direction_z": 0.0}, THAW) + refused("cut_many on a frozen cage", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{"name": "Late", "part": "box", "origin": [3.0, 0.0, 0.1], "direction": [-1.0, 0.0, 0.0]}])}, THAW) + refused("boolean on a frozen cage", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Hole"}, THAW) + for name in ("Plate", "Cage"): + receipt, thawed = send("brokkr_kitbash.thaw", object_name=name) + check("thaw gives both back: the live meshes, every modifier on, the frozen meshes gone, and the same evaluated shapes", receipt["status"] == "accepted" + and thawed == {"object": "Cage", "frozen": False, "modifiers": cage_stack, "faces": len(cage.data.polygons)} and cage.data.name == cage_mesh + and all(m.show_viewport and m.show_render for o in (plate, cage) for m in o.modifiers) and not any(n in bpy.data.meshes for n in ("Cage frozen", "Plate frozen")) + and "kit_frozen" not in cage and "kit_frozen" not in plate and evaluated(plate)[0] == shown and evaluated(cage)[0] == cage_shown, + [receipt["message"], thawed, sorted(m.name for m in bpy.data.meshes)]) + twin = place("Twin", "plate", location=[0.0, -15.0, 0.0]) + send("createObject", objectType="MESH", name="TwinHole", location=[0.0, -15.0, 0.0], size=0.05) + send("brokkr_kitbash.boolean", object_name="Twin", cutter="TwinHole") + copied = twin.copy() # a copied part: its own mesh, and a Kit Difference modifier that reads the same collection + copied.data = twin.data.copy() + bpy.context.scene.collection.objects.link(copied) + receipt, frozen = send("brokkr_kitbash.freeze", object_name="Twin") + kept = bpy.data.collections.get("Twin difference") + check("M6: a frozen part and its copy still read the one collection, and the copy stays live", receipt["status"] == "accepted" and kept is not None + and twin.modifiers["Kit Difference"].collection == kept == copied.modifiers["Kit Difference"].collection and [o.name for o in kept.objects] == ["TwinHole"] + and "kit_frozen" in twin and all(m.show_viewport for m in copied.modifiers), [receipt["message"], [c.name for c in bpy.data.collections]]) + send("brokkr_kitbash.thaw", object_name="Twin") + RINGS = [[[x, y, 0.1 - x * x] for x in (-0.3, -0.1, 0.1, 0.3)] for y in (0.0, 0.2, 0.4)] + lid = {"object_name": "Lid", "sheet": json.dumps({"rings": RINGS}), "thickness": 0.02, "levels": 2} + send("brokkr_kitbash.shell", **lid) + send("setObjectTransform", targetObjectName="Lid", location=[0.0, -30.0, 0.0]) + wall = evaluated(bpy.data.objects["Lid"])[0] + receipt, frozen = send("brokkr_kitbash.freeze", object_name="Lid") + check("freeze takes a shell: the wall its Kit Subsurf and Kit Solidify make", receipt["status"] == "accepted" and frozen["modifiers"] == ["Kit Subsurf", "Kit Solidify"] + and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} == wall and wall["faces"] > 2 * 6 * 16, [receipt["message"], frozen, wall]) + refused("a rebuild of a frozen shell", "brokkr_kitbash.shell", lid, THAW) + refused("a rebuild of a frozen shell that counts folds", "brokkr_kitbash.shell", {**lid, "count_folds": True}, THAW) + send("brokkr_kitbash.thaw", object_name="Lid") + receipt, rebuilt = send("brokkr_kitbash.shell", **lid) + check("and thawed, the shell rebuilds", receipt["status"] == "accepted" and rebuilt["rebuilt"] is True and evaluated(bpy.data.objects["Lid"])[0] == wall, [receipt["message"], rebuilt]) + # --- cut-refusals ----------------------------------------------------------------------------------------------------------- section('cut-refusals') RAY = {"object_name": "Cage", "cutter_name": "New", "part": "box", "origin_x": 3.0, "origin_y": 0.0, "origin_z": 0.1, "direction_x": -1.0, "direction_y": 0.0, "direction_z": 0.0} @@ -454,6 +505,8 @@ try: refused(f"cut_many on a target {why}", "brokkr_kitbash.cut_many", {"object_name": name, "cuts": json.dumps([{"name": "Unseen", "part": "box", "origin": [0.1, 0.1, 3.0], "direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]}])}, NOT) refused(f"boolean on a target {why}", "brokkr_kitbash.boolean", {"object_name": name, "cutter": "Sheet"}, NOT) + refused("freeze on a part disabled in viewports", "brokkr_kitbash.freeze", {"object_name": "Plate"}, "Blender does not evaluate 'Plate' in this view layer") + refused("freeze on a part in a collection outside the view layer", "brokkr_kitbash.freeze", {"object_name": "Loose"}, "Blender does not evaluate 'Loose' in this view layer") veil.hide_viewport = plate.hide_viewport = False bpy.context.view_layer.update() diff --git a/surfaces/blender/tests/live/kitbash_shell.result.json b/surfaces/blender/tests/live/kitbash_shell.result.json index 3b6c679..603575a 100644 --- a/surfaces/blender/tests/live/kitbash_shell.result.json +++ b/surfaces/blender/tests/live/kitbash_shell.result.json @@ -222,17 +222,62 @@ "detail": null }, { - "name": "apply removes the three collections its modifiers held and leaves every cutter in the scene", + "name": "freeze keeps the three modifiers, off, the three collections they read and every cutter in the scene", "ok": true, "detail": null }, { - "name": "refused, scene unchanged: apply on the cage, which is not a kit part", + "name": "freeze takes the cage, which is not a kit part: its evaluated wall, its stack off, its cutters still its children", "ok": true, "detail": null }, { - "name": "M6: apply keeps a collection a copied part's modifier still reads", + "name": "refused, scene unchanged: ribs from a frozen cage", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut on a frozen cage", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many on a frozen cage", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: boolean on a frozen cage", + "ok": true, + "detail": null + }, + { + "name": "thaw gives both back: the live meshes, every modifier on, the frozen meshes gone, and the same evaluated shapes", + "ok": true, + "detail": null + }, + { + "name": "M6: a frozen part and its copy still read the one collection, and the copy stays live", + "ok": true, + "detail": null + }, + { + "name": "freeze takes a shell: the wall its Kit Subsurf and Kit Solidify make", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a rebuild of a frozen shell", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a rebuild of a frozen shell that counts folds", + "ok": true, + "detail": null + }, + { + "name": "and thawed, the shell rebuilds", "ok": true, "detail": null }, @@ -327,12 +372,12 @@ "detail": null }, { - "name": "refused, scene unchanged: apply on a part disabled in viewports", + "name": "refused, scene unchanged: freeze on a part disabled in viewports", "ok": true, "detail": null }, { - "name": "refused, scene unchanged: apply on a part in a collection outside the view layer", + "name": "refused, scene unchanged: freeze on a part in a collection outside the view layer", "ok": true, "detail": null }, diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 0ade179..c253c90 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1812,7 +1812,7 @@ 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.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.ribs", + "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"] @@ -1859,6 +1859,7 @@ class HostFileTests(unittest.TestCase): self.assertEqual(at.validate(boolean, host)["operation"], "DIFFERENCE") for bad in ({**attach, "roll": 360.5}, {**attach, "socket": "a b"}, {**attach, "parent_socket": ""}, {**attach, "matrix": [1, 0, 0]}, {**boolean, "operation": "SLICE"}, {**boolean, "solver": "EXACT"}, {**boolean, "cutter": ""}, + {**envelope, "action": "brokkr_kitbash.freeze"}, {**envelope, "action": "brokkr_kitbash.thaw", "object_name": ""}, {**envelope, "action": "brokkr_kitbash.detach", "object_name": "x" * 64}, {**close, "socket": "end b"}, {**close, "other_socket": "x" * 33}, {**close, "other_name": ""}, {**close, "roll": 10}, {k: v for k, v in close.items() if k != "other_socket"}): @@ -1973,10 +1974,20 @@ class OwnershipTests(unittest.TestCase): self.assertLess(place.index("modifier.show_viewport = False"), place.index("evaluable(")) self.assertLess(place.index("evaluable("), place.index("modifier.show_viewport = True")) # unevaluable-target: every action that evaluates refuses an object Blender does not evaluate before its first write - for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), + for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["freeze"], "bpy.data.meshes.new_from_object("), (bodies["ribs"], "show_viewport = False"), (bodies["shell"], "clear_geometry()")): self.assertLess(body.index("evaluable("), body.index(first_write)) - self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "ribs", "shell", "hose"]) + self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "freeze", "ribs", "shell", "hose"]) + # frozen: thaw evaluates nothing, and every action that writes a mesh or a modifier stack refuses a frozen object before its first write + for call in ("evaluable(", "evaluated_of(", "to_mesh(", "depsgraph", "view_layer.update"): + self.assertNotIn(call, bodies["thaw"]) + for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["freeze"], "bpy.data.meshes.new_from_object("), + (bodies["ribs"], "show_viewport = False"), (bodies["shell"], "clear_geometry()"), (bodies["set_params"], "write_mesh("), + (bodies["hose"], "write_mesh(")): + self.assertLess(body.index("live("), body.index(first_write)) + self.assertEqual((source.count("obj[FROZEN] ="), source.count("del obj[FROZEN]"), source.count("live(")), (1, 1, 8)) # its def and the seven callers above + self.assertIn("obj[FROZEN] =", bodies["freeze"]) + self.assertIn("del obj[FROZEN]", bodies["thaw"]) ribs = bodies["ribs"] # every refusal before the ribs object is written, and the cage's modifiers shown again whatever happened self.assertLess(ribs.rindex("raise Refused("), ribs.index("mesh = bpy.data.meshes.new(self.ribs_name)")) self.assertLess(ribs.index("finally:"), ribs.index("modifier.show_viewport = True")) @@ -2100,7 +2111,7 @@ class OwnershipTests(unittest.TestCase): 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) - self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 1, True)) + self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 2, True)) # detach's keys, and thaw'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" self.assertIsNone(re.search(placing, bodies["close"])) -- 2.47.3 From a69bb89374bf7f384320a76c3efc0a72a4dbc7a1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:48:35 +0100 Subject: [PATCH 3/5] docs/kitbash.md: freezing, what triggers a live collection Boolean, and what freeze buys on KESTREL (cut kit-freeze) Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 63 ++++++++++++++++++++++++++++---- 1 file changed, 56 insertions(+), 7 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 8e789ba..7cc37a6 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -1,7 +1,7 @@ # Kitbash parts: machinery from kits `surfaces/blender/brokkr_kitbash` is a Blender add-on that places parametric machine parts from a **kit**, mates -them **socket** to socket, cuts them with booleans and bakes them, and makes the faceted armor **shell** they sit under. It is the machinery vocabulary of a ship's fixed chassis: the frame, tanks, +them **socket** to socket, cuts them with booleans and freezes them, and makes the faceted armor **shell** they sit under. It is the machinery vocabulary of a ship's fixed chassis: the frame, tanks, actuators, housings and plumbing an agent assembles offline under a hand-fit armor cage, baked once. It is a host add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish` and `brokkr_rig`: it imports the polish package's operator base, `Refused` and `mesh_object`, and nothing from `brokkr_bridge`. @@ -31,6 +31,8 @@ Who owns what: and `kit_close_to_socket` properties. Only `close` writes them and only `detach` clears them. A closure places nothing: whether it holds is derived at each report. - A boolean belongs to its Boolean modifier on the part that is cut. +- Whether a cut object is live or frozen belongs to its `kit_frozen` property, which holds the live mesh while + the object carries its evaluated one. Only `freeze` sets it, and `thaw`, which deletes it, is its one undo. ## A part, end to end @@ -317,12 +319,56 @@ took 1.89 s through the collection modifier, 12.6 s with a Boolean modifier for eight cutters joined into one mesh (medians of five interleaved evaluations, Blender 5.3 on Starfire; an earlier probe with raw cutters read 2.04, 14.7 and 1.94 s). All three give the same faces and volume. The cost is the target's, hardly the cutters': one cutter on that shell already costs 1.4 s. The target pays it each time it is -evaluated, and Blender evaluates it after every action that changes it or a cutter. `boolean` +evaluated, and Blender evaluates it after every action that changes it or a cutter, and after much that changes +neither ("Freezing", below): `freeze` an object when its cuts are settled. `boolean` evaluates the target once and reports `evaluated: {faces, volume, nonManifoldEdges}`; `report` never evaluates a modifier. The cutter is any other mesh object and is not changed: hide it with `setObjectVisibility`. A cutter with no material leaves the target's material slots as they are; a cutter that has materials brings them, after the target's own, on the faces it makes. +### Freezing + +A live Boolean over a collection is paid for far more often than its target changes. In Blender 5.3 every such +Boolean in the scene is evaluated again, whatever it cuts, after any datablock is removed (an orphan mesh +included), after any object's `hide_viewport` changes, and after any evaluated mesh is copied out +(`new_from_object`). Adding objects, collections or modifiers does not do it. Nearly every action here does one of +the three (`cut_many` hides its target's Booleans to cast, `ribs` makes and removes working objects), so each +finished cut object is paid for again at each later action. Hiding the finished object does not help while its +cutters show, and the hide is itself one more trigger. On a replica of six cut plates (a subdivided, solidified +sphere under one Exact Boolean of four cutters each), each trigger on an unrelated datablock cost 19 to 23 s; with +the plates frozen, 0.004 to 0.014 s (three interleaved repetitions, Blender 5.3 on Starfire). + +**`freeze`** takes any mesh object that has modifiers, a kit part, a shell or a plain mesh. Its mesh becomes its +evaluated mesh (named ` frozen`), its live mesh is held by an ID-pointer property, `kit_frozen`, so it +survives a purge of orphans, and every modifier stays in the stack with its collections, turned off in viewports +and renders. Nothing is removed: the cutter objects stay, a cutter placed by `cut` keeps its floor socket and what +is attached to it, and `booleans` still lists what cuts the object. The frozen mesh's material slots are the +object's own (an empty one it had included), followed by any a cutter brought; faces a cutter made from an empty +slot of its own take the first slot. A frozen kit part keeps `kit_kit`, `kit_part`, `kit_params` and its +connections: its sockets are still derived from the params, so `attach`, `detach`, `roll`, `aim`, `reach` and +`close` work on it and on what hangs from it. `freeze` reports the part (or `object`), `frozen`, `faces`, +`volume`, `nonManifoldEdges`, `modifiers` and `booleans`. + +**`thaw`** puts the live mesh back, deletes `kit_frozen`, turns every modifier on and removes the frozen mesh. It +evaluates nothing itself; Blender evaluates the object once afterwards, and the thawed object evaluates to the +faces and volume it had. + +A frozen object's mesh is not its design, so every action that would write its live mesh or its stack refuses it +with "thaw it first": `set_params`, `boolean`, `cut`, `cut_many`, `ribs` from it, a `shell` or `hose` rebuild of +it, and `freeze`. Derive ribs before freezing a cage. `freeze` also refuses an object with no modifiers, one with a +modifier already off in viewports or renders (it names them: `thaw` turns every modifier on, and would not give +that stack back), and one Blender does not evaluate. `thaw` refuses an object that is not frozen, and one whose +held mesh was removed. What nothing detects: a modifier of a frozen object turned on by hand, and a material +assigned to a frozen object, which lands on the frozen mesh and goes at `thaw`. `exportGltf` with `applyModifiers` +exports a frozen object's frozen mesh, since its modifiers are off. + +What it buys on an assembly: KESTREL, an experiment mech of 22 cut shells and blocks, evaluated 1035 Booleans +where its cuts need 139 when each finished component was only hidden, and 139 when each was frozen as it was +finished; the whole build took 4.5 times as long hidden as frozen (medians of three interleaved pairs, 3.4 to 5.7 +within a pair, Blender 5.3 on Starfire under other load; an earlier series on a quieter machine read 251.7 s +against 51.2 s). In `tests/live/kitbash_assembly.py`, removing an orphan mesh beside three cut tanks costs 1.05 s +with them live and 0.0023 s with them frozen. + ## Making a shell `shell` makes an armor plate the way one is modelled by hand: fit a sparse subdivision cage, crease the edges that @@ -419,7 +465,7 @@ medians of three interleaved calls in the live suite (Blender 5.3 on Starfire). are twisted, and the Boolean, which cuts quads into triangles, can read the wall as passing through itself and leave edges with four faces. On the Seraph's cap that began at 0.91 of the thickness at which the first face folds (0.0301 against 0.033), on the left cap and not on its mirror, the right; on its breast plate at 0.91 as -well (0.032 against 0.035). Read `nonManifoldEdges` after cutting (`boolean`, or a count on the evaluated +well (0.032 against 0.035). Read `nonManifoldEdges` after cutting (`boolean`, `freeze`, or a count on the evaluated mesh), and keep `thickness` clear of the first folding one with a thinner wall, fewer `levels` or wider facets at the corner. @@ -493,7 +539,7 @@ attaching a part to a floor) costs an evaluation again while the target is visib more cutters than fit (about 150 of long names), the rows left off the end are counted in `booleansOmitted`. The scene keeps every cutter; the target's `Kit` modifier collections list them. -`cut`, `cut_many` and `boolean` evaluate their object, and refuse one Blender does not evaluate in the +`cut`, `cut_many`, `boolean` and `freeze` evaluate their object, and refuse one Blender does not evaluate in the view layer: an object disabled in viewports that nothing evaluated depends on, or one whose collections no view layer shows. A disabled object that an evaluated object needs (a parent of one, a cutter of one) is evaluated all the same, and is cut. @@ -920,8 +966,8 @@ Python loop of BVH queries with three rays a sample, and the 13,824-candidate se | --- | --- | --- | | `brokkr_kitbash.describe` | `kit` (default `mechanical`), `part` (default: all) | Parts with their params (type, min, max, default, doc) and sockets in the part frame at default params. Changes nothing. | | `brokkr_kitbash.place_part` | `kit`, `part`, `object_name`, `params` | A new mesh object at the origin: the part's mesh, a `Kit Bevel` modifier when the part has a bevel, and the three ID properties. Refuses a name an object already has. | -| `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: modifiers and material slots stay, and the Bevel width follows. Per-face materials are carried by shape: each shape of the part keeps the material most of its faces had, whatever the new face count. Seats the part and the parts attached to it again; refuses a change that breaks a connection or a closure's mate. Reports the part and `closures`, every closure in the scene as `{part, to, holds}`: its own first, then the broken, then the rest; rows that would not fit a receipt are left off the end and counted in `closuresOmitted`. Each closure in the scene adds a few milliseconds (both its parts are built again to find their sockets). | -| `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, each socket's world frame, `connection` and `closure`. Changes nothing and evaluates no modifier. | +| `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: modifiers and material slots stay, and the Bevel width follows. Per-face materials are carried by shape: each shape of the part keeps the material most of its faces had, whatever the new face count. Seats the part and the parts attached to it again; refuses a change that breaks a connection or a closure's mate, and a frozen part. Reports the part and `closures`, every closure in the scene as `{part, to, holds}`: its own first, then the broken, then the rest; rows that would not fit a receipt are left off the end and counted in `closuresOmitted`. Each closure in the scene adds a few milliseconds (both its parts are built again to find their sockets). | +| `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, each socket's world frame, `connection`, `closure` and `frozen`. Changes nothing and evaluates no modifier. | | `brokkr_kitbash.attach` | `object_name` (the child), `socket`, `parent_name`, `parent_socket`, `roll` (degrees, -360 to 360, default 0) | Seats the child's socket on the parent's and parents it there; the two parts are of one kit or of two whose socket types agree. Reports the child. | | `brokkr_kitbash.detach` | `object_name` | Clears the part's connection and the closure it states; it stays where it stands. Refuses a part that has neither. | | `brokkr_kitbash.roll` | `object_name`, `roll` (degrees, -360 to 360) | Turns an attached part to that roll where it hangs. Refuses a part that is not attached. Reports the part and `closures` as `set_params` does. | @@ -931,6 +977,8 @@ Python loop of BVH queries with three rays a sample, and the 13,824-candidate se | `brokkr_kitbash.boolean` | `object_name` (any mesh), `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds the cutter to the collection of the target's one live Exact Boolean for the operation, above the Bevel. Refuses a cutter that is the target, is not a mesh, or already cuts it, and a scaled target. Reports the part (or `object` for a mesh that is not one), `booleans: [{cutter, operation}]` (difference, union, intersect; each in the order added; `booleansOmitted` counts rows a receipt had no room for) and `evaluated`. | | `brokkr_kitbash.cut` | `object_name` (any mesh), `cutter_name`, `part` (`box`, `cyl`, `slot`, `slab`), `params`, `origin_x/y/z`, `direction_x/y/z`, `up_x/y/z` (default 0, 0, 1), `roll` (degrees, default 0), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans` (with `booleansOmitted`, as `boolean`). | | `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans` (with `booleansOmitted`, as `boolean`). | +| `brokkr_kitbash.freeze` | `object_name` (any mesh with modifiers) | Makes the evaluated mesh the object's mesh, holds the live mesh in `kit_frozen` and turns every modifier off, keeping the stack, its collections and the cutters. Refuses a frozen object, one with no modifiers, one with a modifier already off and one Blender does not evaluate. Reports the part (or `object`), `frozen`, `faces`, `volume`, `nonManifoldEdges`, `modifiers` and `booleans`. | +| `brokkr_kitbash.thaw` | `object_name` | Puts the live mesh back, turns every modifier on and removes the frozen mesh; evaluates nothing. Refuses an object that is not frozen or whose held mesh is gone. Reports `object`, `frozen`, `modifiers` and the live mesh's `faces`. | | `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | | `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel`, `count_folds` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `folded` (with `count_folds`, the number of the evaluated wall's inner faces that fold; else null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | | `brokkr_kitbash.hose` | `object_name`, `start`, `end`, `count`, `radius`, `spread`, `clearance`, `bend`, `step`, `sag`, `clamps` (a JSON array of up to 8 `{socket}`), `joint` (empty, or a JSON object `{socket, standoff, range}`) | Routes a bundle of hoses between two sockets around every other mesh, over clamps and through a pin's axis across its roll range; on a hose's name, rebuilds it in place. Reports `length`, `lengthChange`, `clearance`, `radii`, `sag`, `voxels`, `seed`, `rolls`, `worstRoll`, `faces`, `nonManifoldEdges`. | @@ -967,6 +1015,7 @@ assembly by its root: an attached part is placed by its connection. {"action": "createObject", "objectType": "MESH", "name": "Cutter", "location": [0.3, 0.6, 0], "size": 0.2}, {"action": "brokkr_kitbash.boolean", "object_name": "Tank", "cutter": "Cutter"}, {"action": "setObjectVisibility", "targetObjectName": "Cutter", "visible": false}, + {"action": "brokkr_kitbash.freeze", "object_name": "Tank"}, {"action": "brokkr_kitbash.report", "object_name": "Nozzle"}, {"action": "exportGltf", "filepath": "engine.glb", "selection": ["Tank", "Tee", "Nozzle"]} ]} @@ -1057,6 +1106,6 @@ frame `cut` gives a cutter. `MateTests` covers the mate arithmetic and what may `PoseTests` the closed-form rolls. The operators are exercised in a real Blender by `tests/live/kitbash.py` (placing and re-parameterising, and the frame kit: its nine parts placed, the truss re-parameterised, a beam seated on a bracket), `tests/live/kitbash_assembly.py` (attach, detach, -`set_params` on assemblies, a braced leg closed by `close` and boolean), `tests/live/kitbash_shell.py` +`set_params` on assemblies, a braced leg closed by `close`, boolean, and freeze and thaw with what a frozen part costs), `tests/live/kitbash_shell.py` (`cut` and `cut_many` on a cage that is not a kit part, a part on a cutter's floor, the three Boolean modifiers, an object in no collection) and `tests/live/kitbash_pose.py` (roll, aim and reach). -- 2.47.3 From 6743e5680b1e79073f2680c88720320b85d8652d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 21:58:03 +0100 Subject: [PATCH 4/5] brokkr_kitbash freeze: kit_* refused by the bridge's property setter, the held live mesh kept by a fake user, a dirty frozen part reported and refused at export (cut kit-freeze, fix batch h2) Answers verdict aetheria-release:verdict:cut-kit-freeze.s1. - setObjectCustomProperty refuses any name starting with kit_: those properties are brokkr_kitbash's state, so kit_frozen keeps freeze and thaw as its only writers. - freeze gives the held live mesh a fake user (marked kit_kept, taken back by the last thaw), so a purge cannot delete it when kit_frozen is overwritten by hand; thaw's refusal then names the kept meshes no frozen object holds. - part_report: faces is the live mesh's count, frozen or not; a frozen part adds evaluated {faces}; a frozen part with a modifier shown again reports dirty (the modifiers) and frozen false. freeze reports faces (live) and evaluated {faces, volume, nonManifoldEdges}. - exportGltf with applyModifiers refuses an export that includes a frozen object with a modifier shown. - Live pins: kitbash_hose freezes a hose and its rebuild is refused; kitbash_assembly pins the setter refusal, the purge with an overwritten kit_frozen, the dirty report and the export refusal. - kitbash_assembly and kitbash_faceted print their wall times and keep them out of the result files. - docs/kitbash.md: the KESTREL wall-time ratio as a range (about 2.7 to 5.7), the Boolean evaluation counts (1035 against 139) as the stable measure. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_bridge/actions.json | 2 +- .../blender/brokkr_bridge/blender_target.py | 12 ++ surfaces/blender/brokkr_kitbash/__init__.py | 38 +++++-- .../brokkr_kitbash/brokkr_actions.json | 4 +- surfaces/blender/docs/kitbash.md | 39 ++++--- .../blender/tests/live/kitbash_assembly.py | 46 ++++++-- .../tests/live/kitbash_assembly.result.json | 105 ++++++++++++------ .../blender/tests/live/kitbash_faceted.py | 4 +- .../tests/live/kitbash_faceted.result.json | 8 -- surfaces/blender/tests/live/kitbash_hose.py | 8 ++ .../tests/live/kitbash_hose.result.json | 15 +++ surfaces/blender/tests/live/kitbash_shell.py | 6 +- surfaces/blender/tests/test_node_actions.py | 10 ++ surfaces/blender/tests/test_scene_actions.py | 16 +++ 14 files changed, 235 insertions(+), 78 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/actions.json b/surfaces/blender/brokkr_bridge/actions.json index a605e01..3f6a8b9 100644 --- a/surfaces/blender/brokkr_bridge/actions.json +++ b/surfaces/blender/brokkr_bridge/actions.json @@ -33,7 +33,7 @@ {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, {"name": "parentObjectName", "type": "string", "doc": "empty or absent clears the parent"} ]}, - {"name": "setObjectCustomProperty", "doc": "Set one custom property on an object.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "setObjectCustomProperty", "doc": "Set one custom property on an object. Refuses a name starting with kit_: those are brokkr_kitbash's own state, written by its actions.", "changesScene": true, "editModeSafe": false, "fields": [ {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, {"name": "propertyName", "type": "string", "default": "brokkrValue"}, {"name": "value", "type": "any", "required": true, "doc": "any JSON value Blender accepts as a property"} diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index db3a939..a24f09b 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -46,6 +46,8 @@ DEFAULT_DEBUG_MIRROR_ROOT = "//.brokkr/blender-editor-debug" HOST_SNAPSHOT_SCHEMA = "brokkr.blender.host_snapshot.v0" HOST_ACTIONS_FILE = "brokkr_actions.json" HOST_RESULT_LIMIT = 16000 # characters of a host operator's result copied into a receipt +KIT_RESERVED = "kit_" # brokkr_kitbash owns every custom property so named: setObjectCustomProperty refuses them +KIT_FROZEN = "kit_frozen" # brokkr_kitbash's frozen state (its FROZEN): read here only, to refuse an export that would apply a stack twice COMMAND_INTENT_SCHEMA = "brokkr.blender.command_intent.v0" COMMAND_RECEIPT_SCHEMA = "brokkr.blender.command_receipt.v0" SYNC_SESSION_SCHEMA = "brokkr.sync.session.v0" @@ -944,6 +946,9 @@ class BrokkrBlenderTarget: property_name = command["propertyName"] if property_name.startswith("customProperties."): property_name = property_name[len("customProperties."):] + if property_name.startswith(KIT_RESERVED): + raise sa.ActionRefused(f"{property_name!r} is brokkr_kitbash's own state ({KIT_RESERVED}*): its actions write it, and a value set " + "here would leave the object and the property disagreeing. Use the brokkr_kitbash action; nothing changed.") modifier_name = na.drives_modifier_input(obj, property_name) if modifier_name: return self._receipt(command, "failed", f"{property_name!r} is an input of Geometry Nodes modifier {modifier_name!r}; " @@ -1027,6 +1032,13 @@ class BrokkrBlenderTarget: off_layer = [o.name for o in chosen if o.name not in context.view_layer.objects] if off_layer: raise sa.ActionRefused(f"Selection object is not in the active view layer: {off_layer[0]}") + if command["applyModifiers"]: + # A frozen object's mesh is already its stack's result: a modifier shown on it again would be applied twice. + dirty = sorted(o.name for o in (chosen or context.view_layer.objects.values()) + if o.get(KIT_FROZEN) is not None and any(m.show_viewport for m in o.modifiers)) + if dirty: + raise sa.ActionRefused(f"{', '.join(dirty)}: frozen (brokkr_kitbash.freeze) with a modifier shown again, so the export would apply " + "the stack on top of its own result. Thaw it (brokkr_kitbash.thaw), or hide its modifiers; nothing written.") # The exporter writes into a fresh staging folder beside the target, never onto the output # directory: it may also write a .bin and texture files whose names Brokkr does not choose. Only # after it finishes does every file move into place, each refused if its name is taken, so no diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 3ff8135..26e50e6 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -89,6 +89,7 @@ from . import core, route KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" SOCKET, PARENT_SOCKET, ROLL = "kit_socket", "kit_parent_socket", "kit_roll" FROZEN = "kit_frozen" # on a frozen object: an ID pointer to its live mesh; its presence is the frozen state, freeze sets it and thaw deletes it +KEPT = "kit_kept" # on a live mesh a frozen object holds: freeze gave it the fake user that keeps it through a purge, and the last thaw takes it back 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) BEVEL = "Kit Bevel" @@ -351,12 +352,26 @@ def scene_closures(context, report: dict, ends=()) -> list: def part_report(obj, part, built) -> dict: - """A part as the scene has it. Reads stored properties and matrices only: no modifier is evaluated.""" - return {"object": obj.name, "kit": part["kit"], "part": part["name"], "params": built.params, - "faces": len(obj.data.polygons), "shells": built.shell_count, "bevel": round(built.bevel, 6), - "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world)), - "connection": connection_report(obj, part, built), "closure": closure_report(obj, part, built), - "frozen": FROZEN in obj} + """A part as the scene has it. Reads stored properties and matrices only: no modifier is evaluated. `faces` is the + live mesh's count, frozen or not; a frozen part adds `evaluated`, the count of the frozen mesh it carries. A frozen + part with a modifier shown again (by hand: no action does it) is `dirty`, the modifiers named, and not `frozen`: + Blender applies them on top of the frozen mesh, so what it shows and exports is not what was frozen.""" + held = obj.get(FROZEN) + report = {"object": obj.name, "kit": part["kit"], "part": part["name"], "params": built.params, + "faces": len((held if isinstance(held, bpy.types.Mesh) else obj.data).polygons), "shells": built.shell_count, "bevel": round(built.bevel, 6), + "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world)), + "connection": connection_report(obj, part, built), "closure": closure_report(obj, part, built), + "frozen": FROZEN in obj and not shown(obj)} + if FROZEN in obj: + report["evaluated"] = {"faces": len(obj.data.polygons)} + if shown(obj): + report["dirty"] = shown(obj) + return report + + +def shown(obj) -> list: + """The modifiers Blender evaluates for the object, in a viewport or a render, by name.""" + return [modifier.name for modifier in obj.modifiers if modifier.show_viewport or modifier.show_render] def live(obj, doing: str) -> None: @@ -917,11 +932,13 @@ class BROKKR_KITBASH_OT_freeze(PolishOperator): if (index < 0).any(): # faces from a cutter's empty slot: slot 0, as faces from a cutter with no material frozen.polygons.foreach_set("material_index", np.maximum(index, 0)) frozen.name = f"{obj.name} frozen" + if not obj.data.use_fake_user: # the pointer below is a user too, but a property can be overwritten: the mesh outlives that + obj.data.use_fake_user = obj.data[KEPT] = True obj[FROZEN] = obj.data obj.data = frozen for modifier in obj.modifiers: modifier.show_viewport = modifier.show_render = False - report.update(frozen=True, **measured(frozen), modifiers=[modifier.name for modifier in obj.modifiers]) + report.update(frozen=True, faces=len(obj[FROZEN].polygons), evaluated=measured(frozen), modifiers=[modifier.name for modifier in obj.modifiers]) report["booleans"] = fitted(report, "booleans", booleans(obj)) return report @@ -940,9 +957,14 @@ class BROKKR_KITBASH_OT_thaw(PolishOperator): raise Refused(f"{obj.name!r} is not frozen; nothing changed.") held, frozen = obj[FROZEN], obj.data if not isinstance(held, bpy.types.Mesh): - raise Refused(f"{obj.name!r} is frozen and the live mesh its {FROZEN} held is gone: there is nothing to thaw to; nothing changed.") + kept = sorted(mesh.name for mesh in bpy.data.meshes if KEPT in mesh and not any(other.get(FROZEN) == mesh for other in bpy.data.objects)) + raise Refused(f"{obj.name!r} is frozen and the live mesh its {FROZEN} held is gone: there is nothing to thaw to" + + (f". Live meshes freeze kept that no frozen object holds: {', '.join(kept)}" if kept else "") + "; nothing changed.") obj.data = held del obj[FROZEN] + if KEPT in held and not any(other.get(FROZEN) == held for other in bpy.data.objects): + del held[KEPT] + held.use_fake_user = False for modifier in obj.modifiers: modifier.show_viewport = modifier.show_render = True if frozen.users == 0: diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 17a3d57..4ea390e 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. 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 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", @@ -553,7 +553,7 @@ }, { "name": "brokkr_kitbash.freeze", - "doc": "Freeze a mesh object that has modifiers (a kit part, a shell or any mesh) when its cuts are settled: its mesh becomes its evaluated mesh, its live mesh is held by its kit_frozen property, and every modifier stays in the stack, turned off, with its collections and cutters. Blender re-evaluates a live collection Boolean after any removal, hide or mesh read anywhere in the scene; a frozen object costs nothing there. Sockets, connections and report rows stay. set_params, boolean, cut, cut_many, ribs and a shell or hose rebuild refuse a frozen object: thaw it first. Refuses a frozen object, one with no modifiers, one with a modifier already off (named) and one Blender does not evaluate. Reports object (or the part), frozen, faces, volume, nonManifoldEdges, modifiers and booleans.", + "doc": "Freeze a mesh object that has modifiers (a kit part, a shell or any mesh) when its cuts are settled: its mesh becomes its evaluated mesh, its live mesh is held by its kit_frozen property, and every modifier stays in the stack, turned off, with its collections and cutters. Blender re-evaluates a live collection Boolean after any removal, hide or mesh read anywhere in the scene; a frozen object costs nothing there. Sockets, connections and report rows stay. set_params, boolean, cut, cut_many, ribs and a shell or hose rebuild refuse a frozen object: thaw it first. Refuses a frozen object, one with no modifiers, one with a modifier already off (named) and one Blender does not evaluate. Reports object (or the part), frozen, faces (the live mesh's), evaluated {faces, volume, nonManifoldEdges}, modifiers and booleans.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 7cc37a6..ed81032 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -33,6 +33,8 @@ Who owns what: - A boolean belongs to its Boolean modifier on the part that is cut. - Whether a cut object is live or frozen belongs to its `kit_frozen` property, which holds the live mesh while the object carries its evaluated one. Only `freeze` sets it, and `thaw`, which deletes it, is its one undo. +- Every `kit_*` custom property is the kit's: Brokkr's `setObjectCustomProperty` refuses a name that starts with + `kit_`, so each has only the writers named here. ## A part, end to end @@ -339,15 +341,18 @@ sphere under one Exact Boolean of four cutters each), each trigger on an unrelat the plates frozen, 0.004 to 0.014 s (three interleaved repetitions, Blender 5.3 on Starfire). **`freeze`** takes any mesh object that has modifiers, a kit part, a shell or a plain mesh. Its mesh becomes its -evaluated mesh (named ` frozen`), its live mesh is held by an ID-pointer property, `kit_frozen`, so it -survives a purge of orphans, and every modifier stays in the stack with its collections, turned off in viewports -and renders. Nothing is removed: the cutter objects stay, a cutter placed by `cut` keeps its floor socket and what +evaluated mesh (named ` frozen`), its live mesh is held by an ID-pointer property, `kit_frozen`, and +given a fake user (marked `kit_kept` on the mesh, and taken back by the last `thaw`), so it survives a purge of +orphans even if `kit_frozen` is edited by hand, and every modifier stays in the stack with its collections, turned +off in viewports and renders. Nothing is removed: the cutter objects stay, a cutter placed by `cut` keeps its floor socket and what is attached to it, and `booleans` still lists what cuts the object. The frozen mesh's material slots are the object's own (an empty one it had included), followed by any a cutter brought; faces a cutter made from an empty slot of its own take the first slot. A frozen kit part keeps `kit_kit`, `kit_part`, `kit_params` and its connections: its sockets are still derived from the params, so `attach`, `detach`, `roll`, `aim`, `reach` and -`close` work on it and on what hangs from it. `freeze` reports the part (or `object`), `frozen`, `faces`, -`volume`, `nonManifoldEdges`, `modifiers` and `booleans`. +`close` work on it and on what hangs from it. `freeze` reports the part (or `object`), `frozen`, `faces` (the live +mesh's count, as in every report), `evaluated: {faces, volume, nonManifoldEdges}` (the frozen mesh), `modifiers` +and `booleans`. `report` on a frozen part gives `faces`, still the live mesh's, and `evaluated: {faces}`, the +frozen mesh's. **`thaw`** puts the live mesh back, deletes `kit_frozen`, turns every modifier on and removes the frozen mesh. It evaluates nothing itself; Blender evaluates the object once afterwards, and the thawed object evaluates to the @@ -358,16 +363,22 @@ with "thaw it first": `set_params`, `boolean`, `cut`, `cut_many`, `ribs` from it it, and `freeze`. Derive ribs before freezing a cage. `freeze` also refuses an object with no modifiers, one with a modifier already off in viewports or renders (it names them: `thaw` turns every modifier on, and would not give that stack back), and one Blender does not evaluate. `thaw` refuses an object that is not frozen, and one whose -held mesh was removed. What nothing detects: a modifier of a frozen object turned on by hand, and a material -assigned to a frozen object, which lands on the frozen mesh and goes at `thaw`. `exportGltf` with `applyModifiers` -exports a frozen object's frozen mesh, since its modifiers are off. +`kit_frozen` no longer holds a mesh; if a hand edit overwrote it, the refusal names the live meshes freeze kept +that no frozen object holds, and setting `kit_frozen` back to that mesh by hand lets `thaw` through. + +A modifier of a frozen object turned on by hand is applied on top of the frozen mesh. `report` shows such a part +with `frozen` false and `dirty`, the names of the modifiers shown; it stays refused by the actions above until it +is thawed. `exportGltf` with `applyModifiers` exports a frozen object's frozen mesh, since its modifiers are off, +and refuses an export that includes a frozen object with a modifier shown in viewports. What nothing detects: a +material assigned to a frozen object, which lands on the frozen mesh and goes at `thaw`. What it buys on an assembly: KESTREL, an experiment mech of 22 cut shells and blocks, evaluated 1035 Booleans where its cuts need 139 when each finished component was only hidden, and 139 when each was frozen as it was -finished; the whole build took 4.5 times as long hidden as frozen (medians of three interleaved pairs, 3.4 to 5.7 -within a pair, Blender 5.3 on Starfire under other load; an earlier series on a quieter machine read 251.7 s -against 51.2 s). In `tests/live/kitbash_assembly.py`, removing an orphan mesh beside three cut tanks costs 1.05 s -with them live and 0.0023 s with them frozen. +finished. The evaluation counts are the stable measure: they repeat exactly. Wall time follows the machine's +load: the whole build took about 2.7 to 5.7 times as long hidden as frozen across two series of three interleaved +pairs (Blender 5.3 on Starfire under other load; 133 to 149 s against 32 to 54 s in the later one). In +`tests/live/kitbash_assembly.py`, removing an orphan mesh beside three cut tanks costs about 1 s with them live +and about 0.002 s with them frozen. ## Making a shell @@ -967,7 +978,7 @@ Python loop of BVH queries with three rays a sample, and the 13,824-candidate se | `brokkr_kitbash.describe` | `kit` (default `mechanical`), `part` (default: all) | Parts with their params (type, min, max, default, doc) and sockets in the part frame at default params. Changes nothing. | | `brokkr_kitbash.place_part` | `kit`, `part`, `object_name`, `params` | A new mesh object at the origin: the part's mesh, a `Kit Bevel` modifier when the part has a bevel, and the three ID properties. Refuses a name an object already has. | | `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: modifiers and material slots stay, and the Bevel width follows. Per-face materials are carried by shape: each shape of the part keeps the material most of its faces had, whatever the new face count. Seats the part and the parts attached to it again; refuses a change that breaks a connection or a closure's mate, and a frozen part. Reports the part and `closures`, every closure in the scene as `{part, to, holds}`: its own first, then the broken, then the rest; rows that would not fit a receipt are left off the end and counted in `closuresOmitted`. Each closure in the scene adds a few milliseconds (both its parts are built again to find their sockets). | -| `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, each socket's world frame, `connection`, `closure` and `frozen`. Changes nothing and evaluates no modifier. | +| `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, each socket's world frame, `connection`, `closure` and `frozen`; a frozen part adds `evaluated: {faces}`, and `dirty` (with `frozen` false) when a modifier of it is shown again. `faces` is the live mesh's count. Changes nothing and evaluates no modifier. | | `brokkr_kitbash.attach` | `object_name` (the child), `socket`, `parent_name`, `parent_socket`, `roll` (degrees, -360 to 360, default 0) | Seats the child's socket on the parent's and parents it there; the two parts are of one kit or of two whose socket types agree. Reports the child. | | `brokkr_kitbash.detach` | `object_name` | Clears the part's connection and the closure it states; it stays where it stands. Refuses a part that has neither. | | `brokkr_kitbash.roll` | `object_name`, `roll` (degrees, -360 to 360) | Turns an attached part to that roll where it hangs. Refuses a part that is not attached. Reports the part and `closures` as `set_params` does. | @@ -977,7 +988,7 @@ Python loop of BVH queries with three rays a sample, and the 13,824-candidate se | `brokkr_kitbash.boolean` | `object_name` (any mesh), `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds the cutter to the collection of the target's one live Exact Boolean for the operation, above the Bevel. Refuses a cutter that is the target, is not a mesh, or already cuts it, and a scaled target. Reports the part (or `object` for a mesh that is not one), `booleans: [{cutter, operation}]` (difference, union, intersect; each in the order added; `booleansOmitted` counts rows a receipt had no room for) and `evaluated`. | | `brokkr_kitbash.cut` | `object_name` (any mesh), `cutter_name`, `part` (`box`, `cyl`, `slot`, `slab`), `params`, `origin_x/y/z`, `direction_x/y/z`, `up_x/y/z` (default 0, 0, 1), `roll` (degrees, default 0), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans` (with `booleansOmitted`, as `boolean`). | | `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans` (with `booleansOmitted`, as `boolean`). | -| `brokkr_kitbash.freeze` | `object_name` (any mesh with modifiers) | Makes the evaluated mesh the object's mesh, holds the live mesh in `kit_frozen` and turns every modifier off, keeping the stack, its collections and the cutters. Refuses a frozen object, one with no modifiers, one with a modifier already off and one Blender does not evaluate. Reports the part (or `object`), `frozen`, `faces`, `volume`, `nonManifoldEdges`, `modifiers` and `booleans`. | +| `brokkr_kitbash.freeze` | `object_name` (any mesh with modifiers) | Makes the evaluated mesh the object's mesh, holds the live mesh in `kit_frozen` and turns every modifier off, keeping the stack, its collections and the cutters. Refuses a frozen object, one with no modifiers, one with a modifier already off and one Blender does not evaluate. Reports the part (or `object`), `frozen`, `faces` (live), `evaluated: {faces, volume, nonManifoldEdges}`, `modifiers` and `booleans`. | | `brokkr_kitbash.thaw` | `object_name` | Puts the live mesh back, turns every modifier on and removes the frozen mesh; evaluates nothing. Refuses an object that is not frozen or whose held mesh is gone. Reports `object`, `frozen`, `modifiers` and the live mesh's `faces`. | | `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | | `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel`, `count_folds` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `folded` (with `count_folds`, the number of the evaluated wall's inner faces that fold; else null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index d0b66c4..b18a340 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -625,11 +625,11 @@ try: receipt, frozen = send("brokkr_kitbash.freeze", object_name="Tank") after = np.zeros(len(tank.data.polygons), dtype=np.int32) tank.data.polygons.foreach_get("material_index", after) - facts = frozen and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} + facts = frozen and frozen["evaluated"] check("freeze makes the evaluated mesh the tank's mesh: the same faces, volume and non-manifold edges, and the tank still evaluates to them", receipt["status"] == "accepted" and facts == shown == measure(tank.data) == evaluated(tank)[0] and tank.data.name == "Tank frozen" and len(bpy.data.meshes) == meshes + 1, [receipt["message"], facts, shown]) - check("freeze holds the live mesh in kit_frozen and keeps the stack, off, with its collection and cutter", frozen and frozen["frozen"] is True + check("freeze holds the live mesh in kit_frozen and keeps the stack, off, with its collection and cutter", frozen and frozen["frozen"] is True and frozen["faces"] == live_faces and tank["kit_frozen"].name == mesh_name and len(tank["kit_frozen"].polygons) == live_faces and stack(tank) == frozen["modifiers"] == ["Kit Difference", "Kit Bevel"] and not any(m.show_viewport or m.show_render for m in tank.modifiers) and tank.modifiers["Kit Difference"].collection.objects[:] == [box] and frozen["booleans"] == [{"cutter": "Box", "operation": "DIFFERENCE"}] and len(bpy.data.collections) == collections and "Box" in bpy.context.scene.objects, @@ -647,7 +647,8 @@ try: refused("freeze on a frozen part", "brokkr_kitbash.freeze", {"object_name": "Tank"}, THAW) receipt, report = send("brokkr_kitbash.report", object_name="Tank") check("a frozen part still reports its sockets where its params put them, and what is attached to it still holds", report and report["parts"][0]["frozen"] is True - and report["parts"][0]["sockets"] == sockets_before and report["parts"][0]["faces"] == frozen["faces"] and holds("Tee", "Tank", "b", "port_a", 180.0)[0] + and report["parts"][0]["sockets"] == sockets_before and report["parts"][0]["faces"] == live_faces != shown["faces"] and report["parts"][0]["evaluated"] == {"faces": shown["faces"]} + and "dirty" not in report["parts"][0] and holds("Tee", "Tank", "b", "port_a", 180.0)[0] and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], report) receipt, report = send("brokkr_kitbash.attach", object_name="Radiator", socket="base", parent_name="Tank", parent_socket="saddle") check("a new part attaches to a frozen one", receipt["status"] == "accepted" and held(report) @@ -661,15 +662,42 @@ try: bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True) check("the held live mesh survives a purge of orphans", bpy.data.meshes.get(mesh_name) is not None and tank["kit_frozen"] == bpy.data.meshes[mesh_name] and len(tank["kit_frozen"].polygons) == live_faces, sorted(m.name for m in bpy.data.meshes)) + # kit_* belongs to the kit: the bridge's property setter refuses it, so kit_frozen keeps its one writer + for name in ("kit_frozen", "customProperties.kit_frozen", "kit_roll", "kit_anything"): + refused(f"setObjectCustomProperty on {name}", "setObjectCustomProperty", {"targetObjectName": "Tank", "propertyName": name, "value": "oops"}, "is brokkr_kitbash's own state (kit_*)") + # a modifier shown again by hand on a frozen part: the report says dirty, not frozen, and an export that applies modifiers refuses it + tank.modifiers["Kit Bevel"].show_viewport = True + dirty = send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0] + check("a frozen part with a modifier shown again reports dirty with the modifier, and not frozen", dirty["frozen"] is False and dirty["dirty"] == ["Kit Bevel"] + and dirty["faces"] == live_faces, dirty) + for label, fields in (("the scene", {}), ("the part by name", {"selection": ["Tank"]})): + refused(f"exportGltf applying modifiers over a dirty frozen part: {label}", "exportGltf", {"filepath": "dirty.glb", "applyModifiers": True, **fields}, + "Tank: frozen (brokkr_kitbash.freeze) with a modifier shown again") + refused("set_params on a dirty frozen part", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"}, THAW) + tank.modifiers["Kit Bevel"].show_viewport = False + check("with the modifier hidden again the part reports frozen; the refused exports wrote nothing", "dirty" not in send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0] + and send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["frozen"] is True and not (WORK / "dirty.glb").exists(), sorted(p.name for p in WORK.iterdir())) for name in ("Tee", "Tank"): receipt, thawed = send("brokkr_kitbash.thaw", object_name=name) check("thaw puts the live mesh back, turns every modifier on and removes the frozen mesh", receipt["status"] == "accepted" and tank.data.name == mesh_name and "kit_frozen" not in tank and thawed == {"object": "Tank", "frozen": False, "modifiers": ["Kit Difference", "Kit Bevel"], "faces": live_faces} and stack(tank) == ["Kit Difference", "Kit Bevel"] and all(m.show_viewport and m.show_render for m in tank.modifiers) and "Tank frozen" not in bpy.data.meshes and "kit_frozen" not in tee - and len(bpy.data.collections) == collections, [receipt["message"], thawed, sorted(m.name for m in bpy.data.meshes)]) + and len(bpy.data.collections) == collections and not tank.data.use_fake_user and "kit_kept" not in tank.data and tank.data.users == 1, + [receipt["message"], thawed, sorted(m.name for m in bpy.data.meshes), tank.data.users]) check("the thawed tank evaluates to what it did before freeze, and reports frozen false", evaluated(tank)[0] == shown and send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["frozen"] is False, [evaluated(tank)[0], shown]) lost = place("Lost", "plate", location=[0.0, -24.0, 0.0]) + lost_mesh = lost.data.name + send("brokkr_kitbash.freeze", object_name="Lost") + lost["kit_frozen"] = "oops" # by hand: no action writes it. The live mesh has lost its one real user + bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True) + check("a live mesh whose kit_frozen was overwritten by hand survives a purge of orphans", lost_mesh in bpy.data.meshes and bpy.data.meshes[lost_mesh].use_fake_user, + sorted(m.name for m in bpy.data.meshes)) + refused("thaw on a frozen part whose kit_frozen was overwritten names the kept mesh", "brokkr_kitbash.thaw", {"object_name": "Lost"}, + f"Live meshes freeze kept that no frozen object holds: {lost_mesh};") + lost["kit_frozen"] = bpy.data.meshes[lost_mesh] # the way back, by hand, that the refusal names + receipt, _ = send("brokkr_kitbash.thaw", object_name="Lost") + check("and with the kept mesh put back in kit_frozen it thaws", receipt["status"] == "accepted" and lost.data.name == lost_mesh and not lost.data.use_fake_user, receipt["message"]) send("brokkr_kitbash.freeze", object_name="Lost") bpy.data.meshes.remove(lost["kit_frozen"]) refused("thaw on a frozen part whose held mesh was removed", "brokkr_kitbash.thaw", {"object_name": "Lost"}, "the live mesh its kit_frozen held is gone") @@ -695,7 +723,7 @@ try: receipt, frozen = send("brokkr_kitbash.freeze", object_name="Plate") check("freeze on a part with no material slot leaves the frozen mesh with none (Blender's Boolean shows it with one empty slot); a linked duplicate keeps the live mesh", receipt["status"] == "accepted" and shown_slots == [None] and len(plate.data.materials) == 0 and len(plate.material_slots) == 0 - and frozen["booleans"] == second["booleans"] and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown + and frozen["booleans"] == second["booleans"] and frozen["evaluated"] == shown and twin.data.name == "Plate" and plate["kit_frozen"] == twin.data and all(m.show_viewport for m in twin.modifiers), [shown_slots, len(plate.data.materials), len(plate.material_slots), frozen]) bpy.data.objects.remove(twin) @@ -803,12 +831,14 @@ try: send("brokkr_kitbash.thaw", object_name=obj.name) bpy.app.handlers.depsgraph_update_post.remove(seen) medians = {state: sorted(seconds for seconds, _ in rows)[1] for state, rows in costs.items()} - R["frozenCost"] = {"liveSeconds": round(medians["live"], 4), "frozenSeconds": round(medians["frozen"], 5), - "live": [[round(s, 4), names] for s, names in costs["live"]], "frozen": [[round(s, 5), names] for s, names in costs["frozen"]]} + # wall time is this machine's: printed, and kept out of the result file, which carries what was re-evaluated + SECONDS = {"live": [round(s, 4) for s, _ in costs["live"]], "frozen": [round(s, 5) for s, _ in costs["frozen"]], "frozenOverLive": medians["frozen"] / medians["live"]} + print("SECONDS", SECONDS, flush=True) + R["frozenCost"] = {state: [names for _, names in rows] for state, rows in costs.items()} check("removing an orphan mesh re-evaluates the three live cut tanks, and none of them frozen", all(names == ["Cold0", "Cold1", "Cold2"] for _, names in costs["live"]) and all(names == [] for _, names in costs["frozen"]), R["frozenCost"]) check("and the update with them frozen costs under the bound of what it costs with them live", - reading("frozenCost", medians["frozen"] / medians["live"]) < FROZEN_COST, R["frozenCost"]) + SECONDS["frozenOverLive"] < FROZEN_COST, SECONDS) except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json index db1ffde..7cc08bf 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.result.json +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -576,6 +576,51 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: setObjectCustomProperty on kit_frozen", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: setObjectCustomProperty on customProperties.kit_frozen", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: setObjectCustomProperty on kit_roll", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: setObjectCustomProperty on kit_anything", + "ok": true, + "detail": null + }, + { + "name": "a frozen part with a modifier shown again reports dirty with the modifier, and not frozen", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: exportGltf applying modifiers over a dirty frozen part: the scene", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: exportGltf applying modifiers over a dirty frozen part: the part by name", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a dirty frozen part", + "ok": true, + "detail": null + }, + { + "name": "with the modifier hidden again the part reports frozen; the refused exports wrote nothing", + "ok": true, + "detail": null + }, { "name": "thaw puts the live mesh back, turns every modifier on and removes the frozen mesh", "ok": true, @@ -586,6 +631,21 @@ "ok": true, "detail": null }, + { + "name": "a live mesh whose kit_frozen was overwritten by hand survives a purge of orphans", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: thaw on a frozen part whose kit_frozen was overwritten names the kept mesh", + "ok": true, + "detail": null + }, + { + "name": "and with the kept mesh put back in kit_frozen it thaws", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: thaw on a frozen part whose held mesh was removed", "ok": true, @@ -658,7 +718,6 @@ "close nudged": 0.00032, "closed": 3.9e-07, "cut": 0.25, - "frozenCost": 0.0016, "kept": 6e-08, "nudged": 0.00032, "roll": 6.6e-06, @@ -699,47 +758,27 @@ "nonManifoldEdges": 0 }, "frozenCost": { - "liveSeconds": 1.0356, - "frozenSeconds": 0.00168, "live": [ [ - 1.0412, - [ - "Cold0", - "Cold1", - "Cold2" - ] + "Cold0", + "Cold1", + "Cold2" ], [ - 1.0356, - [ - "Cold0", - "Cold1", - "Cold2" - ] + "Cold0", + "Cold1", + "Cold2" ], [ - 0.9348, - [ - "Cold0", - "Cold1", - "Cold2" - ] + "Cold0", + "Cold1", + "Cold2" ] ], "frozen": [ - [ - 0.00168, - [] - ], - [ - 0.00264, - [] - ], - [ - 0.00165, - [] - ] + [], + [], + [] ] }, "ok": true diff --git a/surfaces/blender/tests/live/kitbash_faceted.py b/surfaces/blender/tests/live/kitbash_faceted.py index ec02c59..be7a6eb 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.py +++ b/surfaces/blender/tests/live/kitbash_faceted.py @@ -445,8 +445,10 @@ except Exception: # noqa: BLE001 whatever it was, it is a failed check with a finally: 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())} + costs = R.pop("costs", None) # wall time is this machine's: printed, and kept out of the result file Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) - print("READINGS", R["readings"], R["costs"], flush=True) + print("READINGS", R["readings"], flush=True) + print("SECONDS", costs, flush=True) sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/kitbash_faceted.result.json b/surfaces/blender/tests/live/kitbash_faceted.result.json index 1ec749c..14af0bd 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.result.json +++ b/surfaces/blender/tests/live/kitbash_faceted.result.json @@ -183,14 +183,6 @@ "soft": 5.8, "solid": 0.027 }, - "costs": { - "shell": 0.0059, - "shellCountingFolds": 0.0091, - "evaluation": 0.0022, - "rebuildUnderCuts": 1.7, - "rebuildCall": 1.6, - "rebuildCallCountingFolds": 1.6 - }, "folds": { "seeded": { "5185 offset -1": [ diff --git a/surfaces/blender/tests/live/kitbash_hose.py b/surfaces/blender/tests/live/kitbash_hose.py index 65e76c4..7ca00af 100644 --- a/surfaces/blender/tests/live/kitbash_hose.py +++ b/surfaces/blender/tests/live/kitbash_hose.py @@ -438,6 +438,14 @@ try: refused("nine clamps", {**FEED, "clamps": json.dumps([{"socket": "SeatA:front"}] * 9)}, "clamps must be a JSON array of 0 to 8 objects") refused("a pin crossed with no joint", {k: v for k, v in FEED.items() if k != "joint"}, "The hose crosses the pin of 'Shin' on 'Thigh' (socket 'end_b_back'): give joint") refused("a joint where no pin is crossed", {**LINE, "object_name": "New", "joint": json.dumps(JOINT)}, "joint is given and the hose crosses no pin") + feed.modifiers.new("Smooth", "SUBSURF") # by hand: a hose has no modifiers of its own, and freeze takes any mesh that has one + receipt, chilled = send("brokkr_kitbash.freeze", object_name="Feed") + check("a hose given a modifier freezes", receipt["status"] == "accepted" and chilled and chilled["frozen"] is True and feed.data.name == "Feed frozen", receipt["message"]) + refused("a rebuild of a frozen hose", FEED, "'Feed' is frozen, and rebuilding it needs its live mesh and modifiers: thaw it first") + send("brokkr_kitbash.thaw", object_name="Feed") + feed.modifiers.remove(feed.modifiers["Smooth"]) + receipt, thawed = send("brokkr_kitbash.hose", **FEED) + check("the thawed hose rebuilds", receipt["status"] == "accepted" and "Feed frozen" not in bpy.data.meshes and thawed["nonManifoldEdges"] == 0, receipt["message"]) place("Jack", "actuator", "body_r=0.0534;body_len=0.2;extension=0") send("brokkr_kitbash.attach", object_name="Jack", socket="base", parent_name="Shin", parent_socket="end_b", roll=90.0) bpy.context.view_layer.update() diff --git a/surfaces/blender/tests/live/kitbash_hose.result.json b/surfaces/blender/tests/live/kitbash_hose.result.json index acf4864..49cac92 100644 --- a/surfaces/blender/tests/live/kitbash_hose.result.json +++ b/surfaces/blender/tests/live/kitbash_hose.result.json @@ -301,6 +301,21 @@ "ok": true, "detail": null }, + { + "name": "a hose given a modifier freezes", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a rebuild of a frozen hose", + "ok": true, + "detail": null + }, + { + "name": "the thawed hose rebuilds", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: two pins crossed", "ok": true, diff --git a/surfaces/blender/tests/live/kitbash_shell.py b/surfaces/blender/tests/live/kitbash_shell.py index c5eed48..dc4de39 100644 --- a/surfaces/blender/tests/live/kitbash_shell.py +++ b/surfaces/blender/tests/live/kitbash_shell.py @@ -403,12 +403,12 @@ try: receipt, frozen = send("brokkr_kitbash.freeze", object_name="Plate") check("freeze keeps the three modifiers, off, the three collections they read and every cutter in the scene", receipt["status"] == "accepted" and frozen["booleans"] == report["booleans"] and len(bpy.data.collections) == collections and frozen["modifiers"] == stack(plate) == ["Kit Difference", "Kit Union", "Kit Intersect", "Kit Bevel"] - and not any(m.show_viewport or m.show_render for m in plate.modifiers) and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown == evaluated(plate)[0] + and not any(m.show_viewport or m.show_render for m in plate.modifiers) and frozen["evaluated"] == shown == evaluated(plate)[0] and all(name in bpy.context.scene.objects for name in ("Hole", "Boss", "Keep")), [receipt["message"], frozen, shown]) cage_stack, cage_mesh = stack(cage), cage.data.name receipt, frozen = send("brokkr_kitbash.freeze", object_name="Cage") check("freeze takes the cage, which is not a kit part: its evaluated wall, its stack off, its cutters still its children", receipt["status"] == "accepted" and frozen["object"] == "Cage" - and "kit" not in frozen and frozen["frozen"] is True and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} == cage_shown == evaluated(cage)[0] + and "kit" not in frozen and frozen["frozen"] is True and frozen["evaluated"] == cage_shown == evaluated(cage)[0] and frozen["modifiers"] == stack(cage) == cage_stack and not any(m.show_viewport or m.show_render for m in cage.modifiers) and cage.data.name == "Cage frozen" and bpy.data.objects["Bay"].parent == cage and len(bpy.data.collections) == collections, [receipt["message"], frozen and frozen["modifiers"], cage_shown]) refused("ribs from a frozen cage", "brokkr_kitbash.ribs", {"object_name": "Cage", "ribs_name": "ColdRibs", "planes": json.dumps([{"origin": [0.0, 0.0, 0.5], "normal": [0.0, 0.0, 1.0]}])}, THAW) @@ -442,7 +442,7 @@ try: wall = evaluated(bpy.data.objects["Lid"])[0] receipt, frozen = send("brokkr_kitbash.freeze", object_name="Lid") check("freeze takes a shell: the wall its Kit Subsurf and Kit Solidify make", receipt["status"] == "accepted" and frozen["modifiers"] == ["Kit Subsurf", "Kit Solidify"] - and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} == wall and wall["faces"] > 2 * 6 * 16, [receipt["message"], frozen, wall]) + and frozen["evaluated"] == wall and wall["faces"] > 2 * 6 * 16, [receipt["message"], frozen, wall]) refused("a rebuild of a frozen shell", "brokkr_kitbash.shell", lid, THAW) refused("a rebuild of a frozen shell that counts folds", "brokkr_kitbash.shell", {**lid, "count_folds": True}, THAW) send("brokkr_kitbash.thaw", object_name="Lid") diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index 6d4a762..c78056e 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -609,6 +609,16 @@ class NodeActionTests(unittest.TestCase): self.assertIn("setModifierInput", receipt["message"]) self.assertFalse(hasattr(host, "custom")) + def test_custom_property_in_the_kit_namespace_is_refused(self): + self.group() + host = self.bpy.data.objects["Host"] + for name in ("kit_frozen", "customProperties.kit_frozen", "kit_roll", "kit_"): + receipt = self.refused(action="setObjectCustomProperty", targetObjectName="Host", propertyName=name, value=3) + self.assertIn("brokkr_kitbash's own state (kit_*)", receipt["message"]) + self.assertFalse(hasattr(host, "custom")) + self.accepted(action="setObjectCustomProperty", targetObjectName="Host", propertyName="kitchen", value=3) + self.assertEqual(host.custom, ("kitchen", 3)) + def test_custom_property_sharing_only_a_display_name_is_an_ordinary_property(self): self.group() host = self.bpy.data.objects["Host"] diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index ef3ae3b..874d2b6 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -114,6 +114,7 @@ class FakeBpy: for o in self.data.objects.values(): o.selected = o is self.mesh o.select_get = (lambda o=o: o.selected) + o.modifiers, o.get = [], (lambda key, default=None: default) # no modifier, no custom property o.select_set = (lambda state, o=o: setattr(o, "selected", state)) add = lambda kind: (lambda mode, undo, **kw: self.add_object(kind, kw, (mode, undo))) self.ops = NS(import_scene=NS(gltf=self.import_gltf), render=NS(render=self.render_still), @@ -291,6 +292,21 @@ class ActionTests(unittest.TestCase): self.assertEqual(call["selected_at_call"], ["Cam", "Lamp"]) self.assertEqual([o.name for o in self.bpy.data.objects.values() if o.selected], ["Cube"]) + def test_export_applying_modifiers_refuses_a_frozen_object_with_a_modifier_shown(self): + mesh = self.bpy.data.objects["Cube"] + mesh.get = lambda key, default=None: "live mesh" if key == "kit_frozen" else default + mesh.modifiers = [NS(show_viewport=False), NS(show_viewport=True)] + for fields in ({}, {"selection": ["Cube"]}): + receipt = self.run_action(action="exportGltf", filepath="dirty.glb", **fields) + self.assertEqual(receipt["status"], "failed", receipt) + self.assertIn("Cube: frozen (brokkr_kitbash.freeze) with a modifier shown again", receipt["message"]) + self.assertEqual((self.bpy.exported, list((self.root / "out").iterdir())), ([], [])) + for fields in ({"applyModifiers": False}, {"selection": ["Cam"]}): # nothing applied, or the object not exported + receipt = self.run_action(action="exportGltf", filepath=f"ok{len(self.bpy.exported)}.glb", **fields) + self.assertEqual(receipt["status"], "accepted", receipt) + mesh.modifiers[1].show_viewport = False + self.assertEqual(self.run_action(action="exportGltf", filepath="frozen.glb")["status"], "accepted") + def test_export_without_a_selection_never_touches_selection(self): def explode(*a, **k): raise AssertionError("selection touched") -- 2.47.3 From 7845b13ed01770704a6b6998909a1611a68bb7a9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:34:24 +0100 Subject: [PATCH 5/5] brokkr_kitbash freeze: one writer of the frozen state, hold; a deleted frozen object releases its live mesh; importGltf drops kit_* extras (cut kit-freeze, fix batch h3) hold is the only writer of kit_frozen, kit_kept and a held live mesh's fake user, and it swaps the meshes. It settles every live mesh after each depsgraph update and before each save: held meshes are kept, kit_kept pointing at the frozen mesh; a mesh no kit_frozen points at is released unless an object still carries the frozen mesh its kit_kept names. The bridge's kit_owned is the one test for kit_*: setObjectCustomProperty refuses, importGltf drops and reports. thaw removes the frozen mesh by user_map, names the kept mesh when kit_frozen was lost; a dirty part is refused as dirty; the export refusal counts show_render as the report does. Co-Authored-By: Claude Fable 5.2 --- .../blender/brokkr_bridge/blender_target.py | 27 +++++- surfaces/blender/brokkr_kitbash/__init__.py | 92 +++++++++++++++---- surfaces/blender/docs/install.md | 2 + surfaces/blender/docs/kitbash.md | 25 +++-- .../blender/tests/live/kitbash_assembly.py | 81 +++++++++++++++- surfaces/blender/tests/test_kitbash.py | 13 ++- surfaces/blender/tests/test_scene_actions.py | 30 +++++- 7 files changed, 227 insertions(+), 43 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index a24f09b..6e23e8c 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -46,7 +46,7 @@ DEFAULT_DEBUG_MIRROR_ROOT = "//.brokkr/blender-editor-debug" HOST_SNAPSHOT_SCHEMA = "brokkr.blender.host_snapshot.v0" HOST_ACTIONS_FILE = "brokkr_actions.json" HOST_RESULT_LIMIT = 16000 # characters of a host operator's result copied into a receipt -KIT_RESERVED = "kit_" # brokkr_kitbash owns every custom property so named: setObjectCustomProperty refuses them +KIT_RESERVED = "kit_" # brokkr_kitbash owns every custom property so named: kit_owned is the one test, setObjectCustomProperty refuses them and importGltf drops them KIT_FROZEN = "kit_frozen" # brokkr_kitbash's frozen state (its FROZEN): read here only, to refuse an export that would apply a stack twice COMMAND_INTENT_SCHEMA = "brokkr.blender.command_intent.v0" COMMAND_RECEIPT_SCHEMA = "brokkr.blender.command_receipt.v0" @@ -946,7 +946,7 @@ class BrokkrBlenderTarget: property_name = command["propertyName"] if property_name.startswith("customProperties."): property_name = property_name[len("customProperties."):] - if property_name.startswith(KIT_RESERVED): + if kit_owned(property_name): raise sa.ActionRefused(f"{property_name!r} is brokkr_kitbash's own state ({KIT_RESERVED}*): its actions write it, and a value set " "here would leave the object and the property disagreeing. Use the brokkr_kitbash action; nothing changed.") modifier_name = na.drives_modifier_input(obj, property_name) @@ -1008,7 +1008,19 @@ class BrokkrBlenderTarget: before = set(self.bpy.data.objects.keys()) self.bpy.ops.import_scene.gltf("EXEC_DEFAULT", False, filepath=str(path)) added = sorted(set(self.bpy.data.objects.keys()) - before) - return self._receipt(command, "accepted", f"Imported {len(added)} object(s) from {path.name}.", added[0] if added else "") + # A file's extras become custom properties, and kit_* is brokkr_kitbash's own state, as setObjectCustomProperty + # has it: an imported kit_frozen would make a frozen object with no live mesh to thaw to. + dropped = [] + for name in added: + obj = self.bpy.data.objects[name] + for holder in (obj, obj.data): + for key in [key for key in (holder.keys() if holder is not None else ()) if kit_owned(key)]: + del holder[key] + dropped.append(name) + dropped = sorted(set(dropped)) + return self._receipt(command, "accepted", f"Imported {len(added)} object(s) from {path.name}." + ( + f" Dropped the file's {KIT_RESERVED}* properties from {', '.join(dropped)}: they are brokkr_kitbash's own state and its actions write them." if dropped else ""), + added[0] if added else "") def _exportGltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: """Write the scene (or the named objects) as .glb or .gltf under the output directory.""" @@ -1035,10 +1047,10 @@ class BrokkrBlenderTarget: if command["applyModifiers"]: # A frozen object's mesh is already its stack's result: a modifier shown on it again would be applied twice. dirty = sorted(o.name for o in (chosen or context.view_layer.objects.values()) - if o.get(KIT_FROZEN) is not None and any(m.show_viewport for m in o.modifiers)) + if o.get(KIT_FROZEN) is not None and any(m.show_viewport or m.show_render for m in o.modifiers)) if dirty: raise sa.ActionRefused(f"{', '.join(dirty)}: frozen (brokkr_kitbash.freeze) with a modifier shown again, so the export would apply " - "the stack on top of its own result. Thaw it (brokkr_kitbash.thaw), or hide its modifiers; nothing written.") + "the stack on top of its own result. Thaw it (brokkr_kitbash.thaw), or hide its modifiers in viewports and renders; nothing written.") # The exporter writes into a fresh staging folder beside the target, never onto the output # directory: it may also write a .bin and texture files whose names Brokkr does not choose. Only # after it finishes does every file move into place, each refused if its name is taken, so no @@ -1928,6 +1940,11 @@ def _sync_session(session_id: str, display_name: str, updated_at: str) -> dict[s } +def kit_owned(property_name: str) -> bool: + """A custom property brokkr_kitbash owns: no bridge action writes one from outside input.""" + return property_name.startswith(KIT_RESERVED) + + def _unity_custom_property_path(component_type: str, property_path: str) -> str: property_path = (property_path or "value").strip() component_type = (component_type or "").strip() diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 26e50e6..d339078 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -88,8 +88,8 @@ from . import core, route KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" SOCKET, PARENT_SOCKET, ROLL = "kit_socket", "kit_parent_socket", "kit_roll" -FROZEN = "kit_frozen" # on a frozen object: an ID pointer to its live mesh; its presence is the frozen state, freeze sets it and thaw deletes it -KEPT = "kit_kept" # on a live mesh a frozen object holds: freeze gave it the fake user that keeps it through a purge, and the last thaw takes it back +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) BEVEL = "Kit Bevel" @@ -376,9 +376,59 @@ def shown(obj) -> list: def live(obj, doing: str) -> None: """Refuses a frozen object: its mesh is its frozen evaluation and its modifiers are off, so a write would land on - a mesh thaw discards, or under a stack nothing evaluates.""" + a mesh thaw discards, or under a stack nothing evaluates. A dirty one is named dirty, as its report names it.""" if FROZEN in obj: - raise Refused(f"{obj.name!r} is frozen, and {doing} it needs its live mesh and modifiers: thaw it first; nothing changed.") + dirty = shown(obj) + raise Refused(f"{obj.name!r} is frozen" + (f" and dirty ({', '.join(dirty)} shown again)" if dirty else "") + + f", and {doing} it needs its live mesh and modifiers: thaw it first; nothing changed.") + + +def hold(obj=None, frozen=None) -> None: + """The one writer of the frozen state: kit_frozen on an object, and kit_kept and the fake user on a live mesh. + Given an object and its frozen mesh, the object takes that mesh and its kit_frozen takes the live one; given an + object alone, its live mesh comes back from kit_frozen, which goes. Then, given one or not, every live mesh is + settled against the objects there are. One that a frozen object holds has a fake user and kit_kept, a pointer to + that object's frozen mesh. One that no kit_frozen points at loses both and is Blender's to purge, unless an object + still carries the frozen mesh its kit_kept names: that object's kit_frozen was lost by hand, and thaw names the + mesh. So a deleted frozen object releases its live mesh, by an action or by hand, and a hand edit of either + property is put right or reported. The fake user is this function's alone: one she gave a live mesh herself goes + when the mesh is released. Writes only what differs, so settled() may call it after every depsgraph update.""" + if obj is not None: + hold() # what a hand edit left is settled against the holders as they were, before this write changes them + if frozen is None: + obj.data = obj[FROZEN] + del obj[FROZEN] + else: + obj[FROZEN], obj.data = obj.data, frozen + carried, holders = set(), {} + for other in bpy.data.objects: + if other.type == "MESH": + carried.add(other.data.as_pointer()) + held = other.get(FROZEN) + if isinstance(held, bpy.types.Mesh): + holders.setdefault(held.as_pointer(), []).append(other.data) + for held in bpy.data.meshes: + carrying, kept = holders.get(held.as_pointer()), held.get(KEPT) + if carrying: + if not (isinstance(kept, bpy.types.Mesh) and kept in carrying): + held[KEPT] = carrying[0] + if not held.use_fake_user: + held.use_fake_user = True + elif KEPT in held and not (isinstance(kept, bpy.types.Mesh) and kept.as_pointer() in carried): + del held[KEPT] + held.use_fake_user = False + + +@bpy.app.handlers.persistent +def settled(*_) -> None: + """After a depsgraph update and before a save: hold() with no object. A frozen object deleted by any means, the + bridge's deleteObject or a key press, is seen here.""" + hold() + + +def kept_for(obj) -> list: + """The live meshes whose kit_kept names the mesh this object carries, by name.""" + return sorted(mesh.name for mesh in bpy.data.meshes if isinstance(mesh.get(KEPT), bpy.types.Mesh) and mesh[KEPT] == obj.data) def own_mesh(obj, doing: str) -> None: @@ -932,10 +982,7 @@ class BROKKR_KITBASH_OT_freeze(PolishOperator): if (index < 0).any(): # faces from a cutter's empty slot: slot 0, as faces from a cutter with no material frozen.polygons.foreach_set("material_index", np.maximum(index, 0)) frozen.name = f"{obj.name} frozen" - if not obj.data.use_fake_user: # the pointer below is a user too, but a property can be overwritten: the mesh outlives that - obj.data.use_fake_user = obj.data[KEPT] = True - obj[FROZEN] = obj.data - obj.data = frozen + hold(obj, frozen) for modifier in obj.modifiers: modifier.show_viewport = modifier.show_render = False report.update(frozen=True, faces=len(obj[FROZEN].polygons), evaluated=measured(frozen), modifiers=[modifier.name for modifier in obj.modifiers]) @@ -953,21 +1000,19 @@ class BROKKR_KITBASH_OT_thaw(PolishOperator): @kit_work def work(self, context): obj = mesh_object(self.object_name) - if FROZEN not in obj: - raise Refused(f"{obj.name!r} is not frozen; nothing changed.") - held, frozen = obj[FROZEN], obj.data + held, frozen = obj.get(FROZEN), obj.data if not isinstance(held, bpy.types.Mesh): - kept = sorted(mesh.name for mesh in bpy.data.meshes if KEPT in mesh and not any(other.get(FROZEN) == mesh for other in bpy.data.objects)) - raise Refused(f"{obj.name!r} is frozen and the live mesh its {FROZEN} held is gone: there is nothing to thaw to" - + (f". Live meshes freeze kept that no frozen object holds: {', '.join(kept)}" if kept else "") + "; nothing changed.") - obj.data = held - del obj[FROZEN] - if KEPT in held and not any(other.get(FROZEN) == held for other in bpy.data.objects): - del held[KEPT] - held.use_fake_user = False + kept = kept_for(obj) + if FROZEN not in obj and not kept: + raise Refused(f"{obj.name!r} is not frozen; nothing changed.") + raise Refused(f"{obj.name!r} carries a frozen mesh and its {FROZEN} " + ("is gone" if FROZEN not in obj else "no longer points at a mesh") + + (f": freeze kept its live mesh {', '.join(repr(name) for name in kept)}. Point {FROZEN} back at it by hand " + f"(object[{FROZEN!r}] = bpy.data.meshes[{kept[0]!r}]) and thaw" if kept else + ", and no kept live mesh names the mesh it carries: there is nothing to thaw to") + "; nothing changed.") + hold(obj) for modifier in obj.modifiers: modifier.show_viewport = modifier.show_render = True - if frozen.users == 0: + if not bpy.data.user_map(subset=[frozen])[frozen]: # users is no test: a glTF export that applied modifiers leaves the count one high bpy.data.meshes.remove(frozen) return {"object": obj.name, "frozen": False, "modifiers": [modifier.name for modifier in obj.modifiers], "faces": len(held.polygons)} @@ -1910,13 +1955,20 @@ classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KI BROKKR_KITBASH_OT_shell, BROKKR_KITBASH_OT_hose) +SETTLED_ON = (bpy.app.handlers.depsgraph_update_post, bpy.app.handlers.save_pre) + + def register(): if MISSING is not None or not hasattr(bpy.types.WindowManager, RESULT): raise RuntimeError(f"brokkr_kitbash needs brokkr_mesh_polish enabled first ({MISSING or 'its result property is not registered'}).") for cls in classes: bpy.utils.register_class(cls) + for handlers in SETTLED_ON: + handlers.append(settled) def unregister(): + for handlers in SETTLED_ON: + handlers.remove(settled) for cls in reversed(classes): bpy.utils.unregister_class(cls) diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 2659f4d..40362d6 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -186,6 +186,8 @@ Behaviour the table does not say, per action: - `importGltf`: `filepath`, `.gltf` or `.glb`, relative to the add-on preference `Import Directory` (absolute paths, `..` and symlinks that resolve outside it are refused). Empty `Import Directory` disables the action. Needs Blender's glTF add-on. + Custom properties named `kit_*` that the file's extras carry are dropped from the imported + objects and their data, and the receipt names the objects: they are brokkr_kitbash's own state. - `exportGltf`: `filepath`, `.glb` (binary) or `.gltf` (separate `.bin`), relative to the add-on preference `Render Output Directory` (the renderStill rules: no `..`, no links, and an existing name is refused; there is no overwrite). diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index ed81032..4096be7 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -33,8 +33,11 @@ Who owns what: - A boolean belongs to its Boolean modifier on the part that is cut. - Whether a cut object is live or frozen belongs to its `kit_frozen` property, which holds the live mesh while the object carries its evaluated one. Only `freeze` sets it, and `thaw`, which deletes it, is its one undo. + Both go through one function, `hold`, which is also the only writer of `kit_kept` and of the fake user on a held + live mesh ("Freezing"). - Every `kit_*` custom property is the kit's: Brokkr's `setObjectCustomProperty` refuses a name that starts with - `kit_`, so each has only the writers named here. + `kit_`, and `importGltf` drops such properties from the objects and meshes it imports and names the objects in + its receipt, so each has only the writers named here. A kit part exported with extras comes back as a plain mesh. ## A part, end to end @@ -342,8 +345,12 @@ the plates frozen, 0.004 to 0.014 s (three interleaved repetitions, Blender 5.3 **`freeze`** takes any mesh object that has modifiers, a kit part, a shell or a plain mesh. Its mesh becomes its evaluated mesh (named ` frozen`), its live mesh is held by an ID-pointer property, `kit_frozen`, and -given a fake user (marked `kit_kept` on the mesh, and taken back by the last `thaw`), so it survives a purge of -orphans even if `kit_frozen` is edited by hand, and every modifier stays in the stack with its collections, turned +given a fake user and `kit_kept`, a pointer to the frozen mesh, so it survives a purge of orphans and a save even +if `kit_frozen` is edited by hand. The kit settles this after every depsgraph update and before every save: a live +mesh that no `kit_frozen` points at loses its fake user and `kit_kept`, unless an object still carries the frozen +mesh its `kit_kept` names. So deleting a frozen object, by `deleteObject` or in Blender, releases its live mesh to +the next purge or save, and a `kit_kept` cleared by hand is written again. The fake user is the kit's: one already +set on a live mesh goes when the mesh is released. Every modifier stays in the stack with its collections, turned off in viewports and renders. Nothing is removed: the cutter objects stay, a cutter placed by `cut` keeps its floor socket and what is attached to it, and `booleans` still lists what cuts the object. The frozen mesh's material slots are the object's own (an empty one it had included), followed by any a cutter brought; faces a cutter made from an empty @@ -363,13 +370,15 @@ with "thaw it first": `set_params`, `boolean`, `cut`, `cut_many`, `ribs` from it it, and `freeze`. Derive ribs before freezing a cage. `freeze` also refuses an object with no modifiers, one with a modifier already off in viewports or renders (it names them: `thaw` turns every modifier on, and would not give that stack back), and one Blender does not evaluate. `thaw` refuses an object that is not frozen, and one whose -`kit_frozen` no longer holds a mesh; if a hand edit overwrote it, the refusal names the live meshes freeze kept -that no frozen object holds, and setting `kit_frozen` back to that mesh by hand lets `thaw` through. +`kit_frozen` no longer holds a mesh; if a hand edit overwrote or deleted it, the refusal names the kept live mesh +whose `kit_kept` points at the mesh the object carries, and setting `kit_frozen` back to that mesh by hand lets +`thaw` through. A modifier of a frozen object turned on by hand is applied on top of the frozen mesh. `report` shows such a part -with `frozen` false and `dirty`, the names of the modifiers shown; it stays refused by the actions above until it -is thawed. `exportGltf` with `applyModifiers` exports a frozen object's frozen mesh, since its modifiers are off, -and refuses an export that includes a frozen object with a modifier shown in viewports. What nothing detects: a +with `frozen` false and `dirty`, the names of the modifiers shown in viewports or renders; it stays refused by the +actions above, as "frozen and dirty", until it is thawed. `exportGltf` with `applyModifiers` exports a frozen +object's frozen mesh, since its modifiers are off, and refuses an export that includes a dirty one, by the same +rule: a modifier shown in viewports or renders. What nothing detects: a material assigned to a frozen object, which lands on the frozen mesh and goes at `thaw`. What it buys on an assembly: KESTREL, an experiment mech of 22 cut shells and blocks, evaluated 1035 Booleans diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index b18a340..48239fa 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -673,8 +673,14 @@ try: for label, fields in (("the scene", {}), ("the part by name", {"selection": ["Tank"]})): refused(f"exportGltf applying modifiers over a dirty frozen part: {label}", "exportGltf", {"filepath": "dirty.glb", "applyModifiers": True, **fields}, "Tank: frozen (brokkr_kitbash.freeze) with a modifier shown again") - refused("set_params on a dirty frozen part", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"}, THAW) + refused("set_params on a dirty frozen part, named dirty as its report names it", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"}, + "'Tank' is frozen and dirty (Kit Bevel shown again), and setting params of it needs its live mesh and modifiers: thaw it first") tank.modifiers["Kit Bevel"].show_viewport = False + tank.modifiers["Kit Bevel"].show_render = True # shown in renders only: dirty by the same rule, in the report and at the export + check("a frozen part with a modifier shown in renders only reports dirty", send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0].get("dirty") == ["Kit Bevel"]) + refused("exportGltf applying modifiers over a frozen part dirty in renders only", "exportGltf", {"filepath": "dirty.glb", "applyModifiers": True, "selection": ["Tank"]}, + "Tank: frozen (brokkr_kitbash.freeze) with a modifier shown again") + tank.modifiers["Kit Bevel"].show_render = False check("with the modifier hidden again the part reports frozen; the refused exports wrote nothing", "dirty" not in send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0] and send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["frozen"] is True and not (WORK / "dirty.glb").exists(), sorted(p.name for p in WORK.iterdir())) for name in ("Tee", "Tank"): @@ -694,13 +700,82 @@ try: check("a live mesh whose kit_frozen was overwritten by hand survives a purge of orphans", lost_mesh in bpy.data.meshes and bpy.data.meshes[lost_mesh].use_fake_user, sorted(m.name for m in bpy.data.meshes)) refused("thaw on a frozen part whose kit_frozen was overwritten names the kept mesh", "brokkr_kitbash.thaw", {"object_name": "Lost"}, - f"Live meshes freeze kept that no frozen object holds: {lost_mesh};") + f"its kit_frozen no longer points at a mesh: freeze kept its live mesh {lost_mesh!r}. Point kit_frozen back at it by hand") lost["kit_frozen"] = bpy.data.meshes[lost_mesh] # the way back, by hand, that the refusal names receipt, _ = send("brokkr_kitbash.thaw", object_name="Lost") check("and with the kept mesh put back in kit_frozen it thaws", receipt["status"] == "accepted" and lost.data.name == lost_mesh and not lost.data.use_fake_user, receipt["message"]) send("brokkr_kitbash.freeze", object_name="Lost") bpy.data.meshes.remove(lost["kit_frozen"]) - refused("thaw on a frozen part whose held mesh was removed", "brokkr_kitbash.thaw", {"object_name": "Lost"}, "the live mesh its kit_frozen held is gone") + refused("thaw on a frozen part whose held mesh was removed", "brokkr_kitbash.thaw", {"object_name": "Lost"}, "no kept live mesh names the mesh it carries: there is nothing to thaw to") + + # --- the frozen state has one writer, hold: what it does when the holder goes, by an action or by hand, and what an import may not bring --- + def purge(): + bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True) + + def saved_meshes(name): + """The meshes a save writes, read from the file: a save and reload keeps these and no others.""" + bpy.ops.wm.save_as_mainfile(filepath=str(WORK / name), copy=True) + with bpy.data.libraries.load(str(WORK / name)) as (source, _): + return sorted(source.meshes) + + def kept_state(name): + mesh = bpy.data.meshes.get(name) + return mesh and [mesh.use_fake_user, getattr(mesh.get("kit_kept"), "name", mesh.get("kit_kept"))] + + target.configure_action_dirs(str(WORK), str(WORK)) + gone = place("Gone", "plate", location=[0.0, -27.0, 0.0]) + gone_mesh = gone.data.name + send("brokkr_kitbash.freeze", object_name="Gone") + receipt, _ = send("exportGltf", filepath="gone_applied.glb", applyModifiers=True, selection=["Gone"]) + send("brokkr_kitbash.thaw", object_name="Gone") + check("thaw after an export that applied modifiers leaves no frozen mesh behind", receipt["status"] == "accepted" and "Gone frozen" not in bpy.data.meshes + and gone.data.name == gone_mesh, [receipt["message"], sorted(m.name for m in bpy.data.meshes)]) + send("brokkr_kitbash.freeze", object_name="Gone") + check("freeze gives the live mesh a fake user and kit_kept, a pointer to the frozen mesh; a save writes both", kept_state(gone_mesh) == [True, "Gone frozen"] + and {gone_mesh, "Gone frozen"} <= set(saved_meshes("held.blend")), kept_state(gone_mesh)) + receipt, _ = send("exportGltf", filepath="gone.glb", applyModifiers=False, extras=True, selection=["Gone"]) + exported = receipt["status"] + receipt, _ = send("deleteObject", targetObjectName="Gone") + purge() + check("deleteObject on a frozen object releases its live mesh: a purge takes it and the frozen mesh", receipt["status"] == "accepted" and exported == "accepted" + and gone_mesh not in bpy.data.meshes and "Gone frozen" not in bpy.data.meshes, [kept_state(gone_mesh), sorted(m.name for m in bpy.data.meshes)]) + receipt, _ = send("importGltf", filepath="gone.glb") + back = bpy.data.objects.get("Gone") + check("importGltf drops the kit_* properties a file's extras carry, and says so: the imported object is not frozen and not a part", receipt["status"] == "accepted" + and back is not None and not [key for holder in (back, back.data) for key in holder.keys() if key.startswith("kit_")] + and "Dropped the file's kit_* properties from Gone" in receipt["message"], [receipt["message"], back and dict(back.items())]) + refused("thaw on the imported object", "brokkr_kitbash.thaw", {"object_name": "Gone"}, "'Gone' is not frozen") + send("deleteObject", targetObjectName="Gone") + purge() + plain = place("Plain_gone", "plate", location=[0.0, -30.0, 0.0]) + plain_mesh = plain.data.name + send("brokkr_kitbash.freeze", object_name="Plain_gone") + with bpy.context.temp_override(selected_objects=[plain]): + deleted = bpy.ops.object.delete() + written = saved_meshes("deleted.blend") + purge() + check("a frozen object deleted in Blender, by no action: a save writes neither mesh, and a purge takes both", deleted == {"FINISHED"} and "Plain_gone" not in bpy.data.objects + and plain_mesh not in written and "Plain_gone frozen" not in written and plain_mesh not in bpy.data.meshes and "Plain_gone frozen" not in bpy.data.meshes, + [deleted, written, sorted(m.name for m in bpy.data.meshes)]) + hand = place("Hand", "plate", location=[0.0, -33.0, 0.0]) + hand_mesh = hand.data.name + send("brokkr_kitbash.freeze", object_name="Hand") + del bpy.data.meshes[hand_mesh]["kit_kept"] # by hand + receipt, _ = send("brokkr_kitbash.thaw", object_name="Hand") + check("a kept mesh whose kit_kept was cleared by hand still gives its fake user back at thaw", receipt["status"] == "accepted" and kept_state(hand_mesh) == [False, None] + and hand.data.name == hand_mesh, [receipt["message"], kept_state(hand_mesh)]) + send("brokkr_kitbash.freeze", object_name="Hand") + del hand["kit_frozen"] # by hand: the object still carries the frozen mesh the kept mesh names + purge() + check("a live mesh whose kit_frozen was deleted by hand stays kept through a purge and a save", kept_state(hand_mesh) == [True, "Hand frozen"] + and hand_mesh in saved_meshes("lost.blend"), kept_state(hand_mesh)) + refused("thaw on a frozen part whose kit_frozen was deleted names the kept mesh", "brokkr_kitbash.thaw", {"object_name": "Hand"}, + f"'Hand' carries a frozen mesh and its kit_frozen is gone: freeze kept its live mesh {hand_mesh!r}. Point kit_frozen back at it by hand") + hand["kit_frozen"] = bpy.data.meshes[hand_mesh] + receipt, _ = send("brokkr_kitbash.thaw", object_name="Hand") + check("and with kit_frozen pointed back it thaws and the mesh is released", receipt["status"] == "accepted" and hand.data.name == hand_mesh + and kept_state(hand_mesh) == [False, None] and "Hand frozen" not in bpy.data.meshes, [receipt["message"], kept_state(hand_mesh)]) + target.configure_action_dirs("", str(WORK)) # --- the second target: a plate with no material slot, cut twice ---------------------------------------------------------------------- plate = place("Plate", "plate", location=[0.0, -3.0, 0.0]) diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index c253c90..746ee5a 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1985,9 +1985,14 @@ class OwnershipTests(unittest.TestCase): (bodies["ribs"], "show_viewport = False"), (bodies["shell"], "clear_geometry()"), (bodies["set_params"], "write_mesh("), (bodies["hose"], "write_mesh(")): self.assertLess(body.index("live("), body.index(first_write)) - self.assertEqual((source.count("obj[FROZEN] ="), source.count("del obj[FROZEN]"), source.count("live(")), (1, 1, 8)) # its def and the seven callers above - self.assertIn("obj[FROZEN] =", bodies["freeze"]) - self.assertIn("del obj[FROZEN]", bodies["thaw"]) + self.assertEqual(source.count("live("), 8) # its def and the seven callers above + # the frozen state has one writer: every write of kit_frozen, kit_kept and a fake user is in hold, which swaps the meshes too + hold = source.split("\ndef hold(")[1].split("\n\n\n")[0] + writes = r"\[(?:FROZEN|KEPT)\](?:, obj\.data)? =(?!=)|del \w+\[(?:FROZEN|KEPT)\]|use_fake_user = " + self.assertEqual(re.findall(writes, source), re.findall(writes, hold)) + self.assertEqual(len(re.findall(writes, hold)), 6) + self.assertEqual(("hold(obj, frozen)" in bodies["freeze"], "hold(obj)" in bodies["thaw"], "obj.data =" in bodies["freeze"] + bodies["thaw"]), (True, True, False)) + self.assertEqual(re.findall(r"handlers\.(\w+)", source.split("SETTLED_ON = ")[1].split("\n")[0]),["depsgraph_update_post", "save_pre"]) ribs = bodies["ribs"] # every refusal before the ribs object is written, and the cage's modifiers shown again whatever happened self.assertLess(ribs.rindex("raise Refused("), ribs.index("mesh = bpy.data.meshes.new(self.ribs_name)")) self.assertLess(ribs.index("finally:"), ribs.index("modifier.show_viewport = True")) @@ -2111,7 +2116,7 @@ class OwnershipTests(unittest.TestCase): 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) - self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 2, True)) # detach's keys, and thaw's kit_frozen + 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" self.assertIsNone(re.search(placing, bodies["close"])) diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index 874d2b6..8f9de97 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -67,6 +67,15 @@ def fake_render(): return FakeRender() +class Extras(dict): + """An ID with custom properties: a mapping, and the attributes it is given.""" + def __init__(self, properties=(), **attributes): + super().__init__(properties) + self.__dict__.update(attributes) + + __hash__ = object.__hash__ + + class Objects(dict): """bpy.data.objects: a mapping with keys() and get(); like bpy_prop_collection, iterating it yields the objects.""" @@ -89,7 +98,7 @@ class FakeUndo: class FakeBpy: def __init__(self): - self.imported = [] + self.imported, self.import_extras, self.import_mesh_extras = [], {}, {} self.rendered = [] self.scene = NS(name="Scene", camera=None, world=None, render=fake_render()) self.camera_data = NS(lens=50.0, type="PERSP", ortho_scale=6.0, clip_start=0.1, clip_end=100.0, @@ -141,7 +150,7 @@ class FakeBpy: def import_gltf(self, mode, undo, filepath): assert (mode, undo) == ("EXEC_DEFAULT", False) self.imported.append(filepath) - self.data.objects["Imported"] = NS(name="Imported", type="MESH", data=None) + self.data.objects["Imported"] = Extras(self.import_extras, name="Imported", type="MESH", data=Extras(self.import_mesh_extras)) def export_gltf(self, mode, undo, **kwargs): assert (mode, undo) == ("EXEC_DEFAULT", False) @@ -193,6 +202,18 @@ class ActionTests(unittest.TestCase): self.assertEqual(receipt["status"], "accepted") self.assertEqual(self.bpy.imported, [str(self.root / "in" / "model.glb")]) self.assertEqual(receipt["objectName"], "Imported") + self.assertEqual(receipt["message"], "Imported 1 object(s) from model.glb.") + + def test_import_drops_the_kit_properties_a_file_carries(self): + """kit_* is brokkr_kitbash's own state: what setObjectCustomProperty refuses, importGltf does not bring in from extras.""" + self.bpy.import_extras = {"kit_frozen": None, "kit_part": "tank", "kit_params": "{}", "note": "kept", "kitchen": 1} + self.bpy.import_mesh_extras = {"kit_kept": True, "source": "scan"} + receipt = self.run_action(action="importGltf", filepath="model.glb") + imported = self.bpy.data.objects["Imported"] + self.assertEqual((receipt["status"], dict(imported), dict(imported.data)), ("accepted", {"note": "kept", "kitchen": 1}, {"source": "scan"})) + self.assertIn("Dropped the file's kit_* properties from Imported", receipt["message"]) + self.assertEqual(bt.kit_owned("kit_frozen") and bt.kit_owned("kit_anything"), True) + self.assertEqual(bt.kit_owned("kitchen") or bt.kit_owned("akit_x"), False) def test_import_outside_the_import_dir_is_refused_before_bpy(self): for path in ("../secret.glb", str(self.root / "secret.glb"), "/etc/passwd.glb", "sub/../../secret.glb"): @@ -295,7 +316,7 @@ class ActionTests(unittest.TestCase): def test_export_applying_modifiers_refuses_a_frozen_object_with_a_modifier_shown(self): mesh = self.bpy.data.objects["Cube"] mesh.get = lambda key, default=None: "live mesh" if key == "kit_frozen" else default - mesh.modifiers = [NS(show_viewport=False), NS(show_viewport=True)] + mesh.modifiers = [NS(show_viewport=False, show_render=False), NS(show_viewport=True, show_render=False)] for fields in ({}, {"selection": ["Cube"]}): receipt = self.run_action(action="exportGltf", filepath="dirty.glb", **fields) self.assertEqual(receipt["status"], "failed", receipt) @@ -305,6 +326,9 @@ class ActionTests(unittest.TestCase): receipt = self.run_action(action="exportGltf", filepath=f"ok{len(self.bpy.exported)}.glb", **fields) self.assertEqual(receipt["status"], "accepted", receipt) mesh.modifiers[1].show_viewport = False + mesh.modifiers[0].show_render = True # shown in renders only: dirty by the rule brokkr_kitbash's report uses + self.assertIn("with a modifier shown again", self.run_action(action="exportGltf", filepath="render.glb")["message"]) + mesh.modifiers[0].show_render = False self.assertEqual(self.run_action(action="exportGltf", filepath="frozen.glb")["status"], "accepted") def test_export_without_a_selection_never_touches_selection(self): -- 2.47.3