From 8d5b580e5e0b6bf3d2d48326f32d419610592d6d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 28 Jun 2026 11:23:04 +0100 Subject: [PATCH] Add Brokkr prefab mirror pipeline --- README.md | 28 + brokkr-daemon/src/main.rs | 22 + surfaces/blender/brokkr_bridge/__init__.py | 129 ++ .../blender/brokkr_bridge/blender_target.py | 271 +++ surfaces/blender/docs/install.md | 26 +- .../Editor/BrokkrCultMeshMirror.cs | 42 + .../Editor/BrokkrDaemonBridgePostprocessor.cs | 16 + .../BrokkrDaemonBridgePostprocessor.cs.meta | 2 + .../Editor/BrokkrDaemonBridgeReloadHook.cs | 13 + .../BrokkrDaemonBridgeReloadHook.cs.meta | 2 + .../Editor/BrokkrEditorDaemonBridge.cs | 143 ++ .../Editor/BrokkrEditorDaemonBridge.cs.meta | 2 + .../Editor/BrokkrSettings.cs | 6 + .../Editor/BrokkrUnitySnapshotBuilder.cs | 204 ++ .../Editor/BrokkrWindow.cs | 87 + .../Runtime/BrokkrHostSnapshot.cs | 50 + surfaces/unity/README.md | 50 +- tools/brokkr-unity-cache.py | 1658 +++++++++++++++++ tools/check.ps1 | 13 +- 19 files changed, 2756 insertions(+), 8 deletions(-) create mode 100644 surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrDaemonBridgePostprocessor.cs create mode 100644 surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrDaemonBridgePostprocessor.cs.meta create mode 100644 surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrDaemonBridgeReloadHook.cs create mode 100644 surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrDaemonBridgeReloadHook.cs.meta create mode 100644 surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrEditorDaemonBridge.cs create mode 100644 surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrEditorDaemonBridge.cs.meta create mode 100644 tools/brokkr-unity-cache.py diff --git a/README.md b/README.md index 3b7a0e9..6aec6cf 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,34 @@ timeline bindings, and receipts. Unity and Blender editor plugins publish those documents through CultMesh so a daemon sync loop can translate them into host-owned command intents without stealing scene truth. +## Prefab CDN Pipeline + +Brokkr is the authoring front-end for CultMesh's distributed CDN entity prefab +pipeline. Unity prefabs are migration input only. The intended flow is: + +1. In Unity, open `GameCult > Brokkr`, enter a prefab asset path, and click + `Mirror Prefab To Blender`. +2. Unity writes a `brokkr.unity.prefab_mirror_snapshot.v0` document containing + the prefab hierarchy, transforms, components, mesh requirements, material + requirements, and texture requirements. +3. In Blender, click `Import Unity Prefab Mirror` to create a Blender collection + from that snapshot. From this point forward, Blender owns the renderable + entity authoring state. +4. In Blender, configure meshes, transforms, materials, metadata, sockets, and + runtime component hints in the collection. +5. Click `Publish Prefab Snapshot` to write a collection-scoped + `brokkr.prefab.snapshot.v0` document. +6. A deployer consumes the Brokkr prefab snapshot, publishes referenced binary + payloads as CultMesh CDN artifacts, and writes a + `CultMeshEntityPrefabPackage`. +7. Unity, TypeScript, and later runtimes consume the same CultMesh package and + lower it into native runtime objects. + +The CDN is content-addressed and signed at the CultMesh layer. Brokkr does not +turn players into authority for assets; it produces deploy snapshots that the +CDN can distribute through central servers, LAN peers, or visible opt-out peer +asset sharing. + ## Unity Smoke ```powershell diff --git a/brokkr-daemon/src/main.rs b/brokkr-daemon/src/main.rs index f4a58dd..25ca659 100644 --- a/brokkr-daemon/src/main.rs +++ b/brokkr-daemon/src/main.rs @@ -294,6 +294,12 @@ fn build_provider_advertisement() -> ProviderAdvertisement { owner: "brokkr.unity_editor", record_hint: "unity/quest-routes/{routeId}", }, + MirrorDocument { + name: "Unity prefab mirror snapshot", + schema: "brokkr.unity.prefab_mirror_snapshot.v0", + owner: "brokkr.unity_editor", + record_hint: "prefabs/unity-mirrors/{snapshotId}", + }, MirrorDocument { name: "Unity warped video frame", schema: "brokkr.unity.warped_video_frame.v0", @@ -306,6 +312,12 @@ fn build_provider_advertisement() -> ProviderAdvertisement { owner: "brokkr.blender_editor", record_hint: "blender/host/current", }, + MirrorDocument { + name: "Brokkr prefab snapshot", + schema: "brokkr.prefab.snapshot.v0", + owner: "brokkr.blender_editor", + record_hint: "prefabs/snapshots/{snapshotId}", + }, MirrorDocument { name: "Blender command intent", schema: "brokkr.blender.command_intent.v0", @@ -2048,6 +2060,11 @@ mod tests { "brokkr.blender_editor", "blender/host/current" ))); + assert!(documents.contains(&( + "brokkr.prefab.snapshot.v0", + "brokkr.blender_editor", + "prefabs/snapshots/{snapshotId}" + ))); assert!(documents.contains(&( "brokkr.blender.command_intent.v0", "Verse command clients", @@ -2058,6 +2075,11 @@ mod tests { "brokkr.blender_editor", "blender/receipts/{commandId}" ))); + assert!(documents.contains(&( + "brokkr.unity.prefab_mirror_snapshot.v0", + "brokkr.unity_editor", + "prefabs/unity-mirrors/{snapshotId}" + ))); } #[test] diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index e692a49..36b6716 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -100,6 +100,24 @@ class BrokkrPreferences(bpy.types.AddonPreferences): description="Maximum encoded snapshot response size", ) + prefab_id: bpy.props.StringProperty( + name="Prefab Id", + default="", + description="Logical prefab id to publish; blank uses brokkr/{collection}", + ) + + prefab_version: bpy.props.StringProperty( + name="Prefab Version", + default="authoring", + description="Authoring version for the published prefab snapshot", + ) + + prefab_collection_name: bpy.props.StringProperty( + name="Prefab Collection", + default="", + description="Blender collection to publish; blank uses the active collection", + ) + sync_session_id: bpy.props.StringProperty( name="Sync Session", default="default", @@ -262,6 +280,9 @@ class BrokkrPreferences(bpy.types.AddonPreferences): layout.prop(self, "serve_port") layout.prop(self, "max_snapshot_documents") layout.prop(self, "max_snapshot_bytes") + layout.prop(self, "prefab_id") + layout.prop(self, "prefab_version") + layout.prop(self, "prefab_collection_name") layout.prop(self, "sync_session_id") layout.prop(self, "sync_display_name") layout.prop(self, "unity_object_id") @@ -310,6 +331,7 @@ class BROKKR_PT_status(bpy.types.Panel): row = layout.row(align=True) row.operator("brokkr.capture_snapshot", icon="FILE_REFRESH") + row.operator("brokkr.publish_prefab_snapshot", icon="PACKAGE") row.operator("brokkr.drain_commands", icon="PLAY") layout.prop(prefs, "auto_drain_commands") @@ -317,10 +339,19 @@ class BROKKR_PT_status(bpy.types.Panel): server_row.operator("brokkr.start_server", icon="NETWORK_DRIVE") server_row.operator("brokkr.stop_server", icon="CANCEL") + prefab_box = layout.box() + prefab_box.label(text="Prefab Deploy") + prefab_box.prop(prefs, "prefab_id") + prefab_box.prop(prefs, "prefab_version") + prefab_box.prop(prefs, "prefab_collection_name") + prefab_box.operator("brokkr.import_unity_prefab_mirror", icon="IMPORT") + prefab_box.operator("brokkr.publish_prefab_snapshot", icon="PACKAGE") + sync_row = layout.row(align=True) sync_row.operator("brokkr.publish_object_sync", icon="LINKED") sync_row.operator("brokkr.publish_timeline_sync", icon="TIME") sync_row.operator("brokkr.refresh_sync_receipt", icon="FILE_REFRESH") + sync_row.operator("brokkr.refresh_sync_policy", icon="PRESET") object_box = layout.box() object_box.label(text="Object Sync") @@ -367,6 +398,38 @@ class BROKKR_PT_status(bpy.types.Panel): layout.label(text=f"Materials: {adapter.last_snapshot.get('materialCount', 0)}") layout.label(text=f"Selected: {len(adapter.last_snapshot.get('selectedObjectNames', []))}") + if adapter.last_prefab_snapshot: + layout.separator() + layout.label(text=f"Prefab: {adapter.last_prefab_snapshot.get('prefabId', '')}") + layout.label(text=f"Collection: {adapter.last_prefab_snapshot.get('collectionName', '')}") + layout.label(text=f"Prefab objects: {len(adapter.last_prefab_snapshot.get('objects', []))}") + + if adapter.last_unity_prefab_import: + layout.separator() + layout.label(text=f"Imported Unity Prefab: {adapter.last_unity_prefab_import.get('prefabId', '')}") + layout.label(text=f"Import Collection: {adapter.last_unity_prefab_import.get('collectionName', '')}") + layout.label(text=f"Imported objects: {adapter.last_unity_prefab_import.get('objectCount', 0)}") + + if adapter.last_sync_policy: + policy = adapter.last_sync_policy + layout.separator() + layout.label(text="Published Sync Policy") + layout.label(text=f"Object bindings: {len(policy.get('objectBindings', []))}") + for binding in policy.get("objectBindings", [])[:5]: + label = binding.get("displayName", binding.get("bindingId", "")) + state = "" if binding.get("enabled", False) else " (disabled)" + layout.label(text=f"{label}{state}: {binding.get('authority', '')}") + layout.label(text=f"Timeline bindings: {len(policy.get('timelineBindings', []))}") + for binding in policy.get("timelineBindings", [])[:5]: + label = binding.get("displayName", binding.get("bindingId", "")) + state = "" if binding.get("enabled", False) else " (disabled)" + layout.label(text=f"{label}{state}: {binding.get('blenderActionName', '')}") + layout.label(text=f"Sync vars: {len(policy.get('syncVars', []))}") + for sync_var in policy.get("syncVars", [])[:8]: + label = sync_var.get("displayName", sync_var.get("syncVarId", "")) + state = "" if sync_var.get("enabled", False) else " (disabled)" + layout.label(text=f"{label}{state}: {sync_var.get('kind', '')} {sync_var.get('authority', '')}") + if adapter.last_receipt: layout.separator() layout.label(text=f"Last receipt: {adapter.last_receipt.get('status', '')}") @@ -418,6 +481,48 @@ class BROKKR_OT_drain_commands(bpy.types.Operator): return {"FINISHED"} +class BROKKR_OT_publish_prefab_snapshot(bpy.types.Operator): + bl_idname = "brokkr.publish_prefab_snapshot" + bl_label = "Publish Prefab Snapshot" + bl_description = "Publish the active Blender collection as a deployable Brokkr prefab snapshot" + + def execute(self, context): + prefs = context.preferences.addons[__name__].preferences + snapshot = target().publish_prefab_snapshot( + context, + prefs.cultmesh_cache_path, + prefs.cultlib_py_src, + prefs.debug_mirror_root, + prefs.prefab_id, + prefs.prefab_version, + prefs.prefab_collection_name, + ) + self.report( + {"INFO"}, + f"Brokkr prefab snapshot: {snapshot['prefabId']} ({len(snapshot.get('objects', []))} object(s))", + ) + return {"FINISHED"} + + +class BROKKR_OT_import_unity_prefab_mirror(bpy.types.Operator): + bl_idname = "brokkr.import_unity_prefab_mirror" + bl_label = "Import Unity Prefab Mirror" + bl_description = "Import the latest Unity prefab mirror snapshot into a Blender collection" + + def execute(self, context): + prefs = context.preferences.addons[__name__].preferences + result = target().import_latest_unity_prefab_mirror( + context, + prefs.cultmesh_cache_path, + prefs.cultlib_py_src, + ) + self.report( + {"INFO"}, + f"Imported Unity prefab mirror: {result['collectionName']} ({result['objectCount']} object(s))", + ) + return {"FINISHED"} + + class BROKKR_OT_start_server(bpy.types.Operator): bl_idname = "brokkr.start_server" bl_label = "Start Server" @@ -517,6 +622,27 @@ class BROKKR_OT_refresh_sync_receipt(bpy.types.Operator): return {"FINISHED"} +class BROKKR_OT_refresh_sync_policy(bpy.types.Operator): + bl_idname = "brokkr.refresh_sync_policy" + bl_label = "Refresh Sync Policy" + bl_description = "Read published Brokkr sync bindings and sync vars from the Blender mirror" + + def execute(self, context): + prefs = context.preferences.addons[__name__].preferences + policy = target().refresh_sync_policy( + prefs.cultmesh_cache_path, + prefs.cultlib_py_src, + ) + self.report( + {"INFO"}, + "Brokkr sync policy: " + f"{len(policy.get('objectBindings', []))} object binding(s), " + f"{len(policy.get('timelineBindings', []))} timeline binding(s), " + f"{len(policy.get('syncVars', []))} sync var(s)", + ) + return {"FINISHED"} + + class BROKKR_OT_publish_sync_var(bpy.types.Operator): bl_idname = "brokkr.publish_sync_var" bl_label = "Publish Sync Var" @@ -586,11 +712,14 @@ classes = ( BROKKR_PT_status, BROKKR_OT_capture_snapshot, BROKKR_OT_drain_commands, + BROKKR_OT_publish_prefab_snapshot, + BROKKR_OT_import_unity_prefab_mirror, BROKKR_OT_start_server, BROKKR_OT_stop_server, BROKKR_OT_publish_object_sync, BROKKR_OT_publish_timeline_sync, BROKKR_OT_refresh_sync_receipt, + BROKKR_OT_refresh_sync_policy, BROKKR_OT_publish_sync_var, ) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 8ccb08c..25e18ae 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import hashlib import math import os import sys @@ -24,6 +25,8 @@ SYNC_OBJECT_BINDING_SCHEMA = "brokkr.sync.object_binding.v0" SYNC_VAR_SCHEMA = "brokkr.sync.var.v0" SYNC_TIMELINE_BINDING_SCHEMA = "brokkr.sync.timeline_binding.v0" SYNC_RECEIPT_SCHEMA = "brokkr.sync.receipt.v0" +PREFAB_SNAPSHOT_SCHEMA = "brokkr.prefab.snapshot.v0" +UNITY_PREFAB_MIRROR_SCHEMA = "brokkr.unity.prefab_mirror_snapshot.v0" CAPABILITIES = ( "cultcache.mirror.publish", @@ -52,6 +55,9 @@ class BrokkrBlenderTarget: self.last_snapshot: dict[str, Any] | None = None self.last_receipt: dict[str, Any] | None = None self.last_sync_receipt: dict[str, Any] | None = None + self.last_sync_policy: dict[str, Any] | None = None + self.last_prefab_snapshot: dict[str, Any] | None = None + self.last_unity_prefab_import: dict[str, Any] | None = None self.last_auto_drain_error: str = "" self._node_key: tuple[str, str, str] | None = None self._node: Any | None = None @@ -80,6 +86,33 @@ class BrokkrBlenderTarget: self.last_snapshot = snapshot return snapshot + def publish_prefab_snapshot( + self, + context: Any, + cache_path: str, + cultlib_py_src: str, + debug_mirror_root: str, + prefab_id: str, + version: str, + collection_name: str, + ) -> dict[str, Any]: + collection = self._resolve_prefab_collection(context, collection_name) + snapshot = self.capture_prefab_snapshot(context, collection, prefab_id, version) + node, documents = self._open_node(cache_path, cultlib_py_src) + node.database.put( + documents["prefab_snapshot"], + f"prefabs/snapshots/{snapshot['snapshotId']}", + snapshot, + ) + if debug_mirror_root: + self._write_debug_document( + debug_mirror_root, + f"prefabs/snapshots/{snapshot['snapshotId']}.json", + snapshot, + ) + self.last_prefab_snapshot = snapshot + return snapshot + def drain_commands( self, context: Any, @@ -134,6 +167,100 @@ class BrokkrBlenderTarget: ) return self.last_sync_receipt + def refresh_sync_policy( + self, + cache_path: str, + cultlib_py_src: str, + ) -> dict[str, Any]: + node, _documents = self._open_node(cache_path, cultlib_py_src) + snapshot = node.database.snapshot() + object_bindings = sorted( + snapshot.get(SYNC_OBJECT_BINDING_SCHEMA, {}).values(), + key=lambda binding: binding.get("displayName", ""), + ) + timeline_bindings = sorted( + snapshot.get(SYNC_TIMELINE_BINDING_SCHEMA, {}).values(), + key=lambda binding: binding.get("displayName", ""), + ) + sync_vars = sorted( + snapshot.get(SYNC_VAR_SCHEMA, {}).values(), + key=lambda sync_var: ( + sync_var.get("bindingId", ""), + sync_var.get("displayName", ""), + ), + ) + self.last_sync_policy = { + "objectBindings": object_bindings, + "timelineBindings": timeline_bindings, + "syncVars": sync_vars, + } + return self.last_sync_policy + + def import_latest_unity_prefab_mirror( + self, + context: Any, + cache_path: str, + cultlib_py_src: str, + ) -> dict[str, Any]: + node, _documents = self._open_node(cache_path, cultlib_py_src) + snapshots = node.database.snapshot().get(UNITY_PREFAB_MIRROR_SCHEMA, {}) + if not snapshots: + raise RuntimeError("No Unity prefab mirror snapshots were found in the Brokkr mirror.") + + snapshot = max( + snapshots.values(), + key=lambda item: item.get("observedAt", ""), + ) + result = self.import_unity_prefab_mirror(context, snapshot) + self.last_unity_prefab_import = result + return result + + def import_unity_prefab_mirror(self, context: Any, snapshot: dict[str, Any]) -> dict[str, Any]: + collection_name = snapshot.get("blenderCollectionName") or snapshot.get("prefabName") or "Unity Prefab Mirror" + collection = self.bpy.data.collections.get(collection_name) + if collection is None: + collection = self.bpy.data.collections.new(collection_name) + context.scene.collection.children.link(collection) + + collection["brokkr.source"] = "unity-prefab-mirror" + collection["brokkr.prefabId"] = snapshot.get("prefabId", "") + collection["brokkr.prefabAssetPath"] = snapshot.get("prefabAssetPath", "") + collection["brokkr.contentHash"] = snapshot.get("contentHash", "") + + material_names_by_asset: dict[str, str] = {} + for asset in snapshot.get("assets", []): + if asset.get("role") != "material": + continue + material = self.bpy.data.materials.get(asset.get("name", "")) + if material is None: + material = self.bpy.data.materials.new(asset.get("name", "") or asset.get("assetId", "Unity Material")) + material["brokkr.unityAssetId"] = asset.get("assetId", "") + material["brokkr.unityAssetPath"] = asset.get("unityAssetPath", "") + material_names_by_asset[asset.get("assetId", "")] = material.name + + objects_by_node: dict[str, Any] = {} + for node in snapshot.get("nodes", []): + obj = self._create_or_update_prefab_node_object(collection, node, material_names_by_asset) + objects_by_node[node.get("nodeId", "")] = obj + + for node in snapshot.get("nodes", []): + parent_id = node.get("parentNodeId", "") + obj = objects_by_node.get(node.get("nodeId", "")) + if obj is None: + continue + obj.parent = objects_by_node.get(parent_id) if parent_id else None + + result = { + "schema": "brokkr.blender.prefab_import_receipt.v0", + "status": "accepted", + "snapshotId": snapshot.get("snapshotId", ""), + "prefabId": snapshot.get("prefabId", ""), + "collectionName": collection.name, + "objectCount": len(objects_by_node), + "observedAt": _now(), + } + return result + def publish_object_sync( self, context: Any, @@ -395,6 +522,58 @@ class BrokkrBlenderTarget: "collections": [self._collection_snapshot(collection) for collection in bpy.data.collections], } + def capture_prefab_snapshot( + self, + context: Any, + collection: Any, + prefab_id: str, + version: str, + ) -> dict[str, Any]: + scene = context.scene + objects = list(self._collection_objects_recursive(collection)) + object_names = {obj.name for obj in objects} + material_names = sorted({ + slot.material.name + for obj in objects + for slot in getattr(obj, "material_slots", []) + if slot.material + }) + materials = [ + self._material_snapshot(self.bpy.data.materials[name]) + for name in material_names + if name in self.bpy.data.materials + ] + child_collections = list(self._collections_recursive(collection)) + normalized_prefab_id = prefab_id or f"brokkr/{collection.name}" + snapshot = { + "schema": PREFAB_SNAPSHOT_SCHEMA, + "snapshotId": "", + "prefabId": normalized_prefab_id, + "version": version or "authoring", + "providerId": PROVIDER_ID, + "toolKind": TOOL_KIND, + "sourceTool": "brokkr.blender", + "projectPath": self.bpy.data.filepath, + "sceneName": scene.name if scene else "", + "collectionName": collection.name, + "observedAt": _now(), + "objects": [self._object_snapshot(obj) for obj in objects], + "materials": materials, + "collections": [self._collection_snapshot(item) for item in child_collections], + "rootObjectNames": [ + obj.name for obj in collection.objects + if obj.name in object_names and (obj.parent is None or obj.parent.name not in object_names) + ], + "metadata": { + "groundTruth": "blender-collection", + "deployTarget": "cultmesh-cdn", + }, + } + content_hash = _stable_hash(snapshot) + snapshot["contentHash"] = content_hash + snapshot["snapshotId"] = _stable_id("prefab", normalized_prefab_id, version or "authoring", content_hash[:16]) + return snapshot + def execute_command(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: action = command.get("action", "") try: @@ -626,6 +805,8 @@ class BrokkrBlenderTarget: "host_snapshot": cultcache.define_document_type(HOST_SNAPSHOT_SCHEMA), "command_intent": cultcache.define_document_type(COMMAND_INTENT_SCHEMA), "command_receipt": cultcache.define_document_type(COMMAND_RECEIPT_SCHEMA), + "prefab_snapshot": cultcache.define_document_type(PREFAB_SNAPSHOT_SCHEMA), + "unity_prefab_mirror": cultcache.define_document_type(UNITY_PREFAB_MIRROR_SCHEMA), "sync_session": cultcache.define_document_type(SYNC_SESSION_SCHEMA), "sync_object_binding": cultcache.define_document_type(SYNC_OBJECT_BINDING_SCHEMA), "sync_var": cultcache.define_document_type(SYNC_VAR_SCHEMA), @@ -690,6 +871,77 @@ class BrokkrBlenderTarget: "updatedAt": updated_at, }) + def _create_or_update_prefab_node_object( + self, + collection: Any, + node: dict[str, Any], + material_names_by_asset: dict[str, str], + ) -> Any: + name = node.get("name", "") or node.get("nodeId", "") or "Unity Prefab Node" + existing = self.bpy.data.objects.get(name) + mesh_asset_id = node.get("meshAssetId", "") + if existing is None: + if mesh_asset_id: + mesh = self.bpy.data.meshes.new(f"{name} Mesh Placeholder") + existing = self.bpy.data.objects.new(name, mesh) + else: + existing = self.bpy.data.objects.new(name, None) + existing.empty_display_type = "PLAIN_AXES" + collection.objects.link(existing) + elif existing.name not in collection.objects.keys(): + try: + collection.objects.link(existing) + except RuntimeError: + pass + + existing.location = _parse_vector_string(node.get("localPosition", ""), (0.0, 0.0, 0.0)) + existing.rotation_euler = _parse_vector_string(node.get("localEulerAngles", ""), (0.0, 0.0, 0.0), degrees=True) + existing.scale = _parse_vector_string(node.get("localScale", ""), (1.0, 1.0, 1.0)) + existing.hide_viewport = not bool(node.get("activeSelf", True)) + existing.hide_render = not bool(node.get("activeSelf", True)) + existing["brokkr.source"] = "unity-prefab-mirror" + existing["brokkr.nodeId"] = node.get("nodeId", "") + existing["brokkr.unityPath"] = node.get("path", "") + existing["brokkr.meshAssetId"] = mesh_asset_id + existing["brokkr.materialAssetIds"] = ",".join(node.get("materialAssetIds", [])) + existing["brokkr.components"] = json.dumps(node.get("components", []), sort_keys=True) + + if existing.data is not None and hasattr(existing.data, "materials"): + existing.data.materials.clear() + for asset_id in node.get("materialAssetIds", []): + material_name = material_names_by_asset.get(asset_id, "") + material = self.bpy.data.materials.get(material_name) if material_name else None + if material is not None: + existing.data.materials.append(material) + + return existing + + def _resolve_prefab_collection(self, context: Any, collection_name: str) -> Any: + if collection_name: + collection = self.bpy.data.collections.get(collection_name) + if collection is None: + raise RuntimeError(f"Prefab collection was not found: {collection_name}") + return collection + if context.collection is not None: + return context.collection + if context.active_object is not None and context.active_object.users_collection: + return context.active_object.users_collection[0] + raise RuntimeError("Select an object or active collection before publishing a prefab snapshot.") + + def _collections_recursive(self, collection: Any) -> Iterable[Any]: + yield collection + for child in collection.children: + yield from self._collections_recursive(child) + + def _collection_objects_recursive(self, collection: Any) -> Iterable[Any]: + seen: set[str] = set() + for item in self._collections_recursive(collection): + for obj in item.objects: + if obj.name in seen: + continue + seen.add(obj.name) + yield obj + def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: source = Path(cultlib_py_src or DEFAULT_CULTLIB_PY_SRC) @@ -725,6 +977,20 @@ def _vector(value: Any, size: int, fallback: Any) -> tuple[float, ...]: return tuple(result) +def _parse_vector_string(value: str, fallback: tuple[float, float, float], degrees: bool = False) -> tuple[float, float, float]: + if not value: + return fallback + try: + parts = [float(part.strip()) for part in str(value).split(",")[:3]] + while len(parts) < 3: + parts.append(0.0) + if degrees: + parts = [math.radians(part) for part in parts] + return (parts[0], parts[1], parts[2]) + except ValueError: + return fallback + + def _jsonable(value: Any) -> Any: if value is None or isinstance(value, (str, int, float, bool)): if isinstance(value, float) and not math.isfinite(value): @@ -771,6 +1037,11 @@ def _stable_id(*parts: str) -> str: return ":".join(str(part or "").replace(" ", "_").replace("/", "_").replace("\\", "_") for part in parts) +def _stable_hash(value: Any) -> str: + payload = json.dumps(value, sort_keys=True, separators=(",", ":"), default=str).encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + def _active_action_name(context: Any) -> str: obj = context.active_object if obj is not None and obj.animation_data and obj.animation_data.action: diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 52b50bb..46c6b8e 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -57,9 +57,33 @@ owns the mirror state. `Refresh Sync Receipt` to show the latest daemon sync pass observed in the Blender mirror. Keep `Auto Drain Commands` enabled while `sync-loop` is running if Blender should continuously consume daemon command intents. -13. To publish an ad hoc sync variable, fill the `Ad Hoc Sync Var` fields in +13. Click `Refresh Sync Policy` to inspect the object bindings, timeline + bindings, and sync vars currently published in the Blender mirror. +14. To publish an ad hoc sync variable, fill the `Ad Hoc Sync Var` fields in the sidebar or add-on preferences and click `Publish Sync Var`. +## CDN Prefab Authoring + +Brokkr Blender is the authoring side of the CultMesh CDN prefab pipeline. +Existing Unity prefabs are mirrored into Blender once; after that, Blender owns +the renderable entity configuration. + +1. In Unity, click `Mirror Prefab To Blender` for the legacy prefab. +2. In Blender, click `Import Unity Prefab Mirror`. The add-on reads the latest + `brokkr.unity.prefab_mirror_snapshot.v0` document from the shared mirror and + creates or updates a collection. +3. Configure the collection in Blender: meshes, transforms, materials, sockets, + custom properties, and runtime component metadata. +4. Click `Publish Prefab Snapshot`. The add-on writes a + `brokkr.prefab.snapshot.v0` record containing the collection-scoped deploy + snapshot. +5. A deployer consumes that snapshot, publishes binary payloads as CultMesh CDN + artifacts, and writes a `CultMeshEntityPrefabPackage`. + +The Blender deploy snapshot is not a Unity prefab file and not an FBX dump. It +is a portable authoring snapshot that downstream Unity and TypeScript clients +can receive through CultMesh CDN and lower into their own runtime object model. + Admitted command actions: - `createObject` diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs index c8077bf..df584da 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Threading.Tasks; using GameCult.Caching; using GameCult.Mesh; @@ -68,6 +69,16 @@ namespace GameCult.Brokkr.Editor await node.FlushAsync(soft: true); } + internal async Task PublishPrefabMirrorSnapshotAsync(BrokkrUnityPrefabMirrorSnapshot snapshot) + { + RequireRunning(); + var key = string.IsNullOrWhiteSpace(snapshot.snapshotId) + ? $"prefabs/unity-mirrors/{Guid.NewGuid():N}" + : $"prefabs/unity-mirrors/{snapshot.snapshotId}"; + await node.Database.PutAsync(new CultRecordKey(key), snapshot); + await node.FlushAsync(soft: true); + } + internal async Task PublishReceiptAsync(BrokkrUnityCommandReceipt receipt) { RequireRunning(); @@ -148,6 +159,30 @@ namespace GameCult.Brokkr.Editor return false; } + internal BrokkrSyncPolicyView SnapshotSyncPolicy() + { + RequireRunning(); + var documents = node.Database.Cache.AllStoredDocuments + .Select(stored => stored.Document) + .ToArray(); + return new BrokkrSyncPolicyView + { + objectBindings = documents + .OfType() + .OrderBy(binding => binding.displayName, StringComparer.Ordinal) + .ToArray(), + timelineBindings = documents + .OfType() + .OrderBy(binding => binding.displayName, StringComparer.Ordinal) + .ToArray(), + syncVars = documents + .OfType() + .OrderBy(syncVar => syncVar.bindingId, StringComparer.Ordinal) + .ThenBy(syncVar => syncVar.displayName, StringComparer.Ordinal) + .ToArray() + }; + } + internal static string DefaultCachePath() { var projectRoot = Application.dataPath.Replace("/Assets", ""); @@ -172,4 +207,11 @@ namespace GameCult.Brokkr.Editor node = null; } } + + internal sealed class BrokkrSyncPolicyView + { + internal BrokkrSyncObjectBinding[] objectBindings = Array.Empty(); + internal BrokkrSyncTimelineBinding[] timelineBindings = Array.Empty(); + internal BrokkrSyncVar[] syncVars = Array.Empty(); + } } diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrDaemonBridgePostprocessor.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrDaemonBridgePostprocessor.cs new file mode 100644 index 0000000..dab8195 --- /dev/null +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrDaemonBridgePostprocessor.cs @@ -0,0 +1,16 @@ +using UnityEditor; + +namespace GameCult.Brokkr.Editor +{ + public sealed class BrokkrDaemonBridgePostprocessor : AssetPostprocessor + { + private static void OnPostprocessAllAssets( + string[] importedAssets, + string[] deletedAssets, + string[] movedAssets, + string[] movedFromAssetPaths) + { + BrokkrEditorDaemonBridge.InitializeDaemonBridge(); + } + } +} diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrDaemonBridgePostprocessor.cs.meta b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrDaemonBridgePostprocessor.cs.meta new file mode 100644 index 0000000..a928992 --- /dev/null +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrDaemonBridgePostprocessor.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 742fe602d7748754e88e5463e8f75f20 \ No newline at end of file diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrDaemonBridgeReloadHook.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrDaemonBridgeReloadHook.cs new file mode 100644 index 0000000..f9d6f80 --- /dev/null +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrDaemonBridgeReloadHook.cs @@ -0,0 +1,13 @@ +using UnityEditor.Callbacks; + +namespace GameCult.Brokkr.Editor +{ + public static class BrokkrDaemonBridgeReloadHook + { + [DidReloadScripts] + public static void StartAfterScriptsReload() + { + BrokkrEditorDaemonBridge.InitializeDaemonBridge(); + } + } +} diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrDaemonBridgeReloadHook.cs.meta b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrDaemonBridgeReloadHook.cs.meta new file mode 100644 index 0000000..911ec04 --- /dev/null +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrDaemonBridgeReloadHook.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 00e96afda2ec964429638d77bfcf91a3 \ No newline at end of file diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrEditorDaemonBridge.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrEditorDaemonBridge.cs new file mode 100644 index 0000000..0c1d247 --- /dev/null +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrEditorDaemonBridge.cs @@ -0,0 +1,143 @@ +using System; +using UnityEditor; + +namespace GameCult.Brokkr.Editor +{ + [InitializeOnLoad] + public static class BrokkrEditorDaemonBridge + { + private const string AutoStartKey = "GameCult.Brokkr.AutoStartMirror"; + private static readonly BrokkrCultMeshMirror Mirror = new(); + private static double nextPollAt; + private static bool startQueued; + private static bool starting; + + static BrokkrEditorDaemonBridge() + { + Register(); + } + + [InitializeOnLoadMethod] + public static void InitializeDaemonBridge() + { + Register(); + EditorApplication.delayCall += EnsureStarted; + } + + private static void Register() + { + EditorApplication.update -= OnEditorUpdate; + EditorApplication.update += OnEditorUpdate; + } + + private static bool AutoStart + { + get => EditorPrefs.GetBool(AutoStartKey, true); + set => EditorPrefs.SetBool(AutoStartKey, value); + } + + [MenuItem("GameCult/Brokkr/Start Daemon Bridge")] + private static void StartDaemonBridge() + { + AutoStart = true; + EnsureStarted(); + } + + [MenuItem("GameCult/Brokkr/Stop Daemon Bridge")] + private static void StopDaemonBridge() + { + AutoStart = false; + Mirror.Dispose(); + } + + private static async void EnsureStarted() + { + if (!AutoStart || starting || Mirror.IsRunning) + { + return; + } + + starting = true; + try + { + BrokkrSettings.AutoPollCommands = true; + UnityEngine.Debug.Log($"Brokkr daemon bridge starting at {BrokkrSettings.CultMeshCachePath}"); + await Mirror.StartAsync(BrokkrSettings.CultMeshCachePath); + await PublishSnapshot(); + UnityEngine.Debug.Log($"Brokkr daemon bridge started at {Mirror.CachePath}"); + } + catch (Exception error) + { + UnityEngine.Debug.LogWarning($"Brokkr daemon bridge failed to start: {error.Message}"); + } + finally + { + starting = false; + } + } + + private static void OnEditorUpdate() + { + if (!AutoStart) + { + return; + } + + if (!Mirror.IsRunning) + { + if (!startQueued) + { + startQueued = true; + EditorApplication.delayCall += () => + { + startQueued = false; + EnsureStarted(); + }; + } + + return; + } + + if (EditorApplication.timeSinceStartup < nextPollAt) + { + return; + } + + nextPollAt = EditorApplication.timeSinceStartup + 1.0; + DrainCommands(); + DrainSyncReceipts(); + } + + private static void DrainCommands() + { + while (Mirror.TryDequeueCommand(out var command) && command != null) + { + if (string.IsNullOrWhiteSpace(command.commandId)) + { + continue; + } + + var receipt = BrokkrUnityCommandExecutor.Execute(command); + Mirror.PublishReceiptAsync(receipt).GetAwaiter().GetResult(); + PublishSnapshot().GetAwaiter().GetResult(); + } + } + + private static void DrainSyncReceipts() + { + while (Mirror.TryDequeueSyncReceipt(out _)) + { + } + } + + private static async System.Threading.Tasks.Task PublishSnapshot() + { + if (!Mirror.IsRunning) + { + return; + } + + await Mirror.PublishSnapshotAsync(BrokkrUnitySnapshotBuilder.Capture()); + } + } +} diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrEditorDaemonBridge.cs.meta b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrEditorDaemonBridge.cs.meta new file mode 100644 index 0000000..596bd3a --- /dev/null +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrEditorDaemonBridge.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 84750a54e28cc50499c465bc07a42769 \ No newline at end of file diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrSettings.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrSettings.cs index 8676897..4b3118b 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrSettings.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrSettings.cs @@ -152,6 +152,12 @@ namespace GameCult.Brokkr.Editor set => EditorPrefs.SetString("GameCult.Brokkr.PrefabVariantPath", value); } + internal static string PrefabMirrorCollectionName + { + get => EditorPrefs.GetString("GameCult.Brokkr.PrefabMirrorCollectionName", ""); + set => EditorPrefs.SetString("GameCult.Brokkr.PrefabMirrorCollectionName", value); + } + internal static string AdHocSyncVarBindingId { get => EditorPrefs.GetString("GameCult.Brokkr.AdHocSyncVarBindingId", ""); diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs index b26c164..4b08eb5 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs @@ -3,6 +3,8 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; +using System.Security.Cryptography; +using System.Text; using GameCult.Brokkr; using UnityEditor; using UnityEditor.SceneManagement; @@ -47,6 +49,46 @@ namespace GameCult.Brokkr.Editor }; } + internal static BrokkrUnityPrefabMirrorSnapshot CapturePrefabMirror( + string prefabAssetPath, + string blenderCollectionName) + { + if (string.IsNullOrWhiteSpace(prefabAssetPath)) + { + throw new InvalidOperationException("Enter a prefab asset path before mirroring to Blender."); + } + + var prefab = AssetDatabase.LoadAssetAtPath(prefabAssetPath.Trim()); + if (prefab == null) + { + throw new InvalidOperationException($"Prefab was not found: {prefabAssetPath}"); + } + + var nodes = new List(); + var assets = new Dictionary(StringComparer.Ordinal); + CapturePrefabNode(prefab, "", prefab.name, nodes, assets); + + var observedAt = DateTime.UtcNow.ToString("O"); + var prefabId = AssetDatabase.AssetPathToGUID(prefabAssetPath); + var snapshot = new BrokkrUnityPrefabMirrorSnapshot + { + prefabId = string.IsNullOrWhiteSpace(prefabId) ? prefab.name : prefabId, + prefabAssetPath = prefabAssetPath.Trim(), + prefabName = prefab.name, + blenderCollectionName = string.IsNullOrWhiteSpace(blenderCollectionName) + ? prefab.name + : blenderCollectionName.Trim(), + observedAt = observedAt, + nodes = nodes.ToArray(), + assets = assets.Values + .OrderBy(asset => asset.assetId, StringComparer.Ordinal) + .ToArray() + }; + snapshot.contentHash = ComputePrefabMirrorHash(snapshot); + snapshot.snapshotId = StableId("unity-prefab", snapshot.prefabId, snapshot.contentHash.Substring(0, 16)); + return snapshot; + } + private static BrokkrGameObjectSnapshot[] CaptureSceneObjects() { var objects = new List(); @@ -101,6 +143,126 @@ namespace GameCult.Brokkr.Editor } } + private static void CapturePrefabNode( + GameObject gameObject, + string parentNodeId, + string path, + ICollection nodes, + IDictionary assets) + { + var nodeId = StableId("node", path); + var meshAssetId = CaptureMeshRequirement(gameObject, assets); + var materialAssetIds = CaptureMaterialRequirements(gameObject, assets); + nodes.Add(new BrokkrUnityPrefabNodeSnapshot + { + nodeId = nodeId, + parentNodeId = parentNodeId, + name = gameObject.name, + path = path, + activeSelf = gameObject.activeSelf, + tag = gameObject.tag, + layer = gameObject.layer, + localPosition = WriteVector3(gameObject.transform.localPosition), + localEulerAngles = WriteVector3(gameObject.transform.localEulerAngles), + localScale = WriteVector3(gameObject.transform.localScale), + meshAssetId = meshAssetId, + materialAssetIds = materialAssetIds, + components = CaptureComponents(gameObject) + }); + + for (var childIndex = 0; childIndex < gameObject.transform.childCount; childIndex++) + { + var child = gameObject.transform.GetChild(childIndex).gameObject; + CapturePrefabNode(child, nodeId, $"{path}/{child.name}", nodes, assets); + } + } + + private static string CaptureMeshRequirement( + GameObject gameObject, + IDictionary assets) + { + var mesh = gameObject.GetComponent()?.sharedMesh; + if (mesh == null) + { + var skinned = gameObject.GetComponent(); + mesh = skinned != null ? skinned.sharedMesh : null; + } + + return mesh == null ? "" : AddAssetRequirement(assets, "mesh", mesh); + } + + private static string[] CaptureMaterialRequirements( + GameObject gameObject, + IDictionary assets) + { + var renderer = gameObject.GetComponent(); + if (renderer == null) + { + return Array.Empty(); + } + + var result = new List(); + foreach (var material in renderer.sharedMaterials.Where(material => material != null)) + { + var materialId = AddAssetRequirement(assets, "material", material); + result.Add(materialId); + CaptureTextureRequirements(material, assets); + } + + return result.ToArray(); + } + + private static void CaptureTextureRequirements( + Material material, + IDictionary assets) + { + var shader = material.shader; + if (shader == null) + { + return; + } + + var propertyCount = ShaderUtil.GetPropertyCount(shader); + for (var index = 0; index < propertyCount; index++) + { + if (ShaderUtil.GetPropertyType(shader, index) != ShaderUtil.ShaderPropertyType.TexEnv) + { + continue; + } + + var propertyName = ShaderUtil.GetPropertyName(shader, index); + var texture = material.GetTexture(propertyName); + if (texture != null) + { + AddAssetRequirement(assets, "texture", texture); + } + } + } + + private static string AddAssetRequirement( + IDictionary assets, + string role, + UnityEngine.Object asset) + { + var path = AssetDatabase.GetAssetPath(asset); + var guid = string.IsNullOrWhiteSpace(path) ? "" : AssetDatabase.AssetPathToGUID(path); + var assetId = StableId(role, string.IsNullOrWhiteSpace(guid) ? asset.name : guid); + if (!assets.ContainsKey(assetId)) + { + assets[assetId] = new BrokkrUnityPrefabAssetRequirement + { + assetId = assetId, + role = role, + unityAssetPath = path, + guid = guid, + name = asset.name, + typeName = asset.GetType().FullName + }; + } + + return assetId; + } + private static BrokkrComponentSnapshot[] CaptureComponents(GameObject gameObject) { return gameObject.GetComponents() @@ -260,5 +422,47 @@ namespace GameCult.Brokkr.Editor value.y.ToString(CultureInfo.InvariantCulture), value.z.ToString(CultureInfo.InvariantCulture)); } + + private static string ComputePrefabMirrorHash(BrokkrUnityPrefabMirrorSnapshot snapshot) + { + var builder = new StringBuilder(); + builder.Append(snapshot.prefabId).Append('\u001F') + .Append(snapshot.prefabAssetPath).Append('\u001F') + .Append(snapshot.prefabName).Append('\u001F') + .Append(snapshot.blenderCollectionName).Append('\u001F'); + foreach (var node in snapshot.nodes.OrderBy(node => node.nodeId, StringComparer.Ordinal)) + { + builder.Append(node.nodeId).Append('\u001E') + .Append(node.parentNodeId).Append('\u001E') + .Append(node.path).Append('\u001E') + .Append(node.localPosition).Append('\u001E') + .Append(node.localEulerAngles).Append('\u001E') + .Append(node.localScale).Append('\u001E') + .Append(node.meshAssetId).Append('\u001E') + .Append(string.Join(",", node.materialAssetIds.OrderBy(value => value, StringComparer.Ordinal))) + .Append('\u001F'); + } + + foreach (var asset in snapshot.assets.OrderBy(asset => asset.assetId, StringComparer.Ordinal)) + { + builder.Append(asset.assetId).Append('\u001E') + .Append(asset.role).Append('\u001E') + .Append(asset.unityAssetPath).Append('\u001E') + .Append(asset.guid).Append('\u001F'); + } + + using var sha256 = SHA256.Create(); + return string.Concat(sha256 + .ComputeHash(Encoding.UTF8.GetBytes(builder.ToString())) + .Select(value => value.ToString("x2", CultureInfo.InvariantCulture))); + } + + private static string StableId(params string[] parts) + { + return string.Join(":", parts.Select(part => (part ?? "") + .Replace(" ", "_") + .Replace("/", "_") + .Replace("\\", "_"))); + } } } diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrWindow.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrWindow.cs index 28a3d42..5e62098 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrWindow.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrWindow.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using GameCult.Brokkr; using UnityEditor; using UnityEngine; @@ -13,6 +14,7 @@ namespace GameCult.Brokkr.Editor private bool autoPollCommands; private BrokkrHostSnapshot lastSnapshot; private BrokkrSyncReceipt lastSyncReceipt; + private BrokkrSyncPolicyView lastSyncPolicy; private string lastReceipt = "No snapshot published yet."; private MessageType lastMessageType = MessageType.Info; private double nextPollAt; @@ -47,6 +49,7 @@ namespace GameCult.Brokkr.Editor private string prefabAssetPath = ""; private string prefabInstanceName = ""; private string prefabVariantPath = "Assets/BrokkrPrefabVariant.prefab"; + private string prefabMirrorCollectionName = ""; private string adHocSyncVarBindingId = ""; private string adHocSyncVarKind = "custom-property"; private string adHocSyncVarDisplayName = "Custom Property"; @@ -88,6 +91,7 @@ namespace GameCult.Brokkr.Editor prefabAssetPath = BrokkrSettings.PrefabAssetPath; prefabInstanceName = BrokkrSettings.PrefabInstanceName; prefabVariantPath = BrokkrSettings.PrefabVariantPath; + prefabMirrorCollectionName = BrokkrSettings.PrefabMirrorCollectionName; adHocSyncVarBindingId = BrokkrSettings.AdHocSyncVarBindingId; adHocSyncVarKind = BrokkrSettings.AdHocSyncVarKind; adHocSyncVarDisplayName = BrokkrSettings.AdHocSyncVarDisplayName; @@ -147,6 +151,7 @@ namespace GameCult.Brokkr.Editor BrokkrSettings.PrefabAssetPath = prefabAssetPath; BrokkrSettings.PrefabInstanceName = prefabInstanceName; BrokkrSettings.PrefabVariantPath = prefabVariantPath; + BrokkrSettings.PrefabMirrorCollectionName = prefabMirrorCollectionName; BrokkrSettings.AdHocSyncVarBindingId = adHocSyncVarBindingId; BrokkrSettings.AdHocSyncVarKind = adHocSyncVarKind; BrokkrSettings.AdHocSyncVarDisplayName = adHocSyncVarDisplayName; @@ -188,6 +193,11 @@ namespace GameCult.Brokkr.Editor { PollSyncReceipts(false); } + + if (GUILayout.Button("Refresh Sync Policy")) + { + RefreshSyncPolicy(); + } } EditorGUILayout.Space(); @@ -211,10 +221,46 @@ namespace GameCult.Brokkr.Editor EditorGUILayout.LabelField("Selection", string.Join(", ", lastSnapshot.selectedObjectNames)); } + DrawSyncPolicySummary(); DrawAssetCommandSection(); DrawSyncSection(); } + private void DrawSyncPolicySummary() + { + if (lastSyncPolicy == null) + { + return; + } + + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Published Sync Policy", EditorStyles.boldLabel); + EditorGUILayout.LabelField("Object Bindings", lastSyncPolicy.objectBindings.Length.ToString()); + foreach (var binding in lastSyncPolicy.objectBindings.Take(5)) + { + EditorGUILayout.LabelField( + binding.enabled ? binding.displayName : $"{binding.displayName} (disabled)", + $"{binding.authority} {binding.unityPath} -> {binding.blenderObjectName}"); + } + + EditorGUILayout.LabelField("Timeline Bindings", lastSyncPolicy.timelineBindings.Length.ToString()); + foreach (var binding in lastSyncPolicy.timelineBindings.Take(5)) + { + EditorGUILayout.LabelField( + binding.enabled ? binding.displayName : $"{binding.displayName} (disabled)", + $"{binding.blenderSceneName}/{binding.blenderActionName} -> {binding.unityTimelineObjectId}"); + } + + EditorGUILayout.LabelField("Sync Vars", lastSyncPolicy.syncVars.Length.ToString()); + foreach (var syncVar in lastSyncPolicy.syncVars.Take(8)) + { + var label = syncVar.enabled ? syncVar.displayName : $"{syncVar.displayName} (disabled)"; + EditorGUILayout.LabelField( + label, + $"{syncVar.kind} {syncVar.authority} {syncVar.unityPropertyPath} <-> {syncVar.blenderPropertyPath}"); + } + } + private void DrawAssetCommandSection() { EditorGUILayout.Space(); @@ -230,9 +276,15 @@ namespace GameCult.Brokkr.Editor EditorGUILayout.Space(); prefabAssetPath = EditorGUILayout.TextField("Prefab Asset Path", prefabAssetPath); + prefabMirrorCollectionName = EditorGUILayout.TextField("Blender Collection", prefabMirrorCollectionName); prefabInstanceName = EditorGUILayout.TextField("Instance Name", prefabInstanceName); prefabVariantPath = EditorGUILayout.TextField("Variant Path", prefabVariantPath); + if (GUILayout.Button("Mirror Prefab To Blender")) + { + PublishPrefabMirrorSnapshot(); + } + using (new EditorGUILayout.HorizontalScope()) { if (GUILayout.Button("Instantiate Prefab")) @@ -433,6 +485,22 @@ namespace GameCult.Brokkr.Editor } } + private void RefreshSyncPolicy() + { + try + { + RequireMirror(); + lastSyncPolicy = mirror.SnapshotSyncPolicy(); + SetStatus( + $"Loaded sync policy: {lastSyncPolicy.objectBindings.Length} object binding(s), {lastSyncPolicy.timelineBindings.Length} timeline binding(s), {lastSyncPolicy.syncVars.Length} sync var(s).", + MessageType.Info); + } + catch (Exception error) + { + SetStatus(error.Message, MessageType.Error); + } + } + private void PublishCreateScriptableObjectCommand() { try @@ -516,6 +584,25 @@ namespace GameCult.Brokkr.Editor } } + private void PublishPrefabMirrorSnapshot() + { + try + { + RequireMirror(); + var snapshot = BrokkrUnitySnapshotBuilder.CapturePrefabMirror( + prefabAssetPath, + prefabMirrorCollectionName); + mirror.PublishPrefabMirrorSnapshotAsync(snapshot).GetAwaiter().GetResult(); + SetStatus( + $"Published Unity prefab mirror for Blender: {snapshot.prefabName} ({snapshot.nodes.Length} node(s), {snapshot.assets.Length} asset requirement(s)).", + MessageType.Info); + } + catch (Exception error) + { + SetStatus(error.Message, MessageType.Error); + } + } + private void PublishCommandAndPoll(BrokkrUnityCommand command) { mirror.PublishCommandAsync(command).GetAwaiter().GetResult(); diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs index 2814cae..8873205 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs @@ -37,6 +37,56 @@ namespace GameCult.Brokkr [Key(4)] public string status = ""; } + [CultDocument("brokkr.unity.prefab_mirror_snapshot", "brokkr.unity.prefab_mirror_snapshot.v0")] + [MessagePackObject] + [Serializable] + public sealed class BrokkrUnityPrefabMirrorSnapshot + { + [Key(0)] public string schema = "brokkr.unity.prefab_mirror_snapshot.v0"; + [Key(1)] public string snapshotId = ""; + [Key(2)] public string providerId = "brokkr.unity_editor"; + [Key(3)] public string sourceTool = "unity-editor"; + [Key(4)] public string prefabId = ""; + [Key(5)] public string prefabAssetPath = ""; + [Key(6)] public string prefabName = ""; + [Key(7)] public string blenderCollectionName = ""; + [Key(8)] public string observedAt = ""; + [Key(9)] public string contentHash = ""; + [Key(10)] public BrokkrUnityPrefabNodeSnapshot[] nodes = Array.Empty(); + [Key(11)] public BrokkrUnityPrefabAssetRequirement[] assets = Array.Empty(); + } + + [MessagePackObject] + [Serializable] + public sealed class BrokkrUnityPrefabNodeSnapshot + { + [Key(0)] public string nodeId = ""; + [Key(1)] public string parentNodeId = ""; + [Key(2)] public string name = ""; + [Key(3)] public string path = ""; + [Key(4)] public bool activeSelf; + [Key(5)] public string tag = ""; + [Key(6)] public int layer; + [Key(7)] public string localPosition = ""; + [Key(8)] public string localEulerAngles = ""; + [Key(9)] public string localScale = ""; + [Key(10)] public string meshAssetId = ""; + [Key(11)] public string[] materialAssetIds = Array.Empty(); + [Key(12)] public BrokkrComponentSnapshot[] components = Array.Empty(); + } + + [MessagePackObject] + [Serializable] + public sealed class BrokkrUnityPrefabAssetRequirement + { + [Key(0)] public string assetId = ""; + [Key(1)] public string role = ""; + [Key(2)] public string unityAssetPath = ""; + [Key(3)] public string guid = ""; + [Key(4)] public string name = ""; + [Key(5)] public string typeName = ""; + } + [MessagePackObject] [Serializable] public sealed class BrokkrGameObjectSnapshot diff --git a/surfaces/unity/README.md b/surfaces/unity/README.md index 5a9a15d..b8c8276 100644 --- a/surfaces/unity/README.md +++ b/surfaces/unity/README.md @@ -18,6 +18,17 @@ Vendor the CultMesh runtime DLLs before opening Unity: .\tools\vendor-cultmesh-unity.ps1 ``` +The vendor script intentionally copies the MessagePack runtime as +`MessagePack.CultMesh.dll` and removes any sibling `MessagePack.dll`. Unity +projects can already contain a `MessagePack.asmdef`, and importing a DLL with +the same filename makes Unity resolve the wrong assembly identity. Keep +`MessagePack.CultMesh.dll` and `MessagePack.Annotations.dll` on the same +MessagePack package version as CultMesh. + +The script also removes `System.Numerics.Vectors.dll`. Unity provides that +facade assembly through its reference assemblies, so the package should not +ship a second facade DLL with a different identity. + Then open `GameCult > Brokkr`. ## Local Smoke @@ -32,16 +43,24 @@ In Unity: 6. Click `Publish Mirror`. 7. To create a ScriptableObject through the mirror, fill `ScriptableObject Type`, `Asset Name`, and `Asset Path`, then click `Create ScriptableObject Asset`. -8. To instantiate or variant a prefab through the mirror, fill `Prefab Asset - Path`, optional `Instance Name`, and optional `Variant Path`, then click the - matching prefab command. -9. To publish object sync policy, select a GameObject, set the object lane +8. To migrate a Unity prefab into Blender-owned authoring, fill `Prefab Asset + Path`, optionally set `Blender Collection`, then click + `Mirror Prefab To Blender`. This writes + `brokkr.unity.prefab_mirror_snapshot.v0` to the mirror. In Blender, use + `Import Unity Prefab Mirror` to create the authoring collection. +9. To instantiate or variant a prefab through the mirror for legacy/editor + command testing, fill `Prefab Asset Path`, optional `Instance Name`, and + optional `Variant Path`, then click the matching prefab command. These + commands are not the CDN deploy path. +10. To publish object sync policy, select a GameObject, set the object lane toggles including transform, parent, active state, material, and property lanes, then click `Publish Object Sync`. -10. With the mirror running, run `brokkr-daemon sync-once` or `sync-loop`, then +11. Click `Refresh Sync Policy` to inspect the object bindings, timeline + bindings, and sync vars currently published in the Unity mirror. +12. With the mirror running, run `brokkr-daemon sync-once` or `sync-loop`, then click `Poll Sync Receipt` or leave the window open to show the latest daemon sync pass receipt. -11. To publish an ad hoc sync variable, fill `Ad Hoc Sync Var` with a binding id +13. To publish an ad hoc sync variable, fill `Ad Hoc Sync Var` with a binding id or leave it blank for a generated id, set kind/paths/authority/interpolation, then click `Publish Sync Var`. @@ -82,5 +101,24 @@ Recognized Unity asset commands include: - `createPrefabVariant` - `createScriptableObject` +## CDN Prefab Migration + +The CultMesh CDN does not consume Unity prefabs directly. Unity's role is to +publish a bootstrap mirror snapshot for existing prefabs: + +```text +prefabs/unity-mirrors/{snapshotId} +``` + +That document records render requirements discovered from Unity: hierarchy, +transforms, components, mesh assets, material assets, and texture assets. +Brokkr Blender imports it into a collection, and Blender becomes the authoring +ground truth. The Blender add-on then publishes `brokkr.prefab.snapshot.v0` +deploy snapshots for a CDN deployer to lower into CultMesh CDN artifacts and +`CultMeshEntityPrefabPackage` records. + +Players may later receive those packages through CultMesh's visible mesh asset +sharing system. That is runtime CDN behavior, not Unity editor ownership. + The Unity plugin is still an adapter. Unity owns Unity editor truth; Brokkr owns provider discovery; CultCache and CultMesh own the live mirror lane. diff --git a/tools/brokkr-unity-cache.py b/tools/brokkr-unity-cache.py new file mode 100644 index 0000000..1d770e4 --- /dev/null +++ b/tools/brokkr-unity-cache.py @@ -0,0 +1,1658 @@ +#!/usr/bin/env python3 +"""Inspect a running Brokkr Unity editor cache from a scripting runtime. + +This is intentionally a local development utility, not the Codex/Bifrost MCP +boundary. It uses CultCache's single-file MessagePack store directly because +Brokkr is just a daemon in the local Verse. +""" + +from __future__ import annotations + +import argparse +import base64 +import os +import re +import json +import subprocess +import sys +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + + +DEFAULT_CACHE = Path(r"E:\Projects\Aetheria\.brokkr\unity-editor.ccmp") +TUI_SURFACE_KEY = "eve/unity/tui" +TUI_SURFACE_URI = "cultmesh://brokkr/eve/unity/tui" +TUI_SURFACE_ID = "brokkr.eve.unity_editor_tui.v0" +PREFAB_INSPECTION_SCHEMA = "brokkr.unity.prefab_inspection.v0" +PREFAB_GAMEOBJECT_INSPECTION_SCHEMA = "brokkr.unity.prefab_gameobject_inspection.v0" + +UNITY_CLASS_NAMES = { + "1": "GameObject", + "4": "Transform", + "20": "Camera", + "23": "MeshRenderer", + "33": "MeshFilter", + "54": "Rigidbody", + "58": "CircleCollider2D", + "65": "BoxCollider", + "82": "AudioSource", + "95": "Animator", + "114": "MonoBehaviour", + "115": "MonoScript", + "119": "Projector", + "120": "LineRenderer", + "122": "Halo", + "124": "Behaviour", + "135": "SphereCollider", + "136": "CapsuleCollider", + "198": "ParticleSystem", + "199": "ParticleSystemRenderer", + "212": "SpriteRenderer", + "222": "CanvasRenderer", + "223": "Canvas", + "224": "RectTransform", +} + + +@dataclass(frozen=True) +class Document: + key: str + type: str + payload: bytes + stored_at: str | None = None + + +def add_local_cultcache_paths() -> None: + candidates = [ + Path(r"E:\Projects\cultcache-py\src"), + Path(r"E:\Projects\CultLib\packages\cultcache-py\src"), + ] + for candidate in candidates: + if candidate.exists(): + sys.path.insert(0, str(candidate)) + + +def read_documents(cache_path: Path) -> list[Document]: + add_local_cultcache_paths() + try: + from cultcache_py import SingleFileMessagePackBackingStore # type: ignore + + store = SingleFileMessagePackBackingStore(cache_path) + return [ + Document(item.key, item.type, item.payload, item.stored_at) + for item in store.pull_all() + ] + except ModuleNotFoundError: + import msgpack # type: ignore + + raw_items = msgpack.unpackb(cache_path.read_bytes(), raw=False) + return [ + Document( + item["key"], + item["type"], + item["payload"], + item.get("storedAt", item.get("stored_at")), + ) + for item in raw_items + ] + + +def write_document(cache_path: Path, document: Document) -> None: + add_local_cultcache_paths() + try: + from cultcache_py import SingleFileMessagePackBackingStore # type: ignore + from cultcache_py import CultCacheEnvelope # type: ignore + + store = SingleFileMessagePackBackingStore(cache_path) + store.push( + CultCacheEnvelope( + key=document.key, + type=document.type, + payload=document.payload, + stored_at=document.stored_at, + ) + ) + return + except ModuleNotFoundError: + pass + + import msgpack # type: ignore + + existing = { + (doc.type, doc.key): doc + for doc in read_documents(cache_path) + } + existing[(document.type, document.key)] = document + raw_items = [ + { + "key": doc.key, + "type": doc.type, + "payload": doc.payload, + "storedAt": doc.stored_at, + } + for doc in sorted(existing.values(), key=lambda item: (item.type, item.key)) + ] + temp = cache_path.with_suffix(cache_path.suffix + ".tmp") + temp.write_bytes(msgpack.packb(raw_items, use_bin_type=True)) + temp.replace(cache_path) + + +def decode_payload(payload: bytes) -> Any: + try: + return json.loads(payload.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError): + pass + + try: + import msgpack # type: ignore + + return msgpack.unpackb(payload, raw=False) + except Exception: + pass + + try: + return payload.decode("utf-8") + except UnicodeDecodeError: + return {"base64": base64.b64encode(payload).decode("ascii")} + + +def field(value: Any, index: int, name: str, default: Any = None) -> Any: + if isinstance(value, dict): + return value.get(name, default) + if isinstance(value, list) and index < len(value): + return value[index] + return default + + +def file_id(value: str) -> str: + match = re.search(r"fileID:\s*(-?\d+)", value) + return match.group(1) if match else "" + + +def guid_value(value: str) -> str: + match = re.search(r"guid:\s*([0-9a-fA-F]+)", value) + return match.group(1).lower() if match else "" + + +def parse_scalar(lines: list[str], key: str, default: str = "") -> str: + prefix = f" {key}:" + for line in lines: + if line.startswith(prefix): + return line[len(prefix):].strip() + return default + + +def parse_file_ids_after(lines: list[str], key: str) -> list[str]: + ids: list[str] = [] + in_block = False + prefix = f" {key}:" + for line in lines: + if line.startswith(prefix): + in_block = True + continue + if in_block: + if line.startswith(" - "): + found = file_id(line) + if found: + ids.append(found) + continue + if line.startswith(" ") and not line.startswith(" "): + break + return ids + + +def parse_top_level_fields(lines: list[str]) -> dict[str, str]: + fields: dict[str, str] = {} + index = 0 + while index < len(lines): + line = lines[index] + if not line.startswith(" ") or line.startswith(" ") or line.startswith(" - ") or ":" not in line: + index += 1 + continue + + key, value = line.strip().split(":", 1) + value = value.strip() + index += 1 + block: list[str] = [] + while index < len(lines): + next_line = lines[index] + if ( + next_line.startswith(" ") + and not next_line.startswith(" ") + and not next_line.startswith(" - ") + and ":" in next_line + ): + break + if next_line.strip(): + block.append(next_line.strip()) + index += 1 + if block: + fields[key] = (value + " " + " ".join(block)).strip() + else: + fields[key] = value + return fields + + +def display_component_fields(raw_fields: dict[str, str]) -> dict[str, str]: + hidden = { + "m_ObjectHideFlags", + "m_CorrespondingSourceObject", + "m_PrefabInstance", + "m_PrefabAsset", + "m_GameObject", + "m_EditorHideFlags", + "m_EditorClassIdentifier", + "serializedVersion", + } + return { + key: value + for key, value in raw_fields.items() + if key not in hidden and value != "" + } + + +def parse_unity_yaml_sections(prefab_path: Path) -> list[dict[str, Any]]: + text = prefab_path.read_text(encoding="utf-8-sig", errors="replace") + header = re.compile(r"^--- !u!(?P\d+) &(?P-?\d+)", re.MULTILINE) + matches = list(header.finditer(text)) + sections: list[dict[str, Any]] = [] + for index, match in enumerate(matches): + start = match.end() + end = matches[index + 1].start() if index + 1 < len(matches) else len(text) + body = text[start:end].strip("\r\n") + lines = body.splitlines() + type_name = UNITY_CLASS_NAMES.get(match.group("class_id"), "") + for line in lines: + if line and not line.startswith(" ") and line.endswith(":"): + type_name = line[:-1] + break + sections.append( + { + "classId": match.group("class_id"), + "fileId": match.group("file_id"), + "type": type_name or match.group("class_id"), + "lines": lines, + } + ) + return sections + + +def project_root_from_asset_path(asset_path: Path) -> Path: + parts = list(asset_path.resolve().parts) + lowered = [part.lower() for part in parts] + if "assets" in lowered: + index = lowered.index("assets") + return Path(*parts[:index]) + return Path.cwd() + + +def resolve_script_guids(project_root: Path, guids: set[str]) -> dict[str, str]: + if not guids: + return {} + resolved: dict[str, str] = {} + assets_root = project_root / "Assets" + if not assets_root.exists(): + return resolved + + try: + pattern = "|".join(re.escape(guid) for guid in sorted(guids)) + result = subprocess.run( + ["rg", "-l", f"guid:\\s*({pattern})", str(assets_root), "-g", "*.meta"], + cwd=str(project_root), + text=True, + capture_output=True, + timeout=8, + check=False, + ) + for raw_path in result.stdout.splitlines(): + meta_path = Path(raw_path) + if not meta_path.is_absolute(): + meta_path = project_root / meta_path + try: + content = meta_path.read_text(encoding="utf-8", errors="ignore") + except OSError: + continue + match = re.search(r"^guid:\s*([0-9a-fA-F]+)", content, re.MULTILINE) + if not match: + continue + guid = match.group(1).lower() + if guid not in guids: + continue + asset_path = meta_path.with_suffix("") + try: + resolved[guid] = str(asset_path.relative_to(project_root)).replace(os.sep, "/") + except ValueError: + resolved[guid] = str(asset_path) + if len(resolved) == len(guids): + return resolved + except (OSError, subprocess.SubprocessError): + pass + + for meta_path in assets_root.rglob("*.meta"): + if len(resolved) == len(guids): + break + try: + with meta_path.open("r", encoding="utf-8", errors="ignore") as handle: + for line in handle: + if not line.startswith("guid:"): + continue + guid = line.split(":", 1)[1].strip().lower() + if guid in guids: + asset_path = meta_path.with_suffix("") + try: + resolved[guid] = str(asset_path.relative_to(project_root)).replace(os.sep, "/") + except ValueError: + resolved[guid] = str(asset_path) + break + except OSError: + continue + return resolved + + +def resolve_unity_reference( + file_id_value: str, + guid: str, + game_objects: dict[str, dict[str, Any]], + components: dict[str, dict[str, Any]], + guid_paths: dict[str, str], +) -> str: + if file_id_value in ("", "0"): + return "None" + + if guid: + asset_path = guid_paths.get(guid.lower(), f"guid:{guid}") + if file_id_value == "11500000": + return asset_path + return f"{asset_path}#{file_id_value}" + + if file_id_value in game_objects: + game_object = game_objects[file_id_value] + return f"{game_object.get('name', '')} (GameObject {file_id_value})" + + if file_id_value in components: + component_info = components[file_id_value] + game_object = game_objects.get(component_info.get("gameObject", ""), {}) + owner = game_object.get("name", component_info.get("gameObject", "")) + return f"{owner}.{component_info.get('type', 'Component')} ({file_id_value})" + + return f"fileID:{file_id_value}" + + +def resolve_field_value( + value: str, + game_objects: dict[str, dict[str, Any]], + components: dict[str, dict[str, Any]], + guid_paths: dict[str, str], +) -> str: + ref_pattern = re.compile( + r"\{fileID:\s*(-?\d+)(?:,\s*guid:\s*([0-9a-fA-F]+),\s*type:\s*(\d+))?\}" + ) + + def replace(match: re.Match[str]) -> str: + return resolve_unity_reference( + match.group(1), + match.group(2) or "", + game_objects, + components, + guid_paths, + ) + + return ref_pattern.sub(replace, value) + + +def inspect_prefab(prefab_path: Path, max_objects: int = 120) -> dict[str, Any]: + sections = parse_unity_yaml_sections(prefab_path) + game_objects: dict[str, dict[str, Any]] = {} + components: dict[str, dict[str, Any]] = {} + transforms: dict[str, dict[str, Any]] = {} + script_guids: set[str] = set() + reference_guids: set[str] = set() + + for section in sections: + section_type = section["type"] + file_id_value = section["fileId"] + lines = section["lines"] + + if section_type == "GameObject": + component_ids = parse_file_ids_after(lines, "m_Component") + game_objects[file_id_value] = { + "fileId": file_id_value, + "name": parse_scalar(lines, "m_Name", "(unnamed)"), + "tag": parse_scalar(lines, "m_TagString", ""), + "layer": parse_scalar(lines, "m_Layer", ""), + "active": parse_scalar(lines, "m_IsActive", "1") != "0", + "componentIds": component_ids, + "components": [], + "children": [], + "parent": "", + "transform": "", + } + continue + + game_object_id = file_id(parse_scalar(lines, "m_GameObject", "")) + script_guid = guid_value(parse_scalar(lines, "m_Script", "")) + if script_guid: + script_guids.add(script_guid) + raw_fields = parse_top_level_fields(lines) + for raw_value in raw_fields.values(): + reference_guids.update( + guid.lower() + for guid in re.findall(r"guid:\s*([0-9a-fA-F]+)", raw_value) + ) + + component_info = { + "fileId": file_id_value, + "classId": section["classId"], + "type": section_type, + "gameObject": game_object_id, + "enabled": parse_scalar(lines, "m_Enabled", ""), + "scriptGuid": script_guid, + "scriptPath": "", + "fields": display_component_fields(raw_fields), + } + components[file_id_value] = component_info + + if section_type in ("Transform", "RectTransform"): + parent = file_id(parse_scalar(lines, "m_Father", "")) + children = parse_file_ids_after(lines, "m_Children") + transform_info = { + **component_info, + "parentTransform": parent, + "childTransforms": children, + "localPosition": parse_scalar(lines, "m_LocalPosition", ""), + "localRotation": parse_scalar(lines, "m_LocalRotation", ""), + "localScale": parse_scalar(lines, "m_LocalScale", ""), + "localEulerAnglesHint": parse_scalar(lines, "m_LocalEulerAnglesHint", ""), + } + transforms[file_id_value] = transform_info + components[file_id_value] = transform_info + + project_root = project_root_from_asset_path(prefab_path) + guid_paths = resolve_script_guids(project_root, script_guids | reference_guids) + for component_info in components.values(): + guid = component_info.get("scriptGuid", "") + if guid: + component_info["scriptPath"] = guid_paths.get(guid, "") + if component_info["scriptPath"]: + component_info["type"] = Path(component_info["scriptPath"]).stem + + transform_to_game_object = { + transform_id: transform["gameObject"] + for transform_id, transform in transforms.items() + if transform.get("gameObject") + } + for transform_id, transform in transforms.items(): + game_object_id = transform.get("gameObject", "") + if game_object_id in game_objects: + game_objects[game_object_id]["transform"] = transform_id + parent_transform = transform.get("parentTransform", "") + parent_game_object = transform_to_game_object.get(parent_transform, "") + game_objects[game_object_id]["parent"] = parent_game_object + + for game_object in game_objects.values(): + for component_id in game_object["componentIds"]: + component_info = components.get(component_id) + if component_info is not None: + game_object["components"].append(component_info) + + for game_object_id, game_object in game_objects.items(): + parent = game_object.get("parent", "") + if parent in game_objects: + game_objects[parent]["children"].append(game_object_id) + + for component_info in components.values(): + component_info["resolvedFields"] = { + key: resolve_field_value(value, game_objects, components, guid_paths) + for key, value in (component_info.get("fields", {}) or {}).items() + } + + component_histogram: dict[str, int] = {} + mono_scripts: dict[str, int] = {} + missing_scripts = 0 + for component_info in components.values(): + component_type = component_info.get("type", "") + component_histogram[component_type] = component_histogram.get(component_type, 0) + 1 + guid = component_info.get("scriptGuid", "") + if guid: + script_path = component_info.get("scriptPath", "") + if script_path: + mono_scripts[script_path] = mono_scripts.get(script_path, 0) + 1 + else: + missing_scripts += 1 + + roots = [ + game_object_id + for game_object_id, game_object in game_objects.items() + if not game_object.get("parent") + ] + + def build_node(game_object_id: str, depth: int = 0) -> dict[str, Any]: + game_object = game_objects[game_object_id] + component_names = [component["type"] for component in game_object["components"]] + node = { + "name": game_object["name"], + "fileId": game_object["fileId"], + "active": game_object["active"], + "tag": game_object["tag"], + "layer": game_object["layer"], + "components": component_names, + "componentDetails": game_object["components"], + "children": [], + } + if len(build_node.seen) < max_objects: + build_node.seen.add(game_object_id) + node["children"] = [ + build_node(child_id, depth + 1) + for child_id in game_object["children"] + if child_id in game_objects and len(build_node.seen) < max_objects + ] + return node + + build_node.seen = set() # type: ignore[attr-defined] + tree = [build_node(root) for root in roots if root in game_objects] + + return { + "path": str(prefab_path), + "assetPath": str(prefab_path.relative_to(project_root_from_asset_path(prefab_path))).replace(os.sep, "/"), + "bytes": prefab_path.stat().st_size, + "sections": len(sections), + "gameObjects": len(game_objects), + "components": len(components), + "transforms": len(transforms), + "roots": len(roots), + "missingMonoBehaviours": missing_scripts, + "componentHistogram": dict(sorted(component_histogram.items(), key=lambda item: (-item[1], item[0]))), + "monoScripts": dict(sorted(mono_scripts.items(), key=lambda item: (-item[1], item[0]))), + "tree": tree, + "truncatedTree": len(game_objects) > max_objects, + } + + +def as_jsonable(value: Any) -> Any: + if isinstance(value, bytes): + return {"base64": base64.b64encode(value).decode("ascii")} + if isinstance(value, dict): + return {str(key): as_jsonable(item) for key, item in value.items()} + if isinstance(value, list): + return [as_jsonable(item) for item in value] + return value + + +def now_utc() -> str: + return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z") + + +def component( + component_id: str, + kind: str, + props: dict[str, Any] | None = None, + children: list[Any] | None = None, +) -> dict[str, Any]: + return { + "id": component_id, + "kind": kind, + "props": {key: str(value) for key, value in (props or {}).items()}, + "children": children or [], + } + + +def metric(component_id: str, label: str, value: Any) -> dict[str, Any]: + return component(component_id, "inspector.kv", {"label": label, "value": value}) + + +def text(component_id: str, value: str) -> dict[str, Any]: + return component(component_id, "text", {"text": value}) + + +def button(component_id: str, label: str, command: str, **payload: Any) -> dict[str, Any]: + props = {"label": label, "command": command} + for key, value in payload.items(): + props[f"payload.{key}"] = value + return component(component_id, "control.button", props) + + +def object_row(index: int, item: Any) -> dict[str, Any]: + object_id = field(item, 0, "objectId", "") + name = field(item, 1, "name", "") + path = field(item, 2, "path", "") + active = field(item, 4, "activeSelf", False) + child_count = field(item, 7, "childCount", 0) + components = field(item, 9, "components", []) or [] + return component( + f"brokkr.unity.tui.scene.object.{index}", + "inspector.kv", + { + "label": name or path or object_id, + "value": f"{'active' if active else 'inactive'}; children={child_count}; components={len(components)}", + "path": path, + "objectId": object_id, + }, + ) + + +def command_templates() -> list[dict[str, str]]: + return [ + { + "command": "unity.snapshot.refresh", + "label": "Refresh Snapshot", + "transport": "cultcache:intent-documents", + }, + { + "command": "unity.gameobject.create", + "label": "Create GameObject", + "transport": "cultcache:intent-documents", + }, + { + "command": "unity.selection.inspect", + "label": "Inspect Selection", + "transport": "cultcache:intent-documents", + }, + ] + + +def prefab_slug(asset_path: str) -> str: + slug = asset_path.lower().replace("\\", "/") + if slug.startswith("assets/"): + slug = slug[len("assets/"):] + slug = re.sub(r"[^a-z0-9]+", "-", slug).strip("-") + return slug or "prefab" + + +def prefab_inspection_key(asset_path: str) -> str: + return f"unity/prefabs/{prefab_slug(asset_path)}/inspection" + + +def prefab_tui_key(asset_path: str) -> str: + return f"eve/unity/prefabs/{prefab_slug(asset_path)}/tui" + + +def prefab_tui_uri(asset_path: str) -> str: + return f"cultmesh://brokkr/eve/unity/prefabs/{prefab_slug(asset_path)}/tui" + + +def prefab_tui_id(asset_path: str) -> str: + return f"brokkr.eve.unity_prefab.{prefab_slug(asset_path)}.tui.v0" + + +def object_slug(value: str) -> str: + slug = re.sub(r"[^a-zA-Z0-9]+", "-", value).strip("-").lower() + return slug or "gameobject" + + +def prefab_gameobject_inspection_key(asset_path: str, object_id: str) -> str: + return f"unity/prefabs/{prefab_slug(asset_path)}/gameobjects/{object_slug(object_id)}/inspection" + + +def prefab_gameobject_tui_key(asset_path: str, object_id: str) -> str: + return f"eve/unity/prefabs/{prefab_slug(asset_path)}/gameobjects/{object_slug(object_id)}/tui" + + +def prefab_gameobject_tui_uri(asset_path: str, object_id: str) -> str: + return f"cultmesh://brokkr/eve/unity/prefabs/{prefab_slug(asset_path)}/gameobjects/{object_slug(object_id)}/tui" + + +def prefab_gameobject_tui_id(asset_path: str, object_id: str) -> str: + return f"brokkr.eve.unity_prefab.{prefab_slug(asset_path)}.{object_slug(object_id)}.tui.v0" + + +def build_tui_surface(snapshot: Any, version: int = 1) -> dict[str, Any]: + scene_objects = field(snapshot, 12, "sceneObjects", []) or [] + assets = field(snapshot, 13, "assets", []) or [] + capabilities = field(snapshot, 11, "capabilities", []) or [] + selected = field(snapshot, 9, "selectedObjectNames", []) or [] + updated_at = field(snapshot, 4, "observedAt", "") or now_utc() + product_name = field(snapshot, 6, "productName", "") or "Unity" + + root = component( + "brokkr.unity.tui.root", + "surface", + {"title": "Unity Editor TUI"}, + [ + component( + "brokkr.unity.tui.status", + "card", + {"title": product_name}, + [ + metric("brokkr.unity.tui.status.provider", "Provider", field(snapshot, 1, "providerId", "")), + metric("brokkr.unity.tui.status.project", "Project", field(snapshot, 3, "projectPath", "")), + metric("brokkr.unity.tui.status.version", "Unity", field(snapshot, 5, "unityVersion", "")), + metric("brokkr.unity.tui.status.scene", "Scene", field(snapshot, 7, "activeScenePath", "") or "(untitled)"), + metric("brokkr.unity.tui.status.observed", "Observed", updated_at), + ], + ), + component( + "brokkr.unity.tui.counts", + "grid", + {"columns": "4"}, + [ + metric("brokkr.unity.tui.counts.objects", "Scene Objects", len(scene_objects)), + metric("brokkr.unity.tui.counts.assets", "Assets", len(assets)), + metric("brokkr.unity.tui.counts.selected", "Selected", len(selected)), + metric("brokkr.unity.tui.counts.capabilities", "Capabilities", len(capabilities)), + ], + ), + component( + "brokkr.unity.tui.selection", + "card", + {"title": "Selection"}, + [text("brokkr.unity.tui.selection.empty", "(none)")] + if not selected + else [ + metric(f"brokkr.unity.tui.selection.{index}", "Selected", name) + for index, name in enumerate(selected) + ], + ), + component( + "brokkr.unity.tui.scene", + "tree", + {"title": "Scene Objects"}, + [object_row(index, item) for index, item in enumerate(scene_objects[:40])], + ), + component( + "brokkr.unity.tui.actions", + "rail.actions", + {"title": "Actions"}, + [ + button("brokkr.unity.tui.actions.refresh", "Refresh", "unity.snapshot.refresh"), + button("brokkr.unity.tui.actions.create", "Create Object", "unity.gameobject.create", name="GameObject"), + ], + ), + ], + ) + + return { + "type": "surface-state", + "schema": "gamecult.eve.surface.v1", + "providerId": "brokkr.unity_editor", + "providerKind": "creative-tool.editor", + "title": "Unity Editor TUI", + "version": version, + "updatedAt": updated_at, + "surface": { + "id": TUI_SURFACE_ID, + "root": root, + "styles": [ + {"name": "accent", "value": "#3fb6ff"}, + {"name": "status.ok", "value": "#2fbf71"}, + {"name": "density", "value": "compact"}, + ], + }, + "commands": command_templates(), + "cultMeshUri": TUI_SURFACE_URI, + "source": { + "cacheKey": "unity/host/current", + "cachePath": str(DEFAULT_CACHE), + }, + } + + +def prefab_node_row(prefix: str, node: dict[str, Any], index: int) -> dict[str, Any]: + components = ", ".join(node.get("components", [])) + label = node.get("name", "") or node.get("fileId", "") + value_parts = [] + if components: + value_parts.append(components) + value_parts.append("active" if node.get("active") else "inactive") + children = node.get("children", []) + if children: + value_parts.append(f"children={len(children)}") + return component( + f"{prefix}.node.{index}", + "inspector.kv", + { + "label": label, + "value": "; ".join(value_parts), + "fileId": node.get("fileId", ""), + "tag": node.get("tag", ""), + "layer": node.get("layer", ""), + }, + ) + + +def flatten_prefab_tree(nodes: list[dict[str, Any]], limit: int = 80) -> list[dict[str, Any]]: + flattened: list[dict[str, Any]] = [] + + def walk(node: dict[str, Any], depth: int) -> None: + if len(flattened) >= limit: + return + copy = dict(node) + copy["name"] = f"{' ' * depth}{copy.get('name', '')}" + copy["children"] = node.get("children", []) + flattened.append(copy) + for child in node.get("children", []): + walk(child, depth + 1) + + for item in nodes: + walk(item, 0) + return flattened + + +def build_prefab_tui_surface(inspection: dict[str, Any], version: int = 1) -> dict[str, Any]: + asset_path = inspection["assetPath"] + surface_id = prefab_tui_id(asset_path) + surface_uri = prefab_tui_uri(asset_path) + prefix = surface_id.replace(".", "_") + updated_at = now_utc() + histogram = list(inspection.get("componentHistogram", {}).items()) + scripts = list(inspection.get("monoScripts", {}).items()) + flattened_tree = flatten_prefab_tree(inspection.get("tree", []), limit=80) + + root = component( + f"{prefix}.root", + "surface", + {"title": f"Prefab TUI: {Path(asset_path).name}"}, + [ + component( + f"{prefix}.summary", + "card", + {"title": asset_path}, + [ + metric(f"{prefix}.summary.objects", "GameObjects", inspection.get("gameObjects", 0)), + metric(f"{prefix}.summary.components", "Components", inspection.get("components", 0)), + metric(f"{prefix}.summary.transforms", "Transforms", inspection.get("transforms", 0)), + metric(f"{prefix}.summary.roots", "Roots", inspection.get("roots", 0)), + metric(f"{prefix}.summary.bytes", "Bytes", inspection.get("bytes", 0)), + metric( + f"{prefix}.summary.missingMono", + "Unresolved MonoBehaviours", + inspection.get("missingMonoBehaviours", 0), + ), + ], + ), + component( + f"{prefix}.components", + "card", + {"title": "Component Mix"}, + [ + metric(f"{prefix}.components.{index}", name, count) + for index, (name, count) in enumerate(histogram[:24]) + ], + ), + component( + f"{prefix}.scripts", + "card", + {"title": "Script Bindings"}, + [ + metric(f"{prefix}.scripts.{index}", Path(path).name, f"{count} x {path}") + for index, (path, count) in enumerate(scripts[:24]) + ], + ), + component( + f"{prefix}.hierarchy", + "tree", + {"title": "Prefab Hierarchy", "truncated": inspection.get("truncatedTree", False)}, + [ + prefab_node_row(prefix, node, index) + for index, node in enumerate(flattened_tree) + ], + ), + component( + f"{prefix}.actions", + "rail.actions", + {"title": "Actions"}, + [ + button( + f"{prefix}.actions.open", + "Open Prefab", + "unity.prefab.open", + assetPath=asset_path, + ), + button( + f"{prefix}.actions.refresh", + "Refresh Inspection", + "unity.prefab.inspect", + assetPath=asset_path, + ), + ], + ), + ], + ) + + return { + "type": "surface-state", + "schema": "gamecult.eve.surface.v1", + "providerId": "brokkr.unity_editor", + "providerKind": "creative-tool.editor", + "title": f"Prefab TUI: {Path(asset_path).name}", + "version": version, + "updatedAt": updated_at, + "surface": { + "id": surface_id, + "root": root, + "styles": [ + {"name": "accent", "value": "#3fb6ff"}, + {"name": "density", "value": "compact"}, + ], + }, + "commands": [ + { + "command": "unity.prefab.open", + "label": "Open Prefab", + "transport": "cultcache:intent-documents", + }, + { + "command": "unity.prefab.inspect", + "label": "Refresh Prefab Inspection", + "transport": "cultcache:intent-documents", + }, + ], + "cultMeshUri": surface_uri, + "source": { + "cacheKey": prefab_inspection_key(asset_path), + "assetPath": asset_path, + }, + } + + +def find_prefab_gameobject(inspection: dict[str, Any], selector: str) -> dict[str, Any] | None: + def walk(nodes: list[dict[str, Any]]) -> dict[str, Any] | None: + for node in nodes: + if node.get("fileId") == selector or node.get("name") == selector: + return node + found = walk(node.get("children", [])) + if found is not None: + return found + return None + + return walk(inspection.get("tree", [])) + + +def collect_gameobject_ids(nodes: list[dict[str, Any]]) -> set[str]: + ids: set[str] = set() + + def walk(node: dict[str, Any]) -> None: + file_id_value = node.get("fileId", "") + if file_id_value: + ids.add(file_id_value) + for child in node.get("children", []): + walk(child) + + for item in nodes: + walk(item) + return ids + + +def find_full_gameobject(inspection: dict[str, Any], selector: str) -> dict[str, Any] | None: + found = find_prefab_gameobject(inspection, selector) + if found is None: + return None + + object_id = found.get("fileId", "") + target: dict[str, Any] | None = None + + def walk(nodes: list[dict[str, Any]]) -> None: + nonlocal target + for node in nodes: + if target is not None: + return + if node.get("fileId") == object_id: + target = node + return + walk(node.get("children", [])) + + walk(inspection.get("tree", [])) + return target + + +def component_field_rows(prefix: str, component_info: dict[str, Any], component_index: int) -> list[dict[str, Any]]: + rows: list[dict[str, Any]] = [] + fields = component_info.get("resolvedFields", {}) or component_info.get("fields", {}) or {} + if not fields: + return [ + text( + f"{prefix}.component.{component_index}.empty", + "(no serialized fields exposed)", + ) + ] + for field_index, (name, value) in enumerate(fields.items()): + rows.append( + metric( + f"{prefix}.component.{component_index}.field.{field_index}", + name, + value, + ) + ) + return rows + + +def build_prefab_gameobject_inspection(inspection: dict[str, Any], selector: str) -> dict[str, Any]: + target = find_full_gameobject(inspection, selector) + if target is None: + raise ValueError(f"GameObject not found in prefab inspection: {selector}") + asset_path = inspection["assetPath"] + child_ids = collect_gameobject_ids(target.get("children", [])) + return { + "schema": PREFAB_GAMEOBJECT_INSPECTION_SCHEMA, + "providerId": "brokkr.unity_editor", + "observedAt": now_utc(), + "assetPath": asset_path, + "prefabInspectionKey": prefab_inspection_key(asset_path), + "gameObject": target, + "childrenIncluded": len(child_ids), + } + + +def build_prefab_gameobject_tui_surface(object_inspection: dict[str, Any], version: int = 1) -> dict[str, Any]: + asset_path = object_inspection["assetPath"] + game_object = object_inspection["gameObject"] + object_id = game_object["fileId"] + surface_id = prefab_gameobject_tui_id(asset_path, object_id) + surface_uri = prefab_gameobject_tui_uri(asset_path, object_id) + prefix = surface_id.replace(".", "_") + components = game_object.get("componentDetails", []) or game_object.get("components", []) + + root = component( + f"{prefix}.root", + "surface", + {"title": f"GameObject TUI: {game_object.get('name', object_id)}"}, + [ + component( + f"{prefix}.summary", + "card", + {"title": game_object.get("name", object_id)}, + [ + metric(f"{prefix}.summary.prefab", "Prefab", asset_path), + metric(f"{prefix}.summary.fileId", "File ID", object_id), + metric(f"{prefix}.summary.active", "Active", game_object.get("active", "")), + metric(f"{prefix}.summary.tag", "Tag", game_object.get("tag", "")), + metric(f"{prefix}.summary.layer", "Layer", game_object.get("layer", "")), + metric(f"{prefix}.summary.components", "Components", len(components)), + metric(f"{prefix}.summary.children", "Children", len(game_object.get("children", []))), + ], + ), + *[ + component( + f"{prefix}.component.{component_index}", + "card", + { + "title": component_info.get("type", "Component"), + "fileId": component_info.get("fileId", ""), + "scriptPath": component_info.get("scriptPath", ""), + }, + [ + metric( + f"{prefix}.component.{component_index}.type", + "Type", + component_info.get("type", ""), + ), + metric( + f"{prefix}.component.{component_index}.enabled", + "Enabled", + component_info.get("enabled", ""), + ), + *component_field_rows(prefix, component_info, component_index), + ], + ) + for component_index, component_info in enumerate(components) + ], + component( + f"{prefix}.actions", + "rail.actions", + {"title": "Actions"}, + [ + button( + f"{prefix}.actions.open", + "Open Prefab", + "unity.prefab.open", + assetPath=asset_path, + ), + button( + f"{prefix}.actions.select", + "Select GameObject", + "unity.prefab.gameobject.select", + assetPath=asset_path, + fileId=object_id, + ), + ], + ), + ], + ) + + return { + "type": "surface-state", + "schema": "gamecult.eve.surface.v1", + "providerId": "brokkr.unity_editor", + "providerKind": "creative-tool.editor", + "title": f"GameObject TUI: {game_object.get('name', object_id)}", + "version": version, + "updatedAt": object_inspection.get("observedAt", now_utc()), + "surface": { + "id": surface_id, + "root": root, + "styles": [ + {"name": "accent", "value": "#3fb6ff"}, + {"name": "density", "value": "compact"}, + ], + }, + "commands": [ + { + "command": "unity.prefab.open", + "label": "Open Prefab", + "transport": "cultcache:intent-documents", + }, + { + "command": "unity.prefab.gameobject.select", + "label": "Select Prefab GameObject", + "transport": "cultcache:intent-documents", + }, + ], + "cultMeshUri": surface_uri, + "source": { + "cacheKey": prefab_gameobject_inspection_key(asset_path, object_id), + "assetPath": asset_path, + "fileId": object_id, + }, + } + + +def eve_component_to_array(node: dict[str, Any]) -> list[Any]: + return [ + node.get("id", ""), + node.get("kind", ""), + node.get("props", {}), + [eve_component_to_array(child) for child in node.get("children", [])], + ] + + +def eve_surface_to_msgpack_payload(surface: dict[str, Any]) -> bytes: + import msgpack # type: ignore + + tree = surface["surface"] + payload = [ + surface["type"], + surface["schema"], + surface["providerId"], + surface["providerKind"], + surface["title"], + surface["version"], + surface["updatedAt"], + [ + tree["id"], + eve_component_to_array(tree["root"]), + [[item["name"], item["value"]] for item in tree.get("styles", [])], + ], + [ + [item["command"], item["label"], item["transport"]] + for item in surface.get("commands", []) + ], + ] + return msgpack.packb(payload, use_bin_type=True) + + +def load_unity_snapshot(cache_path: Path) -> Any: + docs = {doc.key: doc for doc in read_documents(cache_path)} + snapshot_doc = docs.get("unity/host/current") + if snapshot_doc is None: + raise RuntimeError("Unity host snapshot missing: unity/host/current") + return decode_payload(snapshot_doc.payload) + + +def read_or_build_tui_surface(cache_path: Path) -> dict[str, Any]: + docs = {doc.key: doc for doc in read_documents(cache_path)} + existing = docs.get(TUI_SURFACE_KEY) + if existing is not None: + decoded = decode_payload(existing.payload) + if isinstance(decoded, list): + return msgpack_surface_to_json(decoded, existing.stored_at) + if isinstance(decoded, dict): + return decoded + return build_tui_surface(load_unity_snapshot(cache_path)) + + +def read_surface_document(cache_path: Path, key: str) -> dict[str, Any] | None: + docs = {doc.key: doc for doc in read_documents(cache_path)} + existing = docs.get(key) + if existing is None: + return None + decoded = decode_payload(existing.payload) + if isinstance(decoded, list): + return msgpack_surface_to_json(decoded, existing.stored_at) + if isinstance(decoded, dict): + return decoded + return None + + +def msgpack_component_to_json(node: Any) -> dict[str, Any]: + return component( + field(node, 0, "id", ""), + field(node, 1, "kind", ""), + field(node, 2, "props", {}) or {}, + [msgpack_component_to_json(child) for child in (field(node, 3, "children", []) or [])], + ) + + +def msgpack_surface_to_json(payload: list[Any], stored_at: str | None = None) -> dict[str, Any]: + surface_tree = field(payload, 7, "surface", []) + styles = field(surface_tree, 2, "styles", []) or [] + commands = field(payload, 8, "commands", []) or [] + surface = { + "type": field(payload, 0, "type", ""), + "schema": field(payload, 1, "schema", ""), + "providerId": field(payload, 2, "providerId", ""), + "providerKind": field(payload, 3, "providerKind", ""), + "title": field(payload, 4, "title", ""), + "version": field(payload, 5, "version", 0), + "updatedAt": field(payload, 6, "updatedAt", stored_at or ""), + "surface": { + "id": field(surface_tree, 0, "id", ""), + "root": msgpack_component_to_json(field(surface_tree, 1, "root", [])), + "styles": [ + {"name": field(item, 0, "name", ""), "value": field(item, 1, "value", "")} + for item in styles + ], + }, + "commands": [ + { + "command": field(item, 0, "command", ""), + "label": field(item, 1, "label", ""), + "transport": field(item, 2, "transport", ""), + } + for item in commands + ], + "cultMeshUri": TUI_SURFACE_URI, + } + return surface + + +def command_overview(args: argparse.Namespace) -> int: + docs = read_documents(args.cache) + by_key = {doc.key: doc for doc in docs} + snapshot_doc = by_key.get("unity/host/current") + snapshot = decode_payload(snapshot_doc.payload) if snapshot_doc else None + + command_count = sum(1 for doc in docs if doc.key.startswith("unity/commands/")) + receipt_count = sum(1 for doc in docs if doc.key.startswith("unity/receipts/")) + sync_count = sum(1 for doc in docs if doc.key.startswith("sync/")) + + overview: dict[str, Any] = { + "cache": str(args.cache), + "documents": len(docs), + "commands": command_count, + "receipts": receipt_count, + "syncDocuments": sync_count, + } + + if snapshot is not None: + scene_objects = field(snapshot, 12, "sceneObjects", []) or [] + assets = field(snapshot, 13, "assets", []) or [] + capabilities = field(snapshot, 11, "capabilities", []) or [] + selected = field(snapshot, 9, "selectedObjectNames", []) or [] + overview.update( + { + "providerId": field(snapshot, 1, "providerId", ""), + "toolKind": field(snapshot, 2, "toolKind", ""), + "projectPath": field(snapshot, 3, "projectPath", ""), + "observedAt": field(snapshot, 4, "observedAt", ""), + "unityVersion": field(snapshot, 5, "unityVersion", ""), + "productName": field(snapshot, 6, "productName", ""), + "activeScenePath": field(snapshot, 7, "activeScenePath", ""), + "openSceneCount": field(snapshot, 8, "openSceneCount", 0), + "selectedObjectNames": selected, + "capabilityCount": len(capabilities), + "sceneObjectCount": len(scene_objects), + "assetCount": len(assets), + "sampleSceneObjects": [ + { + "objectId": field(item, 0, "objectId", ""), + "name": field(item, 1, "name", ""), + "path": field(item, 2, "path", ""), + "activeSelf": field(item, 4, "activeSelf", None), + "parentId": field(item, 8, "parentId", ""), + } + for item in scene_objects[: args.limit] + ], + } + ) + else: + overview["unityHostSnapshot"] = "missing" + + print(json.dumps(as_jsonable(overview), indent=2, sort_keys=True)) + return 0 + + +def command_list(args: argparse.Namespace) -> int: + docs = sorted(read_documents(args.cache), key=lambda doc: (doc.type, doc.key)) + for doc in docs[: args.limit]: + stored = f" storedAt={doc.stored_at}" if doc.stored_at else "" + print(f"{doc.type} {doc.key}{stored}") + if len(docs) > args.limit: + print(f"... {len(docs) - args.limit} more") + return 0 + + +def command_get(args: argparse.Namespace) -> int: + docs = {doc.key: doc for doc in read_documents(args.cache)} + doc = docs.get(args.key) + if doc is None: + print(f"Document not found: {args.key}", file=sys.stderr) + return 1 + + payload = decode_payload(doc.payload) + output = { + "key": doc.key, + "type": doc.type, + "storedAt": doc.stored_at, + "payload": payload, + } + print(json.dumps(as_jsonable(output), indent=2, sort_keys=True)) + return 0 + + +def command_surface(args: argparse.Namespace) -> int: + if args.uri in (TUI_SURFACE_URI, TUI_SURFACE_KEY, TUI_SURFACE_ID): + surface = read_or_build_tui_surface(args.cache) + print(json.dumps(as_jsonable(surface), indent=2, sort_keys=True)) + return 0 + + if args.uri.startswith("cultmesh://brokkr/eve/unity/prefabs/"): + key = args.uri.removeprefix("cultmesh://brokkr/") + surface = read_surface_document(args.cache, key) + if surface is not None: + print(json.dumps(as_jsonable(surface), indent=2, sort_keys=True)) + return 0 + print(f"Surface not published in local mirror: {args.uri}", file=sys.stderr) + return 1 + + if args.uri.startswith("eve/unity/prefabs/"): + surface = read_surface_document(args.cache, args.uri) + if surface is not None: + print(json.dumps(as_jsonable(surface), indent=2, sort_keys=True)) + return 0 + print(f"Unsupported local surface URI: {args.uri}", file=sys.stderr) + return 1 + + print(f"Unsupported local surface URI: {args.uri}", file=sys.stderr) + return 1 + + +def command_publish_tui(args: argparse.Namespace) -> int: + surface = build_tui_surface(load_unity_snapshot(args.cache), version=args.version) + document = Document( + key=TUI_SURFACE_KEY, + type="gamecult.eve.surface", + payload=eve_surface_to_msgpack_payload(surface), + stored_at=now_utc(), + ) + write_document(args.cache, document) + if args.quiet: + return 0 + + print( + json.dumps( + { + "published": True, + "cache": str(args.cache), + "key": document.key, + "type": document.type, + "cultMeshUri": TUI_SURFACE_URI, + "surfaceId": TUI_SURFACE_ID, + "storedAt": document.stored_at, + }, + indent=2, + sort_keys=True, + ) + ) + return 0 + + +def command_prefab(args: argparse.Namespace) -> int: + prefab_path = args.path + if not prefab_path.is_absolute(): + prefab_path = (Path.cwd() / prefab_path).resolve() + if not prefab_path.exists(): + print(f"Prefab not found: {prefab_path}", file=sys.stderr) + return 1 + if prefab_path.suffix.lower() != ".prefab": + print(f"Not a Unity prefab: {prefab_path}", file=sys.stderr) + return 1 + + inspection = inspect_prefab(prefab_path, max_objects=args.max_objects) + print(json.dumps(as_jsonable(inspection), indent=2, sort_keys=True)) + return 0 + + +def command_publish_prefab(args: argparse.Namespace) -> int: + prefab_path = args.path + if not prefab_path.is_absolute(): + prefab_path = (Path.cwd() / prefab_path).resolve() + if not prefab_path.exists(): + print(f"Prefab not found: {prefab_path}", file=sys.stderr) + return 1 + if prefab_path.suffix.lower() != ".prefab": + print(f"Not a Unity prefab: {prefab_path}", file=sys.stderr) + return 1 + + inspection = inspect_prefab(prefab_path, max_objects=args.max_objects) + inspection["schema"] = PREFAB_INSPECTION_SCHEMA + inspection["providerId"] = "brokkr.unity_editor" + inspection["observedAt"] = now_utc() + asset_path = inspection["assetPath"] + inspection_key = prefab_inspection_key(asset_path) + surface_key = prefab_tui_key(asset_path) + surface_uri = prefab_tui_uri(asset_path) + surface = build_prefab_tui_surface(inspection, version=args.version) + stored_at = now_utc() + + import msgpack # type: ignore + + write_document( + args.cache, + Document( + key=inspection_key, + type=PREFAB_INSPECTION_SCHEMA, + payload=msgpack.packb(inspection, use_bin_type=True), + stored_at=stored_at, + ), + ) + write_document( + args.cache, + Document( + key=surface_key, + type="gamecult.eve.surface", + payload=eve_surface_to_msgpack_payload(surface), + stored_at=stored_at, + ), + ) + + if args.quiet: + return 0 + + print( + json.dumps( + { + "published": True, + "cache": str(args.cache), + "assetPath": asset_path, + "inspectionKey": inspection_key, + "inspectionType": PREFAB_INSPECTION_SCHEMA, + "surfaceKey": surface_key, + "surfaceType": "gamecult.eve.surface", + "cultMeshUri": surface_uri, + "surfaceId": prefab_tui_id(asset_path), + "storedAt": stored_at, + }, + indent=2, + sort_keys=True, + ) + ) + return 0 + + +def command_publish_prefab_object(args: argparse.Namespace) -> int: + prefab_path = args.path + if not prefab_path.is_absolute(): + prefab_path = (Path.cwd() / prefab_path).resolve() + if not prefab_path.exists(): + print(f"Prefab not found: {prefab_path}", file=sys.stderr) + return 1 + if prefab_path.suffix.lower() != ".prefab": + print(f"Not a Unity prefab: {prefab_path}", file=sys.stderr) + return 1 + + inspection = inspect_prefab(prefab_path, max_objects=args.max_objects) + inspection["schema"] = PREFAB_INSPECTION_SCHEMA + inspection["providerId"] = "brokkr.unity_editor" + inspection["observedAt"] = now_utc() + object_inspection = build_prefab_gameobject_inspection(inspection, args.selector) + asset_path = object_inspection["assetPath"] + object_id = object_inspection["gameObject"]["fileId"] + object_key = prefab_gameobject_inspection_key(asset_path, object_id) + surface_key = prefab_gameobject_tui_key(asset_path, object_id) + surface_uri = prefab_gameobject_tui_uri(asset_path, object_id) + surface = build_prefab_gameobject_tui_surface(object_inspection, version=args.version) + stored_at = now_utc() + + import msgpack # type: ignore + + write_document( + args.cache, + Document( + key=object_key, + type=PREFAB_GAMEOBJECT_INSPECTION_SCHEMA, + payload=msgpack.packb(object_inspection, use_bin_type=True), + stored_at=stored_at, + ), + ) + write_document( + args.cache, + Document( + key=surface_key, + type="gamecult.eve.surface", + payload=eve_surface_to_msgpack_payload(surface), + stored_at=stored_at, + ), + ) + + if args.quiet: + return 0 + + print( + json.dumps( + { + "published": True, + "cache": str(args.cache), + "assetPath": asset_path, + "gameObjectName": object_inspection["gameObject"]["name"], + "fileId": object_id, + "inspectionKey": object_key, + "inspectionType": PREFAB_GAMEOBJECT_INSPECTION_SCHEMA, + "surfaceKey": surface_key, + "surfaceType": "gamecult.eve.surface", + "cultMeshUri": surface_uri, + "surfaceId": prefab_gameobject_tui_id(asset_path, object_id), + "storedAt": stored_at, + }, + indent=2, + sort_keys=True, + ) + ) + return 0 + + +def existing_default_cache() -> Path: + cwd_cache = Path.cwd() / ".brokkr" / "unity-editor.ccmp" + if cwd_cache.exists(): + return cwd_cache + return DEFAULT_CACHE + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description="Inspect a Brokkr Unity CultCache mirror." + ) + parser.add_argument( + "--cache", + type=Path, + default=existing_default_cache(), + help="Path to unity-editor.ccmp.", + ) + subparsers = parser.add_subparsers(dest="command") + + overview = subparsers.add_parser("overview", help="Summarize the Unity mirror.") + overview.add_argument("--limit", type=int, default=8, help="Scene object sample size.") + overview.set_defaults(func=command_overview) + + list_cmd = subparsers.add_parser("list", help="List document keys.") + list_cmd.add_argument("--limit", type=int, default=80, help="Maximum rows to print.") + list_cmd.set_defaults(func=command_list) + + get_cmd = subparsers.add_parser("get", help="Print a decoded document payload.") + get_cmd.add_argument("key", help="CultCache document key.") + get_cmd.set_defaults(func=command_get) + + surface_cmd = subparsers.add_parser("surface", help="Resolve a local Eve surface.") + surface_cmd.add_argument( + "uri", + nargs="?", + default=TUI_SURFACE_URI, + help="Surface URI, key, or id. Defaults to the Unity editor TUI URI.", + ) + surface_cmd.set_defaults(func=command_surface) + + publish_tui = subparsers.add_parser( + "publish-tui", + help="Publish the generated Unity TUI surface into the Brokkr cache.", + ) + publish_tui.add_argument("--version", type=int, default=1, help="Surface document version.") + publish_tui.add_argument("--quiet", action="store_true", help="Do not print the publish receipt.") + publish_tui.set_defaults(func=command_publish_tui) + + prefab = subparsers.add_parser("prefab", help="Inspect a Unity prefab asset.") + prefab.add_argument("path", type=Path, help="Path to a .prefab file.") + prefab.add_argument( + "--max-objects", + type=int, + default=120, + help="Maximum GameObjects to include in the tree.", + ) + prefab.set_defaults(func=command_prefab) + + publish_prefab = subparsers.add_parser( + "publish-prefab", + help="Publish prefab inspection state and an Eve TUI surface into the Brokkr cache.", + ) + publish_prefab.add_argument("path", type=Path, help="Path to a .prefab file.") + publish_prefab.add_argument("--version", type=int, default=1, help="Surface document version.") + publish_prefab.add_argument( + "--max-objects", + type=int, + default=160, + help="Maximum GameObjects to include in the surface tree.", + ) + publish_prefab.add_argument("--quiet", action="store_true", help="Do not print the publish receipt.") + publish_prefab.set_defaults(func=command_publish_prefab) + + publish_prefab_object = subparsers.add_parser( + "publish-prefab-object", + help="Publish one prefab GameObject inspection and an Eve TUI surface.", + ) + publish_prefab_object.add_argument("path", type=Path, help="Path to a .prefab file.") + publish_prefab_object.add_argument("selector", help="GameObject name or fileID.") + publish_prefab_object.add_argument("--version", type=int, default=1, help="Surface document version.") + publish_prefab_object.add_argument( + "--max-objects", + type=int, + default=240, + help="Maximum GameObjects to parse from the prefab hierarchy.", + ) + publish_prefab_object.add_argument("--quiet", action="store_true", help="Do not print the publish receipt.") + publish_prefab_object.set_defaults(func=command_publish_prefab_object) + + parser.set_defaults(func=command_overview, limit=8) + return parser + + +def main() -> int: + parser = build_parser() + args = parser.parse_args() + args.cache = args.cache.resolve() + if not args.cache.exists(): + print(f"Cache not found: {args.cache}", file=sys.stderr) + return 1 + return args.func(args) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/check.ps1 b/tools/check.ps1 index e9d1c8e..4298684 100644 --- a/tools/check.ps1 +++ b/tools/check.ps1 @@ -54,7 +54,8 @@ try { "GameCult.Caching.MessagePack.dll", "GameCult.Mesh.dll", "GameCult.Networking.dll", - "MessagePack.dll", + "MessagePack.CultMesh.dll", + "MessagePack.Annotations.dll", "R3.dll" ) @@ -65,6 +66,16 @@ try { } } + $staleMessagePackPath = Join-Path $pluginRoot "MessagePack.dll" + if (Test-Path $staleMessagePackPath) { + throw "Brokkr Unity package must not vendor MessagePack.dll; use MessagePack.CultMesh.dll to avoid colliding with Unity MessagePack.asmdef." + } + + $staleVectorsPath = Join-Path $pluginRoot "System.Numerics.Vectors.dll" + if (Test-Path $staleVectorsPath) { + throw "Brokkr Unity package must not vendor System.Numerics.Vectors.dll; Unity provides the facade assembly and duplicate versions create resolver conflicts." + } + $bundledPython = Join-Path $env:USERPROFILE ".cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe" if (Test-Path $bundledPython) { $pythonExe = $bundledPython