| | | 1 | | // Copyright (c) 2026 Sideline Authors. All rights reserved. |
| | | 2 | | // Licensed under GPL-3.0. |
| | | 3 | | |
| | | 4 | | using System; |
| | | 5 | | using System.Buffers.Binary; |
| | | 6 | | using System.Collections.Generic; |
| | | 7 | | using Lattice.Core; |
| | | 8 | | using Lattice.ECS.Serialization; |
| | | 9 | | |
| | | 10 | | namespace Lattice.ECS.Core |
| | | 11 | | { |
| | | 12 | | /// <summary> |
| | | 13 | | /// 组件类型元数据。 |
| | | 14 | | /// </summary> |
| | | 15 | | public readonly struct ComponentTypeInfo |
| | | 16 | | { |
| | | 17 | | public ComponentTypeInfo( |
| | | 18 | | Type type, |
| | | 19 | | int id, |
| | | 20 | | int size, |
| | | 21 | | ComponentFlags flags, |
| | | 22 | | StorageFlags storageFlags, |
| | | 23 | | ComponentCallbacks callbacks) |
| | | 24 | | { |
| | 1 | 25 | | Type = type; |
| | 1 | 26 | | Id = id; |
| | 1 | 27 | | Size = size; |
| | 1 | 28 | | Flags = flags; |
| | 1 | 29 | | StorageFlags = storageFlags; |
| | 1 | 30 | | Callbacks = callbacks; |
| | 1 | 31 | | } |
| | | 32 | | |
| | 2 | 33 | | public Type Type { get; } |
| | | 34 | | |
| | 1 | 35 | | public string Name => Type.Name; |
| | | 36 | | |
| | 1 | 37 | | public int Id { get; } |
| | | 38 | | |
| | 1 | 39 | | public int Size { get; } |
| | | 40 | | |
| | 1 | 41 | | public ComponentFlags Flags { get; } |
| | | 42 | | |
| | 0 | 43 | | public StorageFlags StorageFlags { get; } |
| | | 44 | | |
| | 0 | 45 | | public ComponentCallbacks Callbacks { get; } |
| | | 46 | | |
| | 0 | 47 | | public int SerializationVersion => Callbacks.SerializationVersion; |
| | | 48 | | } |
| | | 49 | | |
| | | 50 | | /// <summary> |
| | | 51 | | /// 组件类型注册中心,负责维护运行期组件元数据。 |
| | | 52 | | /// </summary> |
| | | 53 | | public static unsafe class ComponentRegistry |
| | | 54 | | { |
| | | 55 | | private static readonly object SyncRoot = new(); |
| | | 56 | | private static readonly Type?[] Types = new Type[Frame.MaxComponentTypes]; |
| | | 57 | | private static readonly int[] Sizes = new int[Frame.MaxComponentTypes]; |
| | | 58 | | private static readonly ComponentFlags[] Flags = new ComponentFlags[Frame.MaxComponentTypes]; |
| | | 59 | | private static readonly StorageFlags[] StorageFlagsByType = new StorageFlags[Frame.MaxComponentTypes]; |
| | | 60 | | private static readonly ComponentCallbacks[] Callbacks = new ComponentCallbacks[Frame.MaxComponentTypes]; |
| | | 61 | | private static readonly ComponentFrameRemoveDelegate?[] RemoveInvokers = new ComponentFrameRemoveDelegate[Frame. |
| | | 62 | | private static readonly ComponentCommandApplyDelegate?[] AddAppliers = new ComponentCommandApplyDelegate[Frame.M |
| | | 63 | | private static readonly ComponentCommandApplyDelegate?[] SetAppliers = new ComponentCommandApplyDelegate[Frame.M |
| | | 64 | | private static readonly ComponentDeferredCommitDelegate?[] DeferredCommitters = new ComponentDeferredCommitDeleg |
| | | 65 | | private static readonly ComponentSnapshotCaptureDelegate?[] SnapshotCapturers = new ComponentSnapshotCaptureDele |
| | | 66 | | private static readonly ComponentSnapshotRestoreDelegate?[] SnapshotRestorers = new ComponentSnapshotRestoreDele |
| | | 67 | | private static readonly ComponentPendingRemovalDelegate?[] PendingRemovalMarkers = new ComponentPendingRemovalDe |
| | | 68 | | private static readonly ComponentPendingQueueIndexSetterDelegate?[] PendingQueueIndexSetters = new ComponentPend |
| | | 69 | | private static readonly ComponentStorageCopyDelegate?[] StorageCopiers = new ComponentStorageCopyDelegate[Frame. |
| | | 70 | | private static readonly ComponentStorageResetDelegate?[] StorageResetters = new ComponentStorageResetDelegate[Fr |
| | | 71 | | private static readonly ComponentPackedStatePresenceDelegate?[] PackedStatePresenceCheckers = new ComponentPacke |
| | | 72 | | private static readonly ComponentPackedStateWriteDelegate?[] PackedStateWriters = new ComponentPackedStateWriteD |
| | | 73 | | private static readonly ComponentPackedStateRestoreDelegate?[] PackedStateRestorers = new ComponentPackedStateRe |
| | | 74 | | private static readonly int[] FixedPackedPayloadSizes = CreateFixedPackedPayloadSizes(); |
| | | 75 | | private static readonly Dictionary<Type, int> ReverseLookup = new(); |
| | | 76 | | private static readonly Dictionary<string, int> ReverseNameLookup = new(StringComparer.Ordinal); |
| | | 77 | | |
| | | 78 | | private static int _nextId = 1; |
| | | 79 | | |
| | | 80 | | public static int Count => _nextId - 1; |
| | | 81 | | |
| | | 82 | | public static Builder CreateBuilder() |
| | | 83 | | { |
| | | 84 | | return new Builder(); |
| | | 85 | | } |
| | | 86 | | |
| | | 87 | | public static bool IsRegistered<T>() where T : unmanaged, IComponent |
| | | 88 | | { |
| | | 89 | | return ComponentTypeId<T>.IsRegistered; |
| | | 90 | | } |
| | | 91 | | |
| | | 92 | | public static int Register<T>() where T : unmanaged, IComponent |
| | | 93 | | { |
| | | 94 | | return Register<T>(ComponentFlags.None, ComponentCallbacks.Empty, StorageFlags.None); |
| | | 95 | | } |
| | | 96 | | |
| | | 97 | | public static int Register<T>(ComponentFlags flags, ComponentCallbacks callbacks, StorageFlags storageFlags = St |
| | | 98 | | where T : unmanaged, IComponent |
| | | 99 | | { |
| | | 100 | | lock (SyncRoot) |
| | | 101 | | { |
| | | 102 | | StorageFlags resolvedStorageFlags = MapStorageFlags(flags, storageFlags); |
| | | 103 | | |
| | | 104 | | if (ReverseLookup.TryGetValue(typeof(T), out int existingId)) |
| | | 105 | | { |
| | | 106 | | ValidateCompatibleRegistration(existingId, flags, resolvedStorageFlags, callbacks); |
| | | 107 | | return existingId; |
| | | 108 | | } |
| | | 109 | | |
| | | 110 | | if (_nextId >= Frame.MaxComponentTypes) |
| | | 111 | | { |
| | | 112 | | throw new InvalidOperationException($"Reached max components declared: {Frame.MaxComponentTypes - 1} |
| | | 113 | | } |
| | | 114 | | |
| | | 115 | | int id = _nextId++; |
| | | 116 | | |
| | | 117 | | Types[id] = typeof(T); |
| | | 118 | | Sizes[id] = sizeof(T); |
| | | 119 | | Flags[id] = flags; |
| | | 120 | | StorageFlagsByType[id] = resolvedStorageFlags; |
| | | 121 | | Callbacks[id] = callbacks; |
| | | 122 | | FixedPackedPayloadSizes[id] = callbacks.Serialize != null |
| | | 123 | | ? ComponentRuntimeDispatch<T>.MeasurePackedPayloadSize(callbacks.Serialize) |
| | | 124 | | : sizeof(T); |
| | | 125 | | RemoveInvokers[id] = ComponentRuntimeDispatch<T>.RemoveFromFrame; |
| | | 126 | | AddAppliers[id] = ComponentRuntimeDispatch<T>.AddToFrame; |
| | | 127 | | SetAppliers[id] = ComponentRuntimeDispatch<T>.SetInFrame; |
| | | 128 | | DeferredCommitters[id] = ComponentRuntimeDispatch<T>.CommitDeferred; |
| | | 129 | | SnapshotCapturers[id] = ComponentRuntimeDispatch<T>.CaptureSnapshot; |
| | | 130 | | SnapshotRestorers[id] = ComponentRuntimeDispatch<T>.RestoreSnapshot; |
| | | 131 | | PendingRemovalMarkers[id] = ComponentRuntimeDispatch<T>.MarkPendingRemoval; |
| | | 132 | | PendingQueueIndexSetters[id] = ComponentRuntimeDispatch<T>.SetPendingQueueIndex; |
| | | 133 | | StorageCopiers[id] = ComponentRuntimeDispatch<T>.CopyStorage; |
| | | 134 | | StorageResetters[id] = ComponentRuntimeDispatch<T>.ResetStorage; |
| | | 135 | | PackedStatePresenceCheckers[id] = ComponentRuntimeDispatch<T>.HasPackedState; |
| | | 136 | | PackedStateWriters[id] = ComponentRuntimeDispatch<T>.WritePackedState; |
| | | 137 | | PackedStateRestorers[id] = ComponentRuntimeDispatch<T>.RestorePackedState; |
| | | 138 | | |
| | | 139 | | ReverseLookup.Add(typeof(T), id); |
| | | 140 | | ReverseNameLookup[typeof(T).Name] = id; |
| | | 141 | | |
| | | 142 | | ComponentTypeId<T>.SetRegistration(id, sizeof(T), flags, resolvedStorageFlags, callbacks); |
| | | 143 | | ComponentCommandRegistry.Register<T>(id); |
| | | 144 | | return id; |
| | | 145 | | } |
| | | 146 | | } |
| | | 147 | | |
| | | 148 | | /// <summary> |
| | | 149 | | /// 确保组件类型已注册。 |
| | | 150 | | /// </summary> |
| | | 151 | | public static void EnsureRegistered<T>() where T : unmanaged, IComponent |
| | | 152 | | { |
| | | 153 | | if (ComponentTypeId<T>.IsRegistered) |
| | | 154 | | { |
| | | 155 | | return; |
| | | 156 | | } |
| | | 157 | | |
| | | 158 | | Register<T>(); |
| | | 159 | | } |
| | | 160 | | |
| | | 161 | | public static int GetComponentIndex(Type type) |
| | | 162 | | { |
| | | 163 | | if (ReverseLookup.TryGetValue(type, out int id)) |
| | | 164 | | { |
| | | 165 | | return id; |
| | | 166 | | } |
| | | 167 | | |
| | | 168 | | throw new InvalidOperationException($"Type not registered: {type.FullName}"); |
| | | 169 | | } |
| | | 170 | | |
| | | 171 | | public static int GetComponentIndex(string shortTypeName) |
| | | 172 | | { |
| | | 173 | | if (ReverseNameLookup.TryGetValue(shortTypeName, out int id)) |
| | | 174 | | { |
| | | 175 | | return id; |
| | | 176 | | } |
| | | 177 | | |
| | | 178 | | throw new InvalidOperationException($"Type not registered: {shortTypeName}"); |
| | | 179 | | } |
| | | 180 | | |
| | | 181 | | public static ComponentTypeInfo GetTypeInfo(int id) |
| | | 182 | | { |
| | | 183 | | EnsureValidTypeId(id); |
| | | 184 | | return new ComponentTypeInfo(Types[id]!, id, Sizes[id], Flags[id], StorageFlagsByType[id], Callbacks[id]); |
| | | 185 | | } |
| | | 186 | | |
| | | 187 | | internal static ComponentSchemaManifest CreateSchemaManifest(ReadOnlySpan<int> serializedTypeIds, ComponentSeria |
| | | 188 | | { |
| | | 189 | | ulong hash = 0xCBF29CE484222325; |
| | | 190 | | |
| | | 191 | | AppendInt64(ref hash, ComponentSchemaManifest.CurrentVersion); |
| | | 192 | | AppendInt64(ref hash, (int)mode); |
| | | 193 | | AppendInt64(ref hash, serializedTypeIds.Length); |
| | | 194 | | |
| | | 195 | | for (int i = 0; i < serializedTypeIds.Length; i++) |
| | | 196 | | { |
| | | 197 | | int typeId = serializedTypeIds[i]; |
| | | 198 | | EnsureValidTypeId(typeId); |
| | | 199 | | |
| | | 200 | | Type type = Types[typeId]!; |
| | | 201 | | ComponentCallbacks callbacks = Callbacks[typeId]; |
| | | 202 | | |
| | | 203 | | AppendInt64(ref hash, typeId); |
| | | 204 | | AppendString(ref hash, type.FullName ?? type.Name); |
| | | 205 | | AppendInt64(ref hash, Sizes[typeId]); |
| | | 206 | | AppendInt64(ref hash, (int)Flags[typeId]); |
| | | 207 | | AppendInt64(ref hash, (int)StorageFlagsByType[typeId]); |
| | | 208 | | AppendInt64(ref hash, callbacks.Serialize != null ? 1 : 0); |
| | | 209 | | AppendInt64(ref hash, callbacks.SerializationVersion); |
| | | 210 | | AppendInt64(ref hash, FixedPackedPayloadSizes[typeId]); |
| | | 211 | | } |
| | | 212 | | |
| | | 213 | | return new ComponentSchemaManifest(mode, hash, serializedTypeIds.Length); |
| | | 214 | | } |
| | | 215 | | |
| | | 216 | | public static Type GetComponentType(int id) |
| | | 217 | | { |
| | | 218 | | EnsureValidTypeId(id); |
| | | 219 | | return Types[id]!; |
| | | 220 | | } |
| | | 221 | | |
| | | 222 | | public static int GetComponentSize(int id) |
| | | 223 | | { |
| | | 224 | | EnsureValidTypeId(id); |
| | | 225 | | return Sizes[id]; |
| | | 226 | | } |
| | | 227 | | |
| | | 228 | | public static ComponentFlags GetComponentFlags(int id) |
| | | 229 | | { |
| | | 230 | | EnsureValidTypeId(id); |
| | | 231 | | return Flags[id]; |
| | | 232 | | } |
| | | 233 | | |
| | | 234 | | public static ComponentCallbacks GetComponentCallbacks(int id) |
| | | 235 | | { |
| | | 236 | | EnsureValidTypeId(id); |
| | | 237 | | return Callbacks[id]; |
| | | 238 | | } |
| | | 239 | | |
| | | 240 | | public static bool CanSerializeComponent(int id, ComponentSerializationMode mode = ComponentSerializationMode.De |
| | | 241 | | { |
| | | 242 | | EnsureValidTypeId(id); |
| | | 243 | | ComponentFlags flags = Flags[id]; |
| | | 244 | | |
| | | 245 | | if ((flags & ComponentFlags.DontSerialize) != 0) |
| | | 246 | | { |
| | | 247 | | return false; |
| | | 248 | | } |
| | | 249 | | |
| | | 250 | | if (mode == ComponentSerializationMode.Prediction && |
| | | 251 | | (flags & ComponentFlags.ExcludeFromPrediction) != 0) |
| | | 252 | | { |
| | | 253 | | return false; |
| | | 254 | | } |
| | | 255 | | |
| | | 256 | | if (mode == ComponentSerializationMode.Checkpoint && |
| | | 257 | | (flags & ComponentFlags.ExcludeFromCheckpoints) != 0) |
| | | 258 | | { |
| | | 259 | | return false; |
| | | 260 | | } |
| | | 261 | | |
| | | 262 | | return true; |
| | | 263 | | } |
| | | 264 | | |
| | | 265 | | public static unsafe bool SerializeComponent( |
| | | 266 | | int id, |
| | | 267 | | void* component, |
| | | 268 | | IFrameSerializer serializer, |
| | | 269 | | ComponentSerializationMode mode = ComponentSerializationMode.Default) |
| | | 270 | | { |
| | | 271 | | EnsureValidTypeId(id); |
| | | 272 | | |
| | | 273 | | if (!CanSerializeComponent(id, mode)) |
| | | 274 | | { |
| | | 275 | | return false; |
| | | 276 | | } |
| | | 277 | | |
| | | 278 | | ComponentCallbacks callbacks = Callbacks[id]; |
| | | 279 | | if (callbacks.Serialize != null) |
| | | 280 | | { |
| | | 281 | | callbacks.Serialize(component, serializer); |
| | | 282 | | return true; |
| | | 283 | | } |
| | | 284 | | |
| | | 285 | | serializer.Serialize(component, Sizes[id]); |
| | | 286 | | return true; |
| | | 287 | | } |
| | | 288 | | |
| | | 289 | | public static StorageFlags GetComponentStorageFlags(int id) |
| | | 290 | | { |
| | | 291 | | EnsureValidTypeId(id); |
| | | 292 | | return StorageFlagsByType[id]; |
| | | 293 | | } |
| | | 294 | | |
| | | 295 | | internal static ComponentFrameRemoveDelegate GetRemoveInvoker(int id) |
| | | 296 | | { |
| | | 297 | | EnsureValidTypeId(id); |
| | | 298 | | return RemoveInvokers[id] ?? throw new InvalidOperationException($"Remove invoker missing for component type |
| | | 299 | | } |
| | | 300 | | |
| | | 301 | | internal static ComponentCommandApplyDelegate GetAddApplier(int id) |
| | | 302 | | { |
| | | 303 | | EnsureValidTypeId(id); |
| | | 304 | | return AddAppliers[id] ?? throw new InvalidOperationException($"Add applier missing for component type ID {i |
| | | 305 | | } |
| | | 306 | | |
| | | 307 | | internal static ComponentCommandApplyDelegate GetSetApplier(int id) |
| | | 308 | | { |
| | | 309 | | EnsureValidTypeId(id); |
| | | 310 | | return SetAppliers[id] ?? throw new InvalidOperationException($"Set applier missing for component type ID {i |
| | | 311 | | } |
| | | 312 | | |
| | | 313 | | internal static ComponentDeferredCommitDelegate GetDeferredCommitter(int id) |
| | | 314 | | { |
| | | 315 | | EnsureValidTypeId(id); |
| | | 316 | | return DeferredCommitters[id] ?? throw new InvalidOperationException($"Deferred committer missing for compon |
| | | 317 | | } |
| | | 318 | | |
| | | 319 | | internal static ComponentSnapshotCaptureDelegate GetSnapshotCapturer(int id) |
| | | 320 | | { |
| | | 321 | | EnsureValidTypeId(id); |
| | | 322 | | return SnapshotCapturers[id] ?? throw new InvalidOperationException($"Snapshot capturer missing for componen |
| | | 323 | | } |
| | | 324 | | |
| | | 325 | | internal static ComponentSnapshotRestoreDelegate GetSnapshotRestorer(int id) |
| | | 326 | | { |
| | | 327 | | EnsureValidTypeId(id); |
| | | 328 | | return SnapshotRestorers[id] ?? throw new InvalidOperationException($"Snapshot restorer missing for componen |
| | | 329 | | } |
| | | 330 | | |
| | | 331 | | internal static ComponentPendingQueueIndexSetterDelegate GetPendingQueueIndexSetter(int id) |
| | | 332 | | { |
| | | 333 | | EnsureValidTypeId(id); |
| | | 334 | | return PendingQueueIndexSetters[id] ?? throw new InvalidOperationException($"Pending queue index setter miss |
| | | 335 | | } |
| | | 336 | | |
| | | 337 | | internal static ComponentPendingRemovalDelegate GetPendingRemovalMarker(int id) |
| | | 338 | | { |
| | | 339 | | EnsureValidTypeId(id); |
| | | 340 | | return PendingRemovalMarkers[id] ?? throw new InvalidOperationException($"Pending removal marker missing for |
| | | 341 | | } |
| | | 342 | | |
| | | 343 | | internal static ComponentStorageCopyDelegate GetStorageCopier(int id) |
| | | 344 | | { |
| | | 345 | | EnsureValidTypeId(id); |
| | | 346 | | return StorageCopiers[id] ?? throw new InvalidOperationException($"Storage copier missing for component type |
| | | 347 | | } |
| | | 348 | | |
| | | 349 | | internal static ComponentStorageResetDelegate GetStorageResetter(int id) |
| | | 350 | | { |
| | | 351 | | EnsureValidTypeId(id); |
| | | 352 | | return StorageResetters[id] ?? throw new InvalidOperationException($"Storage resetter missing for component |
| | | 353 | | } |
| | | 354 | | |
| | | 355 | | internal static ComponentPackedStatePresenceDelegate GetPackedStatePresenceChecker(int id) |
| | | 356 | | { |
| | | 357 | | EnsureValidTypeId(id); |
| | | 358 | | return PackedStatePresenceCheckers[id] ?? throw new InvalidOperationException($"Packed state presence checke |
| | | 359 | | } |
| | | 360 | | |
| | | 361 | | internal static ComponentPackedStateWriteDelegate GetPackedStateWriter(int id) |
| | | 362 | | { |
| | | 363 | | EnsureValidTypeId(id); |
| | | 364 | | return PackedStateWriters[id] ?? throw new InvalidOperationException($"Packed state writer missing for compo |
| | | 365 | | } |
| | | 366 | | |
| | | 367 | | internal static ComponentPackedStateRestoreDelegate GetPackedStateRestorer(int id) |
| | | 368 | | { |
| | | 369 | | EnsureValidTypeId(id); |
| | | 370 | | return PackedStateRestorers[id] ?? throw new InvalidOperationException($"Packed state restorer missing for c |
| | | 371 | | } |
| | | 372 | | |
| | | 373 | | internal static int GetFixedPackedPayloadSize(int id) |
| | | 374 | | { |
| | | 375 | | EnsureValidTypeId(id); |
| | | 376 | | return FixedPackedPayloadSizes[id]; |
| | | 377 | | } |
| | | 378 | | |
| | | 379 | | internal static StorageFlags GetStorageFlags(int id) |
| | | 380 | | { |
| | | 381 | | EnsureValidTypeId(id); |
| | | 382 | | return StorageFlagsByType[id]; |
| | | 383 | | } |
| | | 384 | | |
| | | 385 | | internal static StorageFlags MapStorageFlags(ComponentFlags componentFlags, StorageFlags storageFlags = StorageF |
| | | 386 | | { |
| | | 387 | | StorageFlags mappedFlags = storageFlags; |
| | | 388 | | |
| | | 389 | | if ((componentFlags & ComponentFlags.Singleton) != 0) |
| | | 390 | | { |
| | | 391 | | mappedFlags |= StorageFlags.Singleton; |
| | | 392 | | } |
| | | 393 | | |
| | | 394 | | return mappedFlags; |
| | | 395 | | } |
| | | 396 | | |
| | | 397 | | private static int[] CreateFixedPackedPayloadSizes() |
| | | 398 | | { |
| | | 399 | | int[] sizes = new int[Frame.MaxComponentTypes]; |
| | | 400 | | Array.Fill(sizes, -1); |
| | | 401 | | return sizes; |
| | | 402 | | } |
| | | 403 | | |
| | | 404 | | private static void EnsureValidTypeId(int id) |
| | | 405 | | { |
| | | 406 | | if (id <= 0 || id >= _nextId || Types[id] == null) |
| | | 407 | | { |
| | | 408 | | throw new InvalidOperationException($"Component type ID not registered: {id}"); |
| | | 409 | | } |
| | | 410 | | } |
| | | 411 | | |
| | | 412 | | private static void ValidateCompatibleRegistration( |
| | | 413 | | int id, |
| | | 414 | | ComponentFlags flags, |
| | | 415 | | StorageFlags storageFlags, |
| | | 416 | | ComponentCallbacks callbacks) |
| | | 417 | | { |
| | | 418 | | if (Flags[id] != flags) |
| | | 419 | | { |
| | | 420 | | throw new InvalidOperationException( |
| | | 421 | | $"Component {Types[id]!.FullName} already registered with different flags. " + |
| | | 422 | | $"Existing={Flags[id]}, Requested={flags}"); |
| | | 423 | | } |
| | | 424 | | |
| | | 425 | | if (StorageFlagsByType[id] != storageFlags) |
| | | 426 | | { |
| | | 427 | | throw new InvalidOperationException( |
| | | 428 | | $"Component {Types[id]!.FullName} already registered with different storage flags. " + |
| | | 429 | | $"Existing={StorageFlagsByType[id]}, Requested={storageFlags}"); |
| | | 430 | | } |
| | | 431 | | |
| | | 432 | | ComponentCallbacks existingCallbacks = Callbacks[id]; |
| | | 433 | | if (existingCallbacks.Serialize != callbacks.Serialize || |
| | | 434 | | existingCallbacks.OnAdded != callbacks.OnAdded || |
| | | 435 | | existingCallbacks.OnRemoved != callbacks.OnRemoved || |
| | | 436 | | existingCallbacks.SerializationVersion != callbacks.SerializationVersion) |
| | | 437 | | { |
| | | 438 | | throw new InvalidOperationException( |
| | | 439 | | $"Component {Types[id]!.FullName} already registered with different callbacks."); |
| | | 440 | | } |
| | | 441 | | } |
| | | 442 | | |
| | | 443 | | private static void AppendInt64(ref ulong hash, int value) |
| | | 444 | | { |
| | | 445 | | Span<byte> buffer = stackalloc byte[sizeof(int)]; |
| | | 446 | | BinaryPrimitives.WriteInt32LittleEndian(buffer, value); |
| | | 447 | | AppendBytes(ref hash, buffer); |
| | | 448 | | } |
| | | 449 | | |
| | | 450 | | private static void AppendString(ref ulong hash, string value) |
| | | 451 | | { |
| | | 452 | | AppendInt64(ref hash, value.Length); |
| | | 453 | | Span<byte> buffer = stackalloc byte[sizeof(char)]; |
| | | 454 | | |
| | | 455 | | for (int i = 0; i < value.Length; i++) |
| | | 456 | | { |
| | | 457 | | BinaryPrimitives.WriteUInt16LittleEndian(buffer, value[i]); |
| | | 458 | | AppendBytes(ref hash, buffer); |
| | | 459 | | } |
| | | 460 | | } |
| | | 461 | | |
| | | 462 | | private static void AppendBytes(ref ulong hash, ReadOnlySpan<byte> data) |
| | | 463 | | { |
| | | 464 | | const ulong fnvPrime = 0x00000100000001B3; |
| | | 465 | | |
| | | 466 | | for (int i = 0; i < data.Length; i++) |
| | | 467 | | { |
| | | 468 | | hash ^= data[i]; |
| | | 469 | | hash *= fnvPrime; |
| | | 470 | | } |
| | | 471 | | } |
| | | 472 | | |
| | | 473 | | /// <summary> |
| | | 474 | | /// 增量式注册 Builder,接口形态向 FrameSync 对齐。 |
| | | 475 | | /// </summary> |
| | | 476 | | public readonly struct Builder |
| | | 477 | | { |
| | | 478 | | public Builder Add<T>( |
| | | 479 | | ComponentCallbacks callbacks, |
| | | 480 | | ComponentFlags flags = ComponentFlags.None, |
| | | 481 | | StorageFlags storageFlags = StorageFlags.None) |
| | | 482 | | where T : unmanaged, IComponent |
| | | 483 | | { |
| | | 484 | | Register<T>(flags, callbacks, storageFlags); |
| | | 485 | | return this; |
| | | 486 | | } |
| | | 487 | | |
| | | 488 | | public Builder Add<T>( |
| | | 489 | | ComponentSerializeDelegate? serialize = null, |
| | | 490 | | ComponentChangedDelegate? onAdded = null, |
| | | 491 | | ComponentChangedDelegate? onRemoved = null, |
| | | 492 | | ComponentFlags flags = ComponentFlags.None, |
| | | 493 | | StorageFlags storageFlags = StorageFlags.None) |
| | | 494 | | where T : unmanaged, IComponent |
| | | 495 | | { |
| | | 496 | | Register<T>(flags, new ComponentCallbacks(serialize, onAdded, onRemoved), storageFlags); |
| | | 497 | | return this; |
| | | 498 | | } |
| | | 499 | | |
| | | 500 | | public void Finish() |
| | | 501 | | { |
| | | 502 | | } |
| | | 503 | | } |
| | | 504 | | } |
| | | 505 | | |
| | | 506 | | /// <summary> |
| | | 507 | | /// 组件类型 ID 与元数据缓存(FrameSync 风格)。 |
| | | 508 | | /// </summary> |
| | | 509 | | public static unsafe class ComponentTypeId<T> where T : unmanaged, IComponent |
| | | 510 | | { |
| | | 511 | | private static int _id; |
| | | 512 | | private static int _size; |
| | | 513 | | private static ComponentFlags _flags; |
| | | 514 | | private static StorageFlags _storageFlags; |
| | | 515 | | private static ComponentCallbacks _callbacks; |
| | | 516 | | |
| | | 517 | | public static int Id |
| | | 518 | | { |
| | | 519 | | get |
| | | 520 | | { |
| | | 521 | | if (_id == 0) |
| | | 522 | | { |
| | | 523 | | ComponentRegistry.Register<T>(); |
| | | 524 | | } |
| | | 525 | | |
| | | 526 | | return _id; |
| | | 527 | | } |
| | | 528 | | } |
| | | 529 | | |
| | | 530 | | public static int Size |
| | | 531 | | { |
| | | 532 | | get |
| | | 533 | | { |
| | | 534 | | if (_size == 0) |
| | | 535 | | { |
| | | 536 | | _ = Id; |
| | | 537 | | } |
| | | 538 | | |
| | | 539 | | return _size; |
| | | 540 | | } |
| | | 541 | | } |
| | | 542 | | |
| | | 543 | | public static ComponentFlags Flags |
| | | 544 | | { |
| | | 545 | | get |
| | | 546 | | { |
| | | 547 | | if (_id == 0) |
| | | 548 | | { |
| | | 549 | | _ = Id; |
| | | 550 | | } |
| | | 551 | | |
| | | 552 | | return _flags; |
| | | 553 | | } |
| | | 554 | | } |
| | | 555 | | |
| | | 556 | | public static StorageFlags StorageFlags |
| | | 557 | | { |
| | | 558 | | get |
| | | 559 | | { |
| | | 560 | | if (_id == 0) |
| | | 561 | | { |
| | | 562 | | _ = Id; |
| | | 563 | | } |
| | | 564 | | |
| | | 565 | | return _storageFlags; |
| | | 566 | | } |
| | | 567 | | } |
| | | 568 | | |
| | | 569 | | public static ComponentCallbacks Callbacks |
| | | 570 | | { |
| | | 571 | | get |
| | | 572 | | { |
| | | 573 | | if (_id == 0) |
| | | 574 | | { |
| | | 575 | | _ = Id; |
| | | 576 | | } |
| | | 577 | | |
| | | 578 | | return _callbacks; |
| | | 579 | | } |
| | | 580 | | } |
| | | 581 | | |
| | | 582 | | public static bool IsRegistered => _id != 0; |
| | | 583 | | |
| | | 584 | | internal static void SetRegistration( |
| | | 585 | | int id, |
| | | 586 | | int size, |
| | | 587 | | ComponentFlags flags, |
| | | 588 | | StorageFlags storageFlags, |
| | | 589 | | ComponentCallbacks callbacks) |
| | | 590 | | { |
| | | 591 | | if (_id != 0 && _id != id) |
| | | 592 | | { |
| | | 593 | | throw new InvalidOperationException($"Component type already registered with ID {_id}"); |
| | | 594 | | } |
| | | 595 | | |
| | | 596 | | _id = id; |
| | | 597 | | _size = size; |
| | | 598 | | _flags = flags; |
| | | 599 | | _storageFlags = storageFlags; |
| | | 600 | | _callbacks = callbacks; |
| | | 601 | | } |
| | | 602 | | } |
| | | 603 | | |
| | | 604 | | internal static unsafe class ComponentRuntimeDispatch<T> where T : unmanaged, IComponent |
| | | 605 | | { |
| | | 606 | | public static int MeasurePackedPayloadSize(ComponentSerializeDelegate serialize) |
| | | 607 | | { |
| | | 608 | | if (serialize == null) |
| | | 609 | | { |
| | | 610 | | return sizeof(T); |
| | | 611 | | } |
| | | 612 | | |
| | | 613 | | T component = default; |
| | | 614 | | var sizingStream = new FrameStateBitStreamWriter(new FrameStateSizingWriter()); |
| | | 615 | | var serializer = new FrameSerializer(sizingStream, writing: true); |
| | | 616 | | sizingStream.BeginPayload(); |
| | | 617 | | serialize(&component, serializer); |
| | | 618 | | return sizingStream.EndPayload(); |
| | | 619 | | } |
| | | 620 | | |
| | | 621 | | public static void RemoveFromFrame(Frame frame, EntityRef entity) |
| | | 622 | | { |
| | | 623 | | frame.Remove<T>(entity); |
| | | 624 | | } |
| | | 625 | | |
| | | 626 | | public static void AddToFrame(Frame frame, EntityRef entity, void* componentData) |
| | | 627 | | { |
| | | 628 | | frame.Add(entity, *(T*)componentData); |
| | | 629 | | } |
| | | 630 | | |
| | | 631 | | public static void SetInFrame(Frame frame, EntityRef entity, void* componentData) |
| | | 632 | | { |
| | | 633 | | frame.Set(entity, *(T*)componentData); |
| | | 634 | | } |
| | | 635 | | |
| | | 636 | | public static void CommitDeferred(void* storage, EntityRef entity) |
| | | 637 | | { |
| | | 638 | | var typedStorage = (Storage<T>*)storage; |
| | | 639 | | if (typedStorage == null) |
| | | 640 | | { |
| | | 641 | | return; |
| | | 642 | | } |
| | | 643 | | |
| | | 644 | | typedStorage->CommitRemoval(entity); |
| | | 645 | | } |
| | | 646 | | |
| | | 647 | | public static ComponentStorageSnapshot? CaptureSnapshot(void* storage, ComponentSerializationMode mode) |
| | | 648 | | { |
| | | 649 | | int typeId = ComponentTypeId<T>.Id; |
| | | 650 | | if (!ComponentRegistry.CanSerializeComponent(typeId, mode)) |
| | | 651 | | { |
| | | 652 | | return null; |
| | | 653 | | } |
| | | 654 | | |
| | | 655 | | var typedStorage = (Storage<T>*)storage; |
| | | 656 | | if (typedStorage == null || typedStorage->Count == 0) |
| | | 657 | | { |
| | | 658 | | return null; |
| | | 659 | | } |
| | | 660 | | |
| | | 661 | | if (ComponentTypeId<T>.Callbacks.Serialize == null) |
| | | 662 | | { |
| | | 663 | | int rawCount = typedStorage->Count; |
| | | 664 | | var entities = new EntityRef[rawCount]; |
| | | 665 | | var data = new byte[rawCount * sizeof(T)]; |
| | | 666 | | |
| | | 667 | | typedStorage->CopyDenseEntities(entities); |
| | | 668 | | typedStorage->CopyDenseComponentBytes(data); |
| | | 669 | | |
| | | 670 | | return new ComponentStorageSnapshot(typeId, entities, data); |
| | | 671 | | } |
| | | 672 | | |
| | | 673 | | int count = typedStorage->Count; |
| | | 674 | | var entries = new ComponentEntrySnapshot[count]; |
| | | 675 | | |
| | | 676 | | for (int index = 1; index <= count; index++) |
| | | 677 | | { |
| | | 678 | | EntityRef entity = typedStorage->GetEntityRefByIndex(index); |
| | | 679 | | T* componentData = typedStorage->GetDataPointerByIndex(index); |
| | | 680 | | var serializer = new FrameSerializer(new BitStream(), writing: true); |
| | | 681 | | ComponentRegistry.SerializeComponent(typeId, componentData, serializer, mode); |
| | | 682 | | entries[index - 1] = new ComponentEntrySnapshot(entity, serializer.Stream.ToArray()); |
| | | 683 | | } |
| | | 684 | | |
| | | 685 | | return new ComponentStorageSnapshot(typeId, entries); |
| | | 686 | | } |
| | | 687 | | |
| | | 688 | | public static void RestoreSnapshot(Frame frame, ComponentStorageSnapshot snapshot, ComponentSerializationMode mo |
| | | 689 | | { |
| | | 690 | | int typeId = ComponentTypeId<T>.Id; |
| | | 691 | | var storage = frame.GetOrCreateStorageForSnapshotRestore<T>(typeId); |
| | | 692 | | |
| | | 693 | | if (snapshot.Kind == ComponentSnapshotDataKind.RawDense) |
| | | 694 | | { |
| | | 695 | | storage->RestoreDenseSnapshot(snapshot.DenseEntities, snapshot.DenseData); |
| | | 696 | | return; |
| | | 697 | | } |
| | | 698 | | |
| | | 699 | | if (snapshot.Entries.Length == 0) |
| | | 700 | | { |
| | | 701 | | return; |
| | | 702 | | } |
| | | 703 | | |
| | | 704 | | for (int i = 0; i < snapshot.Entries.Length; i++) |
| | | 705 | | { |
| | | 706 | | ComponentEntrySnapshot entry = snapshot.Entries[i]; |
| | | 707 | | T component = default; |
| | | 708 | | |
| | | 709 | | if (entry.Payload.Length > 0) |
| | | 710 | | { |
| | | 711 | | var serializer = new FrameSerializer(new BitStream(entry.Payload), writing: false); |
| | | 712 | | ComponentRegistry.SerializeComponent(typeId, &component, serializer, mode); |
| | | 713 | | } |
| | | 714 | | |
| | | 715 | | storage->Add(entry.Entity, component); |
| | | 716 | | } |
| | | 717 | | } |
| | | 718 | | |
| | | 719 | | public static void MarkPendingRemoval(void* storage, EntityRef entity) |
| | | 720 | | { |
| | | 721 | | var typedStorage = (Storage<T>*)storage; |
| | | 722 | | if (typedStorage == null) |
| | | 723 | | { |
| | | 724 | | return; |
| | | 725 | | } |
| | | 726 | | |
| | | 727 | | typedStorage->MarkForRemoval(entity); |
| | | 728 | | } |
| | | 729 | | |
| | | 730 | | public static void SetPendingQueueIndex(void* storage, EntityRef entity, int queueIndex) |
| | | 731 | | { |
| | | 732 | | var typedStorage = (Storage<T>*)storage; |
| | | 733 | | if (typedStorage == null) |
| | | 734 | | { |
| | | 735 | | return; |
| | | 736 | | } |
| | | 737 | | |
| | | 738 | | typedStorage->SetPendingQueueIndex(entity, queueIndex); |
| | | 739 | | } |
| | | 740 | | |
| | | 741 | | public static void CopyStorage(Frame destinationFrame, void* sourceStorage) |
| | | 742 | | { |
| | | 743 | | var destination = destinationFrame.GetOrCreateStorageForSnapshotRestore<T>(ComponentTypeId<T>.Id); |
| | | 744 | | var source = (Storage<T>*)sourceStorage; |
| | | 745 | | if (source == null) |
| | | 746 | | { |
| | | 747 | | return; |
| | | 748 | | } |
| | | 749 | | |
| | | 750 | | destination->CopyFrom(source); |
| | | 751 | | } |
| | | 752 | | |
| | | 753 | | public static void ResetStorage(void* storage) |
| | | 754 | | { |
| | | 755 | | var typedStorage = (Storage<T>*)storage; |
| | | 756 | | if (typedStorage == null) |
| | | 757 | | { |
| | | 758 | | return; |
| | | 759 | | } |
| | | 760 | | |
| | | 761 | | typedStorage->Reset(); |
| | | 762 | | } |
| | | 763 | | |
| | | 764 | | public static bool HasPackedState(void* storage, ComponentSerializationMode mode) |
| | | 765 | | { |
| | | 766 | | int typeId = ComponentTypeId<T>.Id; |
| | | 767 | | if (!ComponentRegistry.CanSerializeComponent(typeId, mode)) |
| | | 768 | | { |
| | | 769 | | return false; |
| | | 770 | | } |
| | | 771 | | |
| | | 772 | | var typedStorage = (Storage<T>*)storage; |
| | | 773 | | return typedStorage != null && typedStorage->Count > 0; |
| | | 774 | | } |
| | | 775 | | |
| | | 776 | | public static bool WritePackedState(void* storage, FrameStateWriter writer, ComponentSerializationMode mode) |
| | | 777 | | { |
| | | 778 | | var typedStorage = (Storage<T>*)storage; |
| | | 779 | | if (typedStorage == null || typedStorage->Count == 0) |
| | | 780 | | { |
| | | 781 | | return false; |
| | | 782 | | } |
| | | 783 | | |
| | | 784 | | int typeId = ComponentTypeId<T>.Id; |
| | | 785 | | |
| | | 786 | | writer.WriteInt32(typeId); |
| | | 787 | | |
| | | 788 | | if (ComponentTypeId<T>.Callbacks.Serialize == null) |
| | | 789 | | { |
| | | 790 | | writer.WriteByte((byte)ComponentSnapshotDataKind.RawDense); |
| | | 791 | | |
| | | 792 | | int denseCount = typedStorage->Count; |
| | | 793 | | writer.WriteInt32(denseCount); |
| | | 794 | | typedStorage->WriteDenseEntities(writer); |
| | | 795 | | |
| | | 796 | | int dataLength = denseCount * sizeof(T); |
| | | 797 | | writer.WriteInt32(dataLength); |
| | | 798 | | typedStorage->WriteDenseComponentBytes(writer); |
| | | 799 | | return true; |
| | | 800 | | } |
| | | 801 | | |
| | | 802 | | int entryCount = typedStorage->Count; |
| | | 803 | | int fixedPayloadBytes = ComponentRegistry.GetFixedPackedPayloadSize(typeId); |
| | | 804 | | if (fixedPayloadBytes >= 0) |
| | | 805 | | { |
| | | 806 | | writer.WriteByte((byte)ComponentSnapshotDataKind.FixedSizeEntryPayloads); |
| | | 807 | | writer.WriteInt32(entryCount); |
| | | 808 | | writer.WriteInt32(fixedPayloadBytes); |
| | | 809 | | |
| | | 810 | | var payloadStream = new FrameStateBitStreamWriter(writer); |
| | | 811 | | var serializer = new FrameSerializer(payloadStream, writing: true); |
| | | 812 | | |
| | | 813 | | for (int index = 1; index <= entryCount; index++) |
| | | 814 | | { |
| | | 815 | | EntityRef entity = typedStorage->GetEntityRefByIndex(index); |
| | | 816 | | T* componentData = typedStorage->GetDataPointerByIndex(index); |
| | | 817 | | |
| | | 818 | | writer.WriteUInt64(entity.Raw); |
| | | 819 | | payloadStream.BeginPayload(); |
| | | 820 | | ComponentRegistry.SerializeComponent(typeId, componentData, serializer, mode); |
| | | 821 | | int actualPayloadBytes = payloadStream.EndPayload(); |
| | | 822 | | if (actualPayloadBytes != fixedPayloadBytes) |
| | | 823 | | { |
| | | 824 | | throw new InvalidOperationException( |
| | | 825 | | $"Component {typeof(T).Name} produced variable-sized serialized payloads. " + |
| | | 826 | | $"Expected={fixedPayloadBytes}, Actual={actualPayloadBytes}."); |
| | | 827 | | } |
| | | 828 | | } |
| | | 829 | | |
| | | 830 | | return true; |
| | | 831 | | } |
| | | 832 | | |
| | | 833 | | writer.WriteByte((byte)ComponentSnapshotDataKind.EntryPayloads); |
| | | 834 | | writer.WriteInt32(entryCount); |
| | | 835 | | |
| | | 836 | | var fallbackPayloadStream = new BitStream(); |
| | | 837 | | var fallbackSerializer = new FrameSerializer(fallbackPayloadStream, writing: true); |
| | | 838 | | |
| | | 839 | | for (int index = 1; index <= entryCount; index++) |
| | | 840 | | { |
| | | 841 | | EntityRef entity = typedStorage->GetEntityRefByIndex(index); |
| | | 842 | | T* componentData = typedStorage->GetDataPointerByIndex(index); |
| | | 843 | | |
| | | 844 | | fallbackPayloadStream.Reset(); |
| | | 845 | | ComponentRegistry.SerializeComponent(typeId, componentData, fallbackSerializer, mode); |
| | | 846 | | |
| | | 847 | | writer.WriteUInt64(entity.Raw); |
| | | 848 | | ReadOnlySpan<byte> payload = fallbackPayloadStream.GetWrittenSpan(); |
| | | 849 | | writer.WriteInt32(payload.Length); |
| | | 850 | | writer.WriteBytes(payload); |
| | | 851 | | } |
| | | 852 | | |
| | | 853 | | return true; |
| | | 854 | | } |
| | | 855 | | |
| | | 856 | | public static void RestorePackedState(Frame frame, FrameStateReader reader, ComponentSerializationMode mode) |
| | | 857 | | { |
| | | 858 | | int typeId = ComponentTypeId<T>.Id; |
| | | 859 | | byte kind = reader.ReadByte(); |
| | | 860 | | var storage = frame.GetOrCreateStorageForSnapshotRestore<T>(typeId); |
| | | 861 | | |
| | | 862 | | if (kind == (byte)ComponentSnapshotDataKind.RawDense) |
| | | 863 | | { |
| | | 864 | | int denseCount = reader.ReadInt32(); |
| | | 865 | | ReadOnlySpan<byte> entityBytes = reader.ReadBytes(denseCount * sizeof(EntityRef)); |
| | | 866 | | int dataLength = reader.ReadInt32(); |
| | | 867 | | ReadOnlySpan<byte> componentBytes = reader.ReadBytes(dataLength); |
| | | 868 | | storage->RestoreDenseSnapshot(entityBytes, componentBytes); |
| | | 869 | | return; |
| | | 870 | | } |
| | | 871 | | |
| | | 872 | | if (kind == (byte)ComponentSnapshotDataKind.FixedSizeEntryPayloads) |
| | | 873 | | { |
| | | 874 | | int fixedEntryCount = reader.ReadInt32(); |
| | | 875 | | int payloadLength = reader.ReadInt32(); |
| | | 876 | | var stream = new FrameStateBitStreamReader(reader); |
| | | 877 | | var serializer = new FrameSerializer(stream, writing: false); |
| | | 878 | | |
| | | 879 | | for (int i = 0; i < fixedEntryCount; i++) |
| | | 880 | | { |
| | | 881 | | EntityRef entity = EntityRef.FromRaw(reader.ReadUInt64()); |
| | | 882 | | T component = default; |
| | | 883 | | |
| | | 884 | | if (payloadLength > 0) |
| | | 885 | | { |
| | | 886 | | stream.BeginPayload(payloadLength); |
| | | 887 | | ComponentRegistry.SerializeComponent(typeId, &component, serializer, mode); |
| | | 888 | | stream.EndPayload(); |
| | | 889 | | } |
| | | 890 | | |
| | | 891 | | storage->Add(entity, component); |
| | | 892 | | } |
| | | 893 | | |
| | | 894 | | return; |
| | | 895 | | } |
| | | 896 | | |
| | | 897 | | int entryCount = reader.ReadInt32(); |
| | | 898 | | for (int i = 0; i < entryCount; i++) |
| | | 899 | | { |
| | | 900 | | EntityRef entity = EntityRef.FromRaw(reader.ReadUInt64()); |
| | | 901 | | int payloadLength = reader.ReadInt32(); |
| | | 902 | | T component = default; |
| | | 903 | | |
| | | 904 | | if (payloadLength > 0) |
| | | 905 | | { |
| | | 906 | | var stream = reader.CreateBitStreamSlice(payloadLength); |
| | | 907 | | var serializer = new FrameSerializer(stream, writing: false); |
| | | 908 | | ComponentRegistry.SerializeComponent(typeId, &component, serializer, mode); |
| | | 909 | | } |
| | | 910 | | |
| | | 911 | | storage->Add(entity, component); |
| | | 912 | | } |
| | | 913 | | } |
| | | 914 | | } |
| | | 915 | | } |