diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index be25999..9bb89d1 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -119,7 +119,13 @@ pub fn run(args: &[String]) -> Result { return Ok(0); } match sub.as_str() { - "send" => send(&options), + "send" => send(&options, one_positional(&options, "send [--set key=json]...")?), + "look" => { + if !options.positional.is_empty() || !options.sets.is_empty() { + bail!("usage: brokkr-ctl blender look [--note text] [--agent name] [--no-wait] [--timeout secs]"); + } + send(&options, "look") + } "wait" => { let id = one_positional(&options, "wait ")?; let store = open_store(&options)?; @@ -232,8 +238,7 @@ fn build_intent( Ok(Value::Object(map)) } -fn send(options: &Options) -> Result { - let action = one_positional(options, "send [--set key=json]...")?; +fn send(options: &Options, action: &str) -> Result { let requested_by = requested_by(options)?; let mut store = open_store(options)?; let command_id = uuid::Uuid::now_v7().simple().to_string(); @@ -399,6 +404,9 @@ brokkr-ctl blender: send typed intents to the live Blender add-on and read what send [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs] Write one intent, then wait for its receipt and print it. `send --help` lists actions. + look [--note text] [--agent name] [--no-wait] [--timeout secs] + `send look`: capture the 3D view she is looking at. The receipt prints lookPath (a PNG), her + Edit Mode selection, and how many edits she made since this agent last looked. wait [--timeout secs] Wait for a receipt and print it. receipts [--last n] Print stored receipts, oldest first. status Print the host snapshot summary, agentCommandsEnabled included. @@ -544,6 +552,7 @@ const ACTIONS: &[(&str, &[Field])] = &[ ("cameraName", "string", ""), ], ), + ("look", &[]), ( "createNodeGroup", &[ diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index 4ea7f24..a7293e1 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -80,6 +80,53 @@ fn send_writes_a_pullable_intent() { assert!(envelopes.iter().any(|e| e.key == "blender/receipts/seed"), "other records survive the write"); } +/// `look` is `send look`: one intent, no fields, the same receipt wait. +#[test] +fn look_sends_the_look_action_and_prints_the_receipts_look_path() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let output = ctl(&path, &["look", "--agent", "hands", "--note", "checking the view", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(0), "{}", String::from_utf8_lossy(&output.stderr)); + let id = stdout(&output).trim().strip_prefix("commandId: ").unwrap().to_string(); + let envelopes = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap(); + let intent = envelopes.iter().find(|e| e.key == format!("blender/commands/{id}")).expect("intent key"); + let payload: Value = cultcache_rs::decode_payload(&intent.payload).unwrap(); + assert_eq!( + payload, + json!({"schema": INTENT, "commandId": id, "action": "look", "requestedBy": "nibu/hands", + "note": "checking the view"}) + ); + // the add-on's receipt for it prints like any other: lookPath and the perception fields are plain lines + let mut store = SingleFileMessagePackBackingStore::new(&path); + let receipt = json!({"schema": RECEIPT, "commandId": id, "status": "accepted", "lookPath": "C:/out/look/x.png", + "humanEditSeq": 3, "editSelection": [{"name": "Cube", "vertices": [0, 2]}]}); + store.push(&envelope(RECEIPT, &format!("blender/receipts/{id}"), &receipt)).unwrap(); + let waited = ctl(&path, &["wait", &id, "--timeout", "5"], None); + assert_eq!(waited.status.code(), Some(0)); + let text = stdout(&waited); + assert!(text.contains("lookPath: C:/out/look/x.png"), "{text}"); + assert!(text.contains("humanEditSeq: 3") && text.contains("\"vertices\":[0,2]"), "{text}"); +} + +#[test] +fn look_takes_no_fields_and_no_second_action() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + for extra in [vec!["--set", "x=1"], vec!["createObject"]] { + let mut args = vec!["look", "--agent", "hands", "--no-wait"]; + args.extend(extra.iter()); + assert_eq!(ctl(&path, &args, Some("nibu")).status.code(), Some(1), "{extra:?}"); + } + let store = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap(); + assert!(!store.iter().any(|e| e.key.starts_with("blender/commands/")), "a refused look writes nothing"); +} + +#[test] +fn the_group_help_names_look() { + let output = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")).args(["blender", "--help"]).output().unwrap(); + assert!(stdout(&output).contains("look")); +} + #[test] fn an_intent_without_instance_or_agent_is_refused_and_writes_nothing() { let dir = tempfile::tempdir().unwrap(); diff --git a/docs/provider-contract.md b/docs/provider-contract.md index 8c1132f..cda8707 100644 --- a/docs/provider-contract.md +++ b/docs/provider-contract.md @@ -220,6 +220,7 @@ All Blender writes use `brokkr.blender.command_intent.v0` and receive - `setLight` - `setWorld` - `renderStill` +- `look` (a read: a PNG of her 3D view under the output directory's `look/`, her Edit Mode selection and her edit counters in the receipt) - `createNodeGroup`, `addNode`, `removeNode`, `linkSockets`, `unlinkSockets`, `addModifier`, `removeModifier`, `setModifierInput` (Geometry Nodes graphs; fields in `surfaces/blender/docs/node-actions.md`) diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index 4926385..58fd75b 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -672,6 +672,30 @@ def _auto_capture(scene, depsgraph): ) +# Human-edit tracking is always on and reads no preference: it must not depend on auto_capture. Persistent, so +# opening another file does not drop them. +@bpy.app.handlers.persistent +def _track_human_edits(scene, depsgraph): + target().track_human_edits(depsgraph) + + +@bpy.app.handlers.persistent +def _track_undo_redo(scene, *_): + target().note_undo_redo() + + +@bpy.app.handlers.persistent +def _new_session(*_): + target().renew_session() + + +_PERCEPTION_HANDLERS = ( + ("depsgraph_update_post", _track_human_edits), + ("undo_post", _track_undo_redo), + ("redo_post", _track_undo_redo), + ("load_post", _new_session), +) + BUSY_INTERVAL = 0.05 # one intent per tick: Stop is a UI event, and it lands between two intents IDLE_INTERVAL = 1.0 @@ -733,6 +757,9 @@ def register(): bpy.utils.register_class(cls) if _auto_capture not in bpy.app.handlers.depsgraph_update_post: bpy.app.handlers.depsgraph_update_post.append(_auto_capture) + for name, handler in _PERCEPTION_HANDLERS: + if handler not in getattr(bpy.app.handlers, name): + getattr(bpy.app.handlers, name).append(handler) if not bpy.app.timers.is_registered(_auto_drain_commands): bpy.app.timers.register(_auto_drain_commands, first_interval=1.0, persistent=True) @@ -740,6 +767,9 @@ def register(): def unregister(): if _auto_capture in bpy.app.handlers.depsgraph_update_post: bpy.app.handlers.depsgraph_update_post.remove(_auto_capture) + for name, handler in _PERCEPTION_HANDLERS: + if handler in getattr(bpy.app.handlers, name): + getattr(bpy.app.handlers, name).remove(handler) if bpy.app.timers.is_registered(_auto_drain_commands): bpy.app.timers.unregister(_auto_drain_commands) global _target diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 363e017..93a9fb5 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -6,8 +6,10 @@ import json import math import os import re +import struct import sys import uuid +import zlib from array import array from collections import deque from datetime import datetime, timedelta, timezone @@ -45,8 +47,8 @@ CREATABLE_OBJECT_TYPES = ("MESH", "LIGHT", "CAMERA", "EMPTY") GL_RENDER_ENGINES = ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT") GL_RUNTIME_LIBRARY = "libEGL.so.1" -# Actions that only read the scene and so push no undo step (live-5 adds look). -READ_ACTIONS: tuple[str, ...] = () +# Actions that only read the scene and so push no undo step. +READ_ACTIONS = ("look",) MUTATING_ACTIONS = ( "createObject", "deleteObject", "setObjectTransform", "setObjectVisibility", "setObjectParent", "setObjectCustomProperty", "selectObject", "assignMaterial", "importGltf", "exportGltf", @@ -57,8 +59,11 @@ MUTATING_ACTIONS = ( NO_SCENE_CHANGE_ACTIONS = ("exportGltf", "renderStill") # While an object is in Edit Mode, undo steps are edit-mesh steps, so a scene write is not reverted by # one undo, and some operators leave Edit Mode (brokkr-live:ruling:object-intents-refused-in-edit-mode). -# Anything that writes scene state or changes her mode is refused; renderStill does neither. -EDIT_MODE_SAFE_ACTIONS = ("renderStill",) +# Anything that writes scene state or changes her mode is refused; renderStill and look do neither. +EDIT_MODE_SAFE_ACTIONS = ("renderStill", "look") +LOOK_DIR = "look" # under the output directory: scratch captures named by command id (brush-tree:ruling:look-files-are-scratch) +LOOK_KEPT = 20 # the newest captures that stay after each look +EDIT_SELECTION_CAP = 4096 # indices listed per element kind and object; the total stays true beside the list REQUESTED_BY_SHAPE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") # A commandId becomes part of a receipt key, so it is a short string of key-safe characters ('.' is left # out: it separates the '.denied' suffix). @@ -121,6 +126,13 @@ class BrokkrBlenderTarget: self._recent: deque[dict[str, Any]] = deque(maxlen=RECEIPTS_KEPT) # display cache of the node's receipts self._receipts_loaded = False self.pending_count = 0 # display cache: intents queued in the node + # What she did, as observed: nothing reads these back to admit or refuse an intent (scene-last-writer-wins). + self.session_id = uuid.uuid4().hex + self.human_edit_seq = 0 + self._last_human_edit: dict[str, int] = {} # object name -> human_edit_seq when she last changed it + self._looked: dict[str, int] = {} # requestedBy -> human_edit_seq at that agent's last look + self.scene_update_seq = 0 # every depsgraph update, hers or the agent's: what a capture reflects + self._coarse = {"seq": 0, "why": ""} # the latest human edit whose per-object stamps are not precise def configure_action_dirs(self, import_dir: str, output_dir: str) -> None: """The directories importGltf and renderStill may touch; empty leaves that action disabled.""" @@ -593,6 +605,9 @@ class BrokkrBlenderTarget: "activeScene": active_scene, "activeObjectName": active_object, "mode": context.mode, + "sessionId": self.session_id, + "humanEditSeq": self.human_edit_seq, + "editSelection": self.edit_selection(), "selectedObjectNames": selected, "sceneCount": len(bpy.data.scenes), "objectCount": len(bpy.data.objects), @@ -702,6 +717,8 @@ class BrokkrBlenderTarget: return self._set_world(context, command) if action == "renderStill": return self._render_still(context, command) + if action == "look": + return self._look(context, command) if action in na.NodeActions.ACTIONS: message, name = self.nodes.execute(action, command) self._wrote = self.nodes.changed @@ -1034,6 +1051,179 @@ class BrokkrBlenderTarget: render.image_settings.file_format, scene.camera) = saved return self._receipt(command, "accepted", f"Rendered still to {path.name}.", scene.name) + # ---- perception: what she sees and what she did ---------------------------------------------------------- + + def renew_session(self) -> None: + """A new session id and zeroed counters: names mean something else in a freshly loaded file.""" + self.session_id = uuid.uuid4().hex + self.human_edit_seq = 0 + self._last_human_edit.clear() + self._looked.clear() + self.scene_update_seq = 0 + self._coarse = {"seq": 0, "why": ""} + + def track_human_edits(self, depsgraph: Any) -> None: + """A depsgraph update outside an agent turn is hers. What changed is read from each update's flags, never + from presence in the list: an update also names what only depends on the change.""" + self.scene_update_seq += 1 + if self.agent_turn: + return + changed = [u.id.name for u in depsgraph.updates + if u.id.id_type == "OBJECT" and (u.is_updated_transform or u.is_updated_geometry or u.is_updated_shading)] + if not changed: + return + self.human_edit_seq += 1 + for name in changed: + self._last_human_edit[name] = self.human_edit_seq + if len(changed) >= 2 and len(changed) == len(self.bpy.data.objects): + self._coarse = {"seq": self.human_edit_seq, "why": "all objects flagged"} # an add or a link does this + + def note_undo_redo(self) -> None: + """An undo or redo cannot be narrowed to objects from its updates, so it moves the session counter only.""" + self.human_edit_seq += 1 + self._coarse = {"seq": self.human_edit_seq, "why": "undo or redo flags all objects"} + + def last_human_edit_seq(self, name: str) -> int: + return self._last_human_edit.get(name, 0) + + def edit_selection(self) -> list[dict[str, Any]]: + """Her selection in every object in Edit Mode, read live from the edit mesh without leaving the mode.""" + editing = [obj for obj in self.bpy.data.objects if getattr(obj, "mode", "OBJECT") == "EDIT"] + entries: list[dict[str, Any]] = [] + if not editing: + return entries + import bmesh # exists only inside Blender; nothing is imported when no object is being edited + for obj in editing: + if obj.type != "MESH": + entries.append({"name": obj.name, "type": obj.type, "unsupported": True}) + continue + mesh = bmesh.from_edit_mesh(obj.data) + entry: dict[str, Any] = {"name": obj.name, "type": obj.type} + # The totals are the mesh's own counts; the scan stops at the cap or when every selected one is found. + for key, elements, total in (("vertices", mesh.verts, obj.data.total_vert_sel), + ("edges", mesh.edges, obj.data.total_edge_sel), + ("faces", mesh.faces, obj.data.total_face_sel)): + chosen: list[int] = [] + want = min(total, EDIT_SELECTION_CAP) + if want: + for index, element in enumerate(elements): + if element.select: + chosen.append(index) + if len(chosen) == want: + break + entry[key] = chosen + entry[key + "Total"] = total + entries.append(entry) + return entries + + def _viewport(self) -> tuple[Any, Any, Any]: + """The window, area and WINDOW region of the largest 3D view: the only pixels look may read.""" + best = None + for window in self.bpy.context.window_manager.windows: + for area in window.screen.areas: + if area.type == "VIEW_3D" and (best is None or area.width * area.height > best[1].width * best[1].height): + best = (window, area) + region = next((r for r in best[1].regions if r.type == "WINDOW"), None) if best else None + if region is None: + raise sa.ActionRefused("No 3D viewport is open to look at.") + return best[0], best[1], region + + def _look(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + """Capture her 3D view to /look/.png. screenshot_area reads Blender's own framebuffer + for the area it is overridden to, so the desktop and other applications are never in the picture; a menu or + popup Blender draws over the view is, as she sees it.""" + name = f"{LOOK_DIR}/{command['commandId']}.png" + path = sa.resolve_inside(self.output_dir, name, "output", new_file=True) + window, area, region = self._viewport() + path.parent.mkdir(parents=True, exist_ok=True) + if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path: + raise sa.ActionRefused("Output path changed while it was being checked.") + source = "region" if self._windows_drawn() else "offscreen" + if source == "region": + with self.bpy.context.temp_override(window=window, area=area, region=region): + result = self.bpy.ops.screen.screenshot_area("EXEC_DEFAULT", False, filepath=str(path)) + if "FINISHED" not in result or not path.is_file(): + raise sa.ActionRefused("Blender did not write the capture.") + else: # a minimised window stops redrawing, so its framebuffer is a stale frame: draw the view itself + try: + width, height, rgba = self._render_view_offscreen(window, area, region) + path.write_bytes(_png_bytes(width, height, rgba)) + except Exception: + path.unlink(missing_ok=True) + raise sa.ActionRefused("Blender is not drawing its window and the view could not be rendered offscreen.") from None + self._prune_looks(path.parent) + requested_by = command["requestedBy"] + since = self._looked.get(requested_by, 0) + self._looked[requested_by] = self.human_edit_seq + coarse = self._coarse["seq"] > since + receipt = self._receipt(command, "accepted", f"Captured the 3D view to {LOOK_DIR}/{path.name}.", "") + receipt.update({ + "lookPath": str(path), + "captureSource": source, + "sceneUpdateSeq": self.scene_update_seq, + "sessionId": self.session_id, + "humanEditSeq": self.human_edit_seq, + "humanEditsSinceLook": self.human_edit_seq - since, + "editedSinceLook": sorted(n for n, seq in self._last_human_edit.items() if seq > since), + "editedSinceLookCoarse": coarse, + "editedSinceLookNote": (f"Coarse: {self._coarse['why']}; editedSinceLook may name objects she did not touch." + if coarse else ""), + "editSelection": self.edit_selection(), + }) + self._wrote = False + return receipt + + def _windows_drawn(self) -> bool: + """False when every Blender window of this process is minimised, so none is redrawing. Only Windows can + say; elsewhere a window is taken as drawn.""" + if sys.platform != "win32": + return True + from ctypes import wintypes + user32 = ctypes.windll.user32 + iconic: list[bool] = [] + + @ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM) + def visit(hwnd, _lparam): + owner = wintypes.DWORD() + user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) + name = ctypes.create_unicode_buffer(64) + user32.GetClassNameW(hwnd, name, 64) + if owner.value == os.getpid() and name.value == "GHOST_WindowClass" and user32.IsWindowVisible(hwnd): + iconic.append(bool(user32.IsIconic(hwnd))) + return True + + user32.EnumWindows(visit, 0) + return not iconic or not all(iconic) + + def _render_view_offscreen(self, window: Any, area: Any, region: Any) -> tuple[int, int, bytes]: + """The 3D view's own viewpoint drawn into an offscreen buffer of the region's size: RGBA bytes, bottom row + first. Overlays and popups are not drawn.""" + import gpu # only inside Blender + space = area.spaces.active + rv3d = space.region_3d + width, height = region.width, region.height + context = self.bpy.context + offscreen = gpu.types.GPUOffScreen(width, height) + try: + offscreen.draw_view3d(context.scene, context.view_layer, space, region, rv3d.view_matrix, + rv3d.window_matrix, do_color_management=True) + with offscreen.bind(): + buffer = gpu.state.active_framebuffer_get().read_color(0, 0, width, height, 4, 0, "UBYTE") + return width, height, bytes(buffer) + finally: + offscreen.free() + + @staticmethod + def _prune_looks(directory: Path) -> None: + """Keep the newest LOOK_KEPT captures: plain .png files directly in the look directory, nothing else.""" + found = [] + with os.scandir(directory) as entries: + for entry in entries: + if entry.name.lower().endswith(".png") and entry.is_file(follow_symlinks=False): + found.append((entry.stat(follow_symlinks=False).st_mtime_ns, entry.name, entry.path)) + for _mtime, _name, old in sorted(found)[:-LOOK_KEPT]: + os.unlink(old) + def _resolve_object(self, command: dict[str, Any]) -> Any: name = command.get("targetObjectName") or command.get("objectName") return self.bpy.data.objects.get(name) if name else None @@ -1061,6 +1251,7 @@ class BrokkrBlenderTarget: "scale": _to_list(obj.scale), "visible": bool(obj.visible_get()), "selected": bool(obj.select_get()), + "lastHumanEditSeq": self.last_human_edit_seq(obj.name), "parentName": obj.parent.name if obj.parent else "", "collections": [collection.name for collection in obj.users_collection], "materials": [slot.material.name for slot in obj.material_slots if slot.material], @@ -1196,6 +1387,7 @@ class BrokkrBlenderTarget: "requestedBy": command["requestedBy"] if isinstance(command.get("requestedBy"), str) else "", "note": command["note"][:NOTE_LIMIT] if isinstance(command.get("note"), str) else "", "undoLabel": "", + "lookPath": "", "observedAt": _now(), } @@ -1344,6 +1536,18 @@ def _parse_time(value: Any) -> datetime | None: return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc) +def _png_bytes(width: int, height: int, rgba: bytes) -> bytes: + """An 8-bit RGBA PNG of bottom-row-first pixels, written top row first.""" + stride = width * 4 + rows = b"".join(b"\x00" + rgba[y * stride:(y + 1) * stride] for y in range(height - 1, -1, -1)) + + def chunk(kind: bytes, data: bytes) -> bytes: + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) + + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(rows, 1)) + chunk(b"IEND", b"")) + + def _now() -> str: return datetime.now(timezone.utc).isoformat() diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 0b5917c..d3dec32 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -175,6 +175,7 @@ Admitted command actions: - `setLight` - `setWorld` - `renderStill` +- `look` Scene action fields (all other keys are ignored; a refused intent changes nothing and gets a `failed` receipt whose message names the rule): @@ -227,6 +228,29 @@ gets a `failed` receipt whose message names the rule): CPU. The check applies to the scene's engine when `engine` is omitted. No such check runs on Windows or macOS. +- `look`: no fields. Captures the 3D view she is looking at (the largest 3D view across the windows, its + main region) to `/look/.png` and puts the absolute path in the receipt's + `lookPath`; refused when the output directory is unset or no 3D view is open. It reads Blender's own + framebuffer for that one region, so her desktop and other applications are never in the picture; a menu, + popup or the splash Blender draws over the view is, as she sees it. It is a read: no undo step, and it runs in + Edit Mode. The capture blocks her UI for about 70 ms. `captureSource` says how it was taken: `region`, or + `offscreen` when every Blender window is minimised (Windows only; a minimised window stops redrawing, so its + framebuffer is a stale frame) and the view's own viewpoint is drawn offscreen at the region's size instead, with + her popups and menus not drawn; an offscreen failure is a refusal, never a stale picture. `sceneUpdateSeq` is the + count of depsgraph updates, hers and the agent's, that the picture reflects. The look directory keeps the newest 20 PNGs (scratch, + never read back). The receipt also carries `sessionId`, `humanEditSeq`, `humanEditsSinceLook` and + `editedSinceLook` (object names), counted for the sending `requestedBy` since its previous look in this + session, and `editSelection`: for each object in Edit Mode its selected vertex, edge and face indices (each + list capped at 4096, the true count beside it as `verticesTotal` and so on; non-mesh objects say + `unsupported`). The host snapshot carries the same `sessionId`, `humanEditSeq`, `editSelection` and each + object's `lastHumanEditSeq`. The sequences come from depsgraph updates outside an agent turn, counted per + flagged object (transform, geometry or shading) and from undo and redo; opening a file starts a new session. An + update also flags objects that only depend on what she changed (a constrained follower), and adding or + linking an object flags all of them, so `editedSinceLook` can name more than she touched; the receipt then + says so: `editedSinceLookCoarse` is true, with the reason in `editedSinceLookNote` (an update that flagged every + object, or an undo or redo). Selection totals are the mesh's own counts and the index scan stops at the cap. They are + observations: no intent is refused because of them. + The scene actions were run against Blender 5.2.3 LTS headless with `surfaces/blender/tests/live/headless_smoke.py` (usage in its docstring). One real failure it found: Blender's `engine` enum is dynamic, so `bl_rna` lists only diff --git a/surfaces/blender/tests/live/perception.py b/surfaces/blender/tests/live/perception.py new file mode 100644 index 0000000..a62aeb8 --- /dev/null +++ b/surfaces/blender/tests/live/perception.py @@ -0,0 +1,275 @@ +"""Live proof, in GUI Blender with the add-on installed as an extension, of perception, with real brokkr-ctl sends. + + BROKKR_SCRATCH= + BROKKR_CTL= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + blender --python perception.py -- + +Run it in a Blender whose resource path is fresh (BLENDER_USER_RESOURCE_PATH) so the add-on's preferences are the +defaults. The driver stands in for the operator's hands only: it saves the blend, ticks the sink and sets the render +output directory (the two preferences an operator sets), enters Edit Mode, selects, moves objects and presses undo. +Every intent is sent by brokkr-ctl and answered by the add-on's own timer. Writes .result.json, then quits. +""" +import importlib +import json +import os +import shutil +import struct +import subprocess +import sys +import time +import traceback +from pathlib import Path + +import bmesh +import bpy + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +CTL = os.environ["BROKKR_CTL"] +OUT = sys.argv[sys.argv.index("--") + 1] +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "bl_ext.user_default.brokkr_bridge") +R = {"blender": bpy.app.version_string, "module": MODULE, "checks": [], "notes": {}} + +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +prefs = bpy.context.preferences.addons[MODULE].preferences +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +adapter = addon.target() +STORE = SCRATCH / ".brokkr" / "blender-editor.ccmp" # what the default blend-relative preference resolves to +ENV = dict(os.environ, EUREKA_INSTANCE="nibu", BROKKR_BLENDER_STORE=str(STORE), BROKKR_AGENT="hands") + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def fields(text): + out = {} + for line in text.splitlines(): + key, _, value = line.partition(": ") + try: + out[key] = json.loads(value) if value[:1] in "[{0123456789" else value + except ValueError: + out[key] = value + return out + + +def ctl(*args): + """A brokkr-ctl run beside Blender's timers (it blocks until the receipt, and the add-on's timer answers it).""" + proc = subprocess.Popen([CTL, "blender", *args], env=ENV, stdout=subprocess.PIPE, text=True) + began = time.perf_counter() + while proc.poll() is None: + yield + out = proc.stdout.read() + return proc.returncode, fields(out), round((time.perf_counter() - began) * 1000) + + +def png_size(path): + data = Path(path).read_bytes() + assert data[:8] == b"\x89PNG\r\n\x1a\n", "not a PNG" + return struct.unpack(">II", data[16:24]) + + +def view3d(): + for window in bpy.context.window_manager.windows: + for area in window.screen.areas: + if area.type == "VIEW_3D": + return window, area, next(r for r in area.regions if r.type == "WINDOW") + + +def snapshot(): + with bpy.context.temp_override(window=bpy.context.window_manager.windows[0]): + bpy.ops.brokkr.capture_snapshot() + return adapter.last_snapshot + + +def objects_named(prefix): + return sorted(o.name for o in bpy.data.objects if o.name.startswith(prefix)) + + +def mode_edit(on): + window, area, region = view3d() + cube = bpy.data.objects["Cube"] + bpy.context.view_layer.objects.active = cube # she clicks it first + cube.select_set(True) + with bpy.context.temp_override(window=window, area=area, region=region, active_object=cube, object=cube): + bpy.ops.object.mode_set(mode="EDIT" if on else "OBJECT") + + +def flow(): + cube = bpy.data.objects["Cube"] + window, area, region = view3d() + R["notes"]["window_px"] = [window.width, window.height] + R["notes"]["region_px"] = [region.width, region.height] + R["notes"]["area_px"] = [area.width, area.height] + + # ---- a default install: the preferences are untouched except what the operator sets ---- + check("default install: the store preference is the blend-relative default", + prefs.cultmesh_cache_path == "//.brokkr/blender-editor.ccmp", prefs.cultmesh_cache_path) + bpy.ops.wm.save_as_mainfile(filepath=str(SCRATCH / "perception.blend")) + prefs.output_dir = str(SCRATCH / "out") + prefs.auto_drain_commands = True # the operator ticks the sink + yield 1.0 + snap = snapshot() + check("the default blend-relative store was created beside the saved blend", STORE.is_file(), str(STORE)) + check("the snapshot carries sessionId, humanEditSeq 0, editSelection [] and per-object lastHumanEditSeq", + snap["sessionId"] == adapter.session_id and snap["humanEditSeq"] == 0 and snap["editSelection"] == [] + and all(o["lastHumanEditSeq"] == 0 for o in snap["objects"]), [snap["sessionId"], snap["humanEditSeq"]]) + session = snap["sessionId"] + + # ---- look: her 3D view, scoped to the viewport ---- + code, r, ms = yield from ctl("look", "--note", "first look") + R["notes"]["first_look"] = r + R["notes"]["first_look_round_trip_ms"] = ms + path = r.get("lookPath", "") + size = png_size(path) if path and Path(path).is_file() else None + check("look: exit 0, accepted, a lookPath PNG under /look/.png", + code == 0 and r.get("status") == "accepted" and size is not None + and Path(path).parent == (SCRATCH / "out" / "look") and Path(path).name == r["commandId"] + ".png", [code, r]) + check("look: the PNG is the 3D view's WINDOW region, not the Blender window and not the desktop", + list(size) == R["notes"]["region_px"] and list(size) != R["notes"]["window_px"], [size, R["notes"]]) + check("look: no undo step, receipt names the session, edits so far 0, none edited since", + r.get("undoLabel", "") == "" and r.get("sessionId") == session and r.get("humanEditSeq") == 0 + and r.get("humanEditsSinceLook") == 0 and r.get("editedSinceLook") == [], r) + + # ---- the agent's own edits are not hers ---- + seq_before = adapter.human_edit_seq + code, r, _ = yield from ctl("send", "createObject", "--set", 'objectType="EMPTY"', "--set", 'name="AgentEmpty"') + code2, r2, _ = yield from ctl("send", "setObjectTransform", "--set", 'targetObjectName="Cube"', "--set", "location=[0,0,0.5]") + for _ in range(12): # a deferred depsgraph update, if the turn left one behind, arrives within a few ticks + yield 0.1 + check("agent turns (createObject, setObjectTransform) leave humanEditSeq unmoved, also after idle ticks", + code == 0 and code2 == 0 and adapter.human_edit_seq == seq_before == 0 + and adapter.last_human_edit_seq("AgentEmpty") == 0 and adapter.last_human_edit_seq("Cube") == 0, + [code, code2, adapter.human_edit_seq, adapter._last_human_edit]) + + # ---- Edit Mode selection, read live, without leaving Edit Mode ---- + mode_edit(True) + yield 0.3 + bm = bmesh.from_edit_mesh(cube.data) + for v in bm.verts: + v.select = False + bm.verts.ensure_lookup_table() + bm.verts[0].select = True + bm.verts[3].select = True + bm.select_flush_mode() + bmesh.update_edit_mesh(cube.data) + yield 0.3 + code, r, _ = yield from ctl("look") + if r.get("lookPath"): + shutil.copy(r["lookPath"], SCRATCH / "edit-look.png") + sel = (r.get("editSelection") or [{}])[0] + check("edit selection: look reads her two selected vertices live; the mode stays Edit Mode", + code == 0 and sel.get("name") == "Cube" and sel.get("vertices") == [0, 3] and sel.get("verticesTotal") == 2 + and bpy.context.mode == "EDIT_MESH", [r.get("editSelection"), bpy.context.mode]) + code, r2, _ = yield from ctl("send", "setObjectTransform", "--set", 'targetObjectName="Cube"', "--set", "location=[0,0,3]") + check("an object intent is refused while she is in Edit Mode (ruling in force); look was not", code == 2 and r2.get("status") == "denied", + r2.get("message")) + snap = snapshot() + check("the snapshot's editSelection matches", snap["editSelection"][0]["vertices"] == [0, 3], snap["editSelection"]) + mode_edit(False) + yield 0.3 + + # ---- her edits: counters, and a follower that moves with its target ---- + follower = bpy.data.objects.new("Follower", bpy.data.meshes.new("FollowerMesh")) + bpy.context.scene.collection.objects.link(follower) + constraint = follower.constraints.new("COPY_LOCATION") + constraint.target = cube + constraint.use_y = False + yield 0.5 + # Linking an object rebuilds the depsgraph relations and Blender flags other objects in that update: collateral + # of her adding an object, recorded, not attributed to a move. + R["notes"]["after_adding_follower"] = dict(adapter._last_human_edit) + code, r, _ = yield from ctl("look") # the marker: what she does next is "since this look" + marker = r["humanEditSeq"] + cube.location.x = 2.0 # her move + yield 0.5 + cube.location.x = 4.0 + yield 0.5 + snap = snapshot() + by = {o["name"]: o["lastHumanEditSeq"] for o in snap["objects"]} + R["notes"]["after_moving_cube"] = {"marker": marker, "humanEditSeq": snap["humanEditSeq"], "last": by} + check("her moves bump humanEditSeq; Cube and its constrained Follower carry the same last sequence, the untouched Light and Camera do not", + snap["humanEditSeq"] > marker and by["Cube"] == by["Follower"] == snap["humanEditSeq"] + and by["Light"] <= marker and by["Camera"] <= marker, [marker, snap["humanEditSeq"], by]) + code, r, _ = yield from ctl("look") + check("the next look says what changed since the last one: exactly the moved Cube and its Follower", + r["humanEditsSinceLook"] >= 2 and r["editedSinceLook"] == ["Cube", "Follower"], r) + code, r, _ = yield from ctl("look") + check("and a look right after it says nothing changed since", r["humanEditsSinceLook"] == 0 and r["editedSinceLook"] == [], r) + + # ---- scene-last-writer-wins and act-then-undo ---- + seq = adapter.human_edit_seq + code, r, _ = yield from ctl("send", "setObjectTransform", "--set", 'targetObjectName="Cube"', "--set", "location=[9,9,9]") + check("after her edit, the agent's action on the same object is accepted (last writer wins)", code == 0 and r.get("status") == "accepted" + and tuple(round(c, 3) for c in bpy.data.objects["Cube"].location) == (9.0, 9.0, 9.0), r) + check("and still did not count as hers", adapter.human_edit_seq == seq, [seq, adapter.human_edit_seq]) + with bpy.context.temp_override(window=bpy.context.window_manager.windows[0]): + bpy.ops.ed.undo() # her Ctrl+Z + yield 0.5 + check("her Ctrl+Z takes the agent's step back and counts as hers", + bpy.data.objects["Cube"].location.x != 9.0 and adapter.human_edit_seq > seq, + [bpy.data.objects["Cube"].location.x, seq, adapter.human_edit_seq]) + + # ---- a popup open over the view is in the picture, as she sees it ---- + window, area, region = view3d() + with bpy.context.temp_override(window=window, area=area, region=region): + bpy.ops.wm.call_menu("INVOKE_DEFAULT", name="VIEW3D_MT_add") + yield 0.8 + code, r, _ = yield from ctl("look", "--note", "with the Add menu open") + R["notes"]["popup_look"] = r.get("lookPath") + if r.get("lookPath"): + shutil.copy(r["lookPath"], SCRATCH / "popup-look.png") # the look directory is pruned; this copy is for a human to see + check("look with a popup open: accepted, a PNG of the same region size", code == 0 and r.get("lookPath") + and list(png_size(r["lookPath"])) == R["notes"]["region_px"], r) + + # ---- prune to twenty ---- + for _ in range(24): + yield from ctl("look") + kept = sorted((SCRATCH / "out" / "look").glob("*.png")) + check("after 30 looks the look directory holds exactly the newest 20 PNGs", len(kept) == 20, len(kept)) + + # ---- refusals ---- + area.type = "OUTLINER" + yield 0.3 + code, r, _ = yield from ctl("look") + area.type = "VIEW_3D" + check("no 3D view open: look is refused naming why, with no path", code == 2 and "3D" in r.get("message", "") and r.get("lookPath", "") == "", r) + prefs.output_dir = "" + code, r, _ = yield from ctl("look") + prefs.output_dir = str(SCRATCH / "out") + check("no output directory set: look is refused naming why", code == 2 and "output" in r.get("message", ""), r) + code, r, _ = yield from ctl("look") + check("the next look works again", code == 0, r) + check("no add-on drain error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) + + +gen = flow() +wait_until = 0.0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def runner(): + global wait_until + try: + delay = next(gen) + return delay if isinstance(delay, (int, float)) and delay else 0.05 + except StopIteration: + write() + bpy.ops.wm.quit_blender() + return None + except Exception: + R.setdefault("errors", []).append(traceback.format_exc()) + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(runner, first_interval=3.0) diff --git a/surfaces/blender/tests/live/perception.result.json b/surfaces/blender/tests/live/perception.result.json new file mode 100644 index 0000000..ac8afdb --- /dev/null +++ b/surfaces/blender/tests/live/perception.result.json @@ -0,0 +1,437 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "default install: the store preference is the blend-relative default", + "ok": true, + "detail": "//.brokkr/blender-editor.ccmp" + }, + { + "name": "the default blend-relative store was created beside the saved blend", + "ok": true, + "detail": "F:\\aeth-wt\\brokkr-live-5.scratch\\.brokkr\\blender-editor.ccmp" + }, + { + "name": "the snapshot carries sessionId, humanEditSeq 0, editSelection [] and per-object lastHumanEditSeq", + "ok": true, + "detail": [ + "3e3712b94e944cb9ad4a74aafdc699bd", + 0 + ] + }, + { + "name": "look: exit 0, accepted, a lookPath PNG under /look/.png", + "ok": true, + "detail": [ + 0, + { + "commandId": "01a21ee5507774d293ea4186f58a4689", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5507774d293ea4186f58a4689.png", + "message": "Captured the 3D view to look/01a21ee5507774d293ea4186f58a4689.png.", + "note": "first look", + "objectName": "", + "observedAt": "2026-11-27T21:24:34.894575+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + ] + }, + { + "name": "look: the PNG is the 3D view's WINDOW region, not the Blender window and not the desktop", + "ok": true, + "detail": [ + [ + 1574, + 888 + ], + { + "window_px": [ + 1920, + 1009 + ], + "region_px": [ + 1574, + 888 + ], + "area_px": [ + 1574, + 888 + ], + "first_look": { + "commandId": "01a21ee5507774d293ea4186f58a4689", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5507774d293ea4186f58a4689.png", + "message": "Captured the 3D view to look/01a21ee5507774d293ea4186f58a4689.png.", + "note": "first look", + "objectName": "", + "observedAt": "2026-11-27T21:24:34.894575+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + }, + "first_look_round_trip_ms": 456, + "after_adding_follower": { + "Cube": 4, + "Light": 4, + "Camera": 4, + "AgentEmpty": 4, + "Follower": 4 + }, + "after_moving_cube": { + "marker": 4, + "humanEditSeq": 6, + "last": { + "AgentEmpty": 4, + "Camera": 4, + "Cube": 6, + "Follower": 6, + "Light": 4 + } + }, + "popup_look": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee581c771d2b3b688dfce3996f3.png" + } + ] + }, + { + "name": "look: no undo step, receipt names the session, edits so far 0, none edited since", + "ok": true, + "detail": { + "commandId": "01a21ee5507774d293ea4186f58a4689", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5507774d293ea4186f58a4689.png", + "message": "Captured the 3D view to look/01a21ee5507774d293ea4186f58a4689.png.", + "note": "first look", + "objectName": "", + "observedAt": "2026-11-27T21:24:34.894575+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "agent turns (createObject, setObjectTransform) leave humanEditSeq unmoved, also after idle ticks", + "ok": true, + "detail": [ + 0, + 0, + 0, + { + "Cube": 8, + "Light": 8, + "Camera": 8, + "AgentEmpty": 8, + "Follower": 6 + } + ] + }, + { + "name": "edit selection: look reads her two selected vertices live; the mode stays Edit Mode", + "ok": true, + "detail": [ + [ + { + "edges": [], + "edgesTotal": 0, + "faces": [], + "facesTotal": 0, + "name": "Cube", + "type": "MESH", + "vertices": [ + 0, + 3 + ], + "verticesTotal": 2 + } + ], + "EDIT_MESH" + ] + }, + { + "name": "an object intent is refused while she is in Edit Mode (ruling in force); look was not", + "ok": true, + "detail": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + }, + { + "name": "the snapshot's editSelection matches", + "ok": true, + "detail": [ + { + "name": "Cube", + "type": "MESH", + "vertices": [ + 0, + 3 + ], + "verticesTotal": 2, + "edges": [], + "edgesTotal": 0, + "faces": [], + "facesTotal": 0 + } + ] + }, + { + "name": "her moves bump humanEditSeq; Cube and its constrained Follower carry the same last sequence, the untouched Light and Camera do not", + "ok": true, + "detail": [ + 4, + 6, + { + "AgentEmpty": 4, + "Camera": 4, + "Cube": 6, + "Follower": 6, + "Light": 4 + } + ] + }, + { + "name": "the next look says what changed since the last one: exactly the moved Cube and its Follower", + "ok": true, + "detail": { + "commandId": "01a21ee56f787012b0f2312b77c478b4", + "action": "look", + "editSelection": [], + "editedSinceLook": [ + "Cube", + "Follower" + ], + "humanEditSeq": 6, + "humanEditsSinceLook": 2, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee56f787012b0f2312b77c478b4.png", + "message": "Captured the 3D view to look/01a21ee56f787012b0f2312b77c478b4.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:24:43.509761+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "and a look right after it says nothing changed since", + "ok": true, + "detail": { + "commandId": "01a21ee574627220a1ed3e104667b73c", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 6, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee574627220a1ed3e104667b73c.png", + "message": "Captured the 3D view to look/01a21ee574627220a1ed3e104667b73c.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:24:44.677117+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "after her edit, the agent's action on the same object is accepted (last writer wins)", + "ok": true, + "detail": { + "commandId": "01a21ee5788978c1b7f353ca2e2147be", + "action": "setObjectTransform", + "lookPath": "", + "message": "Blender object transform updated.", + "note": "", + "objectName": "Cube", + "observedAt": "2026-11-27T21:24:45.745214+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: setObjectTransform 2e2147be" + } + }, + { + "name": "and still did not count as hers", + "ok": true, + "detail": [ + 6, + 6 + ] + }, + { + "name": "her Ctrl+Z takes the agent's step back and counts as hers", + "ok": true, + "detail": [ + 0.0, + 6, + 8 + ] + }, + { + "name": "look with a popup open: accepted, a PNG of the same region size", + "ok": true, + "detail": { + "commandId": "01a21ee581c771d2b3b688dfce3996f3", + "action": "look", + "editSelection": [], + "editedSinceLook": [ + "AgentEmpty", + "Camera", + "Cube", + "Light" + ], + "humanEditSeq": 8, + "humanEditsSinceLook": 2, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee581c771d2b3b688dfce3996f3.png", + "message": "Captured the 3D view to look/01a21ee581c771d2b3b688dfce3996f3.png.", + "note": "with the Add menu open", + "objectName": "", + "observedAt": "2026-11-27T21:24:47.877250+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "after 30 looks the look directory holds exactly the newest 20 PNGs", + "ok": true, + "detail": 20 + }, + { + "name": "no 3D view open: look is refused naming why, with no path", + "ok": true, + "detail": { + "commandId": "01a21ee5f6b27cc2ae9dd61ee3a5bdef", + "action": "look", + "lookPath": "", + "message": "No 3D viewport is open to look at.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:25:17.807716+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "failed", + "undoLabel": "" + } + }, + { + "name": "no output directory set: look is refused naming why", + "ok": true, + "detail": { + "commandId": "01a21ee5fa117271abc6c3536e2194d3", + "action": "look", + "lookPath": "", + "message": "output directory is not configured in the add-on preferences.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:25:18.920883+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "failed", + "undoLabel": "" + } + }, + { + "name": "the next look works again", + "ok": true, + "detail": { + "commandId": "01a21ee5fe627fc3ad7ae77850c6e812", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 8, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5fe627fc3ad7ae77850c6e812.png", + "message": "Captured the 3D view to look/01a21ee5fe627fc3ad7ae77850c6e812.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:25:20.088455+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "no add-on drain error", + "ok": true, + "detail": "" + } + ], + "notes": { + "window_px": [ + 1920, + 1009 + ], + "region_px": [ + 1574, + 888 + ], + "area_px": [ + 1574, + 888 + ], + "first_look": { + "commandId": "01a21ee5507774d293ea4186f58a4689", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5507774d293ea4186f58a4689.png", + "message": "Captured the 3D view to look/01a21ee5507774d293ea4186f58a4689.png.", + "note": "first look", + "objectName": "", + "observedAt": "2026-11-27T21:24:34.894575+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + }, + "first_look_round_trip_ms": 456, + "after_adding_follower": { + "Cube": 4, + "Light": 4, + "Camera": 4, + "AgentEmpty": 4, + "Follower": 4 + }, + "after_moving_cube": { + "marker": 4, + "humanEditSeq": 6, + "last": { + "AgentEmpty": 4, + "Camera": 4, + "Cube": 6, + "Follower": 6, + "Light": 4 + } + }, + "popup_look": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee581c771d2b3b688dfce3996f3.png" + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/perception_fixes.py b/surfaces/blender/tests/live/perception_fixes.py new file mode 100644 index 0000000..7facba2 --- /dev/null +++ b/surfaces/blender/tests/live/perception_fixes.py @@ -0,0 +1,243 @@ +"""Live proof of the live-5 fix batch, in GUI Blender with the add-on installed as an extension, real brokkr-ctl looks. + +Same environment as perception.py (BROKKR_SCRATCH, BROKKR_CTL, BROKKR_CULTLIB; a fresh BLENDER_USER_RESOURCE_PATH). + blender --python perception_fixes.py -- +The driver stands in for the operator: it saves the blend, ticks the sink, sets the output directory, minimises and +restores the Blender window (Windows ShowWindow on this process's own window), moves objects, enters Edit Mode. +""" +import ctypes +import importlib +import json +import os +import statistics +import subprocess +import sys +import time +import traceback +from ctypes import wintypes +from pathlib import Path + +import bmesh +import bpy +import numpy + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +CTL = os.environ["BROKKR_CTL"] +OUT = sys.argv[sys.argv.index("--") + 1] +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "bl_ext.user_default.brokkr_bridge") +R = {"blender": bpy.app.version_string, "checks": [], "notes": {}} +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +prefs = bpy.context.preferences.addons[MODULE].preferences +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +adapter = addon.target() +STORE = SCRATCH / ".brokkr" / "blender-editor.ccmp" +ENV = dict(os.environ, EUREKA_INSTANCE="nibu", BROKKR_BLENDER_STORE=str(STORE), BROKKR_AGENT="hands") +user32 = ctypes.windll.user32 + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def fields(text): + out = {} + for line in text.splitlines(): + key, _, value = line.partition(": ") + try: + out[key] = json.loads(value) if value[:1] in "[{0123456789tf" else value + except ValueError: + out[key] = value + return out + + +def ctl(*args): + proc = subprocess.Popen([CTL, "blender", *args], env=ENV, stdout=subprocess.PIPE, text=True) + while proc.poll() is None: + yield + return proc.returncode, fields(proc.stdout.read()) + + +def blender_windows(): + found = [] + + @ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM) + def visit(hwnd, _): + owner = wintypes.DWORD() + user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) + name = ctypes.create_unicode_buffer(64) + user32.GetClassNameW(hwnd, name, 64) + if owner.value == os.getpid() and name.value == "GHOST_WindowClass" and user32.IsWindowVisible(hwnd): + found.append(hwnd) + return True + + user32.EnumWindows(visit, 0) + return found + + +def show(cmd): # 6 minimise, 9 restore + for hwnd in blender_windows(): + user32.ShowWindow(hwnd, cmd) + + +def pixels(path): + image = bpy.data.images.load(str(path)) + try: + return numpy.array(image.pixels[:], dtype=numpy.float32).reshape(image.size[1], image.size[0], 4) + finally: + bpy.data.images.remove(image) + + +def diff_box(a, b): + mask = numpy.abs(a - b).max(axis=2) > 0.02 + if not mask.any(): + return None + ys, xs = numpy.where(mask) + return [int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max())] + + +def old_scan(obj): + """The scan this fix replaces: every vertex, edge and face walked in Python.""" + mesh = bmesh.from_edit_mesh(obj.data) + out = [] + for elements in (mesh.verts, mesh.edges, mesh.faces): + chosen = [i for i, e in enumerate(elements) if e.select] + out.append((chosen[:4096], len(chosen))) + return out + + +def flow(): + bpy.ops.wm.save_as_mainfile(filepath=str(SCRATCH / "fixes.blend")) + prefs.output_dir = str(SCRATCH / "out") + prefs.auto_drain_commands = True + yield 1.0 + with bpy.context.temp_override(window=bpy.context.window_manager.windows[0]): + bpy.ops.brokkr.capture_snapshot() + cube = bpy.data.objects["Cube"] + # ---- minimised window: look must show the current scene ---- + code, a0 = yield from ctl("look") + check("window up: the region capture, source named", code == 0 and a0["captureSource"] == "region", a0) + show(6) + yield 1.0 + iconic = [bool(user32.IsIconic(h)) for h in blender_windows()] + R["notes"]["iconic_after_minimise"] = iconic + check("the Blender window is minimised (IsIconic)", iconic and all(iconic), iconic) + code, a = yield from ctl("look") + cube.location.x = 3.0 # her edit, while minimised + yield 0.5 + code, b = yield from ctl("look") + pa = pixels(a["lookPath"]) if a.get("lookPath") else None + pb = pixels(b["lookPath"]) if b.get("lookPath") else None + box = diff_box(pa, pb) if pa is not None and pb is not None else None + R["notes"]["minimised"] = {"a": a, "b": b, "diff_box": box} + check("minimised: both looks are accepted and say they were rendered offscreen", + code == 0 and a.get("captureSource") == "offscreen" and b.get("captureSource") == "offscreen", [a.get("captureSource"), b.get("captureSource")]) + check("minimised: the Cube moved by her shows in the next look (the pictures differ, in a box)", box is not None, box) + check("minimised: sceneUpdateSeq advanced between the two looks", b["sceneUpdateSeq"] > a["sceneUpdateSeq"], [a["sceneUpdateSeq"], b["sceneUpdateSeq"]]) + check("minimised: size equals the 3D region", [pb.shape[1], pb.shape[0]] == [1574, 888] if pb is not None else False, + None if pb is None else [pb.shape[1], pb.shape[0]]) + # the agent's own move while minimised, then look + code, m = yield from ctl("send", "setObjectTransform", "--set", 'targetObjectName="Cube"', "--set", "location=[-3,0,0]") + code, c = yield from ctl("look") + pc = pixels(c["lookPath"]) + check("minimised: the agent's own move is in its next look", diff_box(pb, pc) is not None and c["sceneUpdateSeq"] > b["sceneUpdateSeq"], diff_box(pb, pc)) + show(9) + yield 1.5 + code, d = yield from ctl("look") + check("restored: back to the region capture", code == 0 and d.get("captureSource") == "region", d.get("captureSource")) + + # ---- coarse attribution ---- + code, e0 = yield from ctl("look") + follower = bpy.data.objects.new("Follower", bpy.data.meshes.new("FM")) + bpy.context.scene.collection.objects.link(follower) + yield 0.5 + code, e1 = yield from ctl("look") + check("after her link of an object: the receipt says the attribution is coarse", + e1.get("editedSinceLookCoarse") is True and "all objects flagged" in e1.get("editedSinceLookNote", ""), e1) + code, e2 = yield from ctl("look") + cube.location.y = 1.0 + yield 0.5 + code, e3 = yield from ctl("look") + check("after a plain move: not coarse, only the Cube named", e3.get("editedSinceLookCoarse") is False and e3.get("editedSinceLook") == ["Cube"], e3) + with bpy.context.temp_override(window=bpy.context.window_manager.windows[0]): + bpy.ops.ed.undo() + yield 0.5 + code, e4 = yield from ctl("look") + check("after her undo: coarse", e4.get("editedSinceLookCoarse") is True, e4) + + # ---- one million vertices in Edit Mode ---- + mesh = bpy.data.meshes.new("Big") + bm = bmesh.new() + bmesh.ops.create_grid(bm, x_segments=1000, y_segments=1000, size=1.0) + bm.to_mesh(mesh) + bm.free() + big = bpy.data.objects.new("Big", mesh) + bpy.context.scene.collection.objects.link(big) + bpy.context.view_layer.objects.active = big + for o in bpy.context.view_layer.objects: + o.select_set(o is big) + yield 0.5 + window = bpy.context.window_manager.windows[0] + area = next(a for a in window.screen.areas if a.type == "VIEW_3D") + region = next(r for r in area.regions if r.type == "WINDOW") + with bpy.context.temp_override(window=window, area=area, region=region, active_object=big, object=big): + bpy.ops.object.mode_set(mode="EDIT") + bpy.ops.mesh.select_all(action="SELECT") + yield 0.5 + R["notes"]["verts"] = len(mesh.vertices) + new_ms, old_ms = [], [] + for _ in range(5): # paired, interleaved + t = time.perf_counter() + new = adapter.edit_selection() + new_ms.append((time.perf_counter() - t) * 1000) + t = time.perf_counter() + old = old_scan(big) + old_ms.append((time.perf_counter() - t) * 1000) + entry = new[0] + parts = {} + t = time.perf_counter(); bm2 = bmesh.from_edit_mesh(big.data); parts["from_edit_mesh"] = (time.perf_counter() - t) * 1000 + t = time.perf_counter(); totals = (big.data.total_vert_sel, big.data.total_edge_sel, big.data.total_face_sel); parts["totals"] = (time.perf_counter() - t) * 1000 + for name, seq in (("verts", bm2.verts), ("edges", bm2.edges), ("faces", bm2.faces)): + t = time.perf_counter(); n = 0 + for i, e in enumerate(seq): + if e.select: + n += 1 + if n == 4096: + break + parts[name] = (time.perf_counter() - t) * 1000 + R["notes"]["edit_selection_parts_ms"] = {k: round(v, 1) for k, v in parts.items()} + R["notes"]["edit_selection_ms"] = {"new": [round(x) for x in new_ms], "old": [round(x) for x in old_ms], + "new_median": round(statistics.median(new_ms)), "old_median": round(statistics.median(old_ms))} + check("1M vertices: the totals are the mesh's own and the lists are capped at 4096", + entry["verticesTotal"] == 1_002_001 and len(entry["vertices"]) == 4096 and entry["vertices"] == old[0][0] + and entry["edgesTotal"] == old[1][1] and entry["facesTotal"] == old[2][1], [entry["verticesTotal"], entry["edgesTotal"], entry["facesTotal"]]) + check("1M vertices: the read is several times faster than the full scan (medians in notes)", + statistics.median(old_ms) > 3 * statistics.median(new_ms), R["notes"]["edit_selection_ms"]) + with bpy.context.temp_override(window=window, area=area, region=region, active_object=big, object=big): + bpy.ops.object.mode_set(mode="OBJECT") + check("no add-on drain error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) + + +gen = flow() + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def runner(): + try: + delay = next(gen) + return delay if isinstance(delay, (int, float)) and delay else 0.05 + except StopIteration: + write() + bpy.ops.wm.quit_blender() + except Exception: + R.setdefault("errors", []).append(traceback.format_exc()) + write() + bpy.ops.wm.quit_blender() + + +bpy.app.timers.register(runner, first_interval=3.0) diff --git a/surfaces/blender/tests/live/perception_fixes.result.json b/surfaces/blender/tests/live/perception_fixes.result.json new file mode 100644 index 0000000..af2638c --- /dev/null +++ b/surfaces/blender/tests/live/perception_fixes.result.json @@ -0,0 +1,298 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "window up: the region capture, source named", + "ok": true, + "detail": { + "commandId": "01a21f023e60712180b8b5afee5b2621", + "action": "look", + "captureSource": "region", + "editSelection": [], + "editedSinceLook": [], + "editedSinceLookCoarse": false, + "editedSinceLookNote": "", + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f023e60712180b8b5afee5b2621.png", + "message": "Captured the 3D view to look/01a21f023e60712180b8b5afee5b2621.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:56:11.107854+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 0, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "the Blender window is minimised (IsIconic)", + "ok": true, + "detail": [ + true + ] + }, + { + "name": "minimised: both looks are accepted and say they were rendered offscreen", + "ok": true, + "detail": [ + "offscreen", + "offscreen" + ] + }, + { + "name": "minimised: the Cube moved by her shows in the next look (the pictures differ, in a box)", + "ok": true, + "detail": [ + 711, + 248, + 975, + 529 + ] + }, + { + "name": "minimised: sceneUpdateSeq advanced between the two looks", + "ok": true, + "detail": [ + 0, + 1 + ] + }, + { + "name": "minimised: size equals the 3D region", + "ok": true, + "detail": [ + 1574, + 888 + ] + }, + { + "name": "minimised: the agent's own move is in its next look", + "ok": true, + "detail": [ + 656, + 248, + 975, + 581 + ] + }, + { + "name": "restored: back to the region capture", + "ok": true, + "detail": "region" + }, + { + "name": "after her link of an object: the receipt says the attribution is coarse", + "ok": true, + "detail": { + "commandId": "01a21f02711f7571991decbd06059938", + "action": "look", + "captureSource": "region", + "editSelection": [], + "editedSinceLook": [ + "Camera", + "Cube", + "Follower", + "Light" + ], + "editedSinceLookCoarse": true, + "editedSinceLookNote": "Coarse: all objects flagged; editedSinceLook may name objects she did not touch.", + "humanEditSeq": 4, + "humanEditsSinceLook": 1, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f02711f7571991decbd06059938.png", + "message": "Captured the 3D view to look/01a21f02711f7571991decbd06059938.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:56:23.908406+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 5, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "after a plain move: not coarse, only the Cube named", + "ok": true, + "detail": { + "commandId": "01a21f027a1873a1a21df913136a4d49", + "action": "look", + "captureSource": "region", + "editSelection": [], + "editedSinceLook": [ + "Cube" + ], + "editedSinceLookCoarse": false, + "editedSinceLookNote": "", + "humanEditSeq": 5, + "humanEditsSinceLook": 1, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f027a1873a1a21df913136a4d49.png", + "message": "Captured the 3D view to look/01a21f027a1873a1a21df913136a4d49.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:56:26.306053+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 6, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "after her undo: coarse", + "ok": true, + "detail": { + "commandId": "01a21f027ec27dd0bda5c62b0974531a", + "action": "look", + "captureSource": "region", + "editSelection": [], + "editedSinceLook": [ + "Camera", + "Cube", + "Light" + ], + "editedSinceLookCoarse": true, + "editedSinceLookNote": "Coarse: all objects flagged; editedSinceLook may name objects she did not touch.", + "humanEditSeq": 7, + "humanEditsSinceLook": 2, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f027ec27dd0bda5c62b0974531a.png", + "message": "Captured the 3D view to look/01a21f027ec27dd0bda5c62b0974531a.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:56:27.505456+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 7, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "1M vertices: the totals are the mesh's own and the lists are capped at 4096", + "ok": true, + "detail": [ + 1002001, + 2002000, + 1000000 + ] + }, + { + "name": "1M vertices: the read is several times faster than the full scan (medians in notes)", + "ok": true, + "detail": { + "new": [ + 221, + 191, + 185, + 197, + 193 + ], + "old": [ + 977, + 950, + 974, + 1059, + 956 + ], + "new_median": 193, + "old_median": 974 + } + }, + { + "name": "no add-on drain error", + "ok": true, + "detail": "" + } + ], + "notes": { + "iconic_after_minimise": [ + true + ], + "minimised": { + "a": { + "commandId": "01a21f02458877a186fe6a31fe3b32d6", + "action": "look", + "captureSource": "offscreen", + "editSelection": [], + "editedSinceLook": [], + "editedSinceLookCoarse": false, + "editedSinceLookNote": "", + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f02458877a186fe6a31fe3b32d6.png", + "message": "Captured the 3D view to look/01a21f02458877a186fe6a31fe3b32d6.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:56:13.275722+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 0, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "status": "accepted", + "undoLabel": "" + }, + "b": { + "commandId": "01a21f024b1876d0a4ec6281a49404a2", + "action": "look", + "captureSource": "offscreen", + "editSelection": [], + "editedSinceLook": [ + "Cube" + ], + "editedSinceLookCoarse": false, + "editedSinceLookNote": "", + "humanEditSeq": 1, + "humanEditsSinceLook": 1, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f024b1876d0a4ec6281a49404a2.png", + "message": "Captured the 3D view to look/01a21f024b1876d0a4ec6281a49404a2.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:56:14.485857+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 1, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "status": "accepted", + "undoLabel": "" + }, + "diff_box": [ + 711, + 248, + 975, + 529 + ] + }, + "verts": 1002001, + "edit_selection_parts_ms": { + "from_edit_mesh": 0.0, + "totals": 0.0, + "verts": 24.7, + "edges": 79.6, + "faces": 33.2 + }, + "edit_selection_ms": { + "new": [ + 221, + 191, + 185, + 197, + 193 + ], + "old": [ + 977, + 950, + 974, + 1059, + 956 + ], + "new_median": 193, + "old_median": 974 + } + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_addon_ui.py b/surfaces/blender/tests/test_addon_ui.py index 04e97d3..74c8a24 100644 --- a/surfaces/blender/tests/test_addon_ui.py +++ b/surfaces/blender/tests/test_addon_ui.py @@ -32,7 +32,7 @@ def load_addon(): fake = types.ModuleType("bpy") fake.types = NS(AddonPreferences=Base, Panel=Base, Operator=Base) fake.props = props - fake.app = NS(handlers=NS(depsgraph_update_post=[]), timers=NS(is_registered=lambda f: False)) + fake.app = NS(handlers=NS(depsgraph_update_post=[], persistent=lambda f: setattr(f, "persistent", True) or f), timers=NS(is_registered=lambda f: False)) fake.utils = NS() previous = sys.modules.get("bpy") sys.modules["bpy"] = fake diff --git a/surfaces/blender/tests/test_perception.py b/surfaces/blender/tests/test_perception.py new file mode 100644 index 0000000..48ba6fb --- /dev/null +++ b/surfaces/blender/tests/test_perception.py @@ -0,0 +1,728 @@ +"""Perception: look captures her 3D view, the snapshot carries her Edit Mode selection, a session id and +human-edit sequences. A fake bpy, a fake bmesh and fake depsgraphs; no Blender. +""" +from __future__ import annotations + +import contextlib +import inspect +import os +import re +import sys +import types +import unittest +import unittest.mock +from pathlib import Path + +import test_scene_actions as ts +import test_addon_ui as ui + +bt = ts.bt +NS = types.SimpleNamespace +addon = ui.addon +BRIDGE = Path(bt.__file__).parent +PNG = b"\x89PNG\r\n\x1a\n" + b"x" * 32 + + +def area(kind, width, height, name=None): + return NS(type=kind, width=width, height=height, name=name or kind, + regions=[NS(type="HEADER"), NS(type="WINDOW", width=width, height=height)]) + + +def window(*areas): + return NS(screen=NS(areas=list(areas))) + + +class Element: + def __init__(self, selected, fake): + self._select, self._fake = selected, fake + + @property + def select(self): + self._fake.touched += 1 # every look at an element's flag costs a Python call in the real thing + return self._select + + +class Elements: + """A lazy sequence: a million of them without a million objects.""" + def __init__(self, fake, flags): + self.fake, self.flags = fake, flags + + def __iter__(self): + for flag in self.flags: + yield Element(flag, self.fake) + + +class FakeBmesh: + """bmesh.from_edit_mesh(mesh) -> verts, edges, faces that carry .select. The mesh carries + total_vert_sel and friends, as Mesh does in Edit Mode; a test may set them apart from the flags.""" + def __init__(self, meshes): + self.meshes = meshes + self.reads = 0 + self.touched = 0 + self.totals = None # override: (verts, edges, faces) the mesh claims + + def from_edit_mesh(self, mesh): + self.reads += 1 + verts, edges, faces = self.meshes[id(mesh)] + counts = self.totals or tuple(sum(1 for f in kind if f) for kind in (verts, edges, faces)) + mesh.total_vert_sel, mesh.total_edge_sel, mesh.total_face_sel = counts + return NS(verts=Elements(self, verts), edges=Elements(self, edges), faces=Elements(self, faces)) + + +class PerceptionFixture(unittest.TestCase): + """The scene fixture plus a window with a 3D view, a screenshot operator and a bmesh.""" + run_action = ts.ActionTests.run_action + + def setUp(self): + ts.ActionTests.setUp(self) + self.view = area("VIEW_3D", 1574, 888) + self.windows = [window(area("PROPERTIES", 300, 900), self.view, area("TIMELINE", 1600, 100))] + self.stack, self.shots, self.shot_result, self.shot_writes = [], [], {"FINISHED"}, True + bpy = self.bpy + bpy.context.window_manager.windows = self.windows + bpy.context.temp_override = self.override + bpy.ops.screen = NS(screenshot_area=self.screenshot) + bpy.mesh_data = NS(name="CubeMesh", vertices=[], edges=[], polygons=[], uv_layers=[], shape_keys=None) + bpy.mesh.data = bpy.mesh_data + bpy.mesh.mode = "OBJECT" + self.bmesh = FakeBmesh({id(bpy.mesh_data): ([True, False, True], [False, True], [False])}) + patch = unittest.mock.patch.dict(sys.modules, {"bmesh": self.bmesh}) + patch.start() + self.addCleanup(patch.stop) + bpy.data.scenes = [bpy.scene] + + @contextlib.contextmanager + def override(self, **kw): + self.stack.append(kw) + try: + yield + finally: + self.stack.pop() + + def screenshot(self, mode, undo, filepath): + assert (mode, undo) == ("EXEC_DEFAULT", False) # operators run with undo off + self.shots.append((dict(self.stack[-1]) if self.stack else None, filepath)) + if self.shot_writes: + Path(filepath).write_bytes(PNG) + return self.shot_result + + def look(self, **command): + return self.run_action(action="look", **command) + + def look_dir(self): + return self.root / "out" / "look" + + +class LookTests(PerceptionFixture): + def test_look_is_a_read_action(self): + receipt = self.look(commandId="look-0001") + self.assertEqual(receipt["status"], "accepted", receipt["message"]) + self.assertEqual(self.bpy.undo.pushes, []) # reads push no undo step + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(Path(receipt["lookPath"]), self.look_dir() / "look-0001.png") + self.assertEqual((self.look_dir() / "look-0001.png").read_bytes(), PNG) + self.assertEqual(self.bpy.created, []) + + def test_other_receipts_carry_an_empty_look_path(self): + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["lookPath"], "") + + def test_look_captures_only_the_largest_3d_view_and_its_window_region(self): + # the capture is scoped to one area's WINDOW region: that is what keeps the desktop and every + # other Blender area out of the picture + small = area("VIEW_3D", 400, 300) + big = area("VIEW_3D", 1600, 900) + second = window(area("OUTLINER", 3000, 3000), small) + self.windows.append(second) + self.windows[0].screen.areas.append(big) + self.look() + override, path = self.shots[0] + self.assertIs(override["area"], big) + self.assertIs(override["window"], self.windows[0]) + self.assertEqual((override["region"].type, override["region"].width), ("WINDOW", 1600)) + self.assertEqual(len(self.shots), 1) + + def test_look_in_a_second_window_uses_that_window(self): + only = area("VIEW_3D", 800, 600) + self.windows[0].screen.areas.remove(self.view) + self.windows.append(window(only)) + self.look() + self.assertIs(self.shots[0][0]["window"], self.windows[1]) + self.assertIs(self.shots[0][0]["area"], only) + + def test_look_without_a_3d_view_is_refused_and_captures_nothing(self): + self.windows[0].screen.areas.remove(self.view) + receipt = self.look() + self.assertEqual(receipt["status"], "failed") + self.assertIn("3D", receipt["message"]) + self.assertEqual((self.shots, receipt["lookPath"]), ([], "")) + self.assertFalse(self.look_dir().exists()) + self.assertEqual(self.bpy.undo.pushes, []) + + def test_look_without_an_output_directory_is_refused(self): + self.target.configure_action_dirs(str(self.root / "in"), "") + receipt = self.look() + self.assertEqual(receipt["status"], "failed") + self.assertIn("output", receipt["message"]) + self.assertEqual(self.shots, []) + + def test_a_cancelled_or_unwritten_capture_is_a_failed_receipt_with_no_path(self): + self.shot_result = {"CANCELLED"} + receipt = self.look(commandId="look-c1") + self.assertEqual((receipt["status"], receipt["lookPath"]), ("failed", "")) + self.shot_result, self.shot_writes = {"FINISHED"}, False + receipt = self.look(commandId="look-c2") + self.assertEqual((receipt["status"], receipt["lookPath"]), ("failed", "")) + + def test_look_works_in_edit_mode_and_leaves_her_mode_alone(self): + self.bpy.mesh.mode = "EDIT" + receipt = self.look() + self.assertEqual(receipt["status"], "accepted", receipt["message"]) + self.assertEqual(self.bpy.mesh.mode, "EDIT") + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "denied") + + def test_look_prunes_to_twenty(self): + # look-files-are-scratch: the newest twenty files stay, the capture just taken among them + self.look_dir().mkdir(parents=True) + for n in range(30): + old = self.look_dir() / f"old-{n:02d}.png" + old.write_bytes(PNG) + os.utime(old, (1_000_000 + n, 1_000_000 + n)) + receipt = self.look(commandId="look-new") + kept = sorted(p.name for p in self.look_dir().iterdir()) + self.assertEqual(len(kept), 20, kept) + self.assertIn("look-new.png", kept) + self.assertEqual([k for k in kept if k != "look-new.png"], [f"old-{n:02d}.png" for n in range(11, 30)]) # the newest 19 of the old + self.assertTrue(Path(receipt["lookPath"]).is_file()) + + def test_the_pruning_below_the_cap_removes_nothing(self): + for n in range(19): + self.look(commandId=f"look-{n:03d}") + self.assertEqual(len(list(self.look_dir().iterdir())), 19) + self.look(commandId="look-last") + self.assertEqual(len(list(self.look_dir().iterdir())), 20) + + def test_pruning_touches_only_png_files_directly_inside_look(self): + self.look_dir().mkdir(parents=True) + (self.root / "out" / "keep.png").write_bytes(PNG) + (self.look_dir() / "notes.txt").write_text("x") + (self.look_dir() / "dir.png").mkdir() + for n in range(25): + f = self.look_dir() / f"old-{n:02d}.png" + f.write_bytes(PNG) + os.utime(f, (1_000_000 + n, 1_000_000 + n)) + self.look() + self.assertTrue((self.root / "out" / "keep.png").exists()) + self.assertTrue((self.look_dir() / "notes.txt").exists()) + self.assertTrue((self.look_dir() / "dir.png").is_dir()) + self.assertEqual(len([p for p in self.look_dir().iterdir() if p.suffix == ".png" and p.is_file()]), 20) + + def test_a_refused_look_prunes_nothing(self): + self.look_dir().mkdir(parents=True) + for n in range(30): + (self.look_dir() / f"old-{n:02d}.png").write_bytes(PNG) + self.windows[0].screen.areas.remove(self.view) + self.look() + self.assertEqual(len(list(self.look_dir().iterdir())), 30) + + def test_a_refusal_does_not_echo_the_output_path(self): + self.windows[0].screen.areas.remove(self.view) + self.assertNotIn(str(self.root), self.look()["message"]) + + +def rich(obj): + """What the real _object_snapshot reads of an object.""" + for key, value in dict(library=None, location=(0.0, 0.0, 0.0), rotation_euler=(0.0, 0.0, 0.0), scale=(1.0, 1.0, 1.0), + parent=None, users_collection=[], material_slots=[], modifiers=[], constraints=[]).items(): + setattr(obj, key, value) + obj.visible_get = lambda: True + obj.items = lambda: [] + obj.mode = getattr(obj, "mode", "OBJECT") + return obj + + +class _All: + """Endless selected flags: a scan that does not stop at the cap would never return.""" + def __iter__(self): + return iter([True] * 5_000_000) + + +class _First: + """A huge mesh whose first n elements are selected: reading past them would show in the touches.""" + def __init__(self, n): + self.n = n + + def __iter__(self): + for i in range(10_000_000): + yield i < self.n + + +class LookFreshnessTests(PerceptionFixture): + """A minimised Blender stops redrawing, so a region capture is a stale frame. Then the view is drawn offscreen.""" + + def setUp(self): + super().setUp() + self.drawn = True + self.target._windows_drawn = lambda: self.drawn + self.offscreen_calls = [] + self.pixels = bytes([10, 20, 30, 255, 40, 50, 60, 255, # bottom row first, as GL reads it + 70, 80, 90, 255, 100, 110, 120, 255]) + + def render(window, area, region): + self.offscreen_calls.append((window, area, region)) + return 2, 2, self.pixels + + self.target._render_view_offscreen = render + + def test_a_drawn_window_is_captured_from_the_region_and_says_so(self): + receipt = self.look() + self.assertEqual((receipt["captureSource"], len(self.shots), self.offscreen_calls), ("region", 1, [])) + + def test_a_window_that_is_not_drawn_is_rendered_offscreen_and_says_so(self): + self.drawn = False + receipt = self.look(commandId="look-off") + self.assertEqual(receipt["status"], "accepted", receipt["message"]) + self.assertEqual(receipt["captureSource"], "offscreen") + self.assertEqual(self.shots, []) # the stale framebuffer is never read + window, area, region = self.offscreen_calls[0] + self.assertIs(window, self.windows[0]) + self.assertIs(area, self.view) + self.assertEqual(region.type, "WINDOW") + self.assertEqual(Path(receipt["lookPath"]), self.look_dir() / "look-off.png") + + def test_the_offscreen_file_is_a_png_of_the_pixels_top_row_first(self): + import struct + import zlib + self.drawn = False + data = Path(self.look()["lookPath"]).read_bytes() + self.assertEqual(data[:8], b"\x89PNG\r\n\x1a\n") + chunks, at = {}, 8 + while at < len(data): + size, kind = struct.unpack(">I4s", data[at:at + 8]) + chunks[kind] = data[at + 8:at + 8 + size] + at += 12 + size + self.assertEqual(struct.unpack(">IIBBBBB", chunks[b"IHDR"]), (2, 2, 8, 6, 0, 0, 0)) + raw = zlib.decompress(chunks[b"IDAT"]) + rows = [raw[i:i + 9] for i in range(0, len(raw), 9)] # a filter byte, then 2 RGBA pixels + self.assertEqual([r[0] for r in rows], [0, 0]) + self.assertEqual(rows[0][1:], self.pixels[8:]) # the top of the picture is the last row GL read + self.assertEqual(rows[1][1:], self.pixels[:8]) + + def test_an_offscreen_failure_is_a_refusal_never_a_stale_picture(self): + self.drawn = False + + def boom(*a): + raise RuntimeError("no gpu") + + self.target._render_view_offscreen = boom + receipt = self.look() + self.assertEqual((receipt["status"], receipt["lookPath"]), ("failed", "")) + self.assertEqual(self.shots, []) + self.assertEqual(list(self.look_dir().glob("*.png")) if self.look_dir().exists() else [], []) + + def test_the_receipt_names_the_scene_update_the_picture_reflects(self): + first = self.look()["sceneUpdateSeq"] + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertEqual(self.look()["sceneUpdateSeq"], first + 1) + + def test_agent_turn_updates_move_the_scene_update_sequence_too(self): + # it counts every update, hers or the agent's: what the capture reflects is the whole scene + before = self.target.scene_update_seq + self.target.agent_turn = True + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.target.agent_turn = False + self.assertEqual((self.target.scene_update_seq, self.target.human_edit_seq), (before + 1, 0)) + + def test_an_update_without_flags_still_counts_as_a_scene_update(self): + before = self.target.scene_update_seq + self.target.track_human_edits(depsgraph(update("Cube"))) + self.assertEqual(self.target.scene_update_seq, before + 1) + + def test_a_new_session_restarts_the_scene_update_sequence(self): + self.target.track_human_edits(depsgraph(update("Cube"))) + self.target.renew_session() + self.assertEqual(self.target.scene_update_seq, 0) + + def test_the_default_window_check_assumes_drawn_off_windows(self): + target = bt.BrokkrBlenderTarget(self.bpy) + with unittest.mock.patch.object(bt.sys, "platform", "linux"): + self.assertTrue(target._windows_drawn()) + + +class LookPathTests(PerceptionFixture): + def test_a_path_that_changes_after_the_directory_is_made_is_refused_and_nothing_is_captured(self): + # the second check is the guard for the gap between the first check and the capture + real = bt.sa.resolve_inside + calls = [] + + def swapped(root, candidate, label, **kw): + path = real(root, candidate, label, **kw) + calls.append(path) + return path if len(calls) == 1 else path.with_name("elsewhere.png") + + with unittest.mock.patch.object(bt.sa, "resolve_inside", swapped): + receipt = self.look() + self.assertEqual((receipt["status"], len(calls)), ("failed", 2)) + self.assertIn("changed", receipt["message"]) + self.assertEqual((self.shots, receipt["lookPath"]), ([], "")) + + def test_the_prune_does_not_follow_a_link_to_a_file(self): + # a link named *.png is not a plain file: it is never counted or removed through + removed = [] + + class Entry: + def __init__(self, name, mtime, link): + self.name, self.path, self._mtime, self._link = name, "dir/" + name, mtime, link + + def is_file(self, follow_symlinks=True): + return follow_symlinks or not self._link # a link is a file only when followed + + def stat(self, follow_symlinks=True): + return NS(st_mtime_ns=self._mtime) + + entries = [Entry(f"f{n:02d}.png", n, False) for n in range(21)] + [Entry("link.png", 0, True)] + + class Scan: + def __enter__(self): + return iter(entries) + + def __exit__(self, *a): + return False + + with unittest.mock.patch.object(bt.os, "scandir", lambda d: Scan()), \ + unittest.mock.patch.object(bt.os, "unlink", removed.append): + bt.BrokkrBlenderTarget._prune_looks(Path("dir")) + self.assertEqual(removed, ["dir/f00.png"]) + + +class CoarseAttributionTests(PerceptionFixture): + NOTE_WORDS = ("all objects flagged",) + + def edits(self, since_look="nibu/hands"): + return self.look(requestedBy=since_look) + + def test_a_precise_edit_is_not_marked_coarse(self): + self.edits() + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + receipt = self.edits() + self.assertEqual((receipt["editedSinceLookCoarse"], receipt["editedSinceLookNote"]), (False, "")) + + def test_an_update_that_flags_every_object_is_marked_coarse_and_says_why(self): + self.edits() + self.target.track_human_edits(depsgraph(*[update(n, transform=True, geometry=True) for n in ("Cube", "Lamp", "Cam")])) + receipt = self.edits() + self.assertTrue(receipt["editedSinceLookCoarse"]) + self.assertIn("all objects flagged", receipt["editedSinceLookNote"]) + self.assertEqual(receipt["editedSinceLook"], ["Cam", "Cube", "Lamp"]) # the semantics are unchanged + + def test_an_undo_or_redo_is_coarse(self): + self.edits() + self.target.note_undo_redo() + receipt = self.edits() + self.assertTrue(receipt["editedSinceLookCoarse"]) + self.assertIn("undo", receipt["editedSinceLookNote"]) + + def test_coarse_clears_with_the_next_look_and_comes_back_only_for_a_new_coarse_edit(self): + self.edits() + self.target.note_undo_redo() + self.assertTrue(self.edits()["editedSinceLookCoarse"]) + self.assertFalse(self.edits()["editedSinceLookCoarse"]) + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertFalse(self.edits()["editedSinceLookCoarse"]) + + def test_each_agent_has_its_own_coarse_since_its_last_look(self): + self.edits("nibu/hands") + self.target.note_undo_redo() + self.edits("nibu/hands") + self.assertTrue(self.edits("nibu/soul")["editedSinceLookCoarse"]) # soul has not looked since + + def test_a_new_session_forgets_coarse(self): + self.target.note_undo_redo() + self.target.renew_session() + self.assertFalse(self.edits()["editedSinceLookCoarse"]) + + def test_one_object_in_a_scene_of_one_is_not_coarse(self): + # nothing to over-attribute when there is only one object to name + for name in ("Cam", "Lamp"): + del self.bpy.data.objects[name] + self.edits() + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertFalse(self.edits()["editedSinceLookCoarse"]) + + +class EditSelectionTests(PerceptionFixture): + def snapshot(self): + for obj in self.bpy.data.objects: + rich(obj) + self.bpy.camera_data.name, self.bpy.light_data.name, self.bpy.camera_data.angle = "CamData", "LightData", 0.6 + self.bpy.app.version = (5, 3, 0) + self.bpy.data.filepath = "" + for name in ("collections", "materials", "images"): + setattr(self.bpy.data, name, []) + self.bpy.scene.frame_current = self.bpy.scene.frame_start = self.bpy.scene.frame_end = 1 + self.bpy.scene.collection = None + context = NS(selected_objects=[], active_object=None, scene=self.bpy.scene, mode="EDIT_MESH") + with unittest.mock.patch.object(self.target, "_evaluated_snapshot", return_value=None): + return self.target.capture_snapshot(context, False) + + def test_selection_is_read_from_the_edit_mesh_without_leaving_edit_mode(self): + self.bpy.mesh.mode = "EDIT" + selection = self.target.edit_selection() + self.assertEqual(selection, [{"name": "Cube", "type": "MESH", + "vertices": [0, 2], "verticesTotal": 2, + "edges": [1], "edgesTotal": 1, + "faces": [], "facesTotal": 0}]) + self.assertEqual(self.bpy.mesh.mode, "EDIT") + self.assertEqual(self.bmesh.reads, 1) + + def test_nothing_in_edit_mode_is_an_empty_list_and_reads_no_mesh(self): + self.assertEqual(self.target.edit_selection(), []) + self.assertEqual(self.bmesh.reads, 0) + + def test_each_list_is_capped_at_4096_with_the_true_total_beside_it(self): + self.bpy.mesh.mode = "EDIT" + self.bmesh.meshes[id(self.bpy.mesh_data)] = ([True] * 5000, [False] * 5000 + [True], [True] * 4096) + entry = self.target.edit_selection()[0] + self.assertEqual((len(entry["vertices"]), entry["verticesTotal"]), (4096, 5000)) + self.assertEqual(entry["vertices"][:3], [0, 1, 2]) + self.assertEqual((entry["edges"], entry["edgesTotal"]), ([5000], 1)) + self.assertEqual((len(entry["faces"]), entry["facesTotal"]), (4096, 4096)) + + def test_totals_come_from_the_mesh_and_the_scan_stops_at_the_cap(self): + # a million selected of each kind: the totals are the mesh's own counts, and each kind is read only up to the cap + self.bpy.mesh.mode = "EDIT" + self.bmesh.meshes[id(self.bpy.mesh_data)] = (_All(), _All(), _All()) + self.bmesh.totals = (1_000_000, 2_000_000, 3_000_000) + entry = self.target.edit_selection()[0] + self.assertEqual((entry["verticesTotal"], entry["edgesTotal"], entry["facesTotal"]), (1_000_000, 2_000_000, 3_000_000)) + self.assertEqual([len(entry[k]) for k in ("vertices", "edges", "faces")], [4096] * 3) + self.assertEqual(self.bmesh.touched, 3 * 4096) + + def test_a_small_selection_in_a_big_mesh_stops_when_every_selected_element_is_found(self): + self.bpy.mesh.mode = "EDIT" + self.bmesh.meshes[id(self.bpy.mesh_data)] = (_First(3), _First(2), _First(0)) + entry = self.target.edit_selection()[0] + self.assertEqual((entry["vertices"], entry["edges"], entry["faces"]), ([0, 1, 2], [0, 1], [])) + self.assertEqual(self.bmesh.touched, 3 + 2) # no scan past the last selected one, none at all when the total is zero + + def test_every_object_in_edit_mode_is_listed_and_a_non_mesh_says_unsupported(self): + self.bpy.mesh.mode = "EDIT" + self.bpy.cam.mode = "EDIT" + names = {e["name"]: e for e in self.target.edit_selection()} + self.assertEqual(sorted(names), ["Cam", "Cube"]) + self.assertEqual(names["Cam"], {"name": "Cam", "type": "CAMERA", "unsupported": True}) + + def test_the_snapshot_carries_selection_session_and_sequences(self): + self.bpy.mesh.mode = "EDIT" + snap = self.snapshot() + self.assertEqual(snap["editSelection"][0]["vertices"], [0, 2]) + self.assertEqual(snap["sessionId"], self.target.session_id) + self.assertEqual(snap["humanEditSeq"], 0) + self.assertTrue(all(o["lastHumanEditSeq"] == 0 for o in snap["objects"])) + self.assertEqual(self.snapshot()["sessionId"], snap["sessionId"]) + + def test_the_object_snapshot_carries_the_last_human_edit_sequence(self): + self.target._last_human_edit["Cube"] = 7 + objects = {o["name"]: o["lastHumanEditSeq"] for o in self.snapshot()["objects"]} + self.assertEqual(objects, {"Cam": 0, "Lamp": 0, "Cube": 7}) + + +def update(name, *, kind="OBJECT", transform=False, geometry=False, shading=False): + return NS(id=NS(name=name, id_type=kind), is_updated_transform=transform, is_updated_geometry=geometry, + is_updated_shading=shading) + + +def depsgraph(*updates): + return NS(updates=list(updates)) + + +class HumanEditTests(PerceptionFixture): + def test_an_update_outside_an_agent_turn_bumps_the_sequence_and_stamps_the_object(self): + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertEqual(self.target.human_edit_seq, 1) + self.assertEqual(self.target.last_human_edit_seq("Cube"), 1) + self.target.track_human_edits(depsgraph(update("Lamp", geometry=True))) + self.assertEqual((self.target.human_edit_seq, self.target.last_human_edit_seq("Lamp")), (2, 2)) + self.assertEqual(self.target.last_human_edit_seq("Cube"), 1) + + def test_a_constrained_follower_moves_with_its_target(self): + # the update names both objects, the follower's carrying the transform flag only because of its constraint + self.target.track_human_edits(depsgraph(update("Cube", transform=True), update("Follower", transform=True))) + self.assertEqual(self.target.last_human_edit_seq("Follower"), self.target.last_human_edit_seq("Cube")) + self.assertEqual(self.target.human_edit_seq, 1) + + def test_geometry_and_shading_count_and_an_unflagged_presence_does_not(self): + self.target.track_human_edits(depsgraph(update("Cube", shading=True))) + self.assertEqual(self.target.last_human_edit_seq("Cube"), 1) + self.target.track_human_edits(depsgraph(update("Lamp"), update("Cam"))) # named, not changed + self.assertEqual((self.target.human_edit_seq, self.target.last_human_edit_seq("Lamp")), (1, 0)) + + def test_only_objects_are_stamped(self): + self.target.track_human_edits(depsgraph(update("Mesh", kind="MESH", geometry=True))) + self.assertEqual(self.target.human_edit_seq, 0) + + def test_agent_turn_updates_do_not_count_as_human(self): + # the update arrives inside the turn (probe depsgraph-timing), so the in-turn flag attributes it + original = self.bpy.ops.object.empty_add + + def add_and_update(*a, **kw): + original(*a, **kw) + self.target.track_human_edits(depsgraph(update("Empty", transform=True, geometry=True))) + + self.bpy.ops.object.empty_add = add_and_update + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "accepted") + self.assertEqual(self.target.human_edit_seq, 0) + self.assertEqual(self.target.last_human_edit_seq("Empty"), 0) + self.target.track_human_edits(depsgraph(update("Empty", transform=True))) # after the turn: hers + self.assertEqual(self.target.human_edit_seq, 1) + + def test_a_failed_turn_still_ends_the_turn_for_attribution(self): + def boom(*a, **kw): + raise RuntimeError("half done") + self.bpy.ops.object.empty_add = boom + self.run_action(action="createObject", objectType="EMPTY") + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertEqual(self.target.human_edit_seq, 1) + + def test_undo_and_redo_bump_the_sequence_without_naming_an_object(self): + self.target.note_undo_redo() + self.target.note_undo_redo() + self.assertEqual(self.target.human_edit_seq, 2) + self.assertEqual(self.target._last_human_edit, {}) + + def test_human_edit_seq_never_refuses(self): + # scene-last-writer-wins: an intent after her edit is accepted, and so is one that targets what she edited + rich(self.bpy.mesh) + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + receipt = self.run_action(action="setObjectTransform", objectName="Cube", location=[0, 0, 5]) + self.assertEqual(receipt["status"], "accepted", receipt["message"]) + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "accepted") + self.assertEqual(len(self.bpy.undo.pushes), 2) + + def test_the_admission_code_never_reads_the_sequences(self): + source = inspect.getsource(bt.BrokkrBlenderTarget.run_intent) + self.assertEqual(re.findall(r"humanEditSeq|lastHumanEditSeq|human_edit", source), []) + self.assertEqual(re.findall(r"human_edit|session_id", inspect.getsource(bt.BrokkrBlenderTarget._dispatch)), []) + + def test_a_new_session_resets_the_counters_and_mints_a_new_id(self): + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + before = self.target.session_id + self.target.renew_session() + self.assertNotEqual(self.target.session_id, before) + self.assertEqual((self.target.human_edit_seq, self.target.last_human_edit_seq("Cube")), (0, 0)) + + def test_two_targets_mint_different_session_ids(self): + self.assertNotEqual(bt.BrokkrBlenderTarget(self.bpy).session_id, self.target.session_id) + + +class LookReportsHerEditsTests(PerceptionFixture): + def test_the_receipt_carries_the_session_the_selection_and_the_edits_since_the_last_look(self): + self.bpy.mesh.mode = "EDIT" + first = self.look(requestedBy="nibu/hands") + self.assertEqual(first["sessionId"], self.target.session_id) + self.assertEqual((first["humanEditSeq"], first["humanEditsSinceLook"], first["editedSinceLook"]), (0, 0, [])) + self.assertEqual(first["editSelection"][0]["vertices"], [0, 2]) + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.target.track_human_edits(depsgraph(update("Lamp", geometry=True))) + second = self.look(requestedBy="nibu/hands") + self.assertEqual((second["humanEditSeq"], second["humanEditsSinceLook"]), (2, 2)) + self.assertEqual(second["editedSinceLook"], ["Cube", "Lamp"]) + third = self.look(requestedBy="nibu/hands") + self.assertEqual((third["humanEditsSinceLook"], third["editedSinceLook"]), (0, [])) + + def test_each_agent_has_its_own_last_look(self): + self.look(requestedBy="nibu/hands") + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertEqual(self.look(requestedBy="nibu/hands")["humanEditsSinceLook"], 1) + self.assertEqual(self.look(requestedBy="nibu/soul")["humanEditsSinceLook"], 1) # soul's first look: all of it + + def test_a_new_session_forgets_the_last_look(self): + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.look(requestedBy="nibu/hands") # her edit number 1 is now seen + self.target.renew_session() + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) # number 1 again, in the new session + receipt = self.look(requestedBy="nibu/hands") + self.assertEqual((receipt["humanEditSeq"], receipt["humanEditsSinceLook"], receipt["editedSinceLook"]), (1, 1, ["Cube"])) + + def test_a_refused_look_does_not_move_the_last_look(self): + self.look(requestedBy="nibu/hands") + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.windows[0].screen.areas.remove(self.view) + self.look(requestedBy="nibu/hands") + self.windows[0].screen.areas.append(self.view) + self.assertEqual(self.look(requestedBy="nibu/hands")["humanEditsSinceLook"], 1) + + +class StorePathTests(unittest.TestCase): + def test_the_default_blend_relative_store_is_found_where_the_blend_file_is(self): + # live-3 Low: store_exists must resolve the default '//.brokkr/...' against the blend file, as the add-on does + import tempfile + with tempfile.TemporaryDirectory() as tmp: + blend = Path(tmp).resolve() + (blend / ".brokkr").mkdir() + (blend / ".brokkr" / "blender-editor.ccmp").write_bytes(b"") + + def abspath(p): + return str(blend / p[2:]) if p.startswith("//") else p + + target = bt.BrokkrBlenderTarget(NS(path=NS(abspath=abspath))) + self.assertTrue(target.store_exists(bt.DEFAULT_CULTMESH_CACHE_PATH)) + self.assertTrue(target.store_exists("")) # an empty preference means the default + self.assertEqual(Path(target.resolve_cache_path(bt.DEFAULT_CULTMESH_CACHE_PATH)), + blend / ".brokkr" / "blender-editor.ccmp") + (blend / ".brokkr" / "blender-editor.ccmp").unlink() + self.assertFalse(target.store_exists(bt.DEFAULT_CULTMESH_CACHE_PATH)) + + def test_the_preference_default_is_the_blend_relative_path_the_target_resolves(self): + prop = addon.BrokkrPreferences.__annotations__["cultmesh_cache_path"] + self.assertEqual(prop.kwargs["default"], "//.brokkr/blender-editor.ccmp") + self.assertEqual(bt.DEFAULT_CULTMESH_CACHE_PATH, prop.kwargs["default"]) + + +class HandlerWiringTests(unittest.TestCase): + def setUp(self): + self.lists = {name: [] for name in ("depsgraph_update_post", "undo_post", "redo_post", "load_post")} + handlers = NS(persistent=lambda f: setattr(f, "persistent", True) or f, **self.lists) + self.fake = NS(app=NS(handlers=handlers, timers=NS(is_registered=lambda f: False, register=lambda *a, **k: None, + unregister=lambda f: None)), + utils=NS(register_class=lambda c: None, unregister_class=lambda c: None)) + patch = unittest.mock.patch.multiple(addon.bpy, app=self.fake.app, utils=self.fake.utils) + patch.start() + self.addCleanup(patch.stop) + self.target = bt.BrokkrBlenderTarget(NS(path=NS(abspath=lambda p: p))) + addon._target = self.target + self.addCleanup(lambda: setattr(addon, "_target", None)) + + def test_register_adds_persistent_human_edit_handlers_and_unregister_removes_them(self): + addon.register() + for name in ("depsgraph_update_post", "undo_post", "redo_post", "load_post"): + ours = [h for h in self.lists[name] if getattr(h, "persistent", False)] + self.assertEqual(len(ours), 1, name) + self.assertIn(addon._auto_capture, self.lists["depsgraph_update_post"]) # the snapshot handler stays + self.assertEqual(len(self.lists["depsgraph_update_post"]), 2) + addon.register() # twice adds nothing + self.assertEqual(len(self.lists["depsgraph_update_post"]), 2) + addon.unregister() + self.assertEqual([len(v) for v in self.lists.values()], [0, 0, 0, 0]) + + def test_the_handlers_feed_the_target(self): + addon.register() + addon._target = self.target + track = next(h for h in self.lists["depsgraph_update_post"] if getattr(h, "persistent", False)) + track(None, depsgraph(update("Cube", transform=True))) + self.assertEqual(self.target.human_edit_seq, 1) + self.lists["undo_post"][0](None) + self.lists["redo_post"][0](None) + self.assertEqual(self.target.human_edit_seq, 3) + before = self.target.session_id + self.lists["load_post"][0](None) + self.assertNotEqual(self.target.session_id, before) + self.assertEqual(self.target.human_edit_seq, 0) + + def test_the_human_edit_tracker_does_not_depend_on_auto_capture(self): + # always on: it reads no preference at all + source = inspect.getsource(addon._track_human_edits) + self.assertNotRegex(source, r"auto_capture|preferences") + + +if __name__ == "__main__": + unittest.main() diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index 6c73c67..fcc2b64 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -67,7 +67,10 @@ def fake_render(): class Objects(dict): - """bpy.data.objects: a mapping with keys() and get().""" + """bpy.data.objects: a mapping with keys() and get(); like bpy_prop_collection, iterating it yields the objects.""" + + def __iter__(self): + return iter(self.values()) class FakeUndo: