< Summary

Information
Class: Lattice.ECS.Core.FullOwningGroup<T1, T2, T3>
Assembly: Lattice
File(s): /home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Core/FullOwningGroup.cs
Line coverage
65%
Covered lines: 64
Uncovered lines: 33
Coverable lines: 97
Total lines: 604
Line coverage: 65.9%
Branch coverage
65%
Covered branches: 13
Total branches: 20
Branch coverage: 65%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
get_Count()100%11100%
Initialize(...)100%11100%
Add(...)75%44100%
NextBlock(...)0%620%
Next(...)100%22100%
GetAtLinearIndex(...)50%2264.28%
RemoveAtLinearIndex(...)75%10868.18%
EnsureBlockSpace()50%2257.14%

File(s)

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

#LineLine coverage
 1// Copyright (c) 2026 Sideline Authors. All rights reserved.
 2// Licensed under GPL-3.0.
 3
 4// 条件编译:只在支持 .NET 5+ 的平台上启用高级特性
 5#if NET5_0_OR_GREATER
 6#define MODERN_NET
 7#endif
 8
 9using System;
 10using System.Runtime.CompilerServices;
 11using Lattice.Core;
 12
 13// 注意:此文件使用 unsafe 代码进行高性能内存操作
 14// 所有指针操作都经过边界检查(DEBUG 模式下)
 15
 16namespace Lattice.ECS.Core
 17{
 18    /// <summary>
 19    /// Full-Owning Group - 终极性能的多组件存储
 20    ///
 21    /// ============================================================
 22    /// 为什么需要 Full-Owning Group?
 23    /// ============================================================
 24    ///
 25    /// 问题:传统 Storage 的多组件遍历性能瓶颈
 26    /// -------------------------------------------------------------
 27    /// 假设你需要更新 Position 和 Velocity:
 28    ///
 29    /// 传统方式(Filter{T1, T2}):
 30    ///   1. 遍历 Position Storage(缓存命中)
 31    ///   2. 对每个实体查找 Velocity(稀疏查找,缓存未命中)
 32    ///   3. 总内存访问:Position Block + Velocity Block(两个不连续区域)
 33    ///
 34    /// Full-Owning Group 方式:
 35    ///   1. 直接遍历 Group(Position 和 Velocity 在同一缓存行)
 36    ///   2. 总内存访问:一个连续的内存区域
 37    ///
 38    /// 性能对比(理论):
 39    ///   - 传统方式:~20-30 CPU 周期/实体(两次缓存加载)
 40    ///   - Full-Owning:~5-10 CPU 周期/实体(一次缓存加载,预取友好)
 41    ///
 42    /// ============================================================
 43    /// 架构设计决策
 44    /// ============================================================
 45    ///
 46    /// Q: 为什么选择 AOS(Array of Structures)而不是 SOA?
 47    /// A:
 48    ///   1. 缓存局部性极致:一起访问的组件在同一缓存行
 49    ///   2. 预取友好:硬件预取器可以预测下一个 Group 项
 50    ///   3. 更少的指针追踪:不需要通过 EntityRef 查找多个 Storage
 51    ///   4. 与 ECS 原则的妥协:牺牲内存效率换取迭代性能
 52    ///
 53    /// Q: 为什么固定 Block 容量为 128?
 54    /// A:
 55    ///   1. 与 Storage 保持一致,便于互操作(如从 Storage 迁移到 Group)
 56    ///   2. 128 * sizeof(T1+T2) 填满 L1 缓存(假设 T1=16, T2=16,128*32=4096 字节 ≈ L1 容量)
 57    ///   3. SIMD 友好:AVX2 可以一次处理 4 个 Group 项
 58    ///
 59    /// Q: 为什么不支持动态添加/删除?
 60    /// A:
 61    ///   1. 简化内存管理:连续的内存块,无需处理空洞
 62    ///   2. 适合批量创建/销毁的场景(如粒子系统、子弹)
 63    ///   3. 如果需要频繁增删,使用传统 Storage + Filter
 64    ///
 65    /// Q: 与 FrameSync 的区别?
 66    /// A:
 67    ///   1. FrameSync 没有 Full-Owning Group,只有 ComponentDataBuffer
 68    ///   2. FrameSync 的 Filter 每次都要做稀疏查找(_sparse[entity.Index])
 69    ///   3. 这是 Lattice 独有的性能优化特性
 70    ///
 71    /// ============================================================
 72    /// 使用场景
 73    /// ============================================================
 74    ///
 75    /// ✅ 适合使用:
 76    /// - 物理系统(Position + Velocity + Mass)
 77    /// - 移动系统(Transform + Velocity + Rotation)
 78    /// - 粒子系统(Position + Velocity + Lifetime + Color)
 79    /// - 任何"每帧一起更新"的组件组合
 80    ///
 81    /// ❌ 不适合使用:
 82    /// - 随机访问频繁的组件(用 Storage&lt;T&gt;)
 83    /// - 生命周期差异大的组件(用 Storage&lt;T&gt; + 延迟删除)
 84    /// - 需要复杂查询的组件(用 Filter)
 85    ///
 86    /// ============================================================
 87    /// 内存布局
 88    /// ============================================================
 89    ///
 90    /// FullOwningGroup&lt;T1, T2&gt;(AOS - Array of Structures):
 91    ///
 92    /// 我们使用 SOA within Group(组内 SOA)以获得更好的 SIMD 支持:
 93    ///
 94    /// Block 0:
 95    /// ┌─────────────┬─────────────┬─────────────┐
 96    /// │ T1[0]       │ T1[1]       │ ... T1[127] │  ← 连续的 T1 数组(SIMD 友好)
 97    /// ├─────────────┼─────────────┼─────────────┤
 98    /// │ T2[0]       │ T2[1]       │ ... T2[127] │  ← 连续的 T2 数组(SIMD 友好)
 99    /// ├─────────────┼─────────────┼─────────────┤
 100    /// │ Entity[0]   │ Entity[1]   │ ... Entity  │  ← 实体引用
 101    /// └─────────────┴─────────────┴─────────────┘
 102    ///
 103    /// 对比纯 AOS:
 104    /// ┌─────────────────────────────────────────┐
 105    /// │ T1[0] | T2[0] | Entity[0]               │  ← 混合存储,SIMD 不友好
 106    /// │ T1[1] | T2[1] | Entity[1]               │
 107    /// └─────────────────────────────────────────┘
 108    ///
 109    /// 我们的布局兼顾:
 110    /// - AOS 的缓存局部性(一起访问的组件接近)
 111    /// - SOA 的 SIMD 友好性(同类型数据连续)
 112    ///
 113    /// 迭代时的缓存行为:
 114    /// - 访问 T1[i] 时,T2[i] 很可能在同一缓存行(64 字节)
 115    /// - 预取器可以预测 T1[i+1], T2[i+1] 的访问模式
 116    /// </summary>
 117    public unsafe struct FullOwningGroup<T1, T2>
 118        where T1 : unmanaged, IComponent
 119        where T2 : unmanaged, IComponent
 120    {
 121        #region 常量
 122
 123        public const int BlockCapacity = 128;  // 与 Storage 一致,方便互操作
 124
 125        #endregion
 126
 127        #region Block 结构
 128
 129        /// <summary>
 130        /// AOS 布局的数据块
 131        /// 内存布局:[T1_0, T2_0, T1_1, T2_1, ...] 或 [T1_0..T1_127, T2_0..T2_127]
 132        /// 选择后者(SOA 组内)以获得更好的 SIMD 支持
 133        /// </summary>
 134        public struct Block
 135        {
 136            /// <summary>T1 组件数组</summary>
 137            public T1* Data1;
 138            /// <summary>T2 组件数组</summary>
 139            public T2* Data2;
 140            /// <summary>实体引用数组</summary>
 141            public EntityRef* Entities;
 142            /// <summary>有效项数(0-128)</summary>
 143            public int Count;
 144        }
 145
 146        #endregion
 147
 148        #region 字段
 149
 150        private Block* _blocks;
 151        private int _blockCount;
 152        private int _blockCapacity;
 153        private int _count;
 154        private int _version;
 155
 156        private Allocator* _allocator;
 157
 158        #endregion
 159
 160        #region 属性
 161
 162        public int Count => _count;
 163        public int BlockCount => _blockCount;
 164        public int Version => _version;
 165
 166        #endregion
 167
 168        #region 生命周期
 169
 170        public void Initialize(Allocator* allocator)
 171        {
 172            _allocator = allocator;
 173            _blockCapacity = 4;
 174            _blockCount = 0;
 175            _count = 0;
 176            _version = 0;
 177
 178            _blocks = (Block*)allocator->Alloc(sizeof(Block) * _blockCapacity);
 179            for (int i = 0; i < _blockCapacity; i++)
 180            {
 181                _blocks[i].Data1 = null;
 182                _blocks[i].Data2 = null;
 183                _blocks[i].Entities = null;
 184                _blocks[i].Count = 0;
 185            }
 186        }
 187
 188        public void Dispose()
 189        {
 190            _blocks = null;
 191            _blockCount = 0;
 192            _count = 0;
 193        }
 194
 195        #endregion
 196
 197        #region 添加/删除
 198
 199        /// <summary>
 200        /// 添加实体和组件对 - O(1) 均摊
 201        /// </summary>
 202        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 203        public void Add(EntityRef entity, in T1 c1, in T2 c2)
 204        {
 205            // 确保有空间
 206            if (_blockCount == 0 || _blocks[_blockCount - 1].Count >= BlockCapacity)
 207            {
 208                EnsureBlockSpace();
 209            }
 210
 211            Block* block = &_blocks[_blockCount - 1];
 212            int index = block->Count++;
 213
 214            block->Entities[index] = entity;
 215            block->Data1[index] = c1;
 216            block->Data2[index] = c2;
 217
 218            _count++;
 219            _version++;
 220        }
 221
 222        /// <summary>
 223        /// 通过实体查找并删除 - O(N),不推荐频繁使用
 224        /// </summary>
 225        public void Remove(EntityRef entity)
 226        {
 227            // 找到实体
 228            for (int b = 0; b < _blockCount; b++)
 229            {
 230                Block* block = &_blocks[b];
 231                for (int i = 0; i < block->Count; i++)
 232                {
 233                    if (block->Entities[i] == entity)
 234                    {
 235                        RemoveAt(b, i);
 236                        return;
 237                    }
 238                }
 239            }
 240        }
 241
 242        /// <summary>
 243        /// 通过索引删除(高性能版本)
 244        /// </summary>
 245        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 246        public void RemoveAt(int blockIndex, int indexInBlock)
 247        {
 248            RemoveAtLinearIndex((blockIndex * BlockCapacity) + indexInBlock, out _);
 249        }
 250
 251        #endregion
 252
 253        #region 迭代器(终极性能)
 254
 255        /// <summary>
 256        /// Block 迭代器 - 批量访问
 257        /// </summary>
 258        public bool NextBlock(int* blockIndex, out EntityRef* entities, out T1* data1, out T2* data2, out int count)
 259        {
 260            if (*blockIndex >= _blockCount)
 261            {
 262                entities = null;
 263                data1 = null;
 264                data2 = null;
 265                count = 0;
 266                return false;
 267            }
 268
 269            Block* block = &_blocks[*blockIndex];
 270            entities = block->Entities;
 271            data1 = block->Data1;
 272            data2 = block->Data2;
 273            count = block->Count;
 274
 275            (*blockIndex)++;
 276            return true;
 277        }
 278
 279        /// <summary>
 280        /// 逐个迭代(保持接口一致)
 281        /// </summary>
 282        public bool Next(int* globalIndex, out EntityRef entity, out T1* c1, out T2* c2)
 283        {
 284            if (*globalIndex >= _count)
 285            {
 286                entity = EntityRef.None;
 287                c1 = null;
 288                c2 = null;
 289                return false;
 290            }
 291
 292            int blockIdx = *globalIndex / BlockCapacity;
 293            int itemIdx = *globalIndex % BlockCapacity;
 294
 295            Block* block = &_blocks[blockIdx];
 296            entity = block->Entities[itemIdx];
 297            c1 = &block->Data1[itemIdx];
 298            c2 = &block->Data2[itemIdx];
 299
 300            (*globalIndex)++;
 301            return true;
 302        }
 303
 304        /// <summary>
 305        /// 按 0 基 dense 索引直接访问组内条目。
 306        /// </summary>
 307        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 308        public bool GetAtLinearIndex(int linearIndex, out EntityRef entity, out T1* c1, out T2* c2)
 309        {
 310            if ((uint)linearIndex >= (uint)_count)
 311            {
 312                entity = EntityRef.None;
 313                c1 = null;
 314                c2 = null;
 315                return false;
 316            }
 317
 318            int blockIdx = linearIndex / BlockCapacity;
 319            int itemIdx = linearIndex % BlockCapacity;
 320
 321            Block* block = &_blocks[blockIdx];
 322            entity = block->Entities[itemIdx];
 323            c1 = &block->Data1[itemIdx];
 324            c2 = &block->Data2[itemIdx];
 325            return true;
 326        }
 327
 328        /// <summary>
 329        /// 按 0 基 dense 索引删除条目,并返回被交换到该位置的实体。
 330        /// </summary>
 331        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 332        public bool RemoveAtLinearIndex(int linearIndex, out EntityRef movedEntity)
 333        {
 334            if ((uint)linearIndex >= (uint)_count)
 335            {
 336                movedEntity = EntityRef.None;
 337                return false;
 338            }
 339
 340            int lastLinearIndex = _count - 1;
 341            int targetBlockIndex = linearIndex / BlockCapacity;
 342            int targetItemIndex = linearIndex % BlockCapacity;
 343            int lastBlockIndex = lastLinearIndex / BlockCapacity;
 344            int lastItemIndex = lastLinearIndex % BlockCapacity;
 345
 346            Block* targetBlock = &_blocks[targetBlockIndex];
 347            Block* lastBlock = &_blocks[lastBlockIndex];
 348
 349            movedEntity = EntityRef.None;
 350            if (linearIndex != lastLinearIndex)
 351            {
 352                movedEntity = lastBlock->Entities[lastItemIndex];
 353                targetBlock->Entities[targetItemIndex] = movedEntity;
 354                targetBlock->Data1[targetItemIndex] = lastBlock->Data1[lastItemIndex];
 355                targetBlock->Data2[targetItemIndex] = lastBlock->Data2[lastItemIndex];
 356            }
 357
 358            lastBlock->Count--;
 359            _count--;
 360
 361            if (_blockCount > 0 && _blocks[_blockCount - 1].Count == 0)
 362            {
 363                _blockCount--;
 364            }
 365
 366            _version++;
 367            return true;
 368        }
 369
 370        #endregion
 371
 372        #region 内部辅助
 373
 374        private void EnsureBlockSpace()
 375        {
 376            if (_blockCount >= _blockCapacity)
 377            {
 378                int newCapacity = _blockCapacity * 2;
 379                var newBlocks = (Block*)_allocator->Alloc(sizeof(Block) * newCapacity);
 380
 381                Buffer.MemoryCopy(_blocks, newBlocks,
 382                    sizeof(Block) * newCapacity, sizeof(Block) * _blockCapacity);
 383
 384                // 初始化新 block
 385                for (int i = _blockCapacity; i < newCapacity; i++)
 386                {
 387                    newBlocks[i].Data1 = null;
 388                    newBlocks[i].Data2 = null;
 389                    newBlocks[i].Entities = null;
 390                    newBlocks[i].Count = 0;
 391                }
 392
 393                _blocks = newBlocks;
 394                _blockCapacity = newCapacity;
 395            }
 396
 397            // 分配新 block
 398            Block* newBlock = &_blocks[_blockCount++];
 399            newBlock->Data1 = (T1*)_allocator->Alloc(sizeof(T1) * BlockCapacity);
 400            newBlock->Data2 = (T2*)_allocator->Alloc(sizeof(T2) * BlockCapacity);
 401            newBlock->Entities = (EntityRef*)_allocator->Alloc(sizeof(EntityRef) * BlockCapacity);
 402            newBlock->Count = 0;
 403        }
 404
 405        #endregion
 406    }
 407
 408    /// <summary>
 409    /// 三组件 Full-Owning Group
 410    /// </summary>
 411    public unsafe struct FullOwningGroup<T1, T2, T3>
 412        where T1 : unmanaged, IComponent
 413        where T2 : unmanaged, IComponent
 414        where T3 : unmanaged, IComponent
 415    {
 416        public struct Block
 417        {
 418            public T1* Data1;
 419            public T2* Data2;
 420            public T3* Data3;
 421            public EntityRef* Entities;
 422            public int Count;
 423        }
 424
 425        private Block* _blocks;
 426        private int _blockCount;
 427        private int _blockCapacity;
 428        private int _count;
 429
 430        private Allocator* _allocator;
 431
 5432        public int Count => _count;
 433
 434        public void Initialize(Allocator* allocator)
 435        {
 1436            _allocator = allocator;
 1437            _blockCapacity = 4;
 1438            _blockCount = 0;
 1439            _count = 0;
 440
 1441            _blocks = (Block*)allocator->Alloc(sizeof(Block) * _blockCapacity);
 1442        }
 443
 444        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 445        public void Add(EntityRef entity, in T1 c1, in T2 c2, in T3 c3)
 446        {
 1447            if (_blockCount == 0 || _blocks[_blockCount - 1].Count >= FullOwningGroup<T1, T2>.BlockCapacity)
 448            {
 1449                EnsureBlockSpace();
 450            }
 451
 1452            Block* block = &_blocks[_blockCount - 1];
 1453            int index = block->Count++;
 454
 1455            block->Entities[index] = entity;
 1456            block->Data1[index] = c1;
 1457            block->Data2[index] = c2;
 1458            block->Data3[index] = c3;
 459
 1460            _count++;
 1461        }
 462
 463        /// <summary>
 464        /// Block 迭代器 - 批量访问。
 465        /// </summary>
 466        public bool NextBlock(int* blockIndex, out EntityRef* entities, out T1* data1, out T2* data2, out T3* data3, out
 467        {
 0468            if (*blockIndex >= _blockCount)
 469            {
 0470                entities = null;
 0471                data1 = null;
 0472                data2 = null;
 0473                data3 = null;
 0474                count = 0;
 0475                return false;
 476            }
 477
 0478            Block* block = &_blocks[*blockIndex];
 0479            entities = block->Entities;
 0480            data1 = block->Data1;
 0481            data2 = block->Data2;
 0482            data3 = block->Data3;
 0483            count = block->Count;
 484
 0485            (*blockIndex)++;
 0486            return true;
 487        }
 488
 489        /// <summary>
 490        /// 逐个迭代。
 491        /// </summary>
 492        public bool Next(int* globalIndex, out EntityRef entity, out T1* c1, out T2* c2, out T3* c3)
 493        {
 4494            if (*globalIndex >= _count)
 495            {
 2496                entity = EntityRef.None;
 2497                c1 = null;
 2498                c2 = null;
 2499                c3 = null;
 2500                return false;
 501            }
 502
 2503            int blockIdx = *globalIndex / FullOwningGroup<T1, T2>.BlockCapacity;
 2504            int itemIdx = *globalIndex % FullOwningGroup<T1, T2>.BlockCapacity;
 505
 2506            Block* block = &_blocks[blockIdx];
 2507            entity = block->Entities[itemIdx];
 2508            c1 = &block->Data1[itemIdx];
 2509            c2 = &block->Data2[itemIdx];
 2510            c3 = &block->Data3[itemIdx];
 511
 2512            (*globalIndex)++;
 2513            return true;
 514        }
 515
 516        /// <summary>
 517        /// 按 0 基 dense 索引直接访问组内条目。
 518        /// </summary>
 519        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 520        public bool GetAtLinearIndex(int linearIndex, out EntityRef entity, out T1* c1, out T2* c2, out T3* c3)
 521        {
 1522            if ((uint)linearIndex >= (uint)_count)
 523            {
 0524                entity = EntityRef.None;
 0525                c1 = null;
 0526                c2 = null;
 0527                c3 = null;
 0528                return false;
 529            }
 530
 1531            int blockIdx = linearIndex / FullOwningGroup<T1, T2>.BlockCapacity;
 1532            int itemIdx = linearIndex % FullOwningGroup<T1, T2>.BlockCapacity;
 533
 1534            Block* block = &_blocks[blockIdx];
 1535            entity = block->Entities[itemIdx];
 1536            c1 = &block->Data1[itemIdx];
 1537            c2 = &block->Data2[itemIdx];
 1538            c3 = &block->Data3[itemIdx];
 1539            return true;
 540        }
 541
 542        /// <summary>
 543        /// 按 0 基 dense 索引删除条目,并返回被交换到该位置的实体。
 544        /// </summary>
 545        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 546        public bool RemoveAtLinearIndex(int linearIndex, out EntityRef movedEntity)
 547        {
 1548            if ((uint)linearIndex >= (uint)_count)
 549            {
 0550                movedEntity = EntityRef.None;
 0551                return false;
 552            }
 553
 1554            int lastLinearIndex = _count - 1;
 1555            int targetBlockIndex = linearIndex / FullOwningGroup<T1, T2>.BlockCapacity;
 1556            int targetItemIndex = linearIndex % FullOwningGroup<T1, T2>.BlockCapacity;
 1557            int lastBlockIndex = lastLinearIndex / FullOwningGroup<T1, T2>.BlockCapacity;
 1558            int lastItemIndex = lastLinearIndex % FullOwningGroup<T1, T2>.BlockCapacity;
 559
 1560            Block* targetBlock = &_blocks[targetBlockIndex];
 1561            Block* lastBlock = &_blocks[lastBlockIndex];
 562
 1563            movedEntity = EntityRef.None;
 1564            if (linearIndex != lastLinearIndex)
 565            {
 0566                movedEntity = lastBlock->Entities[lastItemIndex];
 0567                targetBlock->Entities[targetItemIndex] = movedEntity;
 0568                targetBlock->Data1[targetItemIndex] = lastBlock->Data1[lastItemIndex];
 0569                targetBlock->Data2[targetItemIndex] = lastBlock->Data2[lastItemIndex];
 0570                targetBlock->Data3[targetItemIndex] = lastBlock->Data3[lastItemIndex];
 571            }
 572
 1573            lastBlock->Count--;
 1574            _count--;
 575
 1576            if (_blockCount > 0 && _blocks[_blockCount - 1].Count == 0)
 577            {
 1578                _blockCount--;
 579            }
 580
 1581            return true;
 582        }
 583
 584        private void EnsureBlockSpace()
 585        {
 1586            if (_blockCount >= _blockCapacity)
 587            {
 0588                int newCapacity = _blockCapacity * 2;
 0589                var newBlocks = (Block*)_allocator->Alloc(sizeof(Block) * newCapacity);
 0590                Buffer.MemoryCopy(_blocks, newBlocks,
 0591                    sizeof(Block) * newCapacity, sizeof(Block) * _blockCapacity);
 0592                _blocks = newBlocks;
 0593                _blockCapacity = newCapacity;
 594            }
 595
 1596            Block* newBlock = &_blocks[_blockCount++];
 1597            newBlock->Data1 = (T1*)_allocator->Alloc(sizeof(T1) * FullOwningGroup<T1, T2>.BlockCapacity);
 1598            newBlock->Data2 = (T2*)_allocator->Alloc(sizeof(T2) * FullOwningGroup<T1, T2>.BlockCapacity);
 1599            newBlock->Data3 = (T3*)_allocator->Alloc(sizeof(T3) * FullOwningGroup<T1, T2>.BlockCapacity);
 1600            newBlock->Entities = (EntityRef*)_allocator->Alloc(sizeof(EntityRef) * FullOwningGroup<T1, T2>.BlockCapacity
 1601            newBlock->Count = 0;
 1602        }
 603    }
 604}