Lower live Aetheria world through CultMesh

This commit is contained in:
Meta Vens 2026-07-13 04:20:12 +01:00
commit 3fee35512c
8 changed files with 302 additions and 70 deletions

View file

@ -230,11 +230,30 @@ namespace GameCult.EveUnity.GenericClient.PlayModeTests
provider);
runtime.ReceiptAvailable += receipt => commandReceipts[receipt.CommandId] = receipt;
var initial = runtime.Connect();
var entityDeadline = Time.realtimeSinceStartup + 12f;
while (initial.ActiveEntities == 0 && Time.realtimeSinceStartup < entityDeadline)
{
yield return new WaitForSecondsRealtime(0.1f);
initial = runtime.Refresh();
}
Assert.That(initial.ActiveEntities, Is.GreaterThan(0));
Assert.That(runtime.ActiveWorld.PlayerEntityId, Is.Not.Empty);
var playerId = runtime.ActiveWorld.PlayerEntityId;
var marker = FindMarker(root, playerId);
var realtimeAction = provider.CurrentInputCapability?.Actions
.FirstOrDefault(action => string.Equals(action.ActionId, "simulation.rate.realtime", StringComparison.Ordinal));
Assert.That(realtimeAction, Is.Not.Null, "Terminus did not advertise its user-controlled simulation clock.");
var resume = runtime.SubmitActionIntent(playerId, realtimeAction.ActionId);
var resumeDeadline = Time.realtimeSinceStartup + 12f;
while (Time.realtimeSinceStartup < resumeDeadline &&
!commandReceipts.TryGetValue(resume.CommandId, out _))
{
yield return new WaitForSecondsRealtime(0.1f);
runtime.Refresh();
}
Assert.That(commandReceipts.TryGetValue(resume.CommandId, out var resumeReceipt), Is.True);
Assert.That(resumeReceipt.State, Is.EqualTo("accepted").Or.EqualTo("reconciled"), resumeReceipt.Message);
Assert.That(
marker.GetComponentsInChildren<Transform>(includeInactive: true).Length,
Is.GreaterThan(1),
@ -264,21 +283,43 @@ namespace GameCult.EveUnity.GenericClient.PlayModeTests
Assert.That(movementDistance, Is.GreaterThan(0.01f));
movementReceipt = WitnessReceipt.From("movement", movementCommandReceipt);
var movementVersion = runtime.ActiveVersion;
var focus = runtime.SubmitFocusIntent(playerId);
var focusDeadline = Time.realtimeSinceStartup + 12f;
while (Time.realtimeSinceStartup < focusDeadline &&
(!commandReceipts.TryGetValue(focus.CommandId, out var observedFocus) ||
runtime.ActiveVersion < observedFocus.SourceVersion))
var stop = runtime.SubmitMoveVectorIntent(playerId, 0f, 0f, 0f);
var stopDeadline = Time.realtimeSinceStartup + 12f;
while (Time.realtimeSinceStartup < stopDeadline &&
(!commandReceipts.TryGetValue(stop.CommandId, out var observedStop) ||
runtime.ActiveVersion < observedStop.SourceVersion))
{
yield return new WaitForSecondsRealtime(0.1f);
runtime.Refresh();
}
Assert.That(commandReceipts.TryGetValue(focus.CommandId, out var focusCommandReceipt), Is.True);
Assert.That(focusCommandReceipt.State, Is.EqualTo("accepted").Or.EqualTo("reconciled"));
Assert.That(focusCommandReceipt.SourceVersion, Is.GreaterThan(movementVersion));
focusReceipt = WitnessReceipt.From("targeting", focusCommandReceipt);
Assert.That(commandReceipts.TryGetValue(stop.CommandId, out var stopCommandReceipt), Is.True);
Assert.That(
stopCommandReceipt.State,
Is.EqualTo("accepted").Or.EqualTo("reconciled"),
stopCommandReceipt.Message);
var pauseAction = provider.CurrentInputCapability.Actions
.Single(candidate => string.Equals(candidate.ActionId, "simulation.pause", StringComparison.Ordinal));
var pause = runtime.SubmitActionIntent(playerId, pauseAction.ActionId);
var pauseDeadline = Time.realtimeSinceStartup + 12f;
while (Time.realtimeSinceStartup < pauseDeadline &&
(!commandReceipts.TryGetValue(pause.CommandId, out var observedPause) ||
runtime.ActiveVersion < observedPause.SourceVersion))
{
yield return new WaitForSecondsRealtime(0.1f);
runtime.Refresh();
}
Assert.That(commandReceipts.TryGetValue(pause.CommandId, out var pauseReceipt), Is.True);
Assert.That(pauseReceipt.State, Is.EqualTo("accepted").Or.EqualTo("reconciled"), pauseReceipt.Message);
var movementVersion = runtime.ActiveVersion;
var targetMarker = root.GetComponentsInChildren<EveUnityPlayableWorldEntityMarker>()
.Where(candidate => candidate.Selectable && !candidate.Controllable &&
string.Equals(candidate.EntityKind, "ship", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(candidate.Faction, marker.Faction, StringComparison.Ordinal))
.OrderBy(candidate => Vector3.Distance(candidate.transform.position, marker.transform.position))
.First();
var focus = runtime.SubmitTargetIntent(playerId, targetMarker.EntityId);
var focusVersion = runtime.ActiveVersion;
var trajectoryRenderer = root.AddComponent<EveUnityShotTrajectoryRenderer>();
runtime.ShotAvailable += shot =>
@ -298,14 +339,34 @@ namespace GameCult.EveUnity.GenericClient.PlayModeTests
string.Equals(candidate.Availability, "available", StringComparison.OrdinalIgnoreCase));
combatActionId = advertisedAction.ActionId;
var action = runtime.SubmitActionIntent(playerId, advertisedAction.ActionId);
var resumeCombat = runtime.SubmitActionIntent(playerId, realtimeAction.ActionId);
var resumeCombatDeadline = Time.realtimeSinceStartup + 12f;
while (Time.realtimeSinceStartup < resumeCombatDeadline &&
(!commandReceipts.TryGetValue(resumeCombat.CommandId, out var observedResumeCombat) ||
runtime.ActiveVersion < observedResumeCombat.SourceVersion))
{
yield return new WaitForSecondsRealtime(0.1f);
runtime.Refresh();
}
Assert.That(commandReceipts.TryGetValue(resumeCombat.CommandId, out var resumeCombatReceipt), Is.True);
Assert.That(resumeCombatReceipt.State, Is.EqualTo("accepted").Or.EqualTo("reconciled"), resumeCombatReceipt.Message);
var actionDeadline = Time.realtimeSinceStartup + 12f;
while (Time.realtimeSinceStartup < actionDeadline &&
(!commandReceipts.TryGetValue(action.CommandId, out var observedAction) ||
(!commandReceipts.TryGetValue(focus.CommandId, out var observedFocus) ||
runtime.ActiveVersion < observedFocus.SourceVersion ||
!commandReceipts.TryGetValue(action.CommandId, out var observedAction) ||
runtime.ActiveVersion < observedAction.SourceVersion || combatShot == null))
{
yield return new WaitForSecondsRealtime(0.1f);
runtime.Refresh();
}
Assert.That(commandReceipts.TryGetValue(focus.CommandId, out var focusCommandReceipt), Is.True);
Assert.That(
focusCommandReceipt.State,
Is.EqualTo("accepted").Or.EqualTo("reconciled"),
focusCommandReceipt.Message);
Assert.That(focusCommandReceipt.SourceVersion, Is.GreaterThan(movementVersion));
focusReceipt = WitnessReceipt.From("targeting", focusCommandReceipt);
Assert.That(commandReceipts.TryGetValue(action.CommandId, out var actionCommandReceipt), Is.True);
Assert.That(
actionCommandReceipt.State,

View file

@ -44,26 +44,32 @@ namespace GameCult.Eve.Surface
this CultMeshClient mesh,
string endpointId,
EveSurfaceRequest? request = null,
CancellationToken cancellationToken = default)
CancellationToken cancellationToken = default,
Action<string>? observeStage = null)
{
if (mesh == null) throw new ArgumentNullException(nameof(mesh));
var resolved = request ?? new EveSurfaceRequest();
IReadOnlyList<EveProviderAdvertisementDocument> providerDocuments;
if (string.IsNullOrWhiteSpace(resolved.ProviderId))
{
observeStage?.Invoke("provider-collection-opening");
var providers = await mesh.CollectionAsync<EveProviderAdvertisementDocument>(endpointId, cancellationToken)
.ConfigureAwait(false);
observeStage?.Invoke("provider-collection-ready");
providerDocuments = await providers.LatestAsync().ConfigureAwait(false);
}
else
{
observeStage?.Invoke("provider-document-opening");
var provider = await mesh.DocumentAsync<EveProviderAdvertisementDocument>(
endpointId,
ProviderAdvertisementRecordRef(resolved.ProviderId),
cancellationToken)
.ConfigureAwait(false);
observeStage?.Invoke("provider-document-ready");
providerDocuments = new[] { await provider.LatestAsync().ConfigureAwait(false) };
}
observeStage?.Invoke("provider-snapshot-ready");
var match = Select(providerDocuments, resolved);
IReadOnlyList<EvePluginAdvertisementDocument> plugins = Array.Empty<EvePluginAdvertisementDocument>();
if (match.Surface.RequiresPlugins.Count > 0)
@ -71,12 +77,15 @@ namespace GameCult.Eve.Surface
var advertisements = await mesh.CollectionAsync<EvePluginAdvertisementDocument>(endpointId, cancellationToken)
.ConfigureAwait(false);
plugins = ResolvePlugins(match.Surface, await advertisements.LatestAsync().ConfigureAwait(false));
observeStage?.Invoke("plugin-snapshot-ready");
}
observeStage?.Invoke("surface-document-opening");
var surface = await mesh.DocumentAsync<EveSurfaceDocument>(
endpointId,
match.Surface.RecordRef,
cancellationToken)
.ConfigureAwait(false);
observeStage?.Invoke("surface-document-ready");
return new EveSurfaceSelection(match.Provider, match.Surface, surface, plugins);
}

View file

@ -1,6 +1,7 @@
using System;
using GameCult.Caching;
using MessagePack;
using GameCult.Mesh;
#nullable enable
@ -25,6 +26,7 @@ namespace GameCult.Eve.Surface
[Key(10)] public EveEntitySoaDirtyRange[] DirtyRanges { get; set; } = Array.Empty<EveEntitySoaDirtyRange>();
[Key(11)] public EveEntityRenderGroup[] RenderGroups { get; set; } = Array.Empty<EveEntityRenderGroup>();
[Key(12)] public EveEntitySoaIdentity[] Identities { get; set; } = Array.Empty<EveEntitySoaIdentity>();
[Key(13)] public CultMeshBodyDescriptor? Body { get; set; }
}
[MessagePackObject]

View file

@ -51,12 +51,15 @@ namespace GameCult.Eve.UnityScene
private readonly List<AssetBundle> _assetBundles = new List<AssetBundle>();
private readonly Dictionary<string, int> _cameraCullingMasks = new Dictionary<string, int>(StringComparer.Ordinal);
private readonly ConcurrentQueue<object> _liveDocuments = new ConcurrentQueue<object>();
private readonly CancellationTokenSource _backgroundCancellation = new CancellationTokenSource();
private CultNetDocumentRegistry? _networkRegistry;
private readonly List<IDisposable> _liveWatches = new List<IDisposable>();
private bool _liveSubscriptionsOpen;
private EveProviderAdvertisementDocument? _advertisement;
private EveAdvertisedSurface? _advertisedSurface;
private string _assetCatalogPointer = "";
private Task? _assetCatalogTask;
private EveEntitySoaViewDocument? _deferredEntityView;
public EveUnityCultMeshLiveProviderTransport(
string replicaPath,
@ -117,7 +120,12 @@ namespace GameCult.Eve.UnityScene
while (_liveDocuments.TryDequeue(out var document))
{
if (document is EveEntitySoaViewDocument entityView)
EntityViewAvailable?.Invoke(entityView);
{
if (!string.IsNullOrWhiteSpace(_assetCatalogPointer) && CurrentAssetCatalogVersion < 0)
_deferredEntityView = entityView;
else
EntityViewAvailable?.Invoke(entityView);
}
else if (document is EveSurfaceDocument surface)
PublishSurface(surface);
else if (document is EveCommandReceiptDocument receipt)
@ -126,6 +134,10 @@ namespace GameCult.Eve.UnityScene
CurrentInputCapability = inputCapability;
else if (document is EveAssetCatalogDocument assetCatalog)
ApplyAssetCatalog(assetCatalog);
else if (document is PreparedAssetCatalog preparedAssetCatalog)
ApplyPreparedAssetCatalog(preparedAssetCatalog);
else if (document is BackgroundFailure failure)
throw new InvalidOperationException(failure.Operation + " failed.", failure.Error);
}
}
@ -148,6 +160,12 @@ namespace GameCult.Eve.UnityScene
throw new InvalidOperationException("Eve command invocations require an idempotency key.");
var recordKey = ChildRecordKey(interaction.CommandRecordRef, commandId);
if (string.IsNullOrWhiteSpace(interaction.ReceiptRecordRef))
throw new InvalidOperationException("The provider advertisement does not publish a receipt record reference.");
var receiptKey = ChildRecordKey(interaction.ReceiptRecordRef, commandId);
var receipt = _mesh.DocumentAsync<EveCommandReceiptDocument>(_endpointId, receiptKey)
.GetAwaiter().GetResult();
_liveWatches.Add(receipt.Watch(value => _liveDocuments.Enqueue(value)));
var message = _networkRegistry!.CreateRawDocumentPutMessage(
$"eve-unity-{commandId}",
new CultRecordHandle<EveSurfaceCommandRequest>(new CultRecordKey(recordKey)),
@ -161,10 +179,44 @@ namespace GameCult.Eve.UnityScene
message.ShardEpoch = 1;
_documentSession!.SendCultNet(message);
_pendingCommandIds.Add(commandId);
_ = AwaitReceiptAsync(receiptKey, commandId, _backgroundCancellation.Token);
}
private async Task AwaitReceiptAsync(string receiptKey, string commandId, CancellationToken cancellationToken)
{
for (var attempt = 0; attempt < 60 && !cancellationToken.IsCancellationRequested; attempt++)
{
try
{
var receipt = await _mesh.ReadAsync<EveCommandReceiptDocument>(
_endpointId,
receiptKey,
TimeSpan.FromSeconds(2),
cancellationToken)
.ConfigureAwait(false);
if (string.Equals(receipt.CommandId, commandId, StringComparison.Ordinal))
{
_liveDocuments.Enqueue(receipt);
return;
}
}
catch (InvalidOperationException)
{
}
try
{
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
}
}
public void Dispose()
{
_backgroundCancellation.Cancel();
foreach (var bundle in _assetBundles) bundle.Unload(unloadAllLoadedObjects: false);
_assetBundles.Clear();
_prefabs.Clear();
@ -176,6 +228,7 @@ namespace GameCult.Eve.UnityScene
_networkRegistry = null;
_pendingCommandIds.Clear();
_publishedReceiptIds.Clear();
_backgroundCancellation.Dispose();
}
public GameObject? ResolvePrefab(EveUnityPlayableWorldAssetBinding asset)
@ -264,11 +317,6 @@ namespace GameCult.Eve.UnityScene
CurrentInputCapability = inputs.LatestAsync().GetAwaiter().GetResult();
_liveWatches.Add(inputs.Watch(document => _liveDocuments.Enqueue(document)));
}
var receipts = _mesh.CollectionAsync<EveCommandReceiptDocument>(_endpointId).GetAwaiter().GetResult();
_liveWatches.Add(receipts.WatchChanges(change =>
{
if (change.Document != null) _liveDocuments.Enqueue(change.Document);
}));
}
private void RefreshAssetCatalog()
@ -281,16 +329,50 @@ namespace GameCult.Eve.UnityScene
return;
_assetCatalogPointer = interaction.AssetManifestRecordRef;
var document = _mesh.DocumentAsync<EveAssetCatalogDocument>(_endpointId, _assetCatalogPointer)
.GetAwaiter().GetResult();
ApplyAssetCatalog(document.LatestAsync().GetAwaiter().GetResult());
_liveWatches.Add(document.Watch(catalog => _liveDocuments.Enqueue(catalog)));
var platform = CurrentBundlePlatform();
var cacheRoot = AssetCacheRoot();
_assetCatalogTask = ObserveBackgroundAsync(
OpenAssetCatalogAsync(_assetCatalogPointer, platform, cacheRoot),
"CultMesh asset catalog preparation");
}
private async Task ObserveBackgroundAsync(Task operation, string name)
{
try
{
await operation.ConfigureAwait(false);
}
catch (Exception error)
{
_liveDocuments.Enqueue(new BackgroundFailure(name, error));
}
}
private async Task OpenAssetCatalogAsync(string pointer, string platform, string cacheRoot)
{
var document = await _mesh.DocumentAsync<EveAssetCatalogDocument>(_endpointId, pointer).ConfigureAwait(false);
var catalog = await document.LatestAsync().ConfigureAwait(false);
_liveDocuments.Enqueue(await PrepareAssetCatalogAsync(catalog, platform, cacheRoot).ConfigureAwait(false));
_liveWatches.Add(document.Watch(next =>
{
_ = Task.Run(async () =>
_liveDocuments.Enqueue(await PrepareAssetCatalogAsync(next, platform, cacheRoot).ConfigureAwait(false)));
}));
}
private void ApplyAssetCatalog(EveAssetCatalogDocument catalog)
{
if (catalog == null || catalog.Version == CurrentAssetCatalogVersion)
return;
if (catalog == null || catalog.Version == CurrentAssetCatalogVersion) return;
var platform = CurrentBundlePlatform();
var cacheRoot = AssetCacheRoot();
_assetCatalogTask = Task.Run(async () =>
_liveDocuments.Enqueue(await PrepareAssetCatalogAsync(catalog, platform, cacheRoot).ConfigureAwait(false)));
}
private void ApplyPreparedAssetCatalog(PreparedAssetCatalog prepared)
{
var catalog = prepared.Catalog;
if (catalog.Version == CurrentAssetCatalogVersion) return;
foreach (var bundle in _assetBundles) bundle.Unload(unloadAllLoadedObjects: false);
_assetBundles.Clear();
@ -303,7 +385,7 @@ namespace GameCult.Eve.UnityScene
Asset = asset,
Variant = asset.Variants.FirstOrDefault(variant =>
string.Equals(variant.RuntimeId, "unity-scene", StringComparison.Ordinal) &&
string.Equals(variant.Platform, CurrentBundlePlatform(), StringComparison.Ordinal))
string.Equals(variant.Platform, prepared.Platform, StringComparison.Ordinal))
})
.Where(selection => selection.Variant != null)
.ToArray();
@ -311,10 +393,7 @@ namespace GameCult.Eve.UnityScene
foreach (var group in selected.GroupBy(selection => selection.Variant!.Uri, StringComparer.Ordinal))
{
var variant = group.First().Variant!;
var descriptor = _mesh.ReadAsync<CultMeshCdnArtifactManifest>(_endpointId, variant.Uri)
.GetAwaiter().GetResult();
var bytes = ReadCachedBundle(descriptor, variant);
VerifyBundle(bytes, variant);
var bytes = prepared.BundleBytes[variant.Uri];
var bundle = AssetBundle.LoadFromMemory(bytes);
if (bundle == null)
throw new InvalidOperationException($"Unity could not load provider asset bundle '{variant.Uri}'.");
@ -336,6 +415,34 @@ namespace GameCult.Eve.UnityScene
}
CurrentAssetCatalogVersion = catalog.Version;
if (_deferredEntityView != null)
{
var deferred = _deferredEntityView;
_deferredEntityView = null;
EntityViewAvailable?.Invoke(deferred);
}
}
private async Task<PreparedAssetCatalog> PrepareAssetCatalogAsync(
EveAssetCatalogDocument catalog,
string platform,
string cacheRoot)
{
var variants = catalog.Assets
.SelectMany(asset => asset.Variants)
.Where(variant => string.Equals(variant.RuntimeId, "unity-scene", StringComparison.Ordinal) &&
string.Equals(variant.Platform, platform, StringComparison.Ordinal))
.GroupBy(variant => variant.Uri, StringComparer.Ordinal)
.Select(group => group.First())
.ToArray();
var bundles = new Dictionary<string, byte[]>(StringComparer.Ordinal);
foreach (var variant in variants)
{
var descriptor = await _mesh.ReadAsync<CultMeshCdnArtifactManifest>(_endpointId, variant.Uri)
.ConfigureAwait(false);
bundles[variant.Uri] = await ReadCachedBundleAsync(descriptor, variant, cacheRoot).ConfigureAwait(false);
}
return new PreparedAssetCatalog(catalog, platform, bundles);
}
private void ReadCameraPolicies(IEnumerable<EveAssetVariant> variants)
@ -373,6 +480,9 @@ namespace GameCult.Eve.UnityScene
}
private byte[] ReadBundle(CultMeshCdnArtifactManifest manifest)
=> ReadBundleAsync(manifest).GetAwaiter().GetResult();
private async Task<byte[]> ReadBundleAsync(CultMeshCdnArtifactManifest manifest)
{
var bytes = new byte[checked((int)manifest.SizeBytes)];
var references = manifest.Chunks.OrderBy(chunk => chunk.Offset).ToArray();
@ -406,15 +516,18 @@ namespace GameCult.Eve.UnityScene
concurrency.Release();
}
}).ToArray();
Task.WhenAll(downloads).GetAwaiter().GetResult();
await Task.WhenAll(downloads).ConfigureAwait(false);
return bytes;
}
private byte[] ReadCachedBundle(CultMeshCdnArtifactManifest manifest, EveAssetVariant variant)
=> ReadCachedBundleAsync(manifest, variant, AssetCacheRoot()).GetAwaiter().GetResult();
private async Task<byte[]> ReadCachedBundleAsync(
CultMeshCdnArtifactManifest manifest,
EveAssetVariant variant,
string cacheRoot)
{
var cacheRoot = Environment.GetEnvironmentVariable("EVEUNITY_ASSET_CACHE_PATH");
if (string.IsNullOrWhiteSpace(cacheRoot))
cacheRoot = Path.Combine(Application.persistentDataPath, "EveUnity", "assets");
Directory.CreateDirectory(cacheRoot);
var hash = variant.ContentHash.StartsWith("sha256:", StringComparison.Ordinal)
? variant.ContentHash.Substring("sha256:".Length)
@ -427,7 +540,7 @@ namespace GameCult.Eve.UnityScene
return cached;
}
var bytes = ReadBundle(manifest);
var bytes = await ReadBundleAsync(manifest).ConfigureAwait(false);
VerifyBundle(bytes, variant);
var temporaryPath = cachePath + ".tmp";
File.WriteAllBytes(temporaryPath, bytes);
@ -436,6 +549,40 @@ namespace GameCult.Eve.UnityScene
return bytes;
}
private static string AssetCacheRoot()
{
var cacheRoot = Environment.GetEnvironmentVariable("EVEUNITY_ASSET_CACHE_PATH");
return string.IsNullOrWhiteSpace(cacheRoot)
? Path.Combine(Application.persistentDataPath, "EveUnity", "assets")
: cacheRoot;
}
private sealed class PreparedAssetCatalog
{
public PreparedAssetCatalog(EveAssetCatalogDocument catalog, string platform, Dictionary<string, byte[]> bundleBytes)
{
Catalog = catalog;
Platform = platform;
BundleBytes = bundleBytes;
}
public EveAssetCatalogDocument Catalog { get; }
public string Platform { get; }
public Dictionary<string, byte[]> BundleBytes { get; }
}
private sealed class BackgroundFailure
{
public BackgroundFailure(string operation, Exception error)
{
Operation = operation;
Error = error;
}
public string Operation { get; }
public Exception Error { get; }
}
private static void VerifyBundle(byte[] bytes, EveAssetVariant variant)
{
if (bytes.LongLength != variant.SizeBytes)

View file

@ -3,6 +3,7 @@ using System.Threading;
using System.Threading.Tasks;
using GameCult.Eve.Surface;
using GameCult.Mesh;
using UnityEngine;
#nullable enable
@ -60,7 +61,8 @@ namespace GameCult.Eve.UnityScene
SurfaceKind = surfaceKind,
LoweringTarget = "unity-scene"
},
cancellationToken).ConfigureAwait(false);
cancellationToken,
stage => Debug.Log($"EveUnity CultMesh discovery: {stage}")).ConfigureAwait(false);
return new EveUnityCultMeshProviderSelection(endpointId, mesh, surface);
}
catch

View file

@ -1,8 +1,8 @@
using System;
using System.Collections.Generic;
using System.IO.MemoryMappedFiles;
using System.Linq;
using GameCult.Eve.Surface;
using GameCult.Mesh;
using UnityEngine;
#nullable enable
@ -11,25 +11,14 @@ namespace GameCult.Eve.UnityScene
{
public sealed class EveUnityEntitySoaView : IDisposable
{
private readonly Dictionary<string, MemoryMappedViewAccessor> _buffers =
new Dictionary<string, MemoryMappedViewAccessor>(StringComparer.Ordinal);
private readonly ICultMeshBodyReadLease _body;
private readonly Dictionary<string, EveEntitySoaColumn> _columns;
private EveUnityEntitySoaView(EveEntitySoaViewDocument document)
private EveUnityEntitySoaView(EveEntitySoaViewDocument document, ICultMeshBodyReadLease body)
{
Document = document;
_body = body;
_columns = document.Columns.ToDictionary(column => column.Semantic, StringComparer.Ordinal);
foreach (var buffer in document.Buffers)
{
if (!string.Equals(buffer.Backend, "memory_mapped_file", StringComparison.Ordinal))
throw new NotSupportedException($"EveUnity does not support entity SoA backend '{buffer.Backend}'.");
var mapped = MemoryMappedFile.OpenExisting(buffer.Location, MemoryMappedFileRights.Read);
_buffers.Add(buffer.BufferId, mapped.CreateViewAccessor(
buffer.ByteOffset,
buffer.ByteLength,
MemoryMappedFileAccess.Read));
mapped.Dispose();
}
}
public EveEntitySoaViewDocument Document { get; }
@ -41,39 +30,51 @@ namespace GameCult.Eve.UnityScene
if (document == null) throw new ArgumentNullException(nameof(document));
if (!string.Equals(document.Schema, EveEntitySoaViewDocument.SchemaId, StringComparison.Ordinal))
throw new ArgumentException($"Expected {EveEntitySoaViewDocument.SchemaId}, got '{document.Schema}'.", nameof(document));
return new EveUnityEntitySoaView(document);
if (document.Body == null)
throw new InvalidOperationException("Eve entity SoA view did not advertise a CultMesh body.");
var request = new CultMeshBodyValidationRequest
{
BodyId = document.Body.BodyId,
SchemaId = document.Body.SchemaId,
LayoutVersion = document.Body.LayoutVersion,
ProducerEpoch = document.Body.ProducerEpoch,
AccessMode = CultMeshBodyAccessMode.ReadOnly,
NowUtc = DateTimeOffset.UtcNow
};
var body = new CultMeshSharedMemoryBodyAdapter().OpenReadOnly(document.Body, request);
return new EveUnityEntitySoaView(document, body);
}
public bool TryReadVector3(string semantic, int index, out Vector3 value)
{
value = default;
if (!TryColumn(semantic, index, "float3", 12, out var column, out var accessor)) return false;
if (!TryColumn(semantic, index, "float3", 12, out var column)) return false;
var offset = column.ByteOffset + (long)index * column.ElementStride;
value = new Vector3(accessor.ReadSingle(offset), accessor.ReadSingle(offset + 4), accessor.ReadSingle(offset + 8));
value = new Vector3(_body.ReadSingle(offset), _body.ReadSingle(offset + 4), _body.ReadSingle(offset + 8));
return true;
}
public bool TryReadFloat(string semantic, int index, out float value)
{
value = default;
if (!TryColumn(semantic, index, "float32", 4, out var column, out var accessor)) return false;
value = accessor.ReadSingle(column.ByteOffset + (long)index * column.ElementStride);
if (!TryColumn(semantic, index, "float32", 4, out var column)) return false;
value = _body.ReadSingle(column.ByteOffset + (long)index * column.ElementStride);
return true;
}
public bool TryReadInt32(string semantic, int index, out int value)
{
value = default;
if (!TryColumn(semantic, index, "int32", 4, out var column, out var accessor)) return false;
value = accessor.ReadInt32(column.ByteOffset + (long)index * column.ElementStride);
if (!TryColumn(semantic, index, "int32", 4, out var column)) return false;
value = _body.ReadInt32(column.ByteOffset + (long)index * column.ElementStride);
return true;
}
public bool TryReadUInt32(string semantic, int index, out uint value)
{
value = default;
if (!TryColumn(semantic, index, "uint32", 4, out var column, out var accessor)) return false;
value = accessor.ReadUInt32(column.ByteOffset + (long)index * column.ElementStride);
if (!TryColumn(semantic, index, "uint32", 4, out var column)) return false;
value = unchecked((uint)_body.ReadInt32(column.ByteOffset + (long)index * column.ElementStride));
return true;
}
@ -84,15 +85,14 @@ namespace GameCult.Eve.UnityScene
public bool TryReadByte(string semantic, int index, out byte value)
{
value = default;
if (!TryColumn(semantic, index, "uint8", 1, out var column, out var accessor)) return false;
value = accessor.ReadByte(column.ByteOffset + (long)index * column.ElementStride);
if (!TryColumn(semantic, index, "uint8", 1, out var column)) return false;
value = _body.ReadByte(column.ByteOffset + (long)index * column.ElementStride);
return true;
}
public void Dispose()
{
foreach (var accessor in _buffers.Values) accessor.Dispose();
_buffers.Clear();
_body.Dispose();
}
private bool TryColumn(
@ -100,15 +100,22 @@ namespace GameCult.Eve.UnityScene
int index,
string scalarType,
int minimumStride,
out EveEntitySoaColumn column,
out MemoryMappedViewAccessor accessor)
out EveEntitySoaColumn column)
{
column = null!;
accessor = null!;
if (index < 0 || !_columns.TryGetValue(semantic ?? "", out column)) return false;
if (index >= column.ElementCount || column.ElementStride < minimumStride) return false;
if (!string.Equals(column.ScalarType, scalarType, StringComparison.Ordinal)) return false;
return _buffers.TryGetValue(column.BufferId, out accessor);
return DocumentBufferContains(column);
}
private bool DocumentBufferContains(EveEntitySoaColumn column)
{
var buffer = Document.Buffers.FirstOrDefault(candidate =>
string.Equals(candidate.BufferId, column.BufferId, StringComparison.Ordinal));
if (buffer == null || buffer.ByteOffset != 0 || Document.Body == null) return false;
var columnEnd = column.ByteOffset + (long)column.ElementStride * column.ElementCount;
return column.ByteOffset >= 0 && columnEnd <= Document.Body.ByteSize;
}
}
}

View file

@ -11,6 +11,7 @@ namespace GameCult.Eve.UnityScene
private readonly EveUnitySceneProviderConnection _connection;
private readonly EveUnityPlayableWorldPresenter _presenter;
private readonly IEveUnitySceneCommandReceiptSource? _receiptSource;
private readonly Func<long>? _visibleStateVersion;
private readonly EveUnityFeedbackPresenter _feedback = new EveUnityFeedbackPresenter();
private readonly EveUnityShotReceiptPresenter _shots = new EveUnityShotReceiptPresenter();
private readonly List<EveUnitySceneCommandReceipt> _pendingReceipts =
@ -21,11 +22,13 @@ namespace GameCult.Eve.UnityScene
public EveUnityPlayableWorldLiveClient(
EveUnitySceneProviderConnection connection,
EveUnityPlayableWorldPresenter presenter,
IEveUnitySceneCommandReceiptSource? receiptSource = null)
IEveUnitySceneCommandReceiptSource? receiptSource = null,
Func<long>? visibleStateVersion = null)
{
_connection = connection ?? throw new ArgumentNullException(nameof(connection));
_presenter = presenter ?? throw new ArgumentNullException(nameof(presenter));
_receiptSource = receiptSource;
_visibleStateVersion = visibleStateVersion;
}
public EveUnitySceneProjection? ActiveProjection => _connection.ActiveProjection;
@ -36,7 +39,7 @@ namespace GameCult.Eve.UnityScene
public EveUnitySceneCommandReceipt? LastReceipt { get; private set; }
public long ActiveVersion => _connection.ActiveVersion;
public long ActiveVersion => Math.Max(_connection.ActiveVersion, _visibleStateVersion?.Invoke() ?? 0);
public string SourcePointer => _connection.SourcePointer;

View file

@ -41,7 +41,8 @@ namespace GameCult.Eve.UnityScene
_client = new EveUnityPlayableWorldLiveClient(
_connection,
new EveUnityPlayableWorldPresenter(sceneSink, assetResolver ?? new EveUnityAssetRefResolver()),
receiptSource);
receiptSource,
() => _entityViews?.CurrentEntityView?.FrameId ?? 0);
if (assetManifestDocuments != null)
_assetManifestSource = new EveUnityPlayableWorldAssetManifestDocumentSource(assetManifestDocuments);