diff --git a/brokkr-daemon/src/main.rs b/brokkr-daemon/src/main.rs index dadd0c5..8925b12 100644 --- a/brokkr-daemon/src/main.rs +++ b/brokkr-daemon/src/main.rs @@ -1,5 +1,7 @@ use anyhow::{Context, Result, bail}; use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::VecDeque; use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use std::sync::{Arc, Mutex}; @@ -92,11 +94,58 @@ struct ToolHostSnapshot { selected_object_names: Vec, asset_count: Option, capabilities: Vec, + #[serde(default)] + scene_objects: Vec, + #[serde(default)] + assets: Vec, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +struct UnityCommand { + schema: String, + command_id: String, + action: String, + #[serde(default)] + target_object_id: String, + #[serde(default)] + name: String, + #[serde(default)] + component_type: String, + #[serde(default)] + property_path: String, + #[serde(default)] + value: String, + #[serde(default)] + asset_path: String, + #[serde(default)] + parent_object_id: String, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +struct UnityCommandEnvelope { + command: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +struct UnityCommandReceipt { + schema: String, + command_id: String, + status: String, + message: String, + #[serde(default)] + object_id: String, + observed_at: String, } #[derive(Default)] struct BrokerState { unity_snapshot: Option, + unity_command_queue: VecDeque, + unity_receipts: Vec, + next_command_number: u64, } #[derive(Debug, Serialize)] @@ -113,6 +162,52 @@ struct HostSnapshotsResponse { unity: Option, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct UnitySceneResponse { + provider_id: &'static str, + observed_at: Option, + scene_objects: Vec, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct UnityAssetsResponse { + provider_id: &'static str, + observed_at: Option, + assets: Vec, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct EveSurfaceDocument { + schema: &'static str, + surface_id: &'static str, + mode: &'static str, + title: &'static str, + provider_id: &'static str, + updated_at: Option, + sections: Vec, + commands: Vec, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct EveSurfaceSection { + id: &'static str, + title: &'static str, + kind: &'static str, + items: Vec, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct EveCommandAffordance { + id: &'static str, + title: &'static str, + command_schema: &'static str, +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct SnapshotReceipt<'a> { @@ -191,6 +286,48 @@ fn handle_connection(mut stream: TcpStream, state: Arc>) -> R }, )? } + ("GET", "/unity/scene") => { + let state = state.lock().expect("broker state poisoned"); + let snapshot = state.unity_snapshot.clone(); + json_response( + 200, + &UnitySceneResponse { + provider_id: "brokkr.unity_editor", + observed_at: snapshot.as_ref().map(|item| item.observed_at.clone()), + scene_objects: snapshot + .as_ref() + .map(|item| item.scene_objects.clone()) + .unwrap_or_default(), + }, + )? + } + ("GET", "/unity/assets") => { + let state = state.lock().expect("broker state poisoned"); + let snapshot = state.unity_snapshot.clone(); + json_response( + 200, + &UnityAssetsResponse { + provider_id: "brokkr.unity_editor", + observed_at: snapshot.as_ref().map(|item| item.observed_at.clone()), + assets: snapshot + .as_ref() + .map(|item| item.assets.clone()) + .unwrap_or_default(), + }, + )? + } + ("GET", "/unity/receipts") => { + let state = state.lock().expect("broker state poisoned"); + json_response(200, &state.unity_receipts)? + } + ("GET", "/eve/unity/gui") => { + let state = state.lock().expect("broker state poisoned"); + json_response(200, &build_unity_eve_surface(&state, "gui"))? + } + ("GET", "/eve/unity/tui") => { + let state = state.lock().expect("broker state poisoned"); + json_response(200, &build_unity_eve_surface(&state, "tui"))? + } ("POST", "/hosts/unity/snapshot") => { let snapshot: ToolHostSnapshot = serde_json::from_slice(&request.body) .context("invalid Unity host snapshot JSON")?; @@ -205,6 +342,34 @@ fn handle_connection(mut stream: TcpStream, state: Arc>) -> R state.lock().expect("broker state poisoned").unity_snapshot = Some(snapshot); json_response(202, &receipt)? } + ("POST", "/commands/unity") => { + let mut command: UnityCommand = + serde_json::from_slice(&request.body).context("invalid Unity command JSON")?; + validate_unity_command(&command)?; + let mut state = state.lock().expect("broker state poisoned"); + if command.command_id.is_empty() { + state.next_command_number += 1; + command.command_id = format!("unity-command-{}", state.next_command_number); + } + state.unity_command_queue.push_back(command.clone()); + json_response(202, &command)? + } + ("GET", "/hosts/unity/commands/next") => { + let mut state = state.lock().expect("broker state poisoned"); + let command = state.unity_command_queue.pop_front(); + json_response(200, &UnityCommandEnvelope { command })? + } + ("POST", "/hosts/unity/commands/receipt") => { + let receipt: UnityCommandReceipt = serde_json::from_slice(&request.body) + .context("invalid Unity command receipt JSON")?; + validate_unity_receipt(&receipt)?; + state + .lock() + .expect("broker state poisoned") + .unity_receipts + .push(receipt.clone()); + json_response(202, &receipt)? + } _ => text_response(404, "not found"), }; @@ -212,6 +377,106 @@ fn handle_connection(mut stream: TcpStream, state: Arc>) -> R Ok(()) } +fn validate_unity_command(command: &UnityCommand) -> Result<()> { + if command.schema != "gamecult.brokkr.unity_command.v0" { + bail!("unexpected Unity command schema: {}", command.schema); + } + match command.action.as_str() { + "createGameObject" + | "attachComponent" + | "setComponentProperty" + | "instantiatePrefab" + | "createPrefabVariant" => Ok(()), + _ => bail!("unsupported Unity command action: {}", command.action), + } +} + +fn validate_unity_receipt(receipt: &UnityCommandReceipt) -> Result<()> { + if receipt.schema != "gamecult.brokkr.unity_command_receipt.v0" { + bail!("unexpected Unity receipt schema: {}", receipt.schema); + } + Ok(()) +} + +fn build_unity_eve_surface(state: &BrokerState, mode: &'static str) -> EveSurfaceDocument { + let snapshot = state.unity_snapshot.clone(); + let scene_objects = snapshot + .as_ref() + .map(|item| item.scene_objects.iter().take(80).cloned().collect()) + .unwrap_or_default(); + let assets = snapshot + .as_ref() + .map(|item| item.assets.iter().take(80).cloned().collect()) + .unwrap_or_default(); + let receipts = state + .unity_receipts + .iter() + .rev() + .take(25) + .map(|receipt| serde_json::to_value(receipt).unwrap_or(Value::Null)) + .collect(); + + EveSurfaceDocument { + schema: "gamecult.eve.surface.v1", + surface_id: if mode == "tui" { + "brokkr.eve.unity_editor_tui.v0" + } else { + "brokkr.eve.unity_editor_gui.v0" + }, + mode, + title: "Unity Editor", + provider_id: "brokkr.unity_editor", + updated_at: snapshot.as_ref().map(|item| item.observed_at.clone()), + sections: vec![ + EveSurfaceSection { + id: "scene", + title: "Scene Graph", + kind: "tree", + items: scene_objects, + }, + EveSurfaceSection { + id: "assets", + title: "Asset Library", + kind: "table", + items: assets, + }, + EveSurfaceSection { + id: "receipts", + title: "Command Receipts", + kind: "log", + items: receipts, + }, + ], + commands: vec![ + EveCommandAffordance { + id: "createGameObject", + title: "Create GameObject", + command_schema: "gamecult.brokkr.unity_command.v0", + }, + EveCommandAffordance { + id: "attachComponent", + title: "Attach Component", + command_schema: "gamecult.brokkr.unity_command.v0", + }, + EveCommandAffordance { + id: "setComponentProperty", + title: "Set Component Property", + command_schema: "gamecult.brokkr.unity_command.v0", + }, + EveCommandAffordance { + id: "instantiatePrefab", + title: "Instantiate Prefab", + command_schema: "gamecult.brokkr.unity_command.v0", + }, + EveCommandAffordance { + id: "createPrefabVariant", + title: "Create Prefab Variant", + command_schema: "gamecult.brokkr.unity_command.v0", + }, + ], + } +} + fn validate_unity_snapshot(snapshot: &ToolHostSnapshot) -> Result<()> { if snapshot.schema != "gamecult.brokkr.tool_host_snapshot.v0" { bail!("unexpected snapshot schema: {}", snapshot.schema); @@ -374,6 +639,18 @@ fn build_provider_advertisement() -> ProviderAdvertisement { cult_mesh_uri: "cultmesh://brokkr/eve/command-receipts", schema: "gamecult.eve.surface.v1", }, + EveSurface { + id: "brokkr.eve.unity_editor_gui.v0", + title: "Unity Editor GUI", + cult_mesh_uri: "cultmesh://brokkr/eve/unity/gui", + schema: "gamecult.eve.surface.v1", + }, + EveSurface { + id: "brokkr.eve.unity_editor_tui.v0", + title: "Unity Editor TUI", + cult_mesh_uri: "cultmesh://brokkr/eve/unity/tui", + schema: "gamecult.eve.surface.v1", + }, ], command_policy: CommandPolicy { mode: "policy-gated", diff --git a/docs/architecture.md b/docs/architecture.md index 2d072cd..6b1b6b9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -9,9 +9,13 @@ daemon, beginning with Unity and Blender plugin surfaces. Brokkr starts as a Rust daemon that emits a provider advertisement and exposes a local HTTP adapter lane for tool plugins. Unity can capture a host snapshot from -the editor and publish it to `POST /hosts/unity/snapshot`; Brokkr validates and -retains that snapshot for `GET /hosts`. Blender still has a thin plugin scaffold -with host-local metadata and connection settings. +the editor, including scene graph, components, serialized component state, and +asset library records, then publish it to `POST /hosts/unity/snapshot`. Brokkr +validates and retains that snapshot for `GET /hosts`, `/unity/scene`, +`/unity/assets`, and Eve GUI/TUI lowerings. Unity writes are queued through +`POST /commands/unity`; the Unity adapter polls, executes the command, and posts +a receipt. Blender still has a thin plugin scaffold with host-local metadata and +connection settings. ## Invariants @@ -56,6 +60,7 @@ Outputs: - `gamecult.brokkr.command_request.v0` - `gamecult.brokkr.command_receipt.v0` - local adapter receipts for accepted host snapshots +- Unity editor GUI/TUI Eve surface projections - Eve/CultUI surface documents for host status, selection, assets, scene/object trees, command palette, and receipt history. diff --git a/docs/provider-contract.md b/docs/provider-contract.md index 6ad32cf..0a78683 100644 --- a/docs/provider-contract.md +++ b/docs/provider-contract.md @@ -33,6 +33,43 @@ has issued a command request with a receipt id. - `GET /provider` - `GET /hosts` - `POST /hosts/unity/snapshot` +- `GET /unity/scene` +- `GET /unity/assets` +- `POST /commands/unity` +- `GET /hosts/unity/commands/next` +- `POST /hosts/unity/commands/receipt` +- `GET /unity/receipts` +- `GET /eve/unity/gui` +- `GET /eve/unity/tui` The HTTP lane is a local adapter transport. It is not the canonical public Verse contract. + +## Unity Command Actions + +All Unity writes use `gamecult.brokkr.unity_command.v0` and receive +`gamecult.brokkr.unity_command_receipt.v0`. + +- `createGameObject` +- `attachComponent` +- `setComponentProperty` +- `instantiatePrefab` +- `createPrefabVariant` + +Unity owns the mutation. Brokkr queues the command and records the receipt after +Unity executes it. + +## Eve/CultUI Lowerings + +`/eve/unity/gui` and `/eve/unity/tui` expose the Unity editor surface as +`gamecult.eve.surface.v1` projections. GUI and TUI clients should render these +documents as views over the same Brokkr state: + +- scene graph +- component state +- asset library +- command affordances +- command receipts + +These documents are not dashboard-owned truth. They are lowerable interface +state over Unity observations and Brokkr command receipts. diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrBrokerClient.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrBrokerClient.cs index 108513b..9bfed33 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrBrokerClient.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrBrokerClient.cs @@ -21,6 +21,19 @@ namespace GameCult.Brokkr.Editor return JsonUtility.FromJson(response); } + internal static BrokkrUnityCommand GetNextUnityCommand(string endpoint) + { + var response = Send(endpoint, "/hosts/unity/commands/next", "GET", null); + var envelope = JsonUtility.FromJson(response); + return envelope?.command; + } + + internal static void PublishUnityCommandReceipt(string endpoint, BrokkrUnityCommandReceipt receipt) + { + var json = JsonUtility.ToJson(receipt); + Send(endpoint, "/hosts/unity/commands/receipt", "POST", json); + } + private static string Send(string endpoint, string path, string method, string body) { var request = (HttpWebRequest)WebRequest.Create(endpoint.TrimEnd('/') + path); @@ -54,4 +67,3 @@ namespace GameCult.Brokkr.Editor } } } - diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrSettings.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrSettings.cs index c708694..81ae6ff 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrSettings.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrSettings.cs @@ -26,5 +26,11 @@ namespace GameCult.Brokkr.Editor get => EditorPrefs.GetBool("GameCult.Brokkr.AutoPublish", false); set => EditorPrefs.SetBool("GameCult.Brokkr.AutoPublish", value); } + + internal static bool AutoPollCommands + { + get => EditorPrefs.GetBool("GameCult.Brokkr.AutoPollCommands", false); + set => EditorPrefs.SetBool("GameCult.Brokkr.AutoPollCommands", value); + } } } diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnityCommandExecutor.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnityCommandExecutor.cs new file mode 100644 index 0000000..69b4b48 --- /dev/null +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnityCommandExecutor.cs @@ -0,0 +1,238 @@ +using System; +using System.Globalization; +using GameCult.Brokkr; +using UnityEditor; +using UnityEditor.SceneManagement; +using UnityEngine; + +namespace GameCult.Brokkr.Editor +{ + internal static class BrokkrUnityCommandExecutor + { + internal static BrokkrUnityCommandReceipt Execute(BrokkrUnityCommand command) + { + try + { + return command.action switch + { + "createGameObject" => CreateGameObject(command), + "attachComponent" => AttachComponent(command), + "setComponentProperty" => SetComponentProperty(command), + "instantiatePrefab" => InstantiatePrefab(command), + "createPrefabVariant" => CreatePrefabVariant(command), + _ => Failed(command, $"Unsupported Unity command action: {command.action}") + }; + } + catch (Exception error) + { + return Failed(command, error.Message); + } + } + + private static BrokkrUnityCommandReceipt CreateGameObject(BrokkrUnityCommand command) + { + var gameObject = new GameObject(string.IsNullOrWhiteSpace(command.name) + ? "Brokkr GameObject" + : command.name); + Undo.RegisterCreatedObjectUndo(gameObject, "Brokkr Create GameObject"); + AttachParent(gameObject, command.parentObjectId); + EditorSceneManager.MarkSceneDirty(gameObject.scene); + return Accepted(command, "GameObject created.", BrokkrUnitySnapshotBuilder.GetObjectId(gameObject)); + } + + private static BrokkrUnityCommandReceipt AttachComponent(BrokkrUnityCommand command) + { + var gameObject = ResolveGameObject(command.targetObjectId); + if (gameObject == null) + { + return Failed(command, "Target GameObject was not found."); + } + + var type = BrokkrUnitySnapshotBuilder.ResolveType(command.componentType); + if (type == null || !typeof(Component).IsAssignableFrom(type)) + { + return Failed(command, $"Component type is not available: {command.componentType}"); + } + + var component = Undo.AddComponent(gameObject, type); + EditorSceneManager.MarkSceneDirty(gameObject.scene); + return Accepted(command, "Component attached.", BrokkrUnitySnapshotBuilder.GetObjectId(component)); + } + + private static BrokkrUnityCommandReceipt SetComponentProperty(BrokkrUnityCommand command) + { + var target = BrokkrUnitySnapshotBuilder.ResolveObjectId(command.targetObjectId); + if (target == null) + { + return Failed(command, "Target object was not found."); + } + + using var serializedObject = new SerializedObject(target); + var property = serializedObject.FindProperty(command.propertyPath); + if (property == null) + { + return Failed(command, $"Serialized property was not found: {command.propertyPath}"); + } + + if (!TryWriteProperty(property, command.value, out var message)) + { + return Failed(command, message); + } + + serializedObject.ApplyModifiedProperties(); + EditorUtility.SetDirty(target); + if (target is Component component) + { + EditorSceneManager.MarkSceneDirty(component.gameObject.scene); + } + + return Accepted(command, "Serialized property updated.", command.targetObjectId); + } + + private static BrokkrUnityCommandReceipt InstantiatePrefab(BrokkrUnityCommand command) + { + var prefab = AssetDatabase.LoadAssetAtPath(command.assetPath); + if (prefab == null) + { + return Failed(command, $"Prefab was not found: {command.assetPath}"); + } + + var instance = (GameObject)PrefabUtility.InstantiatePrefab(prefab); + if (!string.IsNullOrWhiteSpace(command.name)) + { + instance.name = command.name; + } + + Undo.RegisterCreatedObjectUndo(instance, "Brokkr Instantiate Prefab"); + AttachParent(instance, command.parentObjectId); + EditorSceneManager.MarkSceneDirty(instance.scene); + return Accepted(command, "Prefab instantiated.", BrokkrUnitySnapshotBuilder.GetObjectId(instance)); + } + + private static BrokkrUnityCommandReceipt CreatePrefabVariant(BrokkrUnityCommand command) + { + var prefab = AssetDatabase.LoadAssetAtPath(command.assetPath); + if (prefab == null) + { + return Failed(command, $"Prefab was not found: {command.assetPath}"); + } + + var variantPath = command.value; + if (string.IsNullOrWhiteSpace(variantPath)) + { + var baseName = string.IsNullOrWhiteSpace(command.name) ? $"{prefab.name}Variant" : command.name; + variantPath = $"Assets/{baseName}.prefab"; + } + + var instance = (GameObject)PrefabUtility.InstantiatePrefab(prefab); + PrefabUtility.SaveAsPrefabAsset(instance, variantPath); + UnityEngine.Object.DestroyImmediate(instance); + AssetDatabase.SaveAssets(); + AssetDatabase.Refresh(); + return Accepted(command, $"Prefab variant saved: {variantPath}", variantPath); + } + + private static GameObject ResolveGameObject(string objectId) + { + var target = BrokkrUnitySnapshotBuilder.ResolveObjectId(objectId); + return target switch + { + GameObject gameObject => gameObject, + Component component => component.gameObject, + _ => null + }; + } + + private static void AttachParent(GameObject gameObject, string parentObjectId) + { + var parent = ResolveGameObject(parentObjectId); + if (parent != null) + { + gameObject.transform.SetParent(parent.transform); + } + } + + private static bool TryWriteProperty(SerializedProperty property, string value, out string message) + { + message = ""; + switch (property.propertyType) + { + case SerializedPropertyType.Integer: + case SerializedPropertyType.LayerMask: + if (!int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intValue)) + { + message = $"Expected integer value for {property.propertyPath}."; + return false; + } + + property.intValue = intValue; + return true; + case SerializedPropertyType.Boolean: + if (!bool.TryParse(value, out var boolValue)) + { + message = $"Expected boolean value for {property.propertyPath}."; + return false; + } + + property.boolValue = boolValue; + return true; + case SerializedPropertyType.Float: + if (!float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var floatValue)) + { + message = $"Expected float value for {property.propertyPath}."; + return false; + } + + property.floatValue = floatValue; + return true; + case SerializedPropertyType.String: + property.stringValue = value; + return true; + case SerializedPropertyType.Enum: + var index = Array.IndexOf(property.enumDisplayNames, value); + if (index < 0 && int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedIndex)) + { + index = parsedIndex; + } + + if (index < 0 || index >= property.enumDisplayNames.Length) + { + message = $"Expected enum display name or index for {property.propertyPath}."; + return false; + } + + property.enumValueIndex = index; + return true; + default: + message = $"Property type is not writable yet: {property.propertyType}."; + return false; + } + } + + private static BrokkrUnityCommandReceipt Accepted(BrokkrUnityCommand command, string message, string objectId) + { + return Receipt(command, "accepted", message, objectId); + } + + private static BrokkrUnityCommandReceipt Failed(BrokkrUnityCommand command, string message) + { + return Receipt(command, "failed", message, ""); + } + + private static BrokkrUnityCommandReceipt Receipt( + BrokkrUnityCommand command, + string status, + string message, + string objectId) + { + return new BrokkrUnityCommandReceipt + { + commandId = command.commandId, + status = status, + message = message, + objectId = objectId, + observedAt = DateTime.UtcNow.ToString("O") + }; + } + } +} diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs index 6239705..48c2339 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs @@ -1,14 +1,20 @@ using System; +using System.Collections.Generic; +using System.Globalization; using System.Linq; +using System.Reflection; using GameCult.Brokkr; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; +using UnityEngine.SceneManagement; namespace GameCult.Brokkr.Editor { internal static class BrokkrUnitySnapshotBuilder { + private const int MaxSerializedPropertiesPerComponent = 160; + private static readonly string[] Capabilities = { "host.status.read", @@ -35,7 +41,197 @@ namespace GameCult.Brokkr.Editor .Select(item => item.name) .ToArray(), assetCount = AssetDatabase.GetAllAssetPaths().Length, - capabilities = Capabilities + capabilities = Capabilities, + sceneObjects = CaptureSceneObjects(), + assets = CaptureAssets() + }; + } + + private static BrokkrGameObjectSnapshot[] CaptureSceneObjects() + { + var objects = new List(); + + for (var sceneIndex = 0; sceneIndex < EditorSceneManager.sceneCount; sceneIndex++) + { + var scene = EditorSceneManager.GetSceneAt(sceneIndex); + if (!scene.isLoaded) + { + continue; + } + + foreach (var root in scene.GetRootGameObjects()) + { + CaptureGameObject(root, scene, root.name, "", objects); + } + } + + return objects.ToArray(); + } + + private static void CaptureGameObject( + GameObject gameObject, + Scene scene, + string path, + string parentId, + ICollection objects) + { + var objectId = GetObjectId(gameObject); + objects.Add(new BrokkrGameObjectSnapshot + { + objectId = objectId, + name = gameObject.name, + path = path, + scenePath = scene.path, + activeSelf = gameObject.activeSelf, + tag = gameObject.tag, + layer = gameObject.layer, + childCount = gameObject.transform.childCount, + parentId = parentId, + components = CaptureComponents(gameObject) + }); + + for (var childIndex = 0; childIndex < gameObject.transform.childCount; childIndex++) + { + var child = gameObject.transform.GetChild(childIndex).gameObject; + CaptureGameObject(child, scene, $"{path}/{child.name}", objectId, objects); + } + } + + private static BrokkrComponentSnapshot[] CaptureComponents(GameObject gameObject) + { + return gameObject.GetComponents() + .Where(component => component != null) + .Select(component => new BrokkrComponentSnapshot + { + componentId = GetObjectId(component), + typeName = component.GetType().FullName, + assemblyQualifiedName = component.GetType().AssemblyQualifiedName, + enabled = ReadEnabled(component), + properties = CaptureProperties(component) + }) + .ToArray(); + } + + private static BrokkrSerializedPropertySnapshot[] CaptureProperties(UnityEngine.Object target) + { + var properties = new List(); + using var serializedObject = new SerializedObject(target); + var iterator = serializedObject.GetIterator(); + var enterChildren = true; + + while (iterator.NextVisible(enterChildren)) + { + enterChildren = false; + if (iterator.propertyPath == "m_Script") + { + continue; + } + + properties.Add(new BrokkrSerializedPropertySnapshot + { + path = iterator.propertyPath, + displayName = iterator.displayName, + propertyType = iterator.propertyType.ToString(), + value = ReadPropertyValue(iterator), + editable = iterator.editable && !iterator.isArray + }); + + if (properties.Count >= MaxSerializedPropertiesPerComponent) + { + break; + } + } + + return properties.ToArray(); + } + + private static BrokkrAssetSnapshot[] CaptureAssets() + { + return AssetDatabase.GetAllAssetPaths() + .Where(path => path.StartsWith("Assets/", StringComparison.Ordinal)) + .Select(path => + { + var type = AssetDatabase.GetMainAssetTypeAtPath(path); + return new BrokkrAssetSnapshot + { + path = path, + guid = AssetDatabase.AssetPathToGUID(path), + typeName = type?.FullName ?? "", + isPrefab = path.EndsWith(".prefab", StringComparison.OrdinalIgnoreCase) + }; + }) + .ToArray(); + } + + internal static string GetObjectId(UnityEngine.Object target) + { + return GlobalObjectId.GetGlobalObjectIdSlow(target).ToString(); + } + + internal static UnityEngine.Object ResolveObjectId(string objectId) + { + if (string.IsNullOrWhiteSpace(objectId)) + { + return null; + } + + return GlobalObjectId.TryParse(objectId, out var globalObjectId) + ? GlobalObjectId.GlobalObjectIdentifierToObjectSlow(globalObjectId) + : null; + } + + internal static Type ResolveType(string typeName) + { + if (string.IsNullOrWhiteSpace(typeName)) + { + return null; + } + + var direct = Type.GetType(typeName); + if (direct != null) + { + return direct; + } + + return AppDomain.CurrentDomain.GetAssemblies() + .Select(assembly => assembly.GetType(typeName)) + .FirstOrDefault(type => type != null); + } + + private static bool ReadEnabled(Component component) + { + return component switch + { + Behaviour behaviour => behaviour.enabled, + Renderer renderer => renderer.enabled, + Collider collider => collider.enabled, + _ => true + }; + } + + private static string ReadPropertyValue(SerializedProperty property) + { + return property.propertyType switch + { + SerializedPropertyType.Integer => property.intValue.ToString(CultureInfo.InvariantCulture), + SerializedPropertyType.Boolean => property.boolValue ? "true" : "false", + SerializedPropertyType.Float => property.floatValue.ToString(CultureInfo.InvariantCulture), + SerializedPropertyType.String => property.stringValue, + SerializedPropertyType.Color => property.colorValue.ToString(), + SerializedPropertyType.ObjectReference => property.objectReferenceValue != null + ? GetObjectId(property.objectReferenceValue) + : "", + SerializedPropertyType.LayerMask => property.intValue.ToString(CultureInfo.InvariantCulture), + SerializedPropertyType.Enum => property.enumDisplayNames.Length > property.enumValueIndex + ? property.enumDisplayNames[property.enumValueIndex] + : property.enumValueIndex.ToString(CultureInfo.InvariantCulture), + SerializedPropertyType.Vector2 => property.vector2Value.ToString(), + SerializedPropertyType.Vector3 => property.vector3Value.ToString(), + SerializedPropertyType.Vector4 => property.vector4Value.ToString(), + SerializedPropertyType.Rect => property.rectValue.ToString(), + SerializedPropertyType.Bounds => property.boundsValue.ToString(), + SerializedPropertyType.Quaternion => property.quaternionValue.eulerAngles.ToString(), + _ => "" }; } } diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrWindow.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrWindow.cs index 572be68..9255529 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrWindow.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrWindow.cs @@ -10,9 +10,11 @@ namespace GameCult.Brokkr.Editor private string brokerUri = BrokkrSettings.DefaultBrokerUri; private string httpEndpoint = BrokkrSettings.DefaultHttpEndpoint; private bool autoPublish; + private bool autoPollCommands; private BrokkrHostSnapshot lastSnapshot; private string lastReceipt = "No snapshot published yet."; private MessageType lastMessageType = MessageType.Info; + private double nextPollAt; [MenuItem("GameCult/Brokkr")] public static void Open() @@ -25,9 +27,11 @@ namespace GameCult.Brokkr.Editor brokerUri = BrokkrSettings.BrokerUri; httpEndpoint = BrokkrSettings.HttpEndpoint; autoPublish = BrokkrSettings.AutoPublish; + autoPollCommands = BrokkrSettings.AutoPollCommands; Selection.selectionChanged += Repaint; EditorSceneManagerBridge.SceneDirtied += OnEditorSignal; EditorApplication.playModeStateChanged += OnPlayModeChanged; + EditorApplication.update += OnEditorUpdate; } private void OnDisable() @@ -35,6 +39,7 @@ namespace GameCult.Brokkr.Editor Selection.selectionChanged -= Repaint; EditorSceneManagerBridge.SceneDirtied -= OnEditorSignal; EditorApplication.playModeStateChanged -= OnPlayModeChanged; + EditorApplication.update -= OnEditorUpdate; } private void OnGUI() @@ -44,12 +49,14 @@ namespace GameCult.Brokkr.Editor brokerUri = EditorGUILayout.TextField("Broker URI", brokerUri); httpEndpoint = EditorGUILayout.TextField("HTTP Endpoint", httpEndpoint); autoPublish = EditorGUILayout.Toggle("Auto Publish", autoPublish); + autoPollCommands = EditorGUILayout.Toggle("Auto Poll Commands", autoPollCommands); if (GUILayout.Button("Save Settings")) { BrokkrSettings.BrokerUri = brokerUri; BrokkrSettings.HttpEndpoint = httpEndpoint; BrokkrSettings.AutoPublish = autoPublish; + BrokkrSettings.AutoPollCommands = autoPollCommands; SetStatus("Settings saved.", MessageType.Info); } @@ -67,9 +74,17 @@ namespace GameCult.Brokkr.Editor } } - if (GUILayout.Button("Ping Brokkr")) + using (new EditorGUILayout.HorizontalScope()) { - PingBroker(); + if (GUILayout.Button("Ping Brokkr")) + { + PingBroker(); + } + + if (GUILayout.Button("Poll Command")) + { + PollAndExecuteCommand(false); + } } EditorGUILayout.Space(); @@ -83,6 +98,7 @@ namespace GameCult.Brokkr.Editor EditorGUILayout.LabelField("Active Scene", lastSnapshot.activeScenePath); EditorGUILayout.LabelField("Open Scenes", lastSnapshot.openSceneCount.ToString()); EditorGUILayout.LabelField("Assets", lastSnapshot.assetCount.ToString()); + EditorGUILayout.LabelField("Scene Objects", lastSnapshot.sceneObjects.Length.ToString()); EditorGUILayout.LabelField("Selection", string.Join(", ", lastSnapshot.selectedObjectNames)); } } @@ -124,6 +140,33 @@ namespace GameCult.Brokkr.Editor } } + private void PollAndExecuteCommand(bool quiet) + { + try + { + var command = BrokkrBrokerClient.GetNextUnityCommand(httpEndpoint); + if (command == null || string.IsNullOrEmpty(command.commandId)) + { + if (!quiet) + { + SetStatus("No queued Unity command.", MessageType.Info); + } + + return; + } + + var receipt = BrokkrUnityCommandExecutor.Execute(command); + BrokkrBrokerClient.PublishUnityCommandReceipt(httpEndpoint, receipt); + lastSnapshot = BrokkrUnitySnapshotBuilder.Capture(); + BrokkrBrokerClient.PublishUnitySnapshot(httpEndpoint, lastSnapshot); + SetStatus($"Command {receipt.status}: {receipt.commandId} {receipt.message}", MessageType.Info); + } + catch (Exception error) + { + SetStatus(error.Message, MessageType.Error); + } + } + private void OnEditorSignal() { if (autoPublish) @@ -142,6 +185,17 @@ namespace GameCult.Brokkr.Editor OnEditorSignal(); } + private void OnEditorUpdate() + { + if (!autoPollCommands || EditorApplication.timeSinceStartup < nextPollAt) + { + return; + } + + nextPollAt = EditorApplication.timeSinceStartup + 1.0; + PollAndExecuteCommand(true); + } + private void SetStatus(string message, MessageType messageType) { lastReceipt = message; diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs index 16feb5b..f3a7139 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs @@ -17,6 +17,8 @@ namespace GameCult.Brokkr public string[] selectedObjectNames = Array.Empty(); public int assetCount; public string[] capabilities = Array.Empty(); + public BrokkrGameObjectSnapshot[] sceneObjects = Array.Empty(); + public BrokkrAssetSnapshot[] assets = Array.Empty(); } [Serializable] @@ -28,4 +30,80 @@ namespace GameCult.Brokkr public string acceptedAt = ""; public string status = ""; } + + [Serializable] + public sealed class BrokkrGameObjectSnapshot + { + public string objectId = ""; + public string name = ""; + public string path = ""; + public string scenePath = ""; + public bool activeSelf; + public string tag = ""; + public int layer; + public int childCount; + public string parentId = ""; + public BrokkrComponentSnapshot[] components = Array.Empty(); + } + + [Serializable] + public sealed class BrokkrComponentSnapshot + { + public string componentId = ""; + public string typeName = ""; + public string assemblyQualifiedName = ""; + public bool enabled; + public BrokkrSerializedPropertySnapshot[] properties = Array.Empty(); + } + + [Serializable] + public sealed class BrokkrSerializedPropertySnapshot + { + public string path = ""; + public string displayName = ""; + public string propertyType = ""; + public string value = ""; + public bool editable; + } + + [Serializable] + public sealed class BrokkrAssetSnapshot + { + public string path = ""; + public string guid = ""; + public string typeName = ""; + public bool isPrefab; + } + + [Serializable] + public sealed class BrokkrUnityCommand + { + public string schema = "gamecult.brokkr.unity_command.v0"; + public string commandId = ""; + public string action = ""; + public string targetObjectId = ""; + public string name = ""; + public string componentType = ""; + public string propertyPath = ""; + public string value = ""; + public string assetPath = ""; + public string parentObjectId = ""; + } + + [Serializable] + public sealed class BrokkrUnityCommandEnvelope + { + public BrokkrUnityCommand command; + } + + [Serializable] + public sealed class BrokkrUnityCommandReceipt + { + public string schema = "gamecult.brokkr.unity_command_receipt.v0"; + public string commandId = ""; + public string status = ""; + public string message = ""; + public string objectId = ""; + public string observedAt = ""; + } } diff --git a/surfaces/unity/README.md b/surfaces/unity/README.md index 77cd566..d3c0616 100644 --- a/surfaces/unity/README.md +++ b/surfaces/unity/README.md @@ -35,5 +35,29 @@ The daemon should retain the latest Unity snapshot at: http://127.0.0.1:8798/hosts ``` +The richer read surfaces are available at: + +```text +http://127.0.0.1:8798/unity/scene +http://127.0.0.1:8798/unity/assets +http://127.0.0.1:8798/eve/unity/gui +http://127.0.0.1:8798/eve/unity/tui +``` + +Writes are queued through Brokkr and executed by the Unity editor adapter: + +```powershell +@' +{ + "schema": "gamecult.brokkr.unity_command.v0", + "commandId": "demo-create", + "action": "createGameObject", + "name": "Brokkr Demo" +} +'@ | curl.exe -s -X POST http://127.0.0.1:8798/commands/unity -H "Content-Type: application/json" --data-binary "@-" +``` + +Then click `Poll Command` in Unity or enable `Auto Poll Commands`. + The Unity plugin is still an adapter. Brokkr owns the Verse-facing provider and receipt lane; Unity owns Unity editor truth. diff --git a/tools/check.ps1 b/tools/check.ps1 index 4162c35..05d6d29 100644 --- a/tools/check.ps1 +++ b/tools/check.ps1 @@ -44,7 +44,7 @@ try { } $snapshotPath = Join-Path $smokeRoot "unity-snapshot.json" - $snapshot = '{"schema":"gamecult.brokkr.tool_host_snapshot.v0","providerId":"brokkr.unity_editor","toolKind":"unity-editor","projectPath":"E:/Projects/StreamPixelsUnity","observedAt":"2026-06-12T12:00:00.0000000Z","unityVersion":"smoke","productName":"StreamPixelsUnity","activeScenePath":"Assets/Scenes/SampleScene.unity","openSceneCount":1,"selectedObjectNames":["SmokeObject"],"assetCount":42,"capabilities":["host.status.read","scene.tree.read","selection.read","asset.catalog.read","command.palette.read","command.execute","receipt.read"]}' + $snapshot = '{"schema":"gamecult.brokkr.tool_host_snapshot.v0","providerId":"brokkr.unity_editor","toolKind":"unity-editor","projectPath":"E:/Projects/StreamPixelsUnity","observedAt":"2026-06-12T12:00:00.0000000Z","unityVersion":"smoke","productName":"StreamPixelsUnity","activeScenePath":"Assets/Scenes/SampleScene.unity","openSceneCount":1,"selectedObjectNames":["SmokeObject"],"assetCount":42,"capabilities":["host.status.read","scene.tree.read","selection.read","asset.catalog.read","command.palette.read","command.execute","receipt.read"],"sceneObjects":[{"objectId":"scene-object-1","name":"SmokeObject","path":"SmokeObject","scenePath":"Assets/Scenes/SampleScene.unity","activeSelf":true,"tag":"Untagged","layer":0,"childCount":0,"parentId":"","components":[{"componentId":"component-1","typeName":"UnityEngine.Transform","assemblyQualifiedName":"UnityEngine.Transform, UnityEngine.CoreModule","enabled":true,"properties":[{"path":"m_LocalPosition.x","displayName":"X","propertyType":"Float","value":"0","editable":true}]}]}],"assets":[{"path":"Assets/Smoke.prefab","guid":"smoke-guid","typeName":"UnityEngine.GameObject","isPrefab":true}]}' [System.IO.File]::WriteAllText($snapshotPath, $snapshot, [System.Text.UTF8Encoding]::new($false)) $receiptText = curl.exe -s -X POST http://127.0.0.1:8798/hosts/unity/snapshot -H "Content-Type: application/json" --data-binary "@$snapshotPath" @@ -60,6 +60,50 @@ try { if ($hosts.unity.providerId -ne "brokkr.unity_editor") { throw "Unity host readback smoke failed: $hosts" } + + $scene = curl.exe -s http://127.0.0.1:8798/unity/scene + Assert-NativeSuccess "Unity scene read request" + $scene = $scene | ConvertFrom-Json + if ($scene.providerId -ne "brokkr.unity_editor") { + throw "Unity scene read smoke failed: $scene" + } + + $command = '{"schema":"gamecult.brokkr.unity_command.v0","commandId":"smoke-create","action":"createGameObject","name":"BrokkrSmokeObject"}' + $queued = $command | curl.exe -s -X POST http://127.0.0.1:8798/commands/unity -H "Content-Type: application/json" --data-binary "@-" + Assert-NativeSuccess "Unity command queue request" + $queued = $queued | ConvertFrom-Json + if ($queued.commandId -ne "smoke-create") { + throw "Unity command queue smoke failed: $queued" + } + + $next = curl.exe -s http://127.0.0.1:8798/hosts/unity/commands/next + Assert-NativeSuccess "Unity command next request" + $next = $next | ConvertFrom-Json + if ($next.command.commandId -ne "smoke-create") { + throw "Unity command next smoke failed: $next" + } + + $commandReceipt = '{"schema":"gamecult.brokkr.unity_command_receipt.v0","commandId":"smoke-create","status":"accepted","message":"smoke","objectId":"smoke-object","observedAt":"2026-06-12T12:00:00.0000000Z"}' + $postedReceipt = $commandReceipt | curl.exe -s -X POST http://127.0.0.1:8798/hosts/unity/commands/receipt -H "Content-Type: application/json" --data-binary "@-" + Assert-NativeSuccess "Unity command receipt request" + $postedReceipt = $postedReceipt | ConvertFrom-Json + if ($postedReceipt.status -ne "accepted") { + throw "Unity command receipt smoke failed: $postedReceipt" + } + + $gui = curl.exe -s http://127.0.0.1:8798/eve/unity/gui + Assert-NativeSuccess "Unity Eve GUI request" + $gui = $gui | ConvertFrom-Json + if ($gui.schema -ne "gamecult.eve.surface.v1") { + throw "Unity Eve GUI smoke failed: $gui" + } + + $tui = curl.exe -s http://127.0.0.1:8798/eve/unity/tui + Assert-NativeSuccess "Unity Eve TUI request" + $tui = $tui | ConvertFrom-Json + if ($tui.mode -ne "tui") { + throw "Unity Eve TUI smoke failed: $tui" + } } finally { Stop-Process -Id $daemon.Id -ErrorAction SilentlyContinue