Add Brokkr prefab mirror pipeline

This commit is contained in:
Meta Vens 2026-06-28 11:23:04 +01:00
commit 8d5b580e5e
19 changed files with 2756 additions and 8 deletions

View file

@ -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

View file

@ -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]

View file

@ -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,
)

View file

@ -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:

View file

@ -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`

View file

@ -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<BrokkrSyncObjectBinding>()
.OrderBy(binding => binding.displayName, StringComparer.Ordinal)
.ToArray(),
timelineBindings = documents
.OfType<BrokkrSyncTimelineBinding>()
.OrderBy(binding => binding.displayName, StringComparer.Ordinal)
.ToArray(),
syncVars = documents
.OfType<BrokkrSyncVar>()
.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<BrokkrSyncObjectBinding>();
internal BrokkrSyncTimelineBinding[] timelineBindings = Array.Empty<BrokkrSyncTimelineBinding>();
internal BrokkrSyncVar[] syncVars = Array.Empty<BrokkrSyncVar>();
}
}

View file

@ -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();
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 742fe602d7748754e88e5463e8f75f20

View file

@ -0,0 +1,13 @@
using UnityEditor.Callbacks;
namespace GameCult.Brokkr.Editor
{
public static class BrokkrDaemonBridgeReloadHook
{
[DidReloadScripts]
public static void StartAfterScriptsReload()
{
BrokkrEditorDaemonBridge.InitializeDaemonBridge();
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 00e96afda2ec964429638d77bfcf91a3

View file

@ -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());
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 84750a54e28cc50499c465bc07a42769

View file

@ -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", "");

View file

@ -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<GameObject>(prefabAssetPath.Trim());
if (prefab == null)
{
throw new InvalidOperationException($"Prefab was not found: {prefabAssetPath}");
}
var nodes = new List<BrokkrUnityPrefabNodeSnapshot>();
var assets = new Dictionary<string, BrokkrUnityPrefabAssetRequirement>(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<BrokkrGameObjectSnapshot>();
@ -101,6 +143,126 @@ namespace GameCult.Brokkr.Editor
}
}
private static void CapturePrefabNode(
GameObject gameObject,
string parentNodeId,
string path,
ICollection<BrokkrUnityPrefabNodeSnapshot> nodes,
IDictionary<string, BrokkrUnityPrefabAssetRequirement> 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<string, BrokkrUnityPrefabAssetRequirement> assets)
{
var mesh = gameObject.GetComponent<MeshFilter>()?.sharedMesh;
if (mesh == null)
{
var skinned = gameObject.GetComponent<SkinnedMeshRenderer>();
mesh = skinned != null ? skinned.sharedMesh : null;
}
return mesh == null ? "" : AddAssetRequirement(assets, "mesh", mesh);
}
private static string[] CaptureMaterialRequirements(
GameObject gameObject,
IDictionary<string, BrokkrUnityPrefabAssetRequirement> assets)
{
var renderer = gameObject.GetComponent<Renderer>();
if (renderer == null)
{
return Array.Empty<string>();
}
var result = new List<string>();
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<string, BrokkrUnityPrefabAssetRequirement> 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<string, BrokkrUnityPrefabAssetRequirement> 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<Component>()
@ -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("\\", "_")));
}
}
}

View file

@ -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();

View file

@ -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<BrokkrUnityPrefabNodeSnapshot>();
[Key(11)] public BrokkrUnityPrefabAssetRequirement[] assets = Array.Empty<BrokkrUnityPrefabAssetRequirement>();
}
[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<string>();
[Key(12)] public BrokkrComponentSnapshot[] components = Array.Empty<BrokkrComponentSnapshot>();
}
[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

View file

@ -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.

1658
tools/brokkr-unity-cache.py Normal file

File diff suppressed because it is too large Load diff

View file

@ -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