< Summary

Information
Class: Lattice.ECS.Core.Storage<T>
Assembly: Lattice
File(s): /home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Core/Storage.cs
Line coverage
70%
Covered lines: 403
Uncovered lines: 165
Coverable lines: 568
Total lines: 1613
Line coverage: 70.9%
Branch coverage
62%
Covered branches: 178
Total branches: 284
Branch coverage: 62.6%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
get_IsAllocated()100%210%
get_Count()100%11100%
get_IsEmpty()100%210%
get_Version()100%11100%
get_BlockCount()100%11100%
get_BlockItemCapacity()100%11100%
get_ComponentTypeId()100%210%
get_Flags()100%210%
get_IsSingleton()100%11100%
get_IsDeferredRemoval()100%11100%
get_PendingRemovalCount()100%210%
get_UsedCount()100%11100%
get_HasEntryStateTracking()100%11100%
get_HasPendingQueueTracking()100%11100%
get_SingletonEntity()100%44100%
Initialize(...)100%11100%
Initialize(...)100%11100%
Initialize(...)100%210%
Initialize(...)100%66100%
Dispose()100%44100%
GetSnapshotSize()0%620%
WriteSnapshot(...)0%2040%
ReadSnapshot(...)0%110100%
Reset()100%11100%
CopyFrom(...)50%322068.75%
EnsureEntityCapacity(...)50%231050%
Add(...)87.5%8885.71%
Remove(...)12.5%23838.46%
RemoveImmediate(...)80%101095.65%
CommitRemovals(...)0%4260%
MarkForRemoval(...)50%7670%
CancelPendingRemoval(...)60%121075%
CommitRemoval(...)62.5%9875%
GetSingletonPointer()0%2040%
GetSingleton()50%4480%
Get(...)100%11100%
GetPointer(...)50%22100%
GetPointerAssumePresent(...)50%4477.77%
TryGet(...)0%2040%
Has(...)50%22100%
IsPendingRemoval(...)0%620%
GetPendingQueueIndex(...)50%22100%
SetPendingQueueIndex(...)50%2280%
GetBlockData(...)100%11100%
GetBlockEntityRefs(...)100%11100%
GetBlockItemCount(...)50%44100%
GetEntityRefByIndex(...)100%11100%
GetDataPointerByIndex(...)100%11100%
GetDenseEntryByLinearIndex(...)100%11100%
IsDenseEntryActive(...)100%11100%
CopyDenseEntities(...)50%9871.42%
WriteDenseEntities(...)87.5%8890%
CopyDenseComponentBytes(...)50%9875%
WriteDenseComponentBytes(...)87.5%8890%
RestoreDenseSnapshot(...)50%171475%
RestoreDenseSnapshot(...)50%4480%
GetEntityRefByGlobalIndex(...)100%11100%
ResolveBlockCapacity(...)50%2280%
GetSparseIndex(...)83.33%6688.88%
CopyDenseEntities(...)87.5%8892.85%
CopyDenseComponentBytes(...)87.5%8892.85%
RestoreDenseEntities(...)100%66100%
RestoreDenseComponentBytes(...)100%66100%
GetDenseBlockCopyCount(...)50%4475%
CopyDenseEntitiesFrom(...)100%66100%
CopyDenseComponentBytesFrom(...)100%66100%
ClearSparseAndStates()100%66100%
RestoreDenseSnapshot(...)83.33%6694.11%
GetEntryStateByIndex(...)100%22100%
SetEntryStateByIndex(...)100%22100%
GetPendingQueueIndexByIndex(...)100%44100%
SetPendingQueueIndexByIndex(...)75%44100%
RoundDownToPowerOfTwo(...)50%2266.66%
EnsureBlockSpace()90%101095.23%

File(s)

/home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Core/Storage.cs

#LineLine coverage
 1// Copyright (c) 2026 Sideline Authors. All rights reserved.
 2// Licensed under GPL-3.0.
 3
 4using System;
 5using System.Numerics;
 6using System.Runtime.CompilerServices;
 7using Lattice.Core;
 8
 9namespace Lattice.ECS.Core
 10{
 11    /// <summary>
 12    /// 存储标志 - 定义组件存储的特殊行为
 13    ///
 14    /// 设计说明:
 15    /// - 使用 ushort 节省内存(2 字节),足够表示 16 种标志
 16    /// - 单例和延迟删除是预测回滚模型的核心需求
 17    /// </summary>
 18    [Flags]
 19    public enum StorageFlags : ushort
 20    {
 21        /// <summary>无特殊标志</summary>
 22        None = 0,
 23
 24        /// <summary>
 25        /// 单例组件(只允许一个实例)
 26        ///
 27        /// 应用场景:
 28        /// - 全局配置(如 GameConfig)
 29        /// - 唯一的游戏状态(如 GameState)
 30        /// - 避免多个实例导致的逻辑错误
 31        /// </summary>
 32        Singleton = 1 << 0,
 33
 34        /// <summary>
 35        /// 延迟删除(Remove 时标记,需要 Commit 才真正删除)
 36        ///
 37        /// 设计原因:
 38        /// - 预测回滚需要延迟删除,避免预测期间的状态不一致
 39        /// - 允许在帧结束时批量处理删除,减少内存抖动
 40        /// - FrameSync 使用相同的模式(_pendingRemoval)
 41        /// </summary>
 42        DeferredRemoval = 1 << 1,
 43    }
 44
 45    /// <summary>
 46    /// Block-based 高性能组件存储 - 超越 FrameSync 的内存效率与迭代性能
 47    ///
 48    /// ============================================================
 49    /// 架构设计决策
 50    /// ============================================================
 51    ///
 52    /// Q: 为什么选择分离存储(SOA)而不是联合存储(AOS)?
 53    /// A:
 54    ///   1. 预测回滚友好:可以单独快照/恢复单个组件类型
 55    ///   2. Delta 压缩高效:只传输变化的组件
 56    ///   3. SIMD 友好:连续的同类型数据便于向量化
 57    ///   4. 缓存局部性:批量访问同类型组件时命中率更高
 58    ///   5. 与 FrameSync 不同:FrameSync 使用联合存储(ComponentDataBuffer)
 59    ///
 60    /// Q: 为什么 Block 容量固定为 128?
 61    /// A:
 62    ///   1. 与 FrameSync 保持一致,便于对比和迁移
 63    ///   2. 128 * sizeof(T) 通常能填满多个缓存行(假设 T=16 字节,128*16=2048 字节)
 64    ///   3. 128 是 2 的幂,可以用位运算替代除法/取模(block = index >> 7, offset = index &amp; 127)
 65    ///   4. 足够大的批次用于 SIMD 处理(AVX2 可以一次处理 4 个 Vector4FP)
 66    ///
 67    /// Q: 为什么稀疏数组使用 ushort(2 字节)而不是 int(4 字节)?
 68    /// A:
 69    ///   1. 内存节省 50%:65536 个实体的稀疏数组只需 128KB,而 int 需要 256KB
 70    ///   2. 65535 的最大索引足够大多数游戏使用(支持 64K 个组件实例)
 71    ///   3. 缓存行利用更好:同一代码可以追踪更多实体
 72    ///   4. 与 FrameSync 相同的选择(ComponentDataBuffer._sparse 也是 ushort*)
 73    ///
 74    /// Q: 为什么需要版本号(_version)?
 75    /// A:
 76    ///   1. 防止迭代中修改:快速检测并发修改,抛出异常而非崩溃
 77    ///   2. 调试友好:在 DEBUG 模式下提供清晰的错误信息
 78    ///   3. 与 C# 的 IEnumerator 模式一致(检查集合修改)
 79    ///
 80    /// ============================================================
 81    /// 性能特性
 82    /// ============================================================
 83    ///
 84    /// 1. O(1) 添加/删除/访问:稀疏数组保证常数时间
 85    /// 2. 缓存友好:Block 内数据连续,预取友好
 86    /// 3. 内存对齐:16 字节对齐,支持 SIMD
 87    /// 4. 无 GC:完全非托管内存,通过 Allocator 管理
 88    ///
 89    /// ============================================================
 90    /// 内存布局
 91    /// ============================================================
 92    ///
 93    /// Storage&lt;T&gt; (SOA - Structure of Arrays):
 94    ///
 95    ///     Block 0          Block 1          Block 2
 96    /// ┌─────────────┐  ┌─────────────┐  ┌─────────────┐
 97    /// │ EntityRef   │  │ EntityRef   │  │ EntityRef   │  ← 实体引用数组
 98    /// │ [128]       │  │ [128]       │  │ [128]       │     (密集存储)
 99    /// └─────────────┘  └─────────────┘  └─────────────┘
 100    ///       ↓                  ↓                  ↓
 101    /// ┌─────────────┐  ┌─────────────┐  ┌─────────────┐
 102    /// │ T[128]      │  │ T[128]      │  │ T[128]      │  ← 组件数据数组
 103    /// │ (强类型)    │  │ (强类型)    │  │ (强类型)    │     (密集存储)
 104    /// └─────────────┘  └─────────────┘  └─────────────┘
 105    ///       ↓                  ↓                  ↓
 106    /// _sparse[Entity.Index] → GlobalIndex (ushort, 2 字节)
 107    ///
 108    /// 对比 FrameSync (AOS - Array of Structures):
 109    ///
 110    /// Block 内存布局:
 111    /// ┌─────────────────────────────────────────┐
 112    /// │ EntityRef[0] | Padding | T[0]          │  ← 同一 Block 内混合存储
 113    /// │ EntityRef[1] | Padding | T[1]          │     需要 _blockDataOffset
 114    /// │ ...                                    │     计算数据偏移
 115    /// └─────────────────────────────────────────┘
 116    ///
 117    /// 我们的优势:
 118    /// - 类型安全:T* 而不是 byte*
 119    /// - 更简单的偏移计算:直接 array[index] 而不是 ptr + stride * index
 120    /// - 更好的 SIMD 支持:连续的同类型数据
 121    /// </summary>
 122    public unsafe struct Storage<T> where T : unmanaged, IComponent
 123    {
 124        #region 常量
 125
 126        /// <summary>自动推导 Block 容量。</summary>
 127        public const int DefaultBlockCapacity = 0;
 128
 129        /// <summary>Block 数据面的目标字节数。</summary>
 130        public const int TargetBlockBytes = 2048;
 131
 132        /// <summary>Block 列表初始容量</summary>
 133        public const int InitialBlockListCapacity = 4;
 134
 135        /// <summary>自动推导时允许的最小 Block 容量。</summary>
 136        public const int MinBlockCapacity = 8;
 137
 138        /// <summary>自动推导时允许的最大 Block 容量。</summary>
 139        public const int MaxBlockCapacity = 512;
 140
 141        /// <summary>稀疏数组 Tombstone 标记</summary>
 142        public const ushort TOMBSTONE = 0;
 143
 144        #endregion
 145
 146        #region Block 结构
 147
 148        /// <summary>
 149        /// 数据块 - 包含固定数量的实体引用和组件数据
 150        /// </summary>
 151        public struct Block
 152        {
 153            /// <summary>实体引用数组(紧密排列)</summary>
 154            public EntityRef* PackedHandles;
 155
 156            /// <summary>组件数据数组(紧密排列)</summary>
 157            public T* PackedData;
 158
 159            /// <summary>Block 是否已分配</summary>
 0160            public bool IsAllocated => PackedData != null;
 161        }
 162
 163        #endregion
 164
 165        #region 字段
 166
 167        // Block 管理
 168        private Block* _blocks;
 169        private int _blockCount;
 170        private int _blockCapacity;
 171        private int _blockItemCapacity;
 172
 173        // 稀疏数组:Entity.Index → GlobalIndex (1-based, 0 = empty)
 174        private ushort* _sparse;
 175        private int _sparseCapacity;
 176        private byte* _entryStates;
 177        private ushort* _pendingQueueIndices;
 178
 179        // 状态
 180        private int _count;
 181        private int _stride;
 182        private int _version;
 183        private int _componentTypeId;
 184
 185        // 内存分配器
 186        private Allocator* _allocator;
 187        private bool _ownsAllocator;
 188
 189        // 标志和特殊功能
 190        private StorageFlags _flags;
 191        private ushort _singletonSparse;  // 单例的全局索引(0 = 无单例)
 192        private int _pendingRemoval;      // 待删除计数(延迟删除模式)
 193
 194        #endregion
 195
 196        #region 属性
 197
 198        /// <summary>当前组件数量(不包括索引0)</summary>
 14873199        public int Count => _count - 1;
 200
 201        /// <summary>是否为空</summary>
 0202        public bool IsEmpty => _count <= 1;
 203
 204        /// <summary>当前版本号(用于迭代检测)</summary>
 3026205        public int Version => _version;
 206
 207        /// <summary>Block 数量</summary>
 104109208        public int BlockCount => _blockCount;
 209
 210        /// <summary>每个 Block 的容量</summary>
 3032211        public int BlockItemCapacity => _blockItemCapacity;
 212
 213        /// <summary>组件类型ID</summary>
 0214        public int ComponentTypeId => _componentTypeId;
 215
 216        /// <summary>存储标志</summary>
 0217        public StorageFlags Flags => _flags;
 218
 219        /// <summary>是否为单例存储</summary>
 45896220        public bool IsSingleton => (_flags & StorageFlags.Singleton) != 0;
 221
 222        /// <summary>是否启用延迟删除</summary>
 12987223        public bool IsDeferredRemoval => (_flags & StorageFlags.DeferredRemoval) != 0;
 224
 225        /// <summary>待删除组件数量(延迟删除模式)</summary>
 0226        public int PendingRemovalCount => _pendingRemoval;
 227
 228        /// <summary>实际使用中的组件数量(减去待删除)</summary>
 5042229        public int UsedCount => Count - _pendingRemoval;
 230
 231        /// <summary>是否为条目状态分配了独立跟踪存储。</summary>
 2232        internal bool HasEntryStateTracking => _entryStates != null;
 233
 234        /// <summary>是否为延迟删除队列索引分配了独立跟踪存储。</summary>
 2235        internal bool HasPendingQueueTracking => _pendingQueueIndices != null;
 236
 237        /// <summary>单例实体引用(仅单例模式有效)</summary>
 238        public EntityRef SingletonEntity
 239        {
 240            get
 241            {
 449242                if (!IsSingleton || _singletonSparse == 0)
 4243                    return EntityRef.None;
 445244                return GetEntityRefByGlobalIndex(_singletonSparse);
 245            }
 246        }
 247
 248        #endregion
 249
 250        #region 生命周期
 251
 252        /// <summary>
 253        /// 初始化存储(使用内部Allocator)
 254        /// </summary>
 255        public void Initialize(int maxEntities, int blockCapacity = DefaultBlockCapacity, int componentTypeId = 0)
 256        {
 8257            Initialize(maxEntities, StorageFlags.None, blockCapacity, componentTypeId);
 8258        }
 259
 260        /// <summary>
 261        /// 初始化存储(使用内部Allocator,带标志)
 262        /// </summary>
 263        public void Initialize(int maxEntities, StorageFlags flags, int blockCapacity = DefaultBlockCapacity, int compon
 264        {
 9265            var allocatorPtr = Allocator.Create();
 9266            Initialize(maxEntities, allocatorPtr, flags, blockCapacity, componentTypeId);
 9267            _ownsAllocator = true;
 9268        }
 269
 270        /// <summary>
 271        /// 初始化存储(使用外部Allocator)
 272        /// </summary>
 273        public void Initialize(int maxEntities, Allocator* allocator, int blockCapacity = DefaultBlockCapacity, int comp
 274        {
 0275            Initialize(maxEntities, allocator, StorageFlags.None, blockCapacity, componentTypeId);
 0276        }
 277
 278        /// <summary>
 279        /// 初始化存储(使用外部Allocator,带标志)
 280        /// </summary>
 281        public void Initialize(int maxEntities, Allocator* allocator, StorageFlags flags, int blockCapacity = DefaultBlo
 282        {
 1369283            _sparseCapacity = maxEntities;
 1369284            _blockItemCapacity = ResolveBlockCapacity(blockCapacity);
 1369285            _stride = sizeof(T);
 1369286            _componentTypeId = componentTypeId;
 1369287            _count = 1; // 索引0保留为无效值
 1369288            _version = 0;
 1369289            _allocator = allocator;
 1369290            _ownsAllocator = false;
 1369291            _flags = flags;
 1369292            _singletonSparse = 0;
 1369293            _pendingRemoval = 0;
 294
 295            // 分配稀疏数组(初始化为0,即TOMBSTONE)
 1369296            _sparse = (ushort*)_allocator->AllocAndClear(sizeof(ushort) * maxEntities);
 297
 1369298            if (IsDeferredRemoval)
 299            {
 14300                _entryStates = (byte*)_allocator->AllocAndClear(maxEntities + 1);
 14301                _pendingQueueIndices = (ushort*)_allocator->Alloc(sizeof(ushort) * (maxEntities + 1));
 576302                for (int i = 0; i <= maxEntities; i++)
 303                {
 274304                    _pendingQueueIndices[i] = PendingQueueIndexNone;
 305                }
 306            }
 307            else
 308            {
 1355309                _entryStates = null;
 1355310                _pendingQueueIndices = null;
 311            }
 312
 313            // 分配 Block 列表
 1369314            _blockCapacity = InitialBlockListCapacity;
 1369315            _blockCount = 0;
 1369316            _blocks = (Block*)_allocator->Alloc(sizeof(Block) * _blockCapacity);
 13690317            for (int i = 0; i < _blockCapacity; i++)
 318            {
 5476319                _blocks[i].PackedHandles = null;
 5476320                _blocks[i].PackedData = null;
 321            }
 1369322        }
 323
 324        /// <summary>
 325        /// 释放所有内存
 326        /// </summary>
 327        public void Dispose()
 328        {
 9329            if (_ownsAllocator && _allocator != null)
 330            {
 9331                Allocator.Destroy(_allocator);
 332            }
 333
 9334            _blocks = null;
 9335            _sparse = null;
 9336            _entryStates = null;
 9337            _pendingQueueIndices = null;
 9338            _count = 0;
 9339            _blockCount = 0;
 9340            _allocator = null;
 9341        }
 342
 343        #endregion
 344
 345        #region 预测回滚支持(快照/恢复)
 346
 347        /// <summary>
 348        /// 计算快照大小(字节)
 349        /// </summary>
 350        public int GetSnapshotSize()
 351        {
 0352            int denseCount = Count;
 0353            int size =
 0354                sizeof(int) * 6 +    // _count, _version, _blockCount, _blockItemCapacity, _componentTypeId, _sparseCapa
 0355                sizeof(ushort) * 4 + // _singletonSparse, _pendingRemoval, _flags, reserved
 0356                sizeof(EntityRef) * denseCount +
 0357                sizeof(T) * denseCount;
 358
 0359            if (_entryStates != null)
 360            {
 0361                size += denseCount;
 362            }
 363
 0364            return size;
 365        }
 366
 367        /// <summary>
 368        /// 创建快照(用于预测回滚)
 369        /// </summary>
 370        public void WriteSnapshot(byte* buffer, int bufferSize)
 371        {
 0372            byte* ptr = buffer;
 373
 374            // 写入元数据
 0375            *(int*)ptr = _count; ptr += sizeof(int);
 0376            *(int*)ptr = _version; ptr += sizeof(int);
 0377            *(int*)ptr = _blockCount; ptr += sizeof(int);
 0378            *(int*)ptr = _blockItemCapacity; ptr += sizeof(int);
 0379            *(int*)ptr = _componentTypeId; ptr += sizeof(int);
 0380            *(int*)ptr = _sparseCapacity; ptr += sizeof(int);
 0381            *(ushort*)ptr = _singletonSparse; ptr += sizeof(ushort);
 0382            *(ushort*)ptr = (ushort)_pendingRemoval; ptr += sizeof(ushort);
 0383            *(ushort*)ptr = (ushort)_flags; ptr += sizeof(ushort);
 0384            *(ushort*)ptr = 0; ptr += sizeof(ushort);
 385
 0386            int denseCount = Count;
 0387            int handlesBytes = sizeof(EntityRef) * denseCount;
 0388            int dataBytes = sizeof(T) * denseCount;
 389
 0390            CopyDenseEntities((EntityRef*)ptr, denseCount);
 0391            ptr += handlesBytes;
 392
 0393            CopyDenseComponentBytes(ptr, denseCount);
 0394            ptr += dataBytes;
 395
 0396            if (_entryStates != null && denseCount > 0)
 397            {
 0398                Buffer.MemoryCopy(_entryStates + 1, ptr, denseCount, denseCount);
 399            }
 0400        }
 401
 402        /// <summary>
 403        /// 从快照恢复(用于回滚)
 404        /// </summary>
 405        public void ReadSnapshot(byte* buffer, int bufferSize)
 406        {
 0407            byte* ptr = buffer;
 408
 409            // 读取元数据
 0410            int savedCount = *(int*)ptr; ptr += sizeof(int);
 0411            int savedVersion = *(int*)ptr; ptr += sizeof(int);
 0412            int savedBlockCount = *(int*)ptr; ptr += sizeof(int);
 0413            int savedBlockItemCapacity = *(int*)ptr; ptr += sizeof(int);
 0414            int savedComponentTypeId = *(int*)ptr; ptr += sizeof(int);
 0415            int savedSparseCapacity = *(int*)ptr; ptr += sizeof(int);
 0416            ushort savedSingletonSparse = *(ushort*)ptr; ptr += sizeof(ushort);
 0417            ushort savedPendingRemoval = *(ushort*)ptr; ptr += sizeof(ushort);
 0418            StorageFlags savedFlags = (StorageFlags)(*(ushort*)ptr); ptr += sizeof(ushort);
 0419            ptr += sizeof(ushort); // reserved
 420
 0421            if (savedSparseCapacity != _sparseCapacity)
 422            {
 0423                throw new InvalidOperationException(
 0424                    $"Storage<{typeof(T).Name}> 快照容量不匹配。 Snapshot={savedSparseCapacity}, Current={_sparseCapacity}。");
 425            }
 426
 0427            _blockItemCapacity = savedBlockItemCapacity;
 0428            _componentTypeId = savedComponentTypeId;
 0429            _flags = savedFlags;
 430
 431            // 确保容量足够
 0432            EnsureEntityCapacity(savedBlockCount * savedBlockItemCapacity);
 433
 434            // 恢复元数据
 0435            _count = savedCount;
 0436            _version = savedVersion;
 0437            _blockCount = savedBlockCount;
 0438            _singletonSparse = savedSingletonSparse;
 0439            _pendingRemoval = 0;
 440
 0441            ClearSparseAndStates();
 0442            EnsureEntityCapacity(savedCount);
 443
 0444            int denseCount = System.Math.Max(savedCount - 1, 0);
 0445            RestoreDenseEntities((EntityRef*)ptr, denseCount);
 0446            ptr += sizeof(EntityRef) * denseCount;
 447
 0448            RestoreDenseComponentBytes(ptr, denseCount);
 0449            ptr += sizeof(T) * denseCount;
 450
 0451            if (denseCount > 0)
 452            {
 0453                if (_entryStates != null)
 454                {
 0455                    Buffer.MemoryCopy(ptr, _entryStates + 1, denseCount, denseCount);
 0456                    ptr += denseCount;
 457                }
 458                else
 459                {
 0460                    for (int i = 1; i <= denseCount; i++)
 461                    {
 0462                        SetEntryStateByIndex(i, EntryStateActive);
 463                    }
 464                }
 465            }
 466
 0467            for (int globalIndex = 1; globalIndex <= denseCount; globalIndex++)
 468            {
 0469                EntityRef entity = GetEntityRefByIndex(globalIndex);
 0470                _sparse[entity.Index] = (ushort)globalIndex;
 471            }
 472
 0473            _pendingRemoval = savedPendingRemoval;
 0474        }
 475
 476        /// <summary>
 477        /// 重置存储内容但保留已分配容量,供热路径复用。
 478        /// </summary>
 479        internal void Reset()
 480        {
 62481            _count = 1;
 62482            _version = 0;
 62483            _singletonSparse = 0;
 62484            _pendingRemoval = 0;
 62485            ClearSparseAndStates();
 62486        }
 487
 488        /// <summary>
 489        /// 从同类型存储直接复制状态,避免走托管快照分配。
 490        /// </summary>
 491        internal void CopyFrom(Storage<T>* source)
 492        {
 2113493            if (source == null)
 494            {
 0495                throw new ArgumentNullException(nameof(source));
 496            }
 497
 2113498            if (_componentTypeId != source->_componentTypeId)
 499            {
 0500                throw new InvalidOperationException("Cannot copy storage state from a different component type.");
 501            }
 502
 2113503            if (_flags != source->_flags)
 504            {
 0505                throw new InvalidOperationException("Cannot copy storage state from a storage with different flags.");
 506            }
 507
 2113508            if (_blockItemCapacity != source->_blockItemCapacity)
 509            {
 0510                throw new InvalidOperationException("Cannot copy storage state from a storage with different block layou
 511            }
 512
 2113513            _count = source->_count;
 2113514            _version = source->_version;
 2113515            _singletonSparse = source->_singletonSparse;
 2113516            _pendingRemoval = source->_pendingRemoval;
 517
 2113518            ClearSparseAndStates();
 2113519            EnsureEntityCapacity(source->_count);
 520
 2113521            int denseCount = source->Count;
 2113522            if (denseCount <= 0)
 523            {
 2524                return;
 525            }
 526
 2111527            CopyDenseEntitiesFrom(source, denseCount);
 2111528            CopyDenseComponentBytesFrom(source, denseCount);
 529
 2111530            if (_entryStates != null)
 531            {
 0532                if (source->_entryStates != null)
 533                {
 0534                    Buffer.MemoryCopy(source->_entryStates + 1, _entryStates + 1, denseCount, denseCount);
 535                }
 536                else
 537                {
 0538                    Unsafe.InitBlockUnaligned(_entryStates + 1, EntryStateActive, (uint)denseCount);
 539                }
 540            }
 541
 2111542            int pendingQueueIndex = 0;
 14308543            for (int i = 1; i <= denseCount; i++)
 544            {
 5043545                EntityRef entity = GetEntityRefByGlobalIndex(i);
 5043546                _sparse[entity.Index] = (ushort)i;
 547
 5043548                if (_pendingQueueIndices != null)
 549                {
 0550                    if (GetEntryStateByIndex(i) == EntryStatePendingRemoval)
 551                    {
 0552                        _pendingQueueIndices[i] = (ushort)pendingQueueIndex++;
 553                    }
 554                    else
 555                    {
 0556                        _pendingQueueIndices[i] = PendingQueueIndexNone;
 557                    }
 558                }
 559            }
 2111560        }
 561
 562        /// <summary>
 563        /// 确保有足够的实体容量
 564        /// </summary>
 565        private void EnsureEntityCapacity(int requiredCount)
 566        {
 2355567            int requiredBlocks = (requiredCount + _blockItemCapacity - 1) / _blockItemCapacity;
 568
 569            // 扩展 Block 列表
 2355570            if (requiredBlocks > _blockCapacity)
 571            {
 0572                int newCapacity = _blockCapacity;
 0573                while (newCapacity < requiredBlocks)
 0574                    newCapacity *= 2;
 575
 0576                var newBlocks = (Block*)_allocator->Alloc(sizeof(Block) * newCapacity);
 0577                Buffer.MemoryCopy(_blocks, newBlocks, sizeof(Block) * newCapacity, sizeof(Block) * _blockCapacity);
 578
 0579                for (int i = _blockCapacity; i < newCapacity; i++)
 580                {
 0581                    newBlocks[i].PackedHandles = null;
 0582                    newBlocks[i].PackedData = null;
 583                }
 584
 0585                _blocks = newBlocks;
 0586                _blockCapacity = newCapacity;
 587            }
 588
 589            // 分配缺少的 Blocks
 3430590            while (_blockCount < requiredBlocks)
 591            {
 1075592                int blockIndex = _blockCount++;
 1075593                _blocks[blockIndex].PackedHandles = (EntityRef*)_allocator->Alloc(sizeof(EntityRef) * _blockItemCapacity
 1075594                _blocks[blockIndex].PackedData = (T*)_allocator->Alloc(sizeof(T) * _blockItemCapacity);
 595
 1075596                if (blockIndex == 0)
 597                {
 1075598                    _blocks[0].PackedHandles[0] = EntityRef.None;
 1075599                    _blocks[0].PackedData[0] = default;
 600                }
 601            }
 2355602        }
 603
 604        #endregion
 605
 606        #region 核心操作
 607
 608        /// <summary>
 609        /// 添加组件 - O(1) 均摊
 610        /// </summary>
 611        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 612        public void Add(EntityRef entity, in T component)
 613        {
 14086614            int index = entity.Index;
 615
 616#if DEBUG
 617            if ((uint)index >= (uint)_sparseCapacity)
 618                throw new ArgumentOutOfRangeException(nameof(entity), "Entity index out of range");
 619            if (GetSparseIndex(entity) != TOMBSTONE)
 620                throw new InvalidOperationException($"Component already exists for entity {entity}");
 621#endif
 622
 623            // 单例检查
 14086624            if (IsSingleton)
 625            {
 26626                if (_singletonSparse != 0)
 627                {
 0628                    throw new InvalidOperationException(
 0629                        $"Cannot add multiple instances of singleton component {typeof(T).Name}. " +
 0630                        $"Existing entity: {GetEntityRefByGlobalIndex(_singletonSparse)}");
 631                }
 632            }
 633
 634            // 确保有空间
 14086635            if (_count >= (_blockCount * _blockItemCapacity))
 314636                EnsureBlockSpace();
 637
 14086638            int globalIndex = _count++;
 14086639            int block = globalIndex / _blockItemCapacity;
 14086640            int offset = globalIndex % _blockItemCapacity;
 641
 642            // 写入数据
 14086643            Block* b = &_blocks[block];
 14086644            b->PackedHandles[offset] = entity;
 14086645            b->PackedData[offset] = component;
 646
 647            // 更新稀疏数组
 14086648            _sparse[index] = (ushort)globalIndex;
 14086649            SetEntryStateByIndex(globalIndex, EntryStateActive);
 14086650            SetPendingQueueIndexByIndex(globalIndex, PendingQueueIndexNone);
 651
 652            // 更新单例索引
 14086653            if (IsSingleton)
 654            {
 26655                _singletonSparse = (ushort)globalIndex;
 656            }
 657
 14086658            _version++;
 14086659        }
 660
 661        /// <summary>
 662        /// 删除组件 - O(1)
 663        /// 如果启用延迟删除,则标记为待删除,需要调用 CommitRemovals 才真正删除
 664        /// </summary>
 665        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 666        public void Remove(EntityRef entity)
 667        {
 10800668            int index = entity.Index;
 10800669            ushort globalIndex = GetSparseIndex(entity);
 670
 671#if DEBUG
 672            if ((uint)index >= (uint)_sparseCapacity || globalIndex == TOMBSTONE)
 673                throw new InvalidOperationException($"Component not found for entity {entity}");
 674#endif
 675
 676            // 延迟删除模式:只标记,不立即删除
 10800677            if (IsDeferredRemoval)
 678            {
 0679                if (GetEntryStateByIndex(globalIndex) == EntryStatePendingRemoval)
 680                {
 0681                    return;
 682                }
 683
 0684                SetEntryStateByIndex(globalIndex, EntryStatePendingRemoval);
 0685                _pendingRemoval++;
 686
 687                // 清除单例索引
 0688                if (IsSingleton && _singletonSparse == globalIndex)
 689                {
 0690                    _singletonSparse = 0;
 691                }
 692
 0693                _version++;
 0694                return;
 695            }
 696
 697            // 立即删除模式
 10800698            RemoveImmediate(index, globalIndex);
 10800699        }
 700
 701        /// <summary>
 702        /// 立即删除组件(内部方法)
 703        /// </summary>
 704        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 705        private void RemoveImmediate(int entityIndex, ushort globalIndex)
 706        {
 10801707            int lastGlobalIndex = --_count;
 708
 709            // 如果不是最后一个,与末尾交换
 10801710            if (globalIndex != lastGlobalIndex)
 711            {
 5742712                int lastBlock = lastGlobalIndex / _blockItemCapacity;
 5742713                int lastOffset = lastGlobalIndex % _blockItemCapacity;
 714
 5742715                int block = globalIndex / _blockItemCapacity;
 5742716                int offset = globalIndex % _blockItemCapacity;
 717
 5742718                EntityRef lastEntity = _blocks[lastBlock].PackedHandles[lastOffset];
 5742719                T lastComponent = _blocks[lastBlock].PackedData[lastOffset];
 5742720                byte lastState = GetEntryStateByIndex(lastGlobalIndex);
 721
 5742722                _blocks[block].PackedHandles[offset] = lastEntity;
 5742723                _blocks[block].PackedData[offset] = lastComponent;
 5742724                SetEntryStateByIndex(globalIndex, lastState);
 5742725                SetPendingQueueIndexByIndex(globalIndex, GetPendingQueueIndexByIndex(lastGlobalIndex));
 726
 727                // 更新被移动实体的稀疏索引
 5742728                _sparse[lastEntity.Index] = globalIndex;
 729
 730                // 更新单例索引(如果被移动的是单例)
 5742731                if (IsSingleton && _singletonSparse == lastGlobalIndex)
 732                {
 0733                    _singletonSparse = globalIndex;
 734                }
 735            }
 736
 10801737            _sparse[entityIndex] = TOMBSTONE;
 10801738            SetEntryStateByIndex(lastGlobalIndex, EntryStateEmpty);
 10801739            SetPendingQueueIndexByIndex(lastGlobalIndex, PendingQueueIndexNone);
 740
 741            // 清除单例索引
 10801742            if (IsSingleton && _singletonSparse == globalIndex)
 743            {
 2744                _singletonSparse = 0;
 745            }
 746
 10801747            _version++;
 10801748        }
 749
 750        /// <summary>
 751        /// 提交所有待删除(延迟删除模式)
 752        /// 注意:此实现需要 Frame 层维护待删除列表来配合
 753        /// </summary>
 754        public void CommitRemovals(Span<EntityRef> entitiesToRemove)
 755        {
 0756            if (!IsDeferredRemoval || entitiesToRemove.IsEmpty)
 0757                return;
 758
 0759            foreach (var entity in entitiesToRemove)
 760            {
 0761                CommitRemoval(entity);
 762            }
 0763        }
 764
 765        /// <summary>
 766        /// 标记组件为待删除(延迟删除模式)
 767        /// </summary>
 768        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 769        public void MarkForRemoval(EntityRef entity)
 770        {
 8771            if (!IsDeferredRemoval)
 772            {
 0773                Remove(entity);
 0774                return;
 775            }
 776
 777            int index = entity.Index;
 8778            ushort globalIndex = GetSparseIndex(entity);
 779
 780#if DEBUG
 781            if ((uint)index >= (uint)_sparseCapacity || globalIndex == TOMBSTONE)
 782                throw new InvalidOperationException($"Component not found for entity {entity}");
 783#endif
 784
 8785            _pendingRemoval++;
 8786            SetEntryStateByIndex(globalIndex, EntryStatePendingRemoval);
 787
 788            // 清除单例索引
 8789            if (IsSingleton && _singletonSparse == globalIndex)
 790            {
 0791                _singletonSparse = 0;
 792            }
 793
 8794            _version++;
 8795        }
 796
 797        /// <summary>
 798        /// 取消待删除状态,允许组件在同一帧内恢复。
 799        /// </summary>
 800        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 801        internal void CancelPendingRemoval(EntityRef entity)
 802        {
 1803            if (!IsDeferredRemoval)
 804            {
 0805                return;
 806            }
 807
 1808            int index = entity.Index;
 1809            if ((uint)index >= (uint)_sparseCapacity)
 810            {
 0811                return;
 812            }
 813
 1814            ushort globalIndex = GetSparseIndex(entity);
 1815            if (globalIndex == TOMBSTONE)
 816            {
 0817                return;
 818            }
 819
 1820            if (_pendingRemoval > 0)
 821            {
 1822                _pendingRemoval--;
 823            }
 824
 1825            SetEntryStateByIndex(globalIndex, EntryStateActive);
 1826            SetPendingQueueIndexByIndex(globalIndex, PendingQueueIndexNone);
 827
 1828            if (IsSingleton)
 829            {
 0830                _singletonSparse = globalIndex;
 831            }
 832
 1833            _version++;
 1834        }
 835
 836        /// <summary>
 837        /// 提交单个待删除组件。
 838        /// </summary>
 839        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 840        internal void CommitRemoval(EntityRef entity)
 841        {
 1842            int index = entity.Index;
 1843            if ((uint)index >= (uint)_sparseCapacity)
 844            {
 0845                return;
 846            }
 847
 1848            ushort globalIndex = GetSparseIndex(entity);
 1849            if (globalIndex == TOMBSTONE)
 850            {
 0851                return;
 852            }
 853
 1854            if (GetEntryStateByIndex(globalIndex) != EntryStatePendingRemoval)
 855            {
 0856                return;
 857            }
 858
 1859            RemoveImmediate(index, globalIndex);
 1860            if (_pendingRemoval > 0)
 861            {
 1862                _pendingRemoval--;
 863            }
 1864        }
 865
 866        /// <summary>
 867        /// 获取单例组件指针(仅单例模式有效)
 868        /// </summary>
 869        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 870        public T* GetSingletonPointer()
 871        {
 0872            if (!IsSingleton || _singletonSparse == 0)
 0873                return null;
 874
 0875            int block = _singletonSparse / _blockItemCapacity;
 0876            int offset = _singletonSparse % _blockItemCapacity;
 0877            return &_blocks[block].PackedData[offset];
 878        }
 879
 880        /// <summary>
 881        /// 获取单例组件引用(仅单例模式有效)
 882        /// </summary>
 883        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 884        public ref T GetSingleton()
 885        {
 227886            if (!IsSingleton || _singletonSparse == 0)
 0887                throw new InvalidOperationException($"Singleton component {typeof(T).Name} not found");
 888
 227889            int block = _singletonSparse / _blockItemCapacity;
 227890            int offset = _singletonSparse % _blockItemCapacity;
 227891            return ref _blocks[block].PackedData[offset];
 892        }
 893
 894        /// <summary>
 895        /// 获取组件引用 - O(1)
 896        /// </summary>
 897        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 898        public ref T Get(EntityRef entity)
 899        {
 10243900            ushort globalIndex = GetSparseIndex(entity);
 901#if DEBUG
 902            if ((uint)entity.Index >= (uint)_sparseCapacity || globalIndex == TOMBSTONE)
 903                throw new InvalidOperationException($"Component not found for entity {entity}");
 904#endif
 10243905            int block = globalIndex / _blockItemCapacity;
 10243906            int offset = globalIndex % _blockItemCapacity;
 10243907            return ref _blocks[block].PackedData[offset];
 908        }
 909
 910        /// <summary>
 911        /// 获取组件指针 - O(1)
 912        /// </summary>
 913        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 914        public T* GetPointer(EntityRef entity)
 915        {
 16916            ushort globalIndex = GetSparseIndex(entity);
 16917            if (globalIndex == TOMBSTONE) return null;
 16918            int block = globalIndex / _blockItemCapacity;
 16919            int offset = globalIndex % _blockItemCapacity;
 16920            return &_blocks[block].PackedData[offset];
 921        }
 922
 923        /// <summary>
 924        /// 在调用方已经通过 Frame 位图确认组件存在时,直接按实体索引读取组件指针。
 925        /// 该路径跳过额外的 EntityRef 回读校验,用于 Query 热路径。
 926        /// </summary>
 927        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 928        internal T* GetPointerAssumePresent(EntityRef entity)
 929        {
 2426930            uint entityIndex = (uint)entity.Index;
 2426931            if (entityIndex >= (uint)_sparseCapacity)
 932            {
 0933                return null;
 934            }
 935
 2426936            ushort globalIndex = _sparse[entityIndex];
 2426937            if (globalIndex == TOMBSTONE)
 938            {
 0939                return null;
 940            }
 941
 942#if DEBUG
 943            if (GetEntityRefByGlobalIndex(globalIndex).Raw != entity.Raw)
 944            {
 945                throw new InvalidOperationException(
 946                    $"Storage<{typeof(T).Name}> 检测到实体位图与稀疏索引不一致,Entity={entity}。");
 947            }
 948
 949            if (GetEntryStateByIndex(globalIndex) != EntryStateActive)
 950            {
 951                throw new InvalidOperationException(
 952                    $"Storage<{typeof(T).Name}> 检测到非 Active 条目进入 Query 热路径,Entity={entity}。");
 953            }
 954#endif
 955
 2426956            int block = globalIndex / _blockItemCapacity;
 2426957            int offset = globalIndex % _blockItemCapacity;
 2426958            return &_blocks[block].PackedData[offset];
 959        }
 960
 961        /// <summary>
 962        /// 尝试获取组件 - O(1)
 963        /// </summary>
 964        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 965        public bool TryGet(EntityRef entity, out T component)
 966        {
 0967            int index = entity.Index;
 0968            if ((uint)index < (uint)_sparseCapacity)
 969            {
 0970                ushort globalIndex = GetSparseIndex(entity);
 0971                if (globalIndex != TOMBSTONE)
 972                {
 0973                    int block = globalIndex / _blockItemCapacity;
 0974                    int offset = globalIndex % _blockItemCapacity;
 0975                    component = _blocks[block].PackedData[offset];
 0976                    return true;
 977                }
 978            }
 0979            component = default;
 0980            return false;
 981        }
 982
 983        /// <summary>
 984        /// 检查是否存在 - O(1)
 985        /// </summary>
 986        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 987        public bool Has(EntityRef entity)
 988        {
 22217989            uint index = (uint)entity.Index;
 22217990            return index < (uint)_sparseCapacity && GetSparseIndex(entity) != TOMBSTONE;
 991        }
 992
 993        /// <summary>
 994        /// 检查组件是否处于待删除状态。
 995        /// </summary>
 996        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 997        internal bool IsPendingRemoval(EntityRef entity)
 998        {
 0999            ushort globalIndex = GetSparseIndex(entity);
 01000            return globalIndex != TOMBSTONE && GetEntryStateByIndex(globalIndex) == EntryStatePendingRemoval;
 1001        }
 1002
 1003        /// <summary>
 1004        /// 获取待删除队列索引。
 1005        /// </summary>
 1006        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1007        internal int GetPendingQueueIndex(EntityRef entity)
 1008        {
 11009            ushort globalIndex = GetSparseIndex(entity);
 11010            return globalIndex == TOMBSTONE ? PendingQueueIndexNone : GetPendingQueueIndexByIndex(globalIndex);
 1011        }
 1012
 1013        /// <summary>
 1014        /// 设置待删除队列索引。
 1015        /// </summary>
 1016        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1017        internal void SetPendingQueueIndex(EntityRef entity, int queueIndex)
 1018        {
 81019            ushort globalIndex = GetSparseIndex(entity);
 81020            if (globalIndex == TOMBSTONE)
 1021            {
 01022                return;
 1023            }
 1024
 81025            SetPendingQueueIndexByIndex(globalIndex, queueIndex);
 81026        }
 1027
 1028        #endregion
 1029
 1030        #region Block 访问 API
 1031
 1032        /// <summary>
 1033        /// 获取指定 Block 的数据指针
 1034        /// </summary>
 1035        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1036        public T* GetBlockData(int blockIndex)
 1037        {
 1038#if DEBUG
 1039            if ((uint)blockIndex >= (uint)_blockCount)
 1040                throw new ArgumentOutOfRangeException(nameof(blockIndex));
 1041#endif
 1041081042            return _blocks[blockIndex].PackedData;
 1043        }
 1044
 1045        /// <summary>
 1046        /// 获取指定 Block 的实体引用指针
 1047        /// </summary>
 1048        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1049        public EntityRef* GetBlockEntityRefs(int blockIndex)
 1050        {
 1051#if DEBUG
 1052            if ((uint)blockIndex >= (uint)_blockCount)
 1053                throw new ArgumentOutOfRangeException(nameof(blockIndex));
 1054#endif
 1041081055            return _blocks[blockIndex].PackedHandles;
 1056        }
 1057
 1058        /// <summary>
 1059        /// 获取 Block 中有效项的数量
 1060        /// </summary>
 1061        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1062        public int GetBlockItemCount(int blockIndex)
 1063        {
 1041081064            if (blockIndex < 0 || blockIndex >= _blockCount) return 0;
 1065
 1041081066            int startIndex = blockIndex * _blockItemCapacity;
 1041081067            int endIndex = System.Math.Min(startIndex + _blockItemCapacity, _count);
 1041081068            return System.Math.Max(0, endIndex - startIndex);
 1069        }
 1070
 1071        /// <summary>
 1072        /// 获取指定全局索引上的实体引用。
 1073        /// </summary>
 1074        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1075        internal EntityRef GetEntityRefByIndex(int globalIndex)
 1076        {
 81077            return GetEntityRefByGlobalIndex(globalIndex);
 1078        }
 1079
 1080        /// <summary>
 1081        /// 获取指定全局索引上的组件数据指针。
 1082        /// </summary>
 1083        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1084        internal T* GetDataPointerByIndex(int globalIndex)
 1085        {
 1086#if DEBUG
 1087            if (globalIndex <= 0 || globalIndex >= _count)
 1088                throw new ArgumentOutOfRangeException(nameof(globalIndex));
 1089#endif
 81090            int block = globalIndex / _blockItemCapacity;
 81091            int offset = globalIndex % _blockItemCapacity;
 81092            return &_blocks[block].PackedData[offset];
 1093        }
 1094
 1095        /// <summary>
 1096        /// 按 0 基 dense 索引访问条目。
 1097        /// 该辅助方法用于把对外的连续遍历索引映射到内部 1 基稠密存储布局。
 1098        /// </summary>
 1099        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1100        internal void GetDenseEntryByLinearIndex(int denseIndex, out EntityRef entity, out T* component)
 1101        {
 1102#if DEBUG
 1103            if ((uint)denseIndex >= (uint)Count)
 1104                throw new ArgumentOutOfRangeException(nameof(denseIndex));
 1105#endif
 41106            int globalIndex = denseIndex + 1;
 41107            int block = globalIndex / _blockItemCapacity;
 41108            int offset = globalIndex % _blockItemCapacity;
 41109            entity = _blocks[block].PackedHandles[offset];
 41110            component = &_blocks[block].PackedData[offset];
 41111        }
 1112
 1113        /// <summary>
 1114        /// 检查指定全局索引上的条目是否为 active。
 1115        /// 没有启用状态跟踪时,非空 dense 条目都视为 active。
 1116        /// </summary>
 1117        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1118        internal bool IsDenseEntryActive(int globalIndex)
 1119        {
 41061120            return GetEntryStateByIndex(globalIndex) == EntryStateActive;
 1121        }
 1122
 1123        /// <summary>
 1124        /// 将密集实体数组复制到托管缓冲区。
 1125        /// </summary>
 1126        internal void CopyDenseEntities(EntityRef[] destination)
 1127        {
 61128            if (destination == null)
 1129            {
 01130                throw new ArgumentNullException(nameof(destination));
 1131            }
 1132
 61133            if (destination.Length < Count)
 1134            {
 01135                throw new ArgumentException("Destination buffer is too small.", nameof(destination));
 1136            }
 1137
 61138            fixed (EntityRef* dest = destination)
 1139            {
 61140                CopyDenseEntities(dest, Count);
 1141            }
 61142        }
 1143
 1144        /// <summary>
 1145        /// 将密集实体数组直接写入状态写入器。
 1146        /// </summary>
 1147        internal void WriteDenseEntities(FrameStateWriter writer)
 1148        {
 10811149            if (writer == null)
 1150            {
 01151                throw new ArgumentNullException(nameof(writer));
 1152            }
 1153
 10811154            int copied = 0;
 43241155            for (int blockIndex = 0; blockIndex < _blockCount && copied < Count; blockIndex++)
 1156            {
 10811157                int blockCount = GetDenseBlockCopyCount(blockIndex, Count - copied);
 10811158                if (blockCount <= 0)
 1159                {
 1160                    continue;
 1161                }
 1162
 10811163                int sourceOffset = blockIndex == 0 ? 1 : 0;
 10811164                writer.WriteBytes(_blocks[blockIndex].PackedHandles + sourceOffset, sizeof(EntityRef) * blockCount);
 10811165                copied += blockCount;
 1166            }
 10811167        }
 1168
 1169        /// <summary>
 1170        /// 将密集组件数据复制到字节缓冲区。
 1171        /// </summary>
 1172        internal void CopyDenseComponentBytes(byte[] destination)
 1173        {
 61174            if (destination == null)
 1175            {
 01176                throw new ArgumentNullException(nameof(destination));
 1177            }
 1178
 61179            int byteCount = Count * sizeof(T);
 61180            if (destination.Length < byteCount)
 1181            {
 01182                throw new ArgumentException("Destination buffer is too small.", nameof(destination));
 1183            }
 1184
 61185            fixed (byte* dest = destination)
 1186            {
 61187                CopyDenseComponentBytes(dest, Count);
 1188            }
 61189        }
 1190
 1191        /// <summary>
 1192        /// 将密集组件数据直接写入状态写入器。
 1193        /// </summary>
 1194        internal void WriteDenseComponentBytes(FrameStateWriter writer)
 1195        {
 10811196            if (writer == null)
 1197            {
 01198                throw new ArgumentNullException(nameof(writer));
 1199            }
 1200
 10811201            int copied = 0;
 43241202            for (int blockIndex = 0; blockIndex < _blockCount && copied < Count; blockIndex++)
 1203            {
 10811204                int blockCount = GetDenseBlockCopyCount(blockIndex, Count - copied);
 10811205                if (blockCount <= 0)
 1206                {
 1207                    continue;
 1208                }
 1209
 10811210                int sourceOffset = blockIndex == 0 ? 1 : 0;
 10811211                writer.WriteBytes(_blocks[blockIndex].PackedData + sourceOffset, sizeof(T) * blockCount);
 10811212                copied += blockCount;
 1213            }
 10811214        }
 1215
 1216        /// <summary>
 1217        /// 使用原始密集快照恢复组件存储。
 1218        /// </summary>
 1219        internal void RestoreDenseSnapshot(EntityRef[] entities, byte[] componentData)
 1220        {
 41221            if (entities == null)
 1222            {
 01223                throw new ArgumentNullException(nameof(entities));
 1224            }
 1225
 41226            if (componentData == null)
 1227            {
 01228                throw new ArgumentNullException(nameof(componentData));
 1229            }
 1230
 41231            int denseCount = entities.Length;
 41232            if (componentData.Length != denseCount * sizeof(T))
 1233            {
 01234                throw new ArgumentException("Component snapshot data size does not match entity count.", nameof(componen
 1235            }
 1236
 41237            fixed (EntityRef* entityPtr = entities)
 41238            fixed (byte* dataPtr = componentData)
 1239            {
 41240                RestoreDenseSnapshot(entityPtr, dataPtr, denseCount);
 1241            }
 1242
 41243            _version++;
 41244        }
 1245
 1246        /// <summary>
 1247        /// 使用连续字节片段恢复组件存储。
 1248        /// </summary>
 1249        internal void RestoreDenseSnapshot(ReadOnlySpan<byte> entityBytes, ReadOnlySpan<byte> componentBytes)
 1250        {
 2381251            if ((entityBytes.Length % sizeof(EntityRef)) != 0)
 1252            {
 01253                throw new ArgumentException("Entity snapshot byte length is invalid.", nameof(entityBytes));
 1254            }
 1255
 2381256            int denseCount = entityBytes.Length / sizeof(EntityRef);
 2381257            if (componentBytes.Length != denseCount * sizeof(T))
 1258            {
 01259                throw new ArgumentException("Component snapshot byte length does not match entity count.", nameof(compon
 1260            }
 1261
 1262            unsafe
 1263            {
 2381264                fixed (byte* entityPtrRaw = entityBytes)
 2381265                fixed (byte* componentPtr = componentBytes)
 1266                {
 2381267                    RestoreDenseSnapshot((EntityRef*)entityPtrRaw, componentPtr, denseCount);
 1268                }
 1269            }
 1270
 2381271            _version++;
 2381272        }
 1273
 1274        #endregion
 1275
 1276        #region 内部辅助
 1277
 1278        /// <summary>
 1279        /// 通过全局索引获取实体引用(内部辅助)
 1280        /// </summary>
 1281        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1282        private EntityRef GetEntityRefByGlobalIndex(int globalIndex)
 1283        {
 1284#if DEBUG
 1285            if (globalIndex <= 0 || globalIndex >= _count)
 1286                throw new ArgumentOutOfRangeException(nameof(globalIndex));
 1287#endif
 54961288            int block = globalIndex / _blockItemCapacity;
 54961289            int offset = globalIndex % _blockItemCapacity;
 54961290            return _blocks[block].PackedHandles[offset];
 1291        }
 1292
 1293        private static int ResolveBlockCapacity(int requestedCapacity)
 1294        {
 13691295            if (requestedCapacity > 0)
 1296            {
 01297                return System.Math.Clamp(requestedCapacity, MinBlockCapacity, MaxBlockCapacity);
 1298            }
 1299
 13691300            int ideal = TargetBlockBytes / System.Math.Max(sizeof(T), 1);
 13691301            ideal = System.Math.Clamp(ideal, MinBlockCapacity, MaxBlockCapacity);
 13691302            return RoundDownToPowerOfTwo(ideal);
 1303        }
 1304
 1305        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1306        private ushort GetSparseIndex(EntityRef entity)
 1307        {
 432951308            uint index = (uint)entity.Index;
 432951309            if (index >= (uint)_sparseCapacity)
 1310            {
 01311                return TOMBSTONE;
 1312            }
 1313
 432951314            ushort sparse = _sparse[index];
 432951315            if (sparse == TOMBSTONE)
 1316            {
 12831317                return TOMBSTONE;
 1318            }
 1319
 420121320            int block = sparse / _blockItemCapacity;
 420121321            int offset = sparse % _blockItemCapacity;
 420121322            return _blocks[block].PackedHandles[offset].Raw == entity.Raw ? sparse : TOMBSTONE;
 1323        }
 1324
 1325        private void CopyDenseEntities(EntityRef* destination, int denseCount)
 1326        {
 61327            if (denseCount <= 0)
 1328            {
 01329                return;
 1330            }
 1331
 61332            int copied = 0;
 241333            for (int blockIndex = 0; blockIndex < _blockCount && copied < denseCount; blockIndex++)
 1334            {
 61335                int blockCount = GetDenseBlockCopyCount(blockIndex, denseCount - copied);
 61336                if (blockCount <= 0)
 1337                {
 1338                    continue;
 1339                }
 1340
 61341                int sourceOffset = blockIndex == 0 ? 1 : 0;
 61342                Buffer.MemoryCopy(
 61343                    _blocks[blockIndex].PackedHandles + sourceOffset,
 61344                    destination + copied,
 61345                    sizeof(EntityRef) * (denseCount - copied),
 61346                    sizeof(EntityRef) * blockCount);
 61347                copied += blockCount;
 1348            }
 61349        }
 1350
 1351        private void CopyDenseComponentBytes(byte* destination, int denseCount)
 1352        {
 61353            if (denseCount <= 0)
 1354            {
 01355                return;
 1356            }
 1357
 61358            int copied = 0;
 241359            for (int blockIndex = 0; blockIndex < _blockCount && copied < denseCount; blockIndex++)
 1360            {
 61361                int blockCount = GetDenseBlockCopyCount(blockIndex, denseCount - copied);
 61362                if (blockCount <= 0)
 1363                {
 1364                    continue;
 1365                }
 1366
 61367                int sourceOffset = blockIndex == 0 ? 1 : 0;
 61368                Buffer.MemoryCopy(
 61369                    _blocks[blockIndex].PackedData + sourceOffset,
 61370                    destination + (copied * sizeof(T)),
 61371                    sizeof(T) * (denseCount - copied),
 61372                    sizeof(T) * blockCount);
 61373                copied += blockCount;
 1374            }
 61375        }
 1376
 1377        private void RestoreDenseEntities(EntityRef* source, int denseCount)
 1378        {
 2421379            int copied = 0;
 9681380            for (int blockIndex = 0; blockIndex < _blockCount && copied < denseCount; blockIndex++)
 1381            {
 2421382                int blockCount = GetDenseBlockCopyCount(blockIndex, denseCount - copied);
 2421383                if (blockCount <= 0)
 1384                {
 1385                    continue;
 1386                }
 1387
 2421388                int destinationOffset = blockIndex == 0 ? 1 : 0;
 2421389                Buffer.MemoryCopy(
 2421390                    source + copied,
 2421391                    _blocks[blockIndex].PackedHandles + destinationOffset,
 2421392                    sizeof(EntityRef) * blockCount,
 2421393                    sizeof(EntityRef) * blockCount);
 2421394                copied += blockCount;
 1395            }
 2421396        }
 1397
 1398        private void RestoreDenseComponentBytes(byte* source, int denseCount)
 1399        {
 2421400            int copied = 0;
 9681401            for (int blockIndex = 0; blockIndex < _blockCount && copied < denseCount; blockIndex++)
 1402            {
 2421403                int blockCount = GetDenseBlockCopyCount(blockIndex, denseCount - copied);
 2421404                if (blockCount <= 0)
 1405                {
 1406                    continue;
 1407                }
 1408
 2421409                int destinationOffset = blockIndex == 0 ? 1 : 0;
 2421410                Buffer.MemoryCopy(
 2421411                    source + (copied * sizeof(T)),
 2421412                    _blocks[blockIndex].PackedData + destinationOffset,
 2421413                    sizeof(T) * blockCount,
 2421414                    sizeof(T) * blockCount);
 2421415                copied += blockCount;
 1416            }
 2421417        }
 1418
 1419        private int GetDenseBlockCopyCount(int blockIndex, int remainingCount)
 1420        {
 68801421            if (remainingCount <= 0)
 1422            {
 01423                return 0;
 1424            }
 1425
 68801426            int blockCapacity = blockIndex == 0 ? _blockItemCapacity - 1 : _blockItemCapacity;
 68801427            return System.Math.Min(blockCapacity, remainingCount);
 1428        }
 1429
 1430        private void CopyDenseEntitiesFrom(Storage<T>* source, int denseCount)
 1431        {
 21111432            int copied = 0;
 84441433            for (int blockIndex = 0; blockIndex < _blockCount && copied < denseCount; blockIndex++)
 1434            {
 21111435                int blockCount = GetDenseBlockCopyCount(blockIndex, denseCount - copied);
 21111436                if (blockCount <= 0)
 1437                {
 1438                    continue;
 1439                }
 1440
 21111441                int offset = blockIndex == 0 ? 1 : 0;
 21111442                Buffer.MemoryCopy(
 21111443                    source->_blocks[blockIndex].PackedHandles + offset,
 21111444                    _blocks[blockIndex].PackedHandles + offset,
 21111445                    sizeof(EntityRef) * blockCount,
 21111446                    sizeof(EntityRef) * blockCount);
 21111447                copied += blockCount;
 1448            }
 21111449        }
 1450
 1451        private void CopyDenseComponentBytesFrom(Storage<T>* source, int denseCount)
 1452        {
 21111453            int copied = 0;
 84441454            for (int blockIndex = 0; blockIndex < _blockCount && copied < denseCount; blockIndex++)
 1455            {
 21111456                int blockCount = GetDenseBlockCopyCount(blockIndex, denseCount - copied);
 21111457                if (blockCount <= 0)
 1458                {
 1459                    continue;
 1460                }
 1461
 21111462                int offset = blockIndex == 0 ? 1 : 0;
 21111463                Buffer.MemoryCopy(
 21111464                    source->_blocks[blockIndex].PackedData + offset,
 21111465                    _blocks[blockIndex].PackedData + offset,
 21111466                    sizeof(T) * blockCount,
 21111467                    sizeof(T) * blockCount);
 21111468                copied += blockCount;
 1469            }
 21111470        }
 1471
 1472        private void ClearSparseAndStates()
 1473        {
 24171474            Unsafe.InitBlockUnaligned(_sparse, 0, checked((uint)(sizeof(ushort) * _sparseCapacity)));
 24171475            if (_entryStates != null)
 1476            {
 11477                Unsafe.InitBlockUnaligned(_entryStates, 0, checked((uint)(_sparseCapacity + 1)));
 1478            }
 1479
 24171480            if (_pendingQueueIndices != null)
 1481            {
 201482                for (int i = 0; i <= _sparseCapacity; i++)
 1483                {
 91484                    _pendingQueueIndices[i] = PendingQueueIndexNone;
 1485                }
 1486            }
 24171487        }
 1488
 1489        private void RestoreDenseSnapshot(EntityRef* entityPtr, byte* dataPtr, int denseCount)
 1490        {
 2421491            ClearSparseAndStates();
 2421492            _count = denseCount + 1;
 2421493            _pendingRemoval = 0;
 2421494            _singletonSparse = 0;
 1495
 2421496            EnsureEntityCapacity(_count);
 1497
 2421498            if (denseCount == 0)
 1499            {
 01500                return;
 1501            }
 1502
 2421503            RestoreDenseEntities(entityPtr, denseCount);
 2421504            RestoreDenseComponentBytes(dataPtr, denseCount);
 1505
 14761506            for (int i = 0; i < denseCount; i++)
 1507            {
 4961508                EntityRef entity = entityPtr[i];
 4961509                int globalIndex = i + 1;
 4961510                _sparse[entity.Index] = (ushort)globalIndex;
 4961511                SetEntryStateByIndex(globalIndex, EntryStateActive);
 1512
 4961513                if (IsSingleton)
 1514                {
 281515                    _singletonSparse = (ushort)globalIndex;
 1516                }
 1517            }
 2421518        }
 1519
 1520        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1521        private byte GetEntryStateByIndex(int globalIndex)
 1522        {
 98491523            return _entryStates != null ? _entryStates[globalIndex] : EntryStateActive;
 1524        }
 1525
 1526        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1527        private void SetEntryStateByIndex(int globalIndex, byte state)
 1528        {
 311341529            if (_entryStates != null)
 1530            {
 371531                _entryStates[globalIndex] = state;
 1532            }
 311341533        }
 1534
 1535        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1536        private int GetPendingQueueIndexByIndex(int globalIndex)
 1537        {
 57431538            return _pendingQueueIndices != null && _pendingQueueIndices[globalIndex] != PendingQueueIndexNone
 57431539                ? _pendingQueueIndices[globalIndex]
 57431540                : PendingQueueIndexNone;
 1541        }
 1542
 1543        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1544        private void SetPendingQueueIndexByIndex(int globalIndex, int queueIndex)
 1545        {
 306381546            if (_pendingQueueIndices != null)
 1547            {
 361548                _pendingQueueIndices[globalIndex] = queueIndex >= 0 ? checked((ushort)queueIndex) : PendingQueueIndexNon
 1549            }
 306381550        }
 1551
 1552        private static int RoundDownToPowerOfTwo(int value)
 1553        {
 13691554            if (value <= 1)
 1555            {
 01556                return 1;
 1557            }
 1558
 13691559            return 1 << (BitOperations.Log2((uint)value));
 1560        }
 1561
 1562        private void EnsureBlockSpace()
 1563        {
 3141564            int requiredBlock = (_count / _blockItemCapacity) + 1;
 1565
 1566            // 扩展 Block 列表
 3141567            if (requiredBlock > _blockCapacity)
 1568            {
 31569                int newCapacity = _blockCapacity * 2;
 31570                while (newCapacity < requiredBlock)
 01571                    newCapacity *= 2;
 1572
 31573                var newBlocks = (Block*)_allocator->Alloc(sizeof(Block) * newCapacity);
 1574
 1575                // 复制旧数据
 31576                Buffer.MemoryCopy(_blocks, newBlocks,
 31577                    sizeof(Block) * newCapacity, sizeof(Block) * _blockCapacity);
 1578
 1579                // 初始化新 Block
 301580                for (int i = _blockCapacity; i < newCapacity; i++)
 1581                {
 121582                    newBlocks[i].PackedHandles = null;
 121583                    newBlocks[i].PackedData = null;
 1584                }
 1585
 31586                _blocks = newBlocks;
 31587                _blockCapacity = newCapacity;
 1588            }
 1589
 1590            // 分配新 Block
 6281591            while (_blockCount < requiredBlock)
 1592            {
 3141593                int blockIndex = _blockCount++;
 3141594                _blocks[blockIndex].PackedHandles = (EntityRef*)_allocator->Alloc(sizeof(EntityRef) * _blockItemCapacity
 3141595                _blocks[blockIndex].PackedData = (T*)_allocator->Alloc(sizeof(T) * _blockItemCapacity);
 1596
 1597                // 初始化第一个元素(索引0保留为无效)
 3141598                if (blockIndex == 0)
 1599                {
 2901600                    _blocks[0].PackedHandles[0] = EntityRef.None;
 2901601                    _blocks[0].PackedData[0] = default;
 1602                }
 1603            }
 3141604        }
 1605
 1606        private const byte EntryStateEmpty = 0;
 1607        private const byte EntryStateActive = 1;
 1608        private const byte EntryStatePendingRemoval = 2;
 1609        private const ushort PendingQueueIndexNone = ushort.MaxValue;
 1610
 1611        #endregion
 1612    }
 1613}

Methods/Properties

get_IsAllocated()
get_Count()
get_IsEmpty()
get_Version()
get_BlockCount()
get_BlockItemCapacity()
get_ComponentTypeId()
get_Flags()
get_IsSingleton()
get_IsDeferredRemoval()
get_PendingRemovalCount()
get_UsedCount()
get_HasEntryStateTracking()
get_HasPendingQueueTracking()
get_SingletonEntity()
Initialize(System.Int32,System.Int32,System.Int32)
Initialize(System.Int32,Lattice.ECS.Core.StorageFlags,System.Int32,System.Int32)
Initialize(System.Int32,Lattice.ECS.Core.Allocator*,System.Int32,System.Int32)
Initialize(System.Int32,Lattice.ECS.Core.Allocator*,Lattice.ECS.Core.StorageFlags,System.Int32,System.Int32)
Dispose()
GetSnapshotSize()
WriteSnapshot(System.Byte*,System.Int32)
ReadSnapshot(System.Byte*,System.Int32)
Reset()
CopyFrom(Lattice.ECS.Core.Storage`1<T>*)
EnsureEntityCapacity(System.Int32)
Add(Lattice.Core.EntityRef,T&)
Remove(Lattice.Core.EntityRef)
RemoveImmediate(System.Int32,System.UInt16)
CommitRemovals(System.Span`1<Lattice.Core.EntityRef>)
MarkForRemoval(Lattice.Core.EntityRef)
CancelPendingRemoval(Lattice.Core.EntityRef)
CommitRemoval(Lattice.Core.EntityRef)
GetSingletonPointer()
GetSingleton()
Get(Lattice.Core.EntityRef)
GetPointer(Lattice.Core.EntityRef)
GetPointerAssumePresent(Lattice.Core.EntityRef)
TryGet(Lattice.Core.EntityRef,T&)
Has(Lattice.Core.EntityRef)
IsPendingRemoval(Lattice.Core.EntityRef)
GetPendingQueueIndex(Lattice.Core.EntityRef)
SetPendingQueueIndex(Lattice.Core.EntityRef,System.Int32)
GetBlockData(System.Int32)
GetBlockEntityRefs(System.Int32)
GetBlockItemCount(System.Int32)
GetEntityRefByIndex(System.Int32)
GetDataPointerByIndex(System.Int32)
GetDenseEntryByLinearIndex(System.Int32,Lattice.Core.EntityRef&,T*&)
IsDenseEntryActive(System.Int32)
CopyDenseEntities(Lattice.Core.EntityRef[])
WriteDenseEntities(Lattice.ECS.Core.FrameStateWriter)
CopyDenseComponentBytes(System.Byte[])
WriteDenseComponentBytes(Lattice.ECS.Core.FrameStateWriter)
RestoreDenseSnapshot(Lattice.Core.EntityRef[],System.Byte[])
RestoreDenseSnapshot(System.ReadOnlySpan`1<System.Byte>,System.ReadOnlySpan`1<System.Byte>)
GetEntityRefByGlobalIndex(System.Int32)
ResolveBlockCapacity(System.Int32)
GetSparseIndex(Lattice.Core.EntityRef)
CopyDenseEntities(Lattice.Core.EntityRef*,System.Int32)
CopyDenseComponentBytes(System.Byte*,System.Int32)
RestoreDenseEntities(Lattice.Core.EntityRef*,System.Int32)
RestoreDenseComponentBytes(System.Byte*,System.Int32)
GetDenseBlockCopyCount(System.Int32,System.Int32)
CopyDenseEntitiesFrom(Lattice.ECS.Core.Storage`1<T>*,System.Int32)
CopyDenseComponentBytesFrom(Lattice.ECS.Core.Storage`1<T>*,System.Int32)
ClearSparseAndStates()
RestoreDenseSnapshot(Lattice.Core.EntityRef*,System.Byte*,System.Int32)
GetEntryStateByIndex(System.Int32)
SetEntryStateByIndex(System.Int32,System.Byte)
GetPendingQueueIndexByIndex(System.Int32)
SetPendingQueueIndexByIndex(System.Int32,System.Int32)
RoundDownToPowerOfTwo(System.Int32)
EnsureBlockSpace()