From cc98d36f4e8daf8db5927b35c9669b33b0258174 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 05:56:08 +0100 Subject: [PATCH] brokkr_kitbash: the shell-cuts Lows: evaluable, fitted receipts, slot floors at the round ends, live checks that name what died evaluable refuses, before any write, an object the evaluated depsgraph does not hold (disabled in viewports with nothing depending on it, or in a collection outside the view layer): boolean, cut, cut_many and apply call it. fitted trims a report's rows to a receipt and counts the rest in Omitted: scene_closures, cut, cut_many and boolean use it, so place_cutters loses its report hook and cut_many its refusal of a long report. The slot's floor_l and floor_r move to the centres of its round ends, sized so the three never overlap. kitbash_shell.py runs inside one try: an uncaught error is a failed check naming its section and the result file is always written. It pins M1, M3, M6, M7, M16, hidden and unlinked targets, and trimmed receipts. docs: like-for-like cost (13 cutters: cut_many 6.1 s, 13 cuts 51.3 s, 105 s with hides). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 64 +- .../brokkr_kitbash/brokkr_actions.json | 8 +- .../brokkr_kitbash/kits/cutters.v0.json | 8 +- surfaces/blender/docs/kitbash.md | 34 +- surfaces/blender/tests/live/kitbash_shell.py | 617 ++++++++++-------- .../tests/live/kitbash_shell.result.json | 91 ++- surfaces/blender/tests/test_kitbash.py | 38 +- 7 files changed, 546 insertions(+), 314 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 105b694..05b6129 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -32,7 +32,9 @@ cut cuts a mesh where a ray meets it. The cut is a placed part of the cutters ki identity parent inverse: its matrix_basis is the recess frame and its params the recess size, so moving or resizing 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. +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 +receipt is trimmed by fitted, the rows left off counted beside it: the scene keeps what they would have said. Connections are a tree. A loop (a brace from one branch to another) is closed by a closure: three ID properties on the closing part, kit_close_socket, kit_close_to (a pointer to the other part) and kit_close_to_socket. close @@ -297,8 +299,7 @@ def closure_report(obj, part, built, held=None, kits=None): def scene_closures(context, report: dict, ends=()) -> list: """Every closure stated in the scene as {part, to, holds}, for a set_params report: a change of params can open a closure anywhere below the part. The closures `ends` are parts of come first, then those that do not hold, - then the rest, each by name; rows that would take the report past what a receipt carries are left off the end - and counted in closuresOmitted.""" + then the rest, each by name, trimmed to a receipt by fitted.""" held, kits, rows = closers(), {}, [] for obj in (o for o in context.scene.objects if o.type == "MESH" and CLOSE in o): try: @@ -306,14 +307,7 @@ def scene_closures(context, report: dict, ends=()) -> list: except (Refused, core.KitError): # the closing part itself cannot be read (scaled) found = {"to": closure(obj)[1].name if closure(obj)[1] else None, "holds": False} rows.append((obj not in ends and closure(obj)[1] not in ends, found["holds"], obj.name, {"part": obj.name, "to": found["to"], "holds": found["holds"]})) - kept, size = [], len(json.dumps(report, separators=(",", ":"))) + 40 - for *_, row in sorted(rows, key=lambda r: r[:3]): - size += len(json.dumps(row, separators=(",", ":"))) + 1 - if size > REPORT_LIMIT: - report["closuresOmitted"] = len(rows) - len(kept) - break - kept.append(row) - return kept + return fitted(report, "closures", [row for *_, row in sorted(rows, key=lambda r: r[:3])]) def part_report(obj, part, built) -> dict: @@ -375,6 +369,17 @@ def evaluated_of(context, obj): 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 + of it. Every action that evaluates calls this before its first write.""" + depsgraph, evaluated = evaluated_of(context, obj) + if not evaluated.is_evaluated: + raise Refused(f"Blender does not evaluate {obj.name!r} in this view layer: it is disabled in viewports, or in no collection the " + "view layer shows. Enable it, or link it to the scene; nothing changed.") + return depsgraph, evaluated + + def measured(mesh) -> dict: """Faces, signed volume (overlapping shells count twice) and edges that do not join exactly two faces.""" bm = bmesh.new() @@ -407,13 +412,27 @@ def bounded(report: dict, advice: str) -> dict: return report -def place_cutters(context, target, specs, report=None) -> list: +def fitted(report: dict, key: str, rows: list) -> list: + """The rows of one list of a report that fit what a receipt carries beside the rest of the report, in order; those + left off the end are counted in report[key + 'Omitted']. The one rule that trims a report's rows to a receipt: + the scene keeps what the rows would have said.""" + kept, size = [], len(json.dumps(report, separators=(",", ":"))) + 2 * len(key) + 24 + for row in rows: + size += len(json.dumps(row, separators=(",", ":"))) + 1 + if size > REPORT_LIMIT: + report[key + "Omitted"] = len(rows) - len(kept) + break + kept.append(row) + return kept + + +def place_cutters(context, target, specs) -> list: """Place a cutters part for each spec ({name, part, origin, direction} and optionally params, up, roll, axis; the vectors in the target's own frame) and add them to the target's difference Boolean; [(cutter, part, built)]. Every refusal comes before any write. The rays are cast in one evaluation of the target with its Kit Booleans off, the surface as designed and not as already cut: a second cut on the ray of a through bay lands where the first did, and no Boolean is evaluated here. Blender evaluates the changed target once after the action, however - many cutters it placed. `report`, given the booleans rows to be, may refuse a report too long for a receipt.""" + many cutters it placed.""" rigid(target) kit, made, names = core.load_kit(CUTTERS), [], set() for spec in specs: @@ -430,7 +449,7 @@ def place_cutters(context, target, specs, report=None) -> list: try: for modifier in cuts: modifier.show_viewport = False - depsgraph, _ = evaluated_of(context, target) + depsgraph, _ = evaluable(context, target) tree = BVHTree.FromObject(target, depsgraph) finally: for modifier in cuts: @@ -447,8 +466,6 @@ def place_cutters(context, target, specs, report=None) -> list: raise Refused(f"{spec['name']!r}: the axis {tuple(round(v, 6) for v in axis)} points into the surface (its normal there is " f"{tuple(round(v, 6) for v in normal)}); nothing changed.") frames.append(core.surface_frame(hit, axis if axis.length > 0.0 else normal, spec.get("up", (0.0, 0.0, 1.0)), spec.get("roll", 0.0))) - if report is not None: - report(booleans(target) + [{"cutter": spec["name"], "operation": "DIFFERENCE"} for spec in specs]) placed = [] for spec, (part, built), frame in zip(specs, made, frames): mesh = bpy.data.meshes.new(spec["name"]) @@ -743,10 +760,12 @@ class BROKKR_KITBASH_OT_boolean(PolishOperator): report = part_report(obj, *built_part(obj)) if PART in obj else {"object": obj.name} rigid(obj) uncut(obj, cutter) + evaluable(context, obj) operation_collection(obj, self.operation, True).objects.link(cutter) _, evaluated = evaluated_of(context, obj) - report["booleans"], report["evaluated"] = booleans(obj), measured(evaluated.to_mesh()) + report["evaluated"] = measured(evaluated.to_mesh()) evaluated.to_mesh_clear() + report["booleans"] = fitted(report, "booleans", booleans(obj)) return report @@ -782,7 +801,9 @@ class BROKKR_KITBASH_OT_cut(PolishOperator): "origin": (self.origin_x, self.origin_y, self.origin_z), "direction": (self.direction_x, self.direction_y, self.direction_z), "up": (self.up_x, self.up_y, self.up_z), "axis": (self.axis_x, self.axis_y, self.axis_z)} (cutter, part, built), = place_cutters(context, target, [spec]) - return {"object": target.name, "cutter": part_report(cutter, part, built), "booleans": booleans(target)} + report = {"object": target.name, "cutter": part_report(cutter, part, built)} + report["booleans"] = fitted(report, "booleans", booleans(target)) + return report CUT_KEYS = {"name": str, "part": str, "params": str, "origin": list, "direction": list, "up": list, "axis": list, "roll": (int, float)} @@ -815,9 +836,9 @@ class BROKKR_KITBASH_OT_cut_many(PolishOperator): if not isinstance(value, CUT_KEYS[key]) or isinstance(value, bool) or (vector and (len(value) != 3 or not all(core.finite(v) for v in value))) \ or (key == "roll" and not (core.finite(value) and -360.0 <= value <= 360.0)) or (key == "name" and not 1 <= len(value) <= 63): raise Refused(f"{where}.{key} must be {'three numbers' if vector else 'a number from -360 to 360' if key == 'roll' else 'a string' + (' of 1 to 63 characters' if key == 'name' else '')}; nothing changed.") - placed = place_cutters(context, target, specs, report=lambda rows: bounded({"object": target.name, "cutters": [spec["name"] for spec in specs], "booleans": rows}, - "cut fewer at once")) - return {"object": target.name, "cutters": [cutter.name for cutter, _, _ in placed], "booleans": booleans(target)} + report = {"object": target.name, "cutters": [cutter.name for cutter, _, _ in place_cutters(context, target, specs)]} + report["booleans"] = fitted(report, "booleans", booleans(target)) + return report class BROKKR_KITBASH_OT_apply(PolishOperator): @@ -831,6 +852,7 @@ class BROKKR_KITBASH_OT_apply(PolishOperator): @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: diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 99fd330..1fe79d4 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -353,7 +353,7 @@ }, { "name": "brokkr_kitbash.boolean", - "doc": "Cut a mesh, a kit part or any other, with another mesh object: the cutter joins the collection of the target's one live Boolean modifier for the operation (Exact, self-intersection on; difference, then union, then intersect, above its Bevel). Evaluates the target once, from a few tenths of a second to a few seconds: reports the result's faces, volume and non-manifold edges. The cutter is not changed; hide it with setObjectVisibility.", + "doc": "Cut a mesh, a kit part or any other, with another mesh object: the cutter joins the collection of the target's one live Boolean modifier for the operation (Exact, self-intersection on; difference, then union, then intersect, above its Bevel). Evaluates the target once, from a few tenths of a second to a few seconds: reports the result's faces, volume and non-manifold edges, and booleans, what cuts the target (rows a receipt has no room for are left off the end and counted in booleansOmitted). Refuses a target Blender does not evaluate (disabled in viewports, or in no collection the view layer shows). The cutter is not changed; hide it with setObjectVisibility.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -388,7 +388,7 @@ }, { "name": "brokkr_kitbash.cut", - "doc": "Cut a mesh, a kit part or any other, where a ray meets it: places a part of the cutters kit (box, cyl, slot or slab; brokkr_kitbash.describe with kit cutters) on the surface there, parented to the target, and adds it to the target's difference Boolean. The ray is cast at the target without its cuts. The cutter's floor socket (type mount, at the bottom of the recess, facing out) takes a part by brokkr_kitbash.attach; move the cut with setObjectTransform on the cutter, resize it with set_params, hide the cutter with setObjectVisibility. Blender evaluates the changed target after the action: one Boolean evaluation a cut; brokkr_kitbash.cut_many places several cutters for one. Reports the cutter with its sockets, and booleans.", + "doc": "Cut a mesh, a kit part or any other, where a ray meets it: places a part of the cutters kit (box, cyl, slot or slab; brokkr_kitbash.describe with kit cutters) on the surface there, parented to the target, and adds it to the target's difference Boolean. The ray is cast at the target without its cuts. The cutter's floor socket (type mount, at the bottom of the recess, facing out) takes a part by brokkr_kitbash.attach; move the cut with setObjectTransform on the cutter, resize it with set_params, hide the cutter with setObjectVisibility. Blender evaluates the changed target after the action: one Boolean evaluation a cut; brokkr_kitbash.cut_many places several cutters for one. Reports the cutter with its sockets, and booleans (rows a receipt has no room for are counted in booleansOmitted). Refuses a target Blender does not evaluate.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -528,7 +528,7 @@ }, { "name": "brokkr_kitbash.cut_many", - "doc": "Cut a mesh at several rays in one action, as brokkr_kitbash.cut does at one: all the cutters are placed or none, every ray is cast at the target without its cuts, and Blender evaluates the target's Boolean once after the action instead of once a cut. Reports object, the cutters' names and booleans; brokkr_kitbash.report gives a cutter's sockets.", + "doc": "Cut a mesh at several rays in one action, as brokkr_kitbash.cut does at one: all the cutters are placed or none, every ray is cast at the target without its cuts, and Blender evaluates the target's Boolean once after the action instead of once a cut. Reports object, the cutters' names and booleans (rows a receipt has no room for are counted in booleansOmitted); brokkr_kitbash.report gives a cutter's sockets.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -553,7 +553,7 @@ }, { "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 and a mesh another object shares.", + "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", diff --git a/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json b/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json index e15261c..57b5e1b 100644 --- a/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json +++ b/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json @@ -43,7 +43,7 @@ }, { "name": "slot", - "doc": "Round-ended slot, long along x: a visor, a gill, a vent. width must exceed height. Three floor sockets face out of the recess: floor at the frame's centre (between the two middle copies when count is even), floor_l and floor_r a third of the width to each side; each holds one part.", + "doc": "Round-ended slot, long along x: a visor, a gill, a vent. width must exceed height. Three floor sockets face out of the recess: floor at the frame's centre (between the two middle copies when count is even), floor_l and floor_r at the centres of the two round ends; each holds one part and is as large as fits beside the next, min(height, (width-height)/2).", "params": [ {"name": "width", "type": "number", "min": 0.01, "max": 8, "default": 0.3, "doc": "end to end (x); more than height"}, {"name": "height", "type": "number", "min": 0.005, "max": 4, "default": 0.05, "doc": "across the slot (y); the ends are half-rounds of this diameter"}, @@ -58,9 +58,9 @@ {"shape": "repeat", "count": "count", "step": [0, "pitch", 0], "of": {"shape": "tube", "r0": "height/2", "r1": "height/2", "length": "depth+lift", "segments": 32, "at": ["(width-height)/2", "-(count-1)*pitch/2", "-depth"]}} ], "sockets": [ - {"name": "floor", "type": "mount", "size": "height", "at": [0, 0, "-depth"], "z": "+z", "y": "+y"}, - {"name": "floor_l", "type": "mount", "size": "height", "at": ["-width/3", 0, "-depth"], "z": "+z", "y": "+y"}, - {"name": "floor_r", "type": "mount", "size": "height", "at": ["width/3", 0, "-depth"], "z": "+z", "y": "+y"} + {"name": "floor", "type": "mount", "size": "min(height, (width-height)/2)", "at": [0, 0, "-depth"], "z": "+z", "y": "+y"}, + {"name": "floor_l", "type": "mount", "size": "min(height, (width-height)/2)", "at": ["-(width-height)/2", 0, "-depth"], "z": "+z", "y": "+y"}, + {"name": "floor_r", "type": "mount", "size": "min(height, (width-height)/2)", "at": ["(width-height)/2", 0, "-depth"], "z": "+z", "y": "+y"} ] }, { diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index f6070d6..888fd4c 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -315,7 +315,7 @@ kit part, where a ray meets it, and what it places is itself a kit part, of the | --- | --- | --- | | `box` | `width` (x), `height` (y), `count`, `pitch` | `floor` (mount, size the smaller side) | | `cyl` | `r`, `count`, `pitch` | `floor` (mount, size `2*r`) | -| `slot` | `width` (x, end to end), `height` (across; less than `width`), `count`, `pitch` | `floor`, `floor_l`, `floor_r` (mount, size `height`) | +| `slot` | `width` (x, end to end), `height` (across; less than `width`), `count`, `pitch` | `floor`, `floor_l`, `floor_r` (mount, size the smaller of `height` and `(width-height)/2`) | | `slab` | `gap` (x), `length` (y) | none | A cutter's frame has its origin where the ray met the surface, `z` along the surface normal (turned to face @@ -341,8 +341,9 @@ resizes it, and deleting the cutter removes the cut. `cut` does not hide the cut and a hidden cutter still cuts. `box`, `cyl` and `slot` carry a socket, `floor`: on the bottom of the recess at `z = -depth`, at the frame's -centre, facing out of the recess. A `slot` carries two more on the same floor, `floor_l` and `floor_r`, a third -of its width to each side: a visor with three eyes. Machinery attaches there with the ordinary `attach` (a vent's `back`, a +centre, facing out of the recess. A `slot` carries two more on the same floor, `floor_l` and `floor_r`, at the +centres of its two round ends, `(width-height)/2` to each side: a visor with three eyes. The three are sized so +that neighbours never overlap and none passes the slot's ends. Machinery attaches there with the ordinary `attach` (a vent's `back`, a sensor's `mount`), is a child of the cutter, and so follows the cut when the cutter moves and is seated again when `set_params` changes its `depth`. With an even `count` and a `pitch` wider than the copies, the centre lies between the two middle copies: use an odd count, or a cutter of its own, for a recess that carries a part. A @@ -354,11 +355,20 @@ every action, so each `cut` costs one Boolean evaluation of the target: on the s cutter to eight. `cut_many` takes a JSON array of cutters (`name`, `part`, `origin`, `direction`, and optionally `params`, `up`, `roll`, `axis`), checks them all and casts every ray before it writes anything, places all of them or none, and costs one evaluation for the lot. On a pod with a Bevel under the Boolean (6500 faces once -cut; one evaluation 5.2 s), 13 cutters placed by one `cut_many` took 4.9 s, and 15 placed by 15 `cut` actions -took 113 s; the same cuts as one joined cutter, evaluated once and baked, took 4.6 s (Blender 5.3 on Starfire). -Any later action that changes the target or a cutter (hiding the cutters, attaching a part to a floor) costs an -evaluation again while the target is visible. `cut_many` reports `{object, cutters, booleans}` with the cutters -by name. +cut), the same 13 cutters took 6.1 s placed by one `cut_many` and 51.3 s placed by 13 `cut` actions, about 8 +times as long (medians of 3, Blender 5.3 on Starfire); hiding each cutter after its `cut` is a second evaluation +each and brought the 13 to 105 s. Any later action that changes the target or a cutter (hiding the cutters, +attaching a part to a floor) costs an evaluation again while the target is visible. `cut_many` reports +`{object, cutters, booleans}` with the cutters by name. + +`booleans` in a report of `cut`, `cut_many` or `boolean` is trimmed to what a receipt carries: on a target with +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 +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. ## Expressions @@ -388,10 +398,10 @@ vertices overflow. | `brokkr_kitbash.aim` | `object_name`, `axis` (`+x`, `-x`, `+y`, `-y`, `+z` or `-z`, the part's own), `direction_x`, `direction_y`, `direction_z` (world, any length) | Solves the roll that turns the axis as far toward the direction as the pin lets it, and turns the part to it. Refuses an axis or direction along the pin. Reports the part, `aimed: {roll, dot}` and `closures`. | | `brokkr_kitbash.reach` | `object_name`, `socket` (one of the part's), `height` (metres, -1000 to 1000), `direction_x`, `direction_y`, `direction_z` (world; default 0, 0, 1) | Solves the roll that brings the socket's origin to `height` along the direction, the nearer of the two, and turns the part to it. Refuses a height out of reach, naming the range. Reports the part, `reached: {roll, residual}` and `closures`. | | `brokkr_kitbash.close` | `object_name` (the closing part), `socket`, `other_name`, `other_socket` | States that the closing part's socket meets the other part's, closing a loop. Accepted only when they already meet; moves nothing. Reports the closing part. | -| `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) 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`. | -| `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`. | -| `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 and a mesh another object shares. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | +| `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. | `params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored value (`set_params`). A value outside its bounds is refused with the bounds in the message. diff --git a/surfaces/blender/tests/live/kitbash_shell.py b/surfaces/blender/tests/live/kitbash_shell.py index f8dbb11..d5f8e20 100644 --- a/surfaces/blender/tests/live/kitbash_shell.py +++ b/surfaces/blender/tests/live/kitbash_shell.py @@ -1,8 +1,8 @@ """Live proof, in a background Blender, of brokkr_kitbash shell cuts through run_intent: cut on a mesh that is not a kit part (a subdivided, solidified cage), the one Boolean modifier per operation and its collection, a cast at the surface without its cuts, machinery on a cutter's floor socket and what moves when the cutter moves or is resized, boolean on -any mesh, the refusals, cut_many, a cutter's axis, a slot's three floors, an object in no collection, and the order of a set_params report's closures. Not part of the -unittest run: it needs Blender. +any mesh, the refusals, cut_many, a cutter's axis, a slot's three floors, an object in no collection or one Blender does not evaluate, a receipt's rows trimmed +to fit, and the order of a set_params report's closures. Not part of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_shell.py -- @@ -11,6 +11,9 @@ without them). is an absolute path; writes .result.json and exits 1 w Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the geometric mean of the shipped worst reading and the least claimed mutant's, both written beside it; the result file carries the readings. + +The checks run inside one try: an uncaught error is a failed check that names the section it happened in, and the +result file is written and the checks printed whatever happened. """ import importlib.util import json @@ -18,6 +21,7 @@ import math import os import sys import tempfile +import traceback import types from pathlib import Path @@ -160,123 +164,15 @@ def stack(obj): return [m.name for m in obj.modifiers] -# --- a cage: not a kit part. A closed loft of 6 rings of 8, subdivided and given a wall ---------------------------------- -bm = bmesh.new() -rings = [[bm.verts.new((r * math.cos(math.pi / 8 + k * math.pi / 4), r * math.sin(math.pi / 8 + k * math.pi / 4), z)) for k in range(8)] - for z, r in ((-1.0, 0.5), (-0.6, 0.7), (-0.2, 0.8), (0.2, 0.8), (0.6, 0.7), (1.0, 0.5))] -for low, high in zip(rings, rings[1:]): - for k in range(8): - bm.faces.new((low[k], low[(k + 1) % 8], high[(k + 1) % 8], high[k])) -bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) -mesh = bpy.data.meshes.new("Cage") -bm.to_mesh(mesh) -bm.free() -cage = bpy.data.objects.new("Cage", mesh) -bpy.context.scene.collection.objects.link(cage) -cage.modifiers.new("Subsurf", "SUBSURF").levels = 2 -wall = cage.modifiers.new("Solidify", "SOLIDIFY") -wall.thickness, wall.offset, wall.use_even_offset = 0.05, -1.0, True -cage.matrix_world = Matrix.Translation((4.0, -1.0, 2.0)) @ Matrix.Rotation(0.6, 4, "Z") @ Matrix.Rotation(-0.3, 4, "X") -bpy.context.view_layer.update() -world = np.array(cage.matrix_world, dtype=np.float64) -uncut, _ = evaluated(cage) -check("the cage is a closed wall before it is cut", uncut["nonManifoldEdges"] == 0 and 0.15 < uncut["volume"] < 0.4 and "kit_part" not in cage, uncut) -R["cage"] = {"uncut": uncut} +SECTION = ["setup"] -# --- cut-at-ray: a through bay, a blind round recess, a row of gills and a panel break -------------------------------------- -CUTS = [("Bay", "box", (3.0, 0.0, 0.1), (-1.0, 0.0, 0.0), "width=0.3; height=0.3; depth=0.2", {}), - ("Recess", "cyl", (-3.0, 0.1, 0.2), (2.0, 0.0, 0.0), "r=0.1; depth=0.02", {}), - ("Gills", "slot", (0.1, 3.0, -0.2), (0.0, -1.0, 0.0), "width=0.3; height=0.04; count=4; pitch=0.08; depth=0.02", {}), - ("Break", "slab", (0.0, -3.0, 0.3), (0.0, 1.0, 0.0), "length=0.6; depth=0.1", {"roll": 90.0})] -frames, volume, falls, reports = {}, uncut["volume"], [], {} -for name, part, origin, direction, params, more in CUTS: - hit, normal = cast(cage, origin, direction) # before this cutter exists; the cuts made so far are far from this ray - frames[name] = core.surface_frame(hit, normal, (0.0, 0.0, 1.0), more.get("roll", 0.0)) - state = sorted(o.name for o in bpy.data.objects) - receipt, report = cut(name, part, origin, direction, params, **more) - reports[name] = report - cutter = bpy.data.objects.get(name) - ok = receipt["status"] == "accepted" and cutter is not None and sorted(o.name for o in bpy.data.objects) == sorted(state + [name]) - ok = ok and cutter.parent == cage and np.array_equal(np.array(cutter.matrix_parent_inverse), np.eye(4)) - ok = ok and reading("framed", np.abs(np.array(cutter.matrix_basis) - frames[name]).max()) < FRAMED - ok = ok and (cutter["kit_kit"], cutter["kit_part"]) == ("cutters", part) and bpy.context.scene.collection in cutter.users_collection - ok = ok and not cutter.hide_render and not cutter.hide_viewport and len(cutter.modifiers) == 0 - check(f"cut places the {part} cutter {name} on the cage where the ray meets it: parented under an identity inverse, its basis the surface frame", - ok, [receipt["message"], cutter and np.array(cutter.matrix_basis).tolist(), frames[name].tolist()]) - wanted = world @ frames[name] - check(f"cut reports {name} as a cutters part with its sockets in the world, and what cuts the cage, without evaluating it", report - and report["object"] == "Cage" and report["cutter"]["object"] == name and report["cutter"]["kit"] == "cutters" and "evaluated" not in report - and report["booleans"] == [{"cutter": n, "operation": "DIFFERENCE"} for n in [c[0] for c in CUTS][:len(frames)]] - and [s["name"] for s in report["cutter"]["sockets"]] == {"slab": [], "slot": ["floor", "floor_l", "floor_r"]}.get(part, ["floor"]) - and (part == "slab" or np.abs(np.array(report["cutter"]["sockets"][0]["matrix"]) - wanted @ core.build(kits["cutters"]["parts"][part], report["cutter"]["params"]).sockets[0]["matrix"]).max() < 1e-4), - report) - shown, _ = evaluated(cage) - falls.append(shown["volume"] < volume - 1e-4 and shown["nonManifoldEdges"] == 0) - volume = shown["volume"] - R["cage"][name] = shown -modifier = cage.modifiers.get("Kit Difference") -check("four cuts give the cage one Boolean modifier after its own, over one collection of the four cutters in the order they came", - stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and modifier is not None - and (modifier.type, modifier.solver, modifier.use_self, modifier.operation, modifier.operand_type, modifier.material_mode) == ("BOOLEAN", "EXACT", True, "DIFFERENCE", "COLLECTION", "TRANSFER") - and [o.name for o in modifier.collection.objects] == [c[0] for c in CUTS] and modifier.collection.name == "Cage difference" - and not any(modifier.collection in s.collection.children_recursive for s in bpy.data.scenes), [stack(cage), modifier and modifier.operand_type]) -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"]]) -# --- cut-casts-the-uncut-surface -------------------------------------------------------------------------------------------- -through = cast(cage, CUTS[0][2], CUTS[0][3])[0] # as the cage is evaluated now, with its cuts: through the bay to the far wall -receipt, report = cut("Bay2", "cyl", CUTS[0][2], CUTS[0][3], "r=0.05; depth=0.2") -again = bpy.data.objects.get("Bay2") -check("a second cut on the through bay's ray lands where the first did, on the surface as it was before any cut, though the ray now passes through the bay", - receipt["status"] == "accepted" and again is not None and np.linalg.norm(through - frames["Bay"][:3, 3]) > 1.0 - and reading("recast", np.abs(np.array(again.matrix_basis)[:3, 3] - frames["Bay"][:3, 3]).max()) < RECAST - and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and all(m.show_viewport for m in cage.modifiers), - [receipt["message"], through.tolist(), frames["Bay"][:3, 3].tolist(), again and list(again.matrix_basis.translation)]) +def section(name): + SECTION[0] = name -# --- floor-carries-machinery ------------------------------------------------------------------------------------------------ -recess = bpy.data.objects["Recess"] -vent = place("Vent", "vent", "width=0.2; height=0.15") # back size 0.135; the floor's is 0.2 -receipt, report = send("brokkr_kitbash.attach", object_name="Vent", socket="back", parent_name="Recess", parent_socket="floor", roll=30.0) -floor = world @ frames["Recess"] @ np.array(Matrix.Translation((0.0, 0.0, -0.02))) # the hit point, depth along the normal -back = frame(vent, "back") -check("a mechanical vent attaches to the round recess's floor: its back on the hit point taken depth down the normal, facing in, and the connection holds", - receipt["status"] == "accepted" and held(report) and vent.parent == recess and report["connection"]["parent"] == "Recess" and report["kit"] == "mechanical" - and reading("floored", max(np.abs(back[:3, 3] - floor[:3, 3]).max(), np.abs(back[:3, 2] + floor[:3, 2]).max())) < FLOORED, - [receipt["message"], back.tolist(), floor.tolist()]) -big = place("Big", "vent", "width=0.8; height=0.6") -refused("a vent larger than the recess's floor", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Recess", "parent_socket": "floor"}, - "'Big' on 'Recess': socket 'back' (mount, size 0.54) and parent socket 'floor' (mount, size 0.2) are mount sockets, where the child fits the parent: it is larger") -nozzle = place("Nozzle", "nozzle") -refused("a flange on a floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Recess", "parent_socket": "floor"}, "are of different types") -refused("a second part on the floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Recess", "parent_socket": "floor"}, "'Nozzle' on 'Recess'") -refused("a part on a slab, which has no floor", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Break", "parent_socket": "floor"}, - "kit 'cutters' part 'slab' has no socket 'floor'; its sockets: none") -refused("detach of a cutter, which is placed and not attached", "brokkr_kitbash.detach", {"object_name": "Recess"}, "'Recess' is not attached") -before = evaluated(cage)[0] -moved_to = np.array(recess.matrix_basis)[:3, 3] + np.array(recess.matrix_basis)[:3, :3] @ [0.0, 0.25, 0.0] # along the cutter's own y: up the wall -was = frame(vent, "back") -send("setObjectTransform", targetObjectName="Recess", location=moved_to.tolist()) -shift = frame(vent, "back")[:3, 3] - was[:3, 3] -after = evaluated(cage)[0] -check("setObjectTransform on the cutter moves the cut and the vent on its floor together: the vent still holds, and the cage is cut elsewhere", - reading("floored", np.abs(shift - world[:3, :3] @ (moved_to - frames["Recess"][:3, 3])).max()) < FLOORED and abs(np.linalg.norm(shift) - 0.25) < 1e-4 - and (connection := send("brokkr_kitbash.report", object_name="Vent")[1]["parts"][0]["connection"])["holds"] is True - and after["nonManifoldEdges"] == 0 and after != before, [shift.tolist(), before, after]) -was = frame(vent, "back") -receipt, report = send("brokkr_kitbash.set_params", object_name="Recess", params="depth=0.04") -sunk = frame(vent, "back")[:3, 3] - was[:3, 3] -deeper = evaluated(cage)[0] -check("set_params depth=0.04 on the cutter deepens the cut and seats the vent on the new floor, 0.02 further down the normal", - receipt["status"] == "accepted" and report["params"]["depth"] == 0.04 and reading("floored", np.abs(sunk + was[:3, 2] * -0.02).max()) < FLOORED - and send("brokkr_kitbash.report", object_name="Vent")[1]["parts"][0]["connection"]["holds"] is True - and deeper["volume"] < after["volume"] - 1e-5 and deeper["nonManifoldEdges"] == 0 and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"], - [receipt["message"], sunk.tolist(), after, deeper]) -R["cage"]["deeper"] = deeper -# --- cut_many: several cutters for one evaluation, all or none; an axis; a slot's three floors ----------------------------------- def uncut_cast(origin, direction): + """cast at the cage with its Kit Booleans off: the surface as designed.""" shown = [m for m in cage.modifiers if m.name.startswith("Kit ")] for m in shown: m.show_viewport = False @@ -287,151 +183,358 @@ def uncut_cast(origin, direction): m.show_viewport = True -MANY = [{"name": "Visor", "part": "slot", "params": "width=0.6; height=0.14; depth=0.02; lift=0.2", "origin": [0.6, 3.0, 0.5], "direction": [0.0, -1.0, 0.0]}, - {"name": "Seam", "part": "slab", "params": "length=0.4; depth=0.1", "origin": [-0.5, -3.0, -0.7], "direction": [0.0, 1.0, 0.0], "up": [1.0, 0.0, 0.0], "axis": [0.0, -1.0, 0.0]}, - {"name": "Port", "part": "cyl", "params": "r=0.05", "origin": [-0.6, 3.0, -0.5], "direction": [0.0, -2.0, 0.0], "up": [1.0, 0.0, 0.0], "roll": 45.0}] -wanted = {} -for spec in MANY: - hit, normal = uncut_cast(spec["origin"], spec["direction"]) - wanted[spec["name"]] = core.surface_frame(hit, spec.get("axis", normal), spec.get("up", (0.0, 0.0, 1.0)), spec.get("roll", 0.0)) - if "axis" in spec: - lean = float(np.degrees(np.arccos(np.clip(normal @ np.array(spec["axis"]), -1.0, 1.0)))) -refused("cut_many whose second ray misses places none", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "origin": [0.0, -3.0, 5.0]}])}, - "The ray from (0.0, -3.0, 5.0) along (0.0, 1.0, 0.0) misses 'Cage'") -refused("cut_many with a name twice", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "name": "Visor"}])}, "An object named 'Visor' exists in this call") -refused("cut_many with a name an object has", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "name": "Bay"}])}, "An object named 'Bay' exists;") -refused("cut_many whose last cutter has a bad param", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps(MANY[:2] + [{**MANY[2], "params": "r=9"}])}, "param 'r' = 9.0 is outside") -refused("cut_many of text that is not JSON", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": "[{"}, "cuts is not JSON") -refused("cut_many of no cutters", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": "[]"}, "cuts must be a JSON array of 1 to 64 cutters") -refused("cut_many of a cutter with no direction", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{k: v for k, v in MANY[0].items() if k != "direction"}])}, - "cuts[0] must be an object with name, part, origin and direction") -refused("cut_many of a cutter with a key cut does not have", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "operation": "UNION"}])}, "cuts[0] must be an object") -refused("cut_many of an origin of two numbers", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "origin": [0.0, 1.0]}])}, "cuts[0].origin must be three numbers") -refused("cut_many of a roll of 400", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "roll": 400}])}, "cuts[0].roll must be a number from -360 to 360") -refused("an axis that points into the surface", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[1], "axis": [0.0, 1.0, 0.0]}])}, "'Seam': the axis (0.0, 1.0, 0.0) points into the surface") -addon = sys.modules["brokkr_kitbash"] -limit = addon.REPORT_LIMIT -addon.REPORT_LIMIT = 300 -refused("cut_many whose report would not fit a receipt places none", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps(MANY)}, "over the 300 a receipt carries: cut fewer at once") -addon.REPORT_LIMIT = limit -receipt, report = send("brokkr_kitbash.cut_many", object_name="Cage", cuts=json.dumps(MANY)) -placed = [bpy.data.objects.get(spec["name"]) for spec in MANY] -check("cut_many places three cutters in one action, each as cut would: parented under an identity inverse, its basis the surface frame at its own ray on the uncut cage, in the difference collection in order", - receipt["status"] == "accepted" and all(placed) and report == {"object": "Cage", "cutters": ["Visor", "Seam", "Port"], "booleans": report["booleans"]} - and [row["cutter"] for row in report["booleans"]] == ["Bay", "Recess", "Gills", "Break", "Bay2", "Visor", "Seam", "Port"] - and all(c.parent == cage and np.array_equal(np.array(c.matrix_parent_inverse), np.eye(4)) - and reading("framed", np.abs(np.array(c.matrix_basis) - wanted[c.name]).max()) < FRAMED for c in placed) - and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and all(m.show_viewport for m in cage.modifiers) and evaluated(cage)[0]["nonManifoldEdges"] == 0, - [receipt["message"], report]) -seam = bpy.data.objects["Seam"] -check("a slab with an axis stands on the axis, not on the wall's normal, which leans from it there", lean > 5.0 - and reading("framed", np.abs(np.array(seam.matrix_basis)[:3, 2] - [0.0, -1.0, 0.0]).max()) < FRAMED, [lean, np.array(seam.matrix_basis).tolist()]) -receipt, report = send("brokkr_kitbash.cut", object_name="Cage", cutter_name="Seam2", part="slab", params="length=0.3; depth=0.1", origin_x=0.5, origin_y=-3.0, origin_z=-0.7, - direction_x=0.0, direction_y=1.0, direction_z=0.0, up_x=1.0, up_y=0.0, up_z=0.0, axis_x=0.0, axis_y=-1.0, axis_z=0.0) -check("cut takes the same axis", receipt["status"] == "accepted" and reading("framed", np.abs(np.array(bpy.data.objects["Seam2"].matrix_basis)[:3, 2] - [0.0, -1.0, 0.0]).max()) < FRAMED, receipt["message"]) -visor = bpy.data.objects["Visor"] -eyes = {} -for socket, x in (("floor", 0.0), ("floor_l", -0.2), ("floor_r", 0.2)): - eye = place(f"Eye_{socket}", "vent", "width=0.2; height=0.15") # back size 0.135; each floor's is 0.14 - receipt, report = send("brokkr_kitbash.attach", object_name=eye.name, socket="back", parent_name="Visor", parent_socket=socket) - there = world @ wanted["Visor"] @ np.array(Matrix.Translation((x, 0.0, -0.02))) - eyes[socket] = receipt["status"] == "accepted" and held(report) and eye.parent == visor \ - and reading("floored", max(np.abs(frame(eye, "back")[:3, 3] - there[:3, 3]).max(), np.abs(frame(eye, "back")[:3, 2] + there[:3, 2]).max())) < FLOORED -check("a slot's three floors each take a part: at the centre and a third of the width to each side, all on the slot's one floor plane", all(eyes.values()) and len(eyes) == 3, eyes) -refused("a second part on a side floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Visor", "parent_socket": "floor_l"}, "'Nozzle' on 'Visor'") -refused("a fourth eye on a floor that is taken", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Visor", "parent_socket": "floor_l"}, "'Big' on 'Visor'") +def quad(name, location): + """A single square face, 1 m, normal +z: a surface with one side.""" + made = bpy.data.objects.new(name, bpy.data.meshes.new(name)) + made.data.from_pydata([(-0.5, -0.5, 0.0), (0.5, -0.5, 0.0), (0.5, 0.5, 0.0), (-0.5, 0.5, 0.0)], [], [(0, 1, 2, 3)]) + bpy.context.scene.collection.objects.link(made) + made.location = location + bpy.context.view_layer.update() + return made -# --- boolean on any mesh, and the order of the three operations ----------------------------------------------------------------- -lump_at = world @ [0.0, 0.0, 1.0, 1.0] -send("createObject", objectType="MESH", name="Lump", location=lump_at[:3].tolist(), size=0.2) -receipt, report = send("brokkr_kitbash.boolean", object_name="Cage", cutter="Lump", operation="UNION") -check("boolean on the cage, which is not a kit part, adds a second modifier after the difference and reports the object, what cuts it and the evaluated mesh", - receipt["status"] == "accepted" and stack(cage) == ["Subsurf", "Solidify", "Kit Difference", "Kit Union"] - and sorted(report) == ["booleans", "evaluated", "object"] and report["object"] == "Cage" and report["evaluated"] == evaluated(cage)[0] - and report["booleans"] == [{"cutter": n, "operation": "DIFFERENCE"} for n in ("Bay", "Recess", "Gills", "Break", "Bay2", "Visor", "Seam", "Port", "Seam2")] + [{"cutter": "Lump", "operation": "UNION"}] - and report["evaluated"]["volume"] > deeper["volume"], [receipt["message"], report]) -refused("cut-refusals: a cutter already in the target's union collection", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Lump"}, - "'Lump' already cuts 'Cage' (its Kit Union modifier's collection)") -refused("a cut's own cutter given to boolean again", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Bay", "operation": "INTERSECT"}, - "'Bay' already cuts 'Cage' (its Kit Difference modifier's collection)") -plate = place("Plate", "plate", location=[0.0, -6.0, 0.0]) -for name, size, operation in (("Boss", 0.06, "UNION"), ("Keep", 2.0, "INTERSECT"), ("Hole", 0.05, "DIFFERENCE")): - send("createObject", objectType="MESH", name=name, location=[0.0, -6.0, 0.0], size=size) - receipt, report = send("brokkr_kitbash.boolean", object_name="Plate", cutter=name, operation=operation) -check("a part cut by union, then intersect, then difference carries the three modifiers as difference, union, intersect, above its Bevel, and lists its cutters so", - 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") -# --- 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} -refused("a ray that misses", "brokkr_kitbash.cut", {**RAY, "origin_z": 5.0}, "The ray from (3.0, 0.0, 5.0) along (-1.0, 0.0, 0.0) misses 'Cage'") -refused("a ray of no direction", "brokkr_kitbash.cut", {**RAY, "direction_x": 0.0}, "'New': the ray's direction is zero") -refused("a cutter name an object has", "brokkr_kitbash.cut", {**RAY, "cutter_name": "Bay"}, "An object named 'Bay' exists") -refused("a param the cutter part does not have", "brokkr_kitbash.cut", {**RAY, "params": "radius=0.1"}, "kit 'cutters' part 'box' has no param 'radius'") -refused("a slot wider across than along", "brokkr_kitbash.cut", {**RAY, "part": "slot", "params": "width=0.05; height=0.1"}, "every size must be above 0") -refused("a target that is not a mesh", "brokkr_kitbash.cut", {**RAY, "object_name": "Nothing"}, "No mesh object named 'Nothing'") -block = bpy.data.objects.new("Block", bpy.data.meshes.new("Block")) -bm = bmesh.new() -bmesh.ops.create_cube(bm, size=1.0) -bm.to_mesh(block.data) -bm.free() -bpy.context.scene.collection.objects.link(block) -block.location = (0.0, -9.0, 0.0) -bpy.context.view_layer.update() -DOWN = {**RAY, "object_name": "Block", "origin_x": 0.1, "origin_y": 0.1, "origin_z": 3.0, "direction_x": 0.0, "direction_z": -1.0} -refused("an up along the hit normal", "brokkr_kitbash.cut", DOWN, "up [0.0, 0.0, 1.0] runs along the surface normal [0.0, 0.0, 1.0]") -block.scale = (1.0, 1.0, 1.01) -bpy.context.view_layer.update() -refused("a scaled target", "brokkr_kitbash.cut", {**DOWN, "up_y": 1.0, "up_z": 0.0}, "'Block' is scaled, mirrored or sheared in the world (scale 1, 1, 1.01)") -refused("boolean on a scaled target", "brokkr_kitbash.boolean", {"object_name": "Block", "cutter": "Lump"}, "'Block' is scaled, mirrored or sheared") -block.scale = (1.0, 1.0, 1.0) -bpy.context.view_layer.update() -receipt, report = send("brokkr_kitbash.cut", **{**DOWN, "cutter_name": "Pocket", "up_y": 1.0, "up_z": 0.0, "roll": 90.0}) -pocket = bpy.data.objects.get("Pocket") -check("a cut on a plain cube with up +y and roll 90: the cutter's y points along -x, its floor 0.02 under the top face", receipt["status"] == "accepted" and pocket is not None - and np.abs(np.array(pocket.matrix_basis) - [[0, -1, 0, 0.1], [1, 0, 0, 0.1], [0, 0, 1, 0.5], [0, 0, 0, 1]]).max() < 1e-6 - and np.abs(np.array(report["cutter"]["sockets"][0]["matrix"])[:3, 3] - [0.1, -8.9, 0.48]).max() < 1e-6 and stack(block) == ["Kit Difference"], - [receipt["message"], pocket and np.array(pocket.matrix_basis).tolist()]) +try: + # --- a cage: not a kit part. A closed loft of 6 rings of 8, subdivided and given a wall ---------------------------------- + section('a cage: not a kit part. A closed loft of 6 rings of 8, subdivided and given a wall') + bm = bmesh.new() + rings = [[bm.verts.new((r * math.cos(math.pi / 8 + k * math.pi / 4), r * math.sin(math.pi / 8 + k * math.pi / 4), z)) for k in range(8)] + for z, r in ((-1.0, 0.5), (-0.6, 0.7), (-0.2, 0.8), (0.2, 0.8), (0.6, 0.7), (1.0, 0.5))] + for low, high in zip(rings, rings[1:]): + for k in range(8): + bm.faces.new((low[k], low[(k + 1) % 8], high[(k + 1) % 8], high[k])) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + mesh = bpy.data.meshes.new("Cage") + bm.to_mesh(mesh) + bm.free() + cage = bpy.data.objects.new("Cage", mesh) + bpy.context.scene.collection.objects.link(cage) + cage.modifiers.new("Subsurf", "SUBSURF").levels = 2 + wall = cage.modifiers.new("Solidify", "SOLIDIFY") + wall.thickness, wall.offset, wall.use_even_offset = 0.05, -1.0, True + cage.matrix_world = Matrix.Translation((4.0, -1.0, 2.0)) @ Matrix.Rotation(0.6, 4, "Z") @ Matrix.Rotation(-0.3, 4, "X") + bpy.context.view_layer.update() + world = np.array(cage.matrix_world, dtype=np.float64) + uncut, _ = evaluated(cage) + check("the cage is a closed wall before it is cut", uncut["nonManifoldEdges"] == 0 and 0.15 < uncut["volume"] < 0.4 and "kit_part" not in cage, uncut) + R["cage"] = {"uncut": uncut} -# --- cut-orphan and closures-ends-first ----------------------------------------------------------------------------------------- -strut = core.build(kits["mechanical"]["parts"]["strut"], {"width": 0.09}) -end = {name: next(s for s in strut.sockets if s["name"] == name) for name in ("end_a", "end_b")} -for pair, y in (("Zz", -20.0), ("Aa", -24.0)): # two closures that share no part; the open one is named to sort first - anchor, loose = place(f"{pair}_Anchor", "strut", "width=0.09", location=[0.0, y, 0.0]), place(f"{pair}_Loose", "strut", "width=0.09") - meet = Matrix((np.array(anchor.matrix_world) @ core.mate(end["end_b"], end["end_a"], 40.0)).tolist()) - send("setObjectTransform", targetObjectName=f"{pair}_Loose", location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ"))) - send("brokkr_kitbash.close", object_name=f"{pair}_Loose", socket="end_a", other_name=f"{pair}_Anchor", other_socket="end_b") -send("brokkr_kitbash.set_params", object_name="Aa_Anchor", params="length=0.9") # opens Aa's closure -receipt, report = send("brokkr_kitbash.set_params", object_name="Zz_Anchor", params="width=0.09") -check("closures-ends-first: set_params on a part whose own closure holds lists it before another part's closure that is open, though that one sorts first by holds and by name", - receipt["status"] == "accepted" and report["closures"] == [{"part": "Zz_Loose", "to": "Zz_Anchor", "holds": True}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}], - report and report.get("closures")) -ghost = bpy.data.objects["Aa_Anchor"] -with bpy.context.temp_override(selected_objects=[ghost], active_object=ghost): - bpy.ops.object.delete() # the ordinary Delete: Aa_Loose's closure still points at it, so it stays in the file, in no collection -tie = place("Tie", "strut", "width=0.09") -check("a part deleted with the Delete operator that a closure points to is still in the file", bpy.data.objects.get("Aa_Anchor") is not None and not ghost.users_collection, list(bpy.data.objects.keys())) -GONE = "'Aa_Anchor' is in no collection (a deleted object something still points to)" -refused("cut-orphan: attach onto a deleted part's name", "brokkr_kitbash.attach", {"object_name": "Tie", "socket": "end_a", "parent_name": "Aa_Anchor", "parent_socket": "end_a"}, GONE) -refused("attach of a deleted part", "brokkr_kitbash.attach", {"object_name": "Aa_Anchor", "socket": "end_a", "parent_name": "Tie", "parent_socket": "end_a"}, GONE) -refused("set_params on a deleted part", "brokkr_kitbash.set_params", {"object_name": "Aa_Anchor", "params": "length=1.0"}, GONE) -refused("report of a deleted part", "brokkr_kitbash.report", {"object_name": "Aa_Anchor"}, GONE) -refused("cut on a deleted part", "brokkr_kitbash.cut", {**RAY, "object_name": "Aa_Anchor"}, GONE) -refused("boolean on a deleted part", "brokkr_kitbash.boolean", {"object_name": "Aa_Anchor", "cutter": "Lump"}, GONE) -refused("boolean with a deleted part as the cutter", "brokkr_kitbash.boolean", {"object_name": "Tie", "cutter": "Aa_Anchor"}, GONE) -refused("close onto a deleted part", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Aa_Anchor", "other_socket": "end_a"}, GONE) + # --- cut-at-ray: a through bay, a blind round recess, a row of gills and a panel break -------------------------------------- + section('cut-at-ray: a through bay, a blind round recess, a row of gills and a panel break') + CUTS = [("Bay", "box", (3.0, 0.0, 0.1), (-1.0, 0.0, 0.0), "width=0.3; height=0.3; depth=0.2", {}), + ("Recess", "cyl", (-3.0, 0.1, 0.2), (2.0, 0.0, 0.0), "r=0.1; depth=0.02", {}), + ("Gills", "slot", (0.1, 3.0, -0.2), (0.0, -1.0, 0.0), "width=0.3; height=0.04; count=4; pitch=0.08; depth=0.02", {}), + ("Break", "slab", (0.0, -3.0, 0.3), (0.0, 1.0, 0.0), "length=0.6; depth=0.1", {"roll": 90.0})] + frames, volume, falls, reports = {}, uncut["volume"], [], {} + for name, part, origin, direction, params, more in CUTS: + hit, normal = cast(cage, origin, direction) # before this cutter exists; the cuts made so far are far from this ray + frames[name] = core.surface_frame(hit, normal, (0.0, 0.0, 1.0), more.get("roll", 0.0)) + state = sorted(o.name for o in bpy.data.objects) + receipt, report = cut(name, part, origin, direction, params, **more) + reports[name] = report + cutter = bpy.data.objects.get(name) + ok = receipt["status"] == "accepted" and cutter is not None and sorted(o.name for o in bpy.data.objects) == sorted(state + [name]) + ok = ok and cutter.parent == cage and np.array_equal(np.array(cutter.matrix_parent_inverse), np.eye(4)) + ok = ok and reading("framed", np.abs(np.array(cutter.matrix_basis) - frames[name]).max()) < FRAMED + ok = ok and (cutter["kit_kit"], cutter["kit_part"]) == ("cutters", part) and bpy.context.scene.collection in cutter.users_collection + ok = ok and not cutter.hide_render and not cutter.hide_viewport and len(cutter.modifiers) == 0 + check(f"cut places the {part} cutter {name} on the cage where the ray meets it: parented under an identity inverse, its basis the surface frame", + ok, [receipt["message"], cutter and np.array(cutter.matrix_basis).tolist(), frames[name].tolist()]) + wanted = world @ frames[name] + check(f"cut reports {name} as a cutters part with its sockets in the world, and what cuts the cage, without evaluating it", report + and report["object"] == "Cage" and report["cutter"]["object"] == name and report["cutter"]["kit"] == "cutters" and "evaluated" not in report + and report["booleans"] == [{"cutter": n, "operation": "DIFFERENCE"} for n in [c[0] for c in CUTS][:len(frames)]] + and [s["name"] for s in report["cutter"]["sockets"]] == {"slab": [], "slot": ["floor", "floor_l", "floor_r"]}.get(part, ["floor"]) + and (part == "slab" or np.abs(np.array(report["cutter"]["sockets"][0]["matrix"]) - wanted @ core.build(kits["cutters"]["parts"][part], report["cutter"]["params"]).sockets[0]["matrix"]).max() < 1e-4), + report) + shown, _ = evaluated(cage) + falls.append(shown["volume"] < volume - 1e-4 and shown["nonManifoldEdges"] == 0) + volume = shown["volume"] + R["cage"][name] = shown + modifier = cage.modifiers.get("Kit Difference") + check("four cuts give the cage one Boolean modifier after its own, over one collection of the four cutters in the order they came", + stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and modifier is not None + and (modifier.type, modifier.solver, modifier.use_self, modifier.operation, modifier.operand_type, modifier.material_mode) == ("BOOLEAN", "EXACT", True, "DIFFERENCE", "COLLECTION", "TRANSFER") + and [o.name for o in modifier.collection.objects] == [c[0] for c in CUTS] and modifier.collection.name == "Cage difference" + and not any(modifier.collection in s.collection.children_recursive for s in bpy.data.scenes), [stack(cage), modifier and modifier.operand_type]) + 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"]]) -R["ok"] = all(c["ok"] for c in R["checks"]) -R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} -Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") -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"], flush=True) + # --- cut-casts-the-uncut-surface -------------------------------------------------------------------------------------------- + section('cut-casts-the-uncut-surface') + through = cast(cage, CUTS[0][2], CUTS[0][3])[0] # as the cage is evaluated now, with its cuts: through the bay to the far wall + receipt, report = cut("Bay2", "cyl", CUTS[0][2], CUTS[0][3], "r=0.05; depth=0.2") + again = bpy.data.objects.get("Bay2") + check("a second cut on the through bay's ray lands where the first did, on the surface as it was before any cut, though the ray now passes through the bay", + receipt["status"] == "accepted" and again is not None and np.linalg.norm(through - frames["Bay"][:3, 3]) > 1.0 + and reading("recast", np.abs(np.array(again.matrix_basis)[:3, 3] - frames["Bay"][:3, 3]).max()) < RECAST + and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and all(m.show_viewport for m in cage.modifiers), + [receipt["message"], through.tolist(), frames["Bay"][:3, 3].tolist(), again and list(again.matrix_basis.translation)]) + + # --- floor-carries-machinery ------------------------------------------------------------------------------------------------ + section('floor-carries-machinery') + recess = bpy.data.objects["Recess"] + vent = place("Vent", "vent", "width=0.2; height=0.15") # back size 0.135; the floor's is 0.2 + receipt, report = send("brokkr_kitbash.attach", object_name="Vent", socket="back", parent_name="Recess", parent_socket="floor", roll=30.0) + floor = world @ frames["Recess"] @ np.array(Matrix.Translation((0.0, 0.0, -0.02))) # the hit point, depth along the normal + back = frame(vent, "back") + check("a mechanical vent attaches to the round recess's floor: its back on the hit point taken depth down the normal, facing in, and the connection holds", + receipt["status"] == "accepted" and held(report) and vent.parent == recess and report["connection"]["parent"] == "Recess" and report["kit"] == "mechanical" + and reading("floored", max(np.abs(back[:3, 3] - floor[:3, 3]).max(), np.abs(back[:3, 2] + floor[:3, 2]).max())) < FLOORED, + [receipt["message"], back.tolist(), floor.tolist()]) + big = place("Big", "vent", "width=0.8; height=0.6") + refused("a vent larger than the recess's floor", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Recess", "parent_socket": "floor"}, + "'Big' on 'Recess': socket 'back' (mount, size 0.54) and parent socket 'floor' (mount, size 0.2) are mount sockets, where the child fits the parent: it is larger") + nozzle = place("Nozzle", "nozzle") + refused("a flange on a floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Recess", "parent_socket": "floor"}, "are of different types") + refused("a second part on the floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Recess", "parent_socket": "floor"}, "'Nozzle' on 'Recess'") + refused("a part on a slab, which has no floor", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Break", "parent_socket": "floor"}, + "kit 'cutters' part 'slab' has no socket 'floor'; its sockets: none") + refused("detach of a cutter, which is placed and not attached", "brokkr_kitbash.detach", {"object_name": "Recess"}, "'Recess' is not attached") + before = evaluated(cage)[0] + moved_to = np.array(recess.matrix_basis)[:3, 3] + np.array(recess.matrix_basis)[:3, :3] @ [0.0, 0.25, 0.0] # along the cutter's own y: up the wall + was = frame(vent, "back") + send("setObjectTransform", targetObjectName="Recess", location=moved_to.tolist()) + shift = frame(vent, "back")[:3, 3] - was[:3, 3] + after = evaluated(cage)[0] + check("setObjectTransform on the cutter moves the cut and the vent on its floor together: the vent still holds, and the cage is cut elsewhere", + reading("floored", np.abs(shift - world[:3, :3] @ (moved_to - frames["Recess"][:3, 3])).max()) < FLOORED and abs(np.linalg.norm(shift) - 0.25) < 1e-4 + and (connection := send("brokkr_kitbash.report", object_name="Vent")[1]["parts"][0]["connection"])["holds"] is True + and after["nonManifoldEdges"] == 0 and after != before, [shift.tolist(), before, after]) + was = frame(vent, "back") + receipt, report = send("brokkr_kitbash.set_params", object_name="Recess", params="depth=0.04") + sunk = frame(vent, "back")[:3, 3] - was[:3, 3] + deeper = evaluated(cage)[0] + check("set_params depth=0.04 on the cutter deepens the cut and seats the vent on the new floor, 0.02 further down the normal", + receipt["status"] == "accepted" and report["params"]["depth"] == 0.04 and reading("floored", np.abs(sunk + was[:3, 2] * -0.02).max()) < FLOORED + and send("brokkr_kitbash.report", object_name="Vent")[1]["parts"][0]["connection"]["holds"] is True + and deeper["volume"] < after["volume"] - 1e-5 and deeper["nonManifoldEdges"] == 0 and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"], + [receipt["message"], sunk.tolist(), after, deeper]) + R["cage"]["deeper"] = deeper + + # --- cut_many: several cutters for one evaluation, all or none; an axis; a slot's three floors ----------------------------------- + section("cut_many: several cutters for one evaluation, all or none; an axis; a slot's three floors") + MANY = [{"name": "Visor", "part": "slot", "params": "width=0.6; height=0.14; depth=0.02; lift=0.2", "origin": [0.6, 3.0, 0.5], "direction": [0.0, -1.0, 0.0]}, + {"name": "Seam", "part": "slab", "params": "length=0.4; depth=0.1", "origin": [-0.5, -3.0, -0.7], "direction": [0.0, 1.0, 0.0], "up": [1.0, 0.0, 0.0], "axis": [0.0, -1.0, 0.0]}, + {"name": "Port", "part": "cyl", "params": "r=0.05", "origin": [-0.6, 3.0, -0.5], "direction": [0.0, -2.0, 0.0], "up": [1.0, 0.0, 0.0], "roll": 45.0}] + wanted = {} + for spec in MANY: + hit, normal = uncut_cast(spec["origin"], spec["direction"]) + wanted[spec["name"]] = core.surface_frame(hit, spec.get("axis", normal), spec.get("up", (0.0, 0.0, 1.0)), spec.get("roll", 0.0)) + if "axis" in spec: + lean = float(np.degrees(np.arccos(np.clip(normal @ np.array(spec["axis"]), -1.0, 1.0)))) + refused("cut_many whose second ray misses places none", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "origin": [0.0, -3.0, 5.0]}])}, + "The ray from (0.0, -3.0, 5.0) along (0.0, 1.0, 0.0) misses 'Cage'") + refused("cut_many with a name twice", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "name": "Visor"}])}, "An object named 'Visor' exists in this call") + refused("cut_many with a name an object has", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "name": "Bay"}])}, "An object named 'Bay' exists;") + refused("cut_many whose last cutter has a bad param", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps(MANY[:2] + [{**MANY[2], "params": "r=9"}])}, "param 'r' = 9.0 is outside") + refused("cut_many of text that is not JSON", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": "[{"}, "cuts is not JSON") + refused("cut_many of no cutters", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": "[]"}, "cuts must be a JSON array of 1 to 64 cutters") + refused("cut_many of a cutter with no direction", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{k: v for k, v in MANY[0].items() if k != "direction"}])}, + "cuts[0] must be an object with name, part, origin and direction") + refused("cut_many of a cutter with a key cut does not have", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "operation": "UNION"}])}, "cuts[0] must be an object") + refused("cut_many of an origin of two numbers", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "origin": [0.0, 1.0]}])}, "cuts[0].origin must be three numbers") + refused("cut_many of a roll of 400", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "roll": 400}])}, "cuts[0].roll must be a number from -360 to 360") + refused("an axis that points into the surface", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[1], "axis": [0.0, 1.0, 0.0]}])}, "'Seam': the axis (0.0, 1.0, 0.0) points into the surface") + quad("Many", (0.0, -27.0, 0.0)) # a target of its own, cheap to evaluate should the 65 ever be placed + refused("M7: cut_many of 65 cutters, one over the limit", "brokkr_kitbash.cut_many", + {"object_name": "Many", "cuts": json.dumps([{"name": f"Over{k}", "part": "cyl", "params": "r=0.005", "origin": [0.4 - k * 0.012, 0.0, 3.0], "direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]} + for k in range(65)])}, "cuts must be a JSON array of 1 to 64 cutters") + receipt, report = send("brokkr_kitbash.cut_many", object_name="Cage", cuts=json.dumps(MANY)) + placed = [bpy.data.objects.get(spec["name"]) for spec in MANY] + check("cut_many places three cutters in one action, each as cut would: parented under an identity inverse, its basis the surface frame at its own ray on the uncut cage, in the difference collection in order", + receipt["status"] == "accepted" and all(placed) and report == {"object": "Cage", "cutters": ["Visor", "Seam", "Port"], "booleans": report["booleans"]} + and [row["cutter"] for row in report["booleans"]] == ["Bay", "Recess", "Gills", "Break", "Bay2", "Visor", "Seam", "Port"] + and all(c.parent == cage and np.array_equal(np.array(c.matrix_parent_inverse), np.eye(4)) + and reading("framed", np.abs(np.array(c.matrix_basis) - wanted[c.name]).max()) < FRAMED for c in placed) + and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and all(m.show_viewport for m in cage.modifiers) and evaluated(cage)[0]["nonManifoldEdges"] == 0, + [receipt["message"], report]) + seam = bpy.data.objects["Seam"] + check("a slab with an axis stands on the axis, not on the wall's normal, which leans from it there", lean > 5.0 + and reading("framed", np.abs(np.array(seam.matrix_basis)[:3, 2] - [0.0, -1.0, 0.0]).max()) < FRAMED, [lean, np.array(seam.matrix_basis).tolist()]) + receipt, report = send("brokkr_kitbash.cut", object_name="Cage", cutter_name="Seam2", part="slab", params="length=0.3; depth=0.1", origin_x=0.5, origin_y=-3.0, origin_z=-0.7, + direction_x=0.0, direction_y=1.0, direction_z=0.0, up_x=1.0, up_y=0.0, up_z=0.0, axis_x=0.0, axis_y=-1.0, axis_z=0.0) + check("cut takes the same axis", receipt["status"] == "accepted" and reading("framed", np.abs(np.array(bpy.data.objects["Seam2"].matrix_basis)[:3, 2] - [0.0, -1.0, 0.0]).max()) < FRAMED, receipt["message"]) + visor = bpy.data.objects["Visor"] + eyes = {} + for socket, x in (("floor", 0.0), ("floor_l", -0.23), ("floor_r", 0.23)): # the round ends' centres: -+(0.6 - 0.14) / 2 + eye = place(f"Eye_{socket}", "vent", "width=0.2; height=0.15") # back size 0.135; each floor's is 0.14 + receipt, report = send("brokkr_kitbash.attach", object_name=eye.name, socket="back", parent_name="Visor", parent_socket=socket) + there = world @ wanted["Visor"] @ np.array(Matrix.Translation((x, 0.0, -0.02))) + eyes[socket] = receipt["status"] == "accepted" and held(report) and eye.parent == visor \ + and reading("floored", max(np.abs(frame(eye, "back")[:3, 3] - there[:3, 3]).max(), np.abs(frame(eye, "back")[:3, 2] + there[:3, 2]).max())) < FLOORED + check("slot-floors: a slot's three floors each take a part: at the centre and at the round ends, all on the slot's one floor plane", all(eyes.values()) and len(eyes) == 3, eyes) + refused("a second part on a side floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Visor", "parent_socket": "floor_l"}, "'Nozzle' on 'Visor'") + refused("a fourth eye on a floor that is taken", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Visor", "parent_socket": "floor_l"}, "'Big' on 'Visor'") + + # --- boolean on any mesh, and the order of the three operations ----------------------------------------------------------------- + section('boolean on any mesh, and the order of the three operations') + lump_at = world @ [0.0, 0.0, 1.0, 1.0] + send("createObject", objectType="MESH", name="Lump", location=lump_at[:3].tolist(), size=0.2) + receipt, report = send("brokkr_kitbash.boolean", object_name="Cage", cutter="Lump", operation="UNION") + check("boolean on the cage, which is not a kit part, adds a second modifier after the difference and reports the object, what cuts it and the evaluated mesh", + receipt["status"] == "accepted" and stack(cage) == ["Subsurf", "Solidify", "Kit Difference", "Kit Union"] + and sorted(report) == ["booleans", "evaluated", "object"] and report["object"] == "Cage" and report["evaluated"] == evaluated(cage)[0] + and report["booleans"] == [{"cutter": n, "operation": "DIFFERENCE"} for n in ("Bay", "Recess", "Gills", "Break", "Bay2", "Visor", "Seam", "Port", "Seam2")] + [{"cutter": "Lump", "operation": "UNION"}] + and report["evaluated"]["volume"] > deeper["volume"], [receipt["message"], report]) + refused("cut-refusals: a cutter already in the target's union collection", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Lump"}, + "'Lump' already cuts 'Cage' (its Kit Union modifier's collection)") + refused("a cut's own cutter given to boolean again", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Bay", "operation": "INTERSECT"}, + "'Bay' already cuts 'Cage' (its Kit Difference modifier's collection)") + blocked = cast(cage, (-0.3, 0.0, 0.95), (1.0, 0.0, 0.0))[0] # as evaluated now: the ray meets Lump, which the union added inside the cage's mouth + hit, normal = uncut_cast((-0.3, 0.0, 0.95), (1.0, 0.0, 0.0)) + receipt, report = cut("Past", "cyl", (-0.3, 0.0, 0.95), (1.0, 0.0, 0.0), "r=0.02; depth=0.01") + past = bpy.data.objects.get("Past") + check("M3: a cut whose ray meets what a union added lands on the surface as designed: the cast has the Kit Union off too", + receipt["status"] == "accepted" and past is not None and np.linalg.norm(blocked - hit) > 0.3 + and reading("framed", np.abs(np.array(past.matrix_basis) - core.surface_frame(hit, normal, (0.0, 0.0, 1.0))).max()) < FRAMED + and all(m.show_viewport for m in cage.modifiers), [receipt["message"], blocked.tolist(), hit.tolist(), past and list(past.matrix_basis.translation)]) + plate = place("Plate", "plate", location=[0.0, -6.0, 0.0]) + for name, size, operation in (("Boss", 0.06, "UNION"), ("Keep", 2.0, "INTERSECT"), ("Hole", 0.05, "DIFFERENCE")): + send("createObject", objectType="MESH", name=name, location=[0.0, -6.0, 0.0], size=size) + receipt, report = send("brokkr_kitbash.boolean", object_name="Plate", cutter=name, operation=operation) + check("a part cut by union, then intersect, then difference carries the three modifiers as difference, union, intersect, above its Bevel, and lists its cutters so", + 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} + refused("a ray that misses", "brokkr_kitbash.cut", {**RAY, "origin_z": 5.0}, "The ray from (3.0, 0.0, 5.0) along (-1.0, 0.0, 0.0) misses 'Cage'") + refused("a ray of no direction", "brokkr_kitbash.cut", {**RAY, "direction_x": 0.0}, "'New': the ray's direction is zero") + refused("a cutter name an object has", "brokkr_kitbash.cut", {**RAY, "cutter_name": "Bay"}, "An object named 'Bay' exists") + refused("a param the cutter part does not have", "brokkr_kitbash.cut", {**RAY, "params": "radius=0.1"}, "kit 'cutters' part 'box' has no param 'radius'") + refused("a slot wider across than along", "brokkr_kitbash.cut", {**RAY, "part": "slot", "params": "width=0.05; height=0.1"}, "every size must be above 0") + refused("a target that is not a mesh", "brokkr_kitbash.cut", {**RAY, "object_name": "Nothing"}, "No mesh object named 'Nothing'") + block = bpy.data.objects.new("Block", bpy.data.meshes.new("Block")) + bm = bmesh.new() + bmesh.ops.create_cube(bm, size=1.0) + bm.to_mesh(block.data) + bm.free() + bpy.context.scene.collection.objects.link(block) + block.location = (0.0, -9.0, 0.0) + bpy.context.view_layer.update() + DOWN = {**RAY, "object_name": "Block", "origin_x": 0.1, "origin_y": 0.1, "origin_z": 3.0, "direction_x": 0.0, "direction_z": -1.0} + refused("an up along the hit normal", "brokkr_kitbash.cut", DOWN, "up [0.0, 0.0, 1.0] runs along the surface normal [0.0, 0.0, 1.0]") + block.scale = (1.0, 1.0, 1.01) + bpy.context.view_layer.update() + refused("a scaled target", "brokkr_kitbash.cut", {**DOWN, "up_y": 1.0, "up_z": 0.0}, "'Block' is scaled, mirrored or sheared in the world (scale 1, 1, 1.01)") + refused("boolean on a scaled target", "brokkr_kitbash.boolean", {"object_name": "Block", "cutter": "Lump"}, "'Block' is scaled, mirrored or sheared") + block.scale = (1.0, 1.0, 1.0) + bpy.context.view_layer.update() + receipt, report = send("brokkr_kitbash.cut", **{**DOWN, "cutter_name": "Pocket", "up_y": 1.0, "up_z": 0.0, "roll": 90.0}) + pocket = bpy.data.objects.get("Pocket") + check("a cut on a plain cube with up +y and roll 90: the cutter's y points along -x, its floor 0.02 under the top face", receipt["status"] == "accepted" and pocket is not None + and np.abs(np.array(pocket.matrix_basis) - [[0, -1, 0, 0.1], [1, 0, 0, 0.1], [0, 0, 1, 0.5], [0, 0, 0, 1]]).max() < 1e-6 + and np.abs(np.array(report["cutter"]["sockets"][0]["matrix"])[:3, 3] - [0.1, -8.9, 0.48]).max() < 1e-6 and stack(block) == ["Kit Difference"], + [receipt["message"], pocket and np.array(pocket.matrix_basis).tolist()]) + + # --- lows-pinned: the surface's side, an axis along it, and an object Blender does not evaluate -------------------------------- + section("lows-pinned: the surface's side, an axis along it, and an object Blender does not evaluate") + sheet = quad("Sheet", (0.0, -12.0, 0.0)) + UNDER = {"object_name": "Sheet", "cutter_name": "Under", "part": "cyl", "origin_x": 0.1, "origin_y": 0.1, "origin_z": -3.0, "direction_x": 0.0, "direction_y": 0.0, "direction_z": 1.0, + "up_x": 0.0, "up_y": 1.0, "up_z": 0.0} + refused("M1: an axis exactly along the surface, neither out of it nor into it", "brokkr_kitbash.cut", {**UNDER, "cutter_name": "Along", "origin_z": 3.0, "direction_z": -1.0, "axis_x": 1.0}, + "'Along': the axis (1.0, 0.0, 0.0) points into the surface") + receipt, report = send("brokkr_kitbash.cut", **UNDER) + under = bpy.data.objects.get("Under") + check("M16: a ray that meets a one-sided face from behind gives a cutter whose z faces the ray, against the face's own normal", receipt["status"] == "accepted" and under is not None + and reading("framed", np.abs(np.array(under.matrix_basis)[:3, 2] - [0.0, 0.0, -1.0]).max()) < FRAMED, [receipt["message"], under and np.array(under.matrix_basis).tolist()]) + loose = place("Loose", "plate", location=[0.0, -18.0, 0.0]) + apart = bpy.data.collections.new("Apart") # a collection no scene holds: Loose is in a collection, and in no view layer + apart.objects.link(loose) + bpy.context.scene.collection.objects.unlink(loose) + veil = quad("Veil", (0.0, -21.0, 0.0)) # nothing depends on it: a disabled object another evaluated object needs (a parent, a cutter) is still evaluated + veil.hide_viewport = plate.hide_viewport = True + bpy.context.view_layer.update() + for name, why in (("Veil", "disabled in viewports"), ("Loose", "in a collection outside the view layer")): + NOT = f"Blender does not evaluate {name!r} in this view layer" + refused(f"unevaluable-target: cut on a target {why}", "brokkr_kitbash.cut", {**DOWN, "object_name": name, "cutter_name": "Unseen", "up_y": 1.0, "up_z": 0.0}, NOT) + 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() + + # --- receipt-fitted: rows that would not fit a receipt are left off and counted; the scene keeps the cutters --------------------- + section('receipt-fitted: rows that would not fit a receipt are left off and counted; the scene keeps the cutters') + addon = sys.modules["brokkr_kitbash"] + limit, fits = addon.REPORT_LIMIT, {} + SPOT = {"part": "cyl", "params": "r=0.03", "direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]} + try: + addon.REPORT_LIMIT = 200 + fits["cut"] = send("brokkr_kitbash.cut", **{**DOWN, "cutter_name": "Fit1", "part": "cyl", "params": "r=0.03", "origin_x": -0.3, "up_y": 1.0, "up_z": 0.0}) + fits["cut_many"] = send("brokkr_kitbash.cut_many", object_name="Block", cuts=json.dumps([{**SPOT, "name": "Fit2", "origin": [-0.3, -0.3, 3.0]}, {**SPOT, "name": "Fit3", "origin": [0.3, -0.3, 3.0]}])) + fits["boolean"] = send("brokkr_kitbash.boolean", object_name="Block", cutter="Lump", operation="UNION") + finally: + addon.REPORT_LIMIT = limit + ROWS = [{"cutter": name, "operation": "DIFFERENCE"} for name in ("Pocket", "Fit1", "Fit2", "Fit3")] + [{"cutter": "Lump", "operation": "UNION"}] + for action, total, keeps in (("cut", 2, 0), ("cut_many", 4, 2), ("boolean", 5, 1)): # rows the scene had after each action, and how many of them 200 characters carry + receipt, report = fits[action] + check(f"receipt-fitted: {action} past what a receipt carries is accepted, its booleans cut short and the rest counted in booleansOmitted", receipt["status"] == "accepted" + and report is not None and report["booleans"] == ROWS[:keeps] and report.get("booleansOmitted") == total - keeps and (keeps == 0 or len(receipt["hostResult"]) <= 200), + [receipt["message"], receipt.get("hostResult")]) + check("the scene keeps every cutter a short receipt left off", [o.name for o in block.modifiers["Kit Difference"].collection.objects] == ["Pocket", "Fit1", "Fit2", "Fit3"] + and [o.name for o in block.modifiers["Kit Union"].collection.objects] == ["Lump"], stack(block)) + receipt, report = send("brokkr_kitbash.boolean", object_name="Block", cutter="Sheet", operation="INTERSECT") + check("a report that fits carries every row and no count", receipt["status"] == "accepted" and report["booleans"] == ROWS + [{"cutter": "Sheet", "operation": "INTERSECT"}] + and "booleansOmitted" not in report, report) + + # --- cut-orphan and closures-ends-first ----------------------------------------------------------------------------------------- + section('cut-orphan and closures-ends-first') + strut = core.build(kits["mechanical"]["parts"]["strut"], {"width": 0.09}) + end = {name: next(s for s in strut.sockets if s["name"] == name) for name in ("end_a", "end_b")} + for pair, y in (("Zz", -20.0), ("Aa", -24.0)): # two closures that share no part; the open one is named to sort first + anchor, loose = place(f"{pair}_Anchor", "strut", "width=0.09", location=[0.0, y, 0.0]), place(f"{pair}_Loose", "strut", "width=0.09") + meet = Matrix((np.array(anchor.matrix_world) @ core.mate(end["end_b"], end["end_a"], 40.0)).tolist()) + send("setObjectTransform", targetObjectName=f"{pair}_Loose", location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ"))) + send("brokkr_kitbash.close", object_name=f"{pair}_Loose", socket="end_a", other_name=f"{pair}_Anchor", other_socket="end_b") + send("brokkr_kitbash.set_params", object_name="Aa_Anchor", params="length=0.9") # opens Aa's closure + receipt, report = send("brokkr_kitbash.set_params", object_name="Zz_Anchor", params="width=0.09") + check("closures-ends-first: set_params on a part whose own closure holds lists it before another part's closure that is open, though that one sorts first by holds and by name", + receipt["status"] == "accepted" and report["closures"] == [{"part": "Zz_Loose", "to": "Zz_Anchor", "holds": True}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}], + report and report.get("closures")) + ghost = bpy.data.objects["Aa_Anchor"] + with bpy.context.temp_override(selected_objects=[ghost], active_object=ghost): + bpy.ops.object.delete() # the ordinary Delete: Aa_Loose's closure still points at it, so it stays in the file, in no collection + tie = place("Tie", "strut", "width=0.09") + check("a part deleted with the Delete operator that a closure points to is still in the file", bpy.data.objects.get("Aa_Anchor") is not None and not ghost.users_collection, list(bpy.data.objects.keys())) + GONE = "'Aa_Anchor' is in no collection (a deleted object something still points to)" + refused("cut-orphan: attach onto a deleted part's name", "brokkr_kitbash.attach", {"object_name": "Tie", "socket": "end_a", "parent_name": "Aa_Anchor", "parent_socket": "end_a"}, GONE) + refused("attach of a deleted part", "brokkr_kitbash.attach", {"object_name": "Aa_Anchor", "socket": "end_a", "parent_name": "Tie", "parent_socket": "end_a"}, GONE) + refused("set_params on a deleted part", "brokkr_kitbash.set_params", {"object_name": "Aa_Anchor", "params": "length=1.0"}, GONE) + refused("report of a deleted part", "brokkr_kitbash.report", {"object_name": "Aa_Anchor"}, GONE) + refused("cut on a deleted part", "brokkr_kitbash.cut", {**RAY, "object_name": "Aa_Anchor"}, GONE) + refused("boolean on a deleted part", "brokkr_kitbash.boolean", {"object_name": "Aa_Anchor", "cutter": "Lump"}, GONE) + refused("boolean with a deleted part as the cutter", "brokkr_kitbash.boolean", {"object_name": "Tie", "cutter": "Aa_Anchor"}, GONE) + refused("close onto a deleted part", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Aa_Anchor", "other_socket": "end_a"}, GONE) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file + check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-6:]) +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())} + 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"], flush=True) sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/kitbash_shell.result.json b/surfaces/blender/tests/live/kitbash_shell.result.json index 74a159c..3b6c679 100644 --- a/surfaces/blender/tests/live/kitbash_shell.result.json +++ b/surfaces/blender/tests/live/kitbash_shell.result.json @@ -162,7 +162,7 @@ "detail": null }, { - "name": "refused, scene unchanged: cut_many whose report would not fit a receipt places none", + "name": "refused, scene unchanged: M7: cut_many of 65 cutters, one over the limit", "ok": true, "detail": null }, @@ -182,7 +182,7 @@ "detail": null }, { - "name": "a slot's three floors each take a part: at the centre and a third of the width to each side, all on the slot's one floor plane", + "name": "slot-floors: a slot's three floors each take a part: at the centre and at the round ends, all on the slot's one floor plane", "ok": true, "detail": null }, @@ -211,6 +211,11 @@ "ok": true, "detail": null }, + { + "name": "M3: a cut whose ray meets what a union added lands on the surface as designed: the cast has the Kit Union off too", + "ok": true, + "detail": null + }, { "name": "a part cut by union, then intersect, then difference carries the three modifiers as difference, union, intersect, above its Bevel, and lists its cutters so", "ok": true, @@ -226,6 +231,11 @@ "ok": true, "detail": null }, + { + "name": "M6: apply keeps a collection a copied part's modifier still reads", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: a ray that misses", "ok": true, @@ -276,6 +286,81 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: M1: an axis exactly along the surface, neither out of it nor into it", + "ok": true, + "detail": null + }, + { + "name": "M16: a ray that meets a one-sided face from behind gives a cutter whose z faces the ray, against the face's own normal", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: unevaluable-target: cut on a target disabled in viewports", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many on a target disabled in viewports", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: boolean on a target disabled in viewports", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: unevaluable-target: cut on a target in a collection outside the view layer", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many on a target in a collection outside the view layer", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: boolean on a target in a collection outside the view layer", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: apply 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", + "ok": true, + "detail": null + }, + { + "name": "receipt-fitted: cut past what a receipt carries is accepted, its booleans cut short and the rest counted in booleansOmitted", + "ok": true, + "detail": null + }, + { + "name": "receipt-fitted: cut_many past what a receipt carries is accepted, its booleans cut short and the rest counted in booleansOmitted", + "ok": true, + "detail": null + }, + { + "name": "receipt-fitted: boolean past what a receipt carries is accepted, its booleans cut short and the rest counted in booleansOmitted", + "ok": true, + "detail": null + }, + { + "name": "the scene keeps every cutter a short receipt left off", + "ok": true, + "detail": null + }, + { + "name": "a report that fits carries every row and no count", + "ok": true, + "detail": null + }, { "name": "closures-ends-first: set_params on a part whose own closure holds lists it before another part's closure that is open, though that one sorts first by holds and by name", "ok": true, @@ -329,7 +414,7 @@ ], "hostErrors": [], "readings": { - "floored": 2.6e-07, + "floored": 3.3e-07, "framed": 5.1e-07, "recast": 0.0 }, diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index e29e1d3..2eda1cc 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -595,7 +595,7 @@ class CuttersKitTests(unittest.TestCase): self.assertAlmostEqual(float(b.V[:, 2].min()), -depth, places=12) self.assertAlmostEqual(float(b.V[:, 2].max()), lift, places=12) for socket in b.sockets: - side = {"floor": 0.0, "floor_l": -1.0, "floor_r": 1.0}[socket["name"]] * b.params.get("width", 0.0) / 3 + side = {"floor": 0.0, "floor_l": -1.0, "floor_r": 1.0}[socket["name"]] * (b.params.get("width", 0.0) - b.params.get("height", 0.0)) / 2 self.assertEqual(socket["matrix"][:, 3].tolist(), [side, 0.0, -depth, 1.0]) self.assertEqual(socket["matrix"][:3, :3].tolist(), np.eye(3).tolist()) self.assertGreater(socket["size"], 0.0) @@ -619,13 +619,21 @@ class CuttersKitTests(unittest.TestCase): self.assertTrue(seat < 1e-12 if count % 2 else abs(seat - 0.015) < 1e-12, f"{name} x{count}: {seat}") # even: 0.015 from each middle copy def test_a_slot_has_three_floors_on_its_bottom(self): - """A visor carries three eyes: floor_l and floor_r lie a third of the width to each side, on the slot's own - bottom, each the size of the slot's height. Mutant B4 (the two side floors swapped).""" + """slot-floors. A visor carries three eyes: floor_l and floor_r lie at the centres of the slot's round ends, on + its own bottom; the three never overlap (centres at least a size apart) and none passes the slot's ends, also + where height exceeds a third of the width. Mutants B4 (the two side floors swapped) and F1 (the side floors + back at a third of the width, each the size of the height: at 0.3 by 0.25 they overlap by 0.15 and pass the + ends by 0.075).""" part = self.kit["parts"]["slot"] - for given in ({"width": 0.66, "height": 0.12, "depth": 0.045}, {"width": 0.3, "height": 0.25}, {"width": 0.3, "height": 0.05, "count": 3, "pitch": 0.2}): + for given in ({"width": 0.66, "height": 0.12, "depth": 0.045}, {"width": 0.3, "height": 0.25}, {"width": 0.3, "height": 0.05, "count": 3, "pitch": 0.2}, + {"width": 0.06, "height": 0.05}, {"width": 0.3, "height": 0.1}): b = core.build(part, given) - self.assertEqual([(s["name"], round(float(s["matrix"][0, 3]), 12), s["size"]) for s in b.sockets], - [("floor", 0.0, given["height"]), ("floor_l", round(-given["width"] / 3, 12), given["height"]), ("floor_r", round(given["width"] / 3, 12), given["height"])]) + side, size = (given["width"] - given["height"]) / 2, min(given["height"], (given["width"] - given["height"]) / 2) + self.assertEqual([(s["name"], round(float(s["matrix"][0, 3]), 12), round(s["size"], 12)) for s in b.sockets], + [("floor", 0.0, round(size, 12)), ("floor_l", round(-side, 12), round(size, 12)), ("floor_r", round(side, 12), round(size, 12))]) + xs = [float(s["matrix"][0, 3]) for s in b.sockets] + self.assertGreaterEqual(min(xs[0] - xs[1], xs[2] - xs[0]), b.sockets[0]["size"] - 1e-12, given) + self.assertLessEqual(max(abs(x) for x in xs) + b.sockets[0]["size"] / 2, given["width"] / 2 + 1e-12, given) for socket in b.sockets: self.assertLess(socket_seat(b, dict(socket, matrix=socket["matrix"] @ core.FLIP)), 1e-12, socket["name"]) @@ -1275,14 +1283,18 @@ class OwnershipTests(unittest.TestCase): 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]) - callers = [body.split("(")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:] if "evaluated_of(" in body] - self.assertEqual(callers, ["boolean", "apply"]) - self.assertEqual(source.count("evaluated_of("), 4) + 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"]) + self.assertEqual(source.count("evaluated_of("), 4) # its def, evaluable, boolean and apply + 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("evaluated_of("), 1) - self.assertLess(place.index("modifier.show_viewport = False"), place.index("evaluated_of(")) - self.assertLess(place.index("evaluated_of("), place.index("modifier.show_viewport = True")) - self.assertLess(place.index("report(booleans(target)"), place.index("bpy.data.meshes.new(")) # every refusal before any write + 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(")): + self.assertLess(body.index("evaluable("), body.index(first_write)) + self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply"]) for body in (place, *(source.split(f"class BROKKR_KITBASH_OT_{name}(")[1].split("class BROKKR_KITBASH_OT_")[0] for name in ("cut", "cut_many"))): self.assertNotIn("view_layer.update", body) # an update after a cutter joins would evaluate the Boolean self.assertEqual(body.count("place_cutters("), 0 if body is place else 1)