diff --git a/Fensalir.sln b/Fensalir.sln index 1c196ee..f854e84 100644 --- a/Fensalir.sln +++ b/Fensalir.sln @@ -31,6 +31,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Fensalir", "src\Aq EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Saga", "src\Saga\Saga.csproj", "{30324495-56BE-4D45-80E8-CE03C24726C8}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.EveSurface", "src\Aquarium.EveSurface\Aquarium.EveSurface.csproj", "{B8CB4A9F-EBB4-4C6C-9712-AF802E38CB0B}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -173,6 +175,18 @@ Global {30324495-56BE-4D45-80E8-CE03C24726C8}.Release|x64.Build.0 = Release|Any CPU {30324495-56BE-4D45-80E8-CE03C24726C8}.Release|x86.ActiveCfg = Release|Any CPU {30324495-56BE-4D45-80E8-CE03C24726C8}.Release|x86.Build.0 = Release|Any CPU + {B8CB4A9F-EBB4-4C6C-9712-AF802E38CB0B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B8CB4A9F-EBB4-4C6C-9712-AF802E38CB0B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B8CB4A9F-EBB4-4C6C-9712-AF802E38CB0B}.Debug|x64.ActiveCfg = Debug|Any CPU + {B8CB4A9F-EBB4-4C6C-9712-AF802E38CB0B}.Debug|x64.Build.0 = Debug|Any CPU + {B8CB4A9F-EBB4-4C6C-9712-AF802E38CB0B}.Debug|x86.ActiveCfg = Debug|Any CPU + {B8CB4A9F-EBB4-4C6C-9712-AF802E38CB0B}.Debug|x86.Build.0 = Debug|Any CPU + {B8CB4A9F-EBB4-4C6C-9712-AF802E38CB0B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B8CB4A9F-EBB4-4C6C-9712-AF802E38CB0B}.Release|Any CPU.Build.0 = Release|Any CPU + {B8CB4A9F-EBB4-4C6C-9712-AF802E38CB0B}.Release|x64.ActiveCfg = Release|Any CPU + {B8CB4A9F-EBB4-4C6C-9712-AF802E38CB0B}.Release|x64.Build.0 = Release|Any CPU + {B8CB4A9F-EBB4-4C6C-9712-AF802E38CB0B}.Release|x86.ActiveCfg = Release|Any CPU + {B8CB4A9F-EBB4-4C6C-9712-AF802E38CB0B}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -188,5 +202,6 @@ Global {C0D1BFAC-B1B4-4350-92A7-D537AE382909} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84} {F9274D99-3CC6-42B6-9817-EC7F19663B1D} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {30324495-56BE-4D45-80E8-CE03C24726C8} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {B8CB4A9F-EBB4-4C6C-9712-AF802E38CB0B} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} EndGlobalSection EndGlobal diff --git a/README.md b/README.md index e5956bb..0de731d 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,14 @@ consume the shared Eve/CultMesh UI document contract and lower it into `AquariumUiDocument`, while provider repos keep ownership of dashboard state and commands. See `docs/eve-direct2d-client-surface.md`. +Run the native Eve surface client against Mimir's VoidBot dashboard: + +```powershell +$env:FENSALIR_EVE_BROKER = 'ws://127.0.0.1:8795/eve/deck' +$env:FENSALIR_EVE_PROVIDER = 'voidbot.swarm' +.\scripts\dev-reload.ps1 -ClientProject src\Aquarium.EveSurface\Aquarium.EveSurface.csproj +``` + ## Spatial Evidence Machine Fensalir's field work is not just "some fractal helpers." It is a @@ -141,6 +149,8 @@ how WASAPI or Faust got invited to the party. audio/synth host, bundled assets, and renderer-owned shaders. - `src/Aquarium.Engine.Fractal`: `.aquageo`, IFS/fractal fields, temporal reservoirs, evidence tracks, contribution cache, and lowering machinery. +- `src/Aquarium.EveSurface`: native DirectWrite Eve surface client for shared + dashboard documents such as Mimir's `voidbot.swarm` provider. - `src/Saga`: stochastic planetary flow middleware for cube-sphere Transport fields, arbitrary forcing, Coriolis-aware advection, and learned atmosphere / ocean / debris flow packets. diff --git a/docs/eve-direct2d-client-surface.md b/docs/eve-direct2d-client-surface.md index abcab57..ee77b12 100644 --- a/docs/eve-direct2d-client-surface.md +++ b/docs/eve-direct2d-client-surface.md @@ -29,10 +29,19 @@ The existing engine contract already has the right narrow surface: - `D3D12Renderer.UpdateUi` - `DirectWriteOverlay` -The first implementation should add an adapter from the shared Eve surface -document into `AquariumUiDocument`. Do not bypass that path by teaching the -renderer about VoidBot, Mimir, or any provider-specific dashboard. Provider -specificity belongs in the provider document. +`src/Aquarium.EveSurface` is the first native client cut. It subscribes to +Mimir's `/eve/deck` WebSocket, opens a provider such as `voidbot.swarm`, and +lowers the received surface document into `AquariumUiDocument` panels. It does +not teach the renderer about VoidBot, Mimir, or any provider-specific dashboard. +Provider specificity belongs in the provider document. + +Run it locally: + +```powershell +$env:FENSALIR_EVE_BROKER = 'ws://127.0.0.1:8795/eve/deck' +$env:FENSALIR_EVE_PROVIDER = 'voidbot.swarm' +.\scripts\dev-reload.ps1 -ClientProject src\Aquarium.EveSurface\Aquarium.EveSurface.csproj +``` ## Invariants @@ -48,9 +57,9 @@ specificity belongs in the provider document. ## First Cut -1. Define the shared Eve surface DTO in a neutral contract package or mirror the - first schema in Fensalir as an adapter boundary. -2. Map simple nodes into `AquariumUiPanel` and existing controls: +1. Move the mirrored first schema into a neutral shared Eve/CultMesh contract + package once the browser reference stops changing daily. +2. Expand node lowering into `AquariumUiPanel` and existing controls: readouts, buttons, toggles, sliders, options, text boxes, tree items, and detail panes. 3. Route control activation back to a provider command sink. diff --git a/src/Aquarium.EveSurface/Aquarium.EveSurface.csproj b/src/Aquarium.EveSurface/Aquarium.EveSurface.csproj new file mode 100644 index 0000000..dc1f5bf --- /dev/null +++ b/src/Aquarium.EveSurface/Aquarium.EveSurface.csproj @@ -0,0 +1,16 @@ + + + + net10.0 + Aquarium.EveSurface + Aquarium.EveSurface + enable + enable + true + + + + + + + diff --git a/src/Aquarium.EveSurface/EveSurfaceRuntime.cs b/src/Aquarium.EveSurface/EveSurfaceRuntime.cs new file mode 100644 index 0000000..249fc7a --- /dev/null +++ b/src/Aquarium.EveSurface/EveSurfaceRuntime.cs @@ -0,0 +1,375 @@ +using System.Globalization; +using System.Net.WebSockets; +using System.Numerics; +using System.Text; +using System.Text.Json; +using Aquarium.Engine; +using Aquarium.Engine.Audio; +using Aquarium.Engine.Input; +using Aquarium.Engine.Render; +using Aquarium.Engine.Ui; + +namespace Aquarium.EveSurface; + +public sealed class EveSurfaceRuntime : IAquariumRuntime +{ + private const string DefaultBrokerUrl = "ws://127.0.0.1:8795/eve/deck"; + private const string DefaultProviderId = "voidbot.swarm"; + private readonly object sync = new(); + private readonly string brokerUrl = Environment.GetEnvironmentVariable("FENSALIR_EVE_BROKER") ?? DefaultBrokerUrl; + private readonly string providerId = Environment.GetEnvironmentVariable("FENSALIR_EVE_PROVIDER") ?? DefaultProviderId; + private CancellationTokenSource? connectionLifetime; + private Task? connectionTask; + private EveSurfaceState state = EveSurfaceState.Empty; + private string status = "not started"; + private string selectedNodeId = ""; + private float timeSeconds; + + public AquariumRuntimeOptions Options { get; private set; } + + public GraphicsSettings GraphicsSettings { get; set; } = GraphicsSettings.Default; + + public AquariumRenderPlan RenderPlan { get; } = CreateRenderPlan(); + + public AquariumUiDocument Ui => ComposeUi(); + + public AquariumAudioDocument Audio { get; } = new(); + + public AquariumSynthDocument Synth { get; } = AquariumSynthDocument.Empty; + + public AquariumFrame Frame => new( + new ViewFrame(Vector2.Zero, 24.0f), + new Vector3(0.0f, -10.0f, 7.0f), + timeSeconds, + Vector2.Zero, + AquariumSceneState.Empty); + + public AquariumFrame ComposeFrame(AquariumFrame frame, AquariumFrameInput input) => frame; + + public void Start() + { + Console.WriteLine($"Eve surface client connecting to {brokerUrl} provider {providerId}."); + connectionLifetime = new CancellationTokenSource(); + connectionTask = Task.Run(() => RunConnectionLoopAsync(connectionLifetime.Token)); + } + + public void Update(float deltaSeconds, InputState input) + { + timeSeconds += Math.Max(deltaSeconds, 0.0f); + } + + public void FlushState() + { + } + + public void Dispose() + { + connectionLifetime?.Cancel(); + try + { + connectionTask?.Wait(TimeSpan.FromSeconds(1)); + } + catch (AggregateException) + { + } + + connectionLifetime?.Dispose(); + } + + internal void SetOptions(AquariumRuntimeOptions options) + { + Options = options; + } + + private AquariumUiDocument ComposeUi() + { + EveSurfaceState snapshot; + string connectionStatus; + lock (sync) + { + snapshot = state; + connectionStatus = status; + if (string.IsNullOrWhiteSpace(selectedNodeId)) + { + selectedNodeId = snapshot.SelectedNodeId; + } + } + + var nodes = snapshot.Nodes; + var selected = nodes.FirstOrDefault(node => node.Id == selectedNodeId) + ?? nodes.FirstOrDefault(node => node.Id == snapshot.SelectedNodeId) + ?? nodes.FirstOrDefault(); + var ctb = nodes.Where(static node => string.Equals(node.Kind, "ctb-turn", StringComparison.OrdinalIgnoreCase)).Take(12).ToArray(); + var leaves = nodes.Where(static node => string.Equals(node.Kind, "state-leaf", StringComparison.OrdinalIgnoreCase)).Take(32).ToArray(); + var summary = nodes.FirstOrDefault(static node => node.Id == "voidbot-summary"); + var agent = nodes.FirstOrDefault(static node => node.Id == "agent-detail"); + + return new AquariumUiDocument() + .Panel("Eve Surface", 18.0f, 82.0f, 420.0f, panel => + { + panel.Section("CultMesh Provider"); + panel.Readout("Provider", () => string.IsNullOrWhiteSpace(snapshot.ProviderId) ? providerId : snapshot.ProviderId); + panel.Readout("Title", () => snapshot.Title); + panel.Readout("Version", () => snapshot.Version.ToString(CultureInfo.InvariantCulture)); + panel.Readout("Broker", () => brokerUrl); + panel.Readout("Status", () => connectionStatus); + panel.Button("Reconnect", Reconnect, "Restart the WebSocket subscription and reopen the provider."); + }) + .Panel("CTB", 456.0f, 82.0f, 520.0f, panel => + { + panel.Section("VoidBot Turn Bar"); + foreach (var node in ctb) + { + panel.TreeItem( + CompactLabel(node.Label), + 0, + canExpand: false, + isExpanded: static () => false, + setExpanded: static _ => { }, + isSelected: () => selectedNodeId == node.Id, + select: () => selectedNodeId = node.Id, + detail: CompactDetail(node)); + } + }) + .Panel("Selected Face", 18.0f, 382.0f, 420.0f, panel => + { + panel.Section(summary?.Label ?? "VoidBot Swarm"); + panel.Readout("Summary", () => summary?.Health ?? "waiting"); + panel.TextBox("Selected", () => selected?.Label ?? "none", _ => { }, lines: 1, acceptsReturn: false, monospace: false); + panel.TextBox("Detail", () => selected?.Detail ?? agent?.Detail ?? "No provider detail yet.", _ => { }, lines: 12, acceptsReturn: false, monospace: true); + }) + .Panel("State Graph", 456.0f, 222.0f, 520.0f, panel => + { + panel.Section("Leaves"); + foreach (var node in leaves) + { + panel.TreeItem( + CompactLabel(node.Label), + 0, + canExpand: false, + isExpanded: static () => false, + setExpanded: static _ => { }, + isSelected: () => selectedNodeId == node.Id, + select: () => selectedNodeId = node.Id, + detail: CompactDetail(node)); + } + }) + .Panel("Surface Detail", 994.0f, 82.0f, 520.0f, panel => + { + panel.Section(selected?.Kind ?? "detail"); + panel.Readout("Node", () => selected?.Id ?? "none"); + panel.Readout("Health", () => selected?.Health ?? ""); + panel.TextBox("State", () => selected?.Detail ?? "No selected node.", _ => { }, lines: 18, acceptsReturn: false, monospace: true); + }) + .Command("eve-status", _ => $"{connectionStatus}; {snapshot.ProviderId} v{snapshot.Version}; nodes {nodes.Count}", "Report the active Eve surface subscription."); + } + + private void Reconnect() + { + connectionLifetime?.Cancel(); + connectionLifetime = new CancellationTokenSource(); + connectionTask = Task.Run(() => RunConnectionLoopAsync(connectionLifetime.Token)); + } + + private async Task RunConnectionLoopAsync(CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + try + { + SetStatus("connecting"); + using var socket = new ClientWebSocket(); + await socket.ConnectAsync(new Uri(brokerUrl), cancellationToken).ConfigureAwait(false); + SetStatus("connected"); + await SendOpenProviderAsync(socket, cancellationToken).ConfigureAwait(false); + + var buffer = new byte[64 * 1024]; + while (socket.State == WebSocketState.Open && !cancellationToken.IsCancellationRequested) + { + var message = await ReceiveTextAsync(socket, buffer, cancellationToken).ConfigureAwait(false); + if (message is null) + { + break; + } + + var next = EveSurfaceState.Parse(message); + if (!string.Equals(next.ProviderId, providerId, StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + lock (sync) + { + state = next; + status = $"live {next.UpdatedAt}"; + if (string.IsNullOrWhiteSpace(selectedNodeId)) + { + selectedNodeId = next.SelectedNodeId; + } + } + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + return; + } + catch (Exception exception) + { + SetStatus($"error {exception.Message}"); + await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken).ConfigureAwait(false); + } + } + } + + private async Task SendOpenProviderAsync(ClientWebSocket socket, CancellationToken cancellationToken) + { + var payload = Encoding.UTF8.GetBytes($$"""{"type":"open-provider","providerId":"{{providerId}}"}"""); + await socket.SendAsync(payload, WebSocketMessageType.Text, true, cancellationToken).ConfigureAwait(false); + } + + private static async Task ReceiveTextAsync(ClientWebSocket socket, byte[] buffer, CancellationToken cancellationToken) + { + using var stream = new MemoryStream(); + while (true) + { + var result = await socket.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false); + if (result.MessageType == WebSocketMessageType.Close) + { + return null; + } + + stream.Write(buffer, 0, result.Count); + if (result.EndOfMessage) + { + return Encoding.UTF8.GetString(stream.ToArray()); + } + } + } + + private void SetStatus(string value) + { + lock (sync) + { + status = value; + } + } + + private static string CompactLabel(string value) + { + var label = value.Replace('\n', ' ').Replace('\r', ' ').Trim(); + return label.Length <= 72 ? label : label[..69] + "..."; + } + + private static string CompactDetail(EveSurfaceNode node) + { + var parts = new[] { node.Kind, node.Health, node.StatePath } + .Where(static value => !string.IsNullOrWhiteSpace(value)); + return string.Join(" ", parts); + } + + private static AquariumRenderPlan CreateRenderPlan() + { + var app = new AquariumApp(); + var scene = app.RenderTargets.Hdr("scene"); + app.Cameras.Perspective("main"); + app.Graph.Pass("scene").Fullscreen(); + app.Features.Presentation(scene.Color); + app.Features.DirectWriteOverlay(); + app.Debug.View("Scene", scene.Color); + return app.Plan; + } +} + +public sealed class EveSurfaceRuntimeFactory : IAquariumRuntimeFactory +{ + public IAquariumRuntime Create(AquariumRuntimeOptions options) + { + var runtime = new EveSurfaceRuntime(); + runtime.SetOptions(options); + return runtime; + } +} + +internal sealed record EveSurfaceState( + string ProviderId, + string Title, + long Version, + string UpdatedAt, + string SelectedNodeId, + IReadOnlyList Nodes) +{ + public static EveSurfaceState Empty { get; } = new( + "", + "Eve Surface", + 0, + "", + "", + []); + + public static EveSurfaceState Parse(string json) + { + using var document = JsonDocument.Parse(json); + var root = document.RootElement; + var nodes = new List(); + if (root.TryGetProperty("nodes", out var nodeArray) && nodeArray.ValueKind == JsonValueKind.Array) + { + foreach (var node in nodeArray.EnumerateArray()) + { + nodes.Add(new EveSurfaceNode( + ReadString(node, "id"), + ReadString(node, "label"), + ReadString(node, "kind"), + ReadDouble(node, "x"), + ReadDouble(node, "y"), + ReadDouble(node, "width"), + ReadDouble(node, "height"), + ReadString(node, "health"), + ReadString(node, "detail"), + ReadString(node, "statePath"), + ReadString(node, "avatarUrl"))); + } + } + + return new EveSurfaceState( + ReadString(root, "providerId"), + ReadString(root, "title", "Eve Surface"), + ReadInt64(root, "version"), + ReadString(root, "updatedAt"), + ReadString(root, "selectedNodeId"), + nodes); + } + + private static string ReadString(JsonElement element, string property, string fallback = "") + { + return element.TryGetProperty(property, out var value) && value.ValueKind == JsonValueKind.String + ? value.GetString() ?? fallback + : fallback; + } + + private static long ReadInt64(JsonElement element, string property) + { + return element.TryGetProperty(property, out var value) && value.TryGetInt64(out var number) + ? number + : 0; + } + + private static double ReadDouble(JsonElement element, string property) + { + return element.TryGetProperty(property, out var value) && value.TryGetDouble(out var number) + ? number + : 0.0; + } +} + +internal sealed record EveSurfaceNode( + string Id, + string Label, + string Kind, + double X, + double Y, + double Width, + double Height, + string Health, + string Detail, + string StatePath, + string AvatarUrl);