< Summary

Information
Class: Lattice.ECS.Core.ComponentBlockIterator<T>
Assembly: Lattice
File(s): /home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Core/ComponentBlockIterator.cs
Line coverage
43%
Covered lines: 25
Uncovered lines: 33
Coverable lines: 58
Total lines: 351
Line coverage: 43.1%
Branch coverage
50%
Covered branches: 7
Total branches: 14
Branch coverage: 50%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
.ctor(...)100%210%
Reset()100%210%
NextBlock(...)0%4260%
Next(...)87.5%8888.88%
ValidateVersion()100%11100%

File(s)

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

#LineLine coverage
 1// Copyright (c) 2026 Sideline Authors. All rights reserved.
 2// Licensed under GPL-3.0.
 3
 4// 本文件使用 unsafe 指针和块式遍历来实现高性能 ECS 组件迭代。
 5// 所有版本校验仅在 DEBUG 模式下启用,用于在开发期尽早发现边迭代边修改的问题。
 6
 7using System;
 8using System.Runtime.CompilerServices;
 9using Lattice.Core;
 10
 11namespace Lattice.ECS.Core
 12{
 13    /// <summary>
 14    /// 组件块迭代器。
 15    /// 通过按块批量返回实体引用与组件指针,尽量提升缓存命中率并降低循环中的分支与函数调用开销。
 16    /// </summary>
 17    public unsafe struct ComponentBlockIterator<T> where T : unmanaged, IComponent
 18    {
 19        private readonly Storage<T>* _storage;
 20        private readonly int _version;
 21        private readonly int _blockCapacity;
 22
 23        private int _currentBlock;
 24        private int _currentOffset;
 25        private int _remaining;
 26        private int _startGlobalIndex;
 27
 28        /// <summary>
 29        /// 创建一个覆盖整个存储区的迭代器实例。
 30        /// </summary>
 31        internal ComponentBlockIterator(Storage<T>* storage)
 32        {
 10233            _storage = storage;
 10234            _version = storage->Version;
 10235            _blockCapacity = storage->BlockItemCapacity;
 10236            _currentBlock = 0;
 10237            _currentOffset = 1; // 跳过索引 0,保持与实体无效值约定一致。
 10238            _remaining = storage->Count;
 10239            _startGlobalIndex = 1;
 10240        }
 41
 42        /// <summary>
 43        /// 创建一个带偏移量与数量限制的范围迭代器。
 44        /// 该构造用于分页式扫描或仅遍历某一段连续组件数据。
 45        /// </summary>
 46        internal ComponentBlockIterator(Storage<T>* storage, int offset, int count)
 47        {
 048            _storage = storage;
 049            _version = storage->Version;
 050            _blockCapacity = storage->BlockItemCapacity;
 051            _startGlobalIndex = offset + 1;
 52
 53            // 把输入范围收敛到当前存储真实有效范围内,避免越界。
 054            int clampedOffset = System.Math.Min(_startGlobalIndex, storage->Count);
 055            int clampedCount = System.Math.Max(0, System.Math.Min(count, storage->Count - clampedOffset));
 56
 057            _currentBlock = clampedOffset / _blockCapacity;
 058            _currentOffset = clampedOffset % _blockCapacity;
 059            _remaining = clampedCount;
 060        }
 61
 62        /// <summary>
 63        /// 重置迭代器到起始位置,重新遍历当前存储中的所有有效数据。
 64        /// </summary>
 65        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 66        public void Reset()
 67        {
 068            ValidateVersion();
 069            _currentBlock = 0;
 070            _currentOffset = 1;
 071            _remaining = _storage->Count;
 072        }
 73
 74        /// <summary>
 75        /// 获取下一个连续数据块。
 76        /// 调用方可直接对返回的指针区间做顺序遍历或 SIMD 批处理。
 77        /// </summary>
 78        /// <param name="entities">当前块内实体引用数组的起始指针。</param>
 79        /// <param name="components">当前块内组件数组的起始指针。</param>
 80        /// <param name="count">当前块中可用元素数量。</param>
 81        /// <returns>若成功取得下一块数据则返回 <c>true</c>。</returns>
 82        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 83        public bool NextBlock(out EntityRef* entities, out T* components, out int count)
 84        {
 085            ValidateVersion();
 86
 087            while (_currentBlock < _storage->BlockCount && _remaining > 0)
 88            {
 089                int itemsInBlock = _blockCapacity - _currentOffset;
 090                if (itemsInBlock > 0)
 91                {
 092                    count = System.Math.Min(_remaining, itemsInBlock);
 093                    entities = _storage->GetBlockEntityRefs(_currentBlock) + _currentOffset;
 094                    components = _storage->GetBlockData(_currentBlock) + _currentOffset;
 95
 096                    _remaining -= count;
 097                    _currentOffset += count;
 098                    return true;
 99                }
 100
 0101                _currentBlock++;
 0102                _currentOffset = 0;
 103            }
 104
 0105            entities = default;
 0106            components = default;
 0107            count = 0;
 0108            return false;
 109        }
 110
 111        /// <summary>
 112        /// 逐个返回下一个实体与组件指针。
 113        /// 适合单体逻辑较复杂、不适合整块批处理的调用场景。
 114        /// </summary>
 115        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 116        public bool Next(out EntityRef entity, out T* component)
 117        {
 100104118            ValidateVersion();
 119
 100104120            if (_remaining > 0)
 121            {
 122                // 当前块已消耗完时,切到下一个块的起始位置。
 100002123                if (_currentOffset >= _blockCapacity)
 124                {
 700125                    _currentBlock++;
 700126                    _currentOffset = 0;
 127                }
 128
 100002129                while (_currentBlock < _storage->BlockCount)
 130                {
 100002131                    int blockItems = _storage->GetBlockItemCount(_currentBlock);
 100002132                    if (_currentOffset < blockItems)
 133                    {
 100002134                        entity = _storage->GetBlockEntityRefs(_currentBlock)[_currentOffset];
 100002135                        component = &_storage->GetBlockData(_currentBlock)[_currentOffset];
 100002136                        _currentOffset++;
 100002137                        _remaining--;
 100002138                        return true;
 139                    }
 140
 0141                    _currentBlock++;
 0142                    _currentOffset = 0;
 143                }
 144            }
 145
 102146            entity = EntityRef.None;
 102147            component = null;
 102148            return false;
 149        }
 150
 151        /// <summary>
 152        /// 在 DEBUG 模式下校验存储版本,防止遍历过程中对容器做结构性修改。
 153        /// </summary>
 154        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 155        private void ValidateVersion()
 156        {
 157#if DEBUG
 158            if (_storage->Version != _version)
 159            {
 160                throw new InvalidOperationException(
 161                    $"Cannot modify Storage<{typeof(T).Name}> while iterating over it. " +
 162                    "Use a command buffer or defer modifications.");
 163            }
 164#endif
 100104165        }
 166    }
 167
 168    /// <summary>
 169    /// 仅遍历 active 条目的组件迭代器。
 170    /// 相比通用块迭代器,它会跳过延迟删除中的条目,适合 Query 等查询热路径。
 171    /// </summary>
 172    public unsafe struct ActiveComponentIterator<T> where T : unmanaged, IComponent
 173    {
 174        private readonly Storage<T>* _storage;
 175        private readonly int _version;
 176        private readonly int _blockCapacity;
 177        private int _currentBlock;
 178        private int _currentOffset;
 179        private int _remainingActive;
 180
 181        internal ActiveComponentIterator(Storage<T>* storage)
 182        {
 183            _storage = storage;
 184            _version = storage->Version;
 185            _blockCapacity = storage->BlockItemCapacity;
 186            _currentBlock = 0;
 187            _currentOffset = 1;
 188            _remainingActive = storage->UsedCount;
 189        }
 190
 191        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 192        public bool Next(out EntityRef entity, out T* component)
 193        {
 194            ValidateVersion();
 195
 196            while (_remainingActive > 0 && _currentBlock < _storage->BlockCount)
 197            {
 198                if (_currentOffset >= _blockCapacity)
 199                {
 200                    _currentBlock++;
 201                    _currentOffset = 0;
 202                    continue;
 203                }
 204
 205                int blockItems = _storage->GetBlockItemCount(_currentBlock);
 206                while (_currentOffset < blockItems)
 207                {
 208                    int globalIndex = (_currentBlock * _blockCapacity) + _currentOffset;
 209                    EntityRef currentEntity = _storage->GetBlockEntityRefs(_currentBlock)[_currentOffset];
 210                    T* currentComponent = &_storage->GetBlockData(_currentBlock)[_currentOffset];
 211                    _currentOffset++;
 212
 213                    if (!_storage->IsDenseEntryActive(globalIndex))
 214                    {
 215                        continue;
 216                    }
 217
 218                    _remainingActive--;
 219                    entity = currentEntity;
 220                    component = currentComponent;
 221                    return true;
 222                }
 223
 224                _currentBlock++;
 225                _currentOffset = 0;
 226            }
 227
 228            entity = EntityRef.None;
 229            component = null;
 230            return false;
 231        }
 232
 233        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 234        private void ValidateVersion()
 235        {
 236#if DEBUG
 237            if (_storage->Version != _version)
 238            {
 239                throw new InvalidOperationException(
 240                    $"Cannot modify Storage<{typeof(T).Name}> while iterating over it. " +
 241                    "Use a command buffer or defer modifications.");
 242            }
 243#endif
 244        }
 245    }
 246
 247    /// <summary>
 248    /// 带预取优化的块迭代器。
 249    /// 在遍历当前块时尝试提前把后续块拉入缓存,以降低大批量顺序遍历的等待成本。
 250    /// </summary>
 251    public unsafe struct PrefetchedBlockIterator<T> where T : unmanaged, IComponent
 252    {
 253        private readonly Storage<T>* _storage;
 254        private readonly int _version;
 255        private readonly int _blockCapacity;
 256        private readonly int _prefetchDistance;
 257
 258        private int _currentBlock;
 259        private int _currentOffset;
 260        private int _remaining;
 261
 262        /// <summary>
 263        /// 创建带预取能力的块迭代器。
 264        /// <paramref name="prefetchDistance" /> 表示提前预取多少个后续块。
 265        /// </summary>
 266        public PrefetchedBlockIterator(Storage<T>* storage, int prefetchDistance = 2)
 267        {
 268            _storage = storage;
 269            _version = storage->Version;
 270            _blockCapacity = storage->BlockItemCapacity;
 271            _prefetchDistance = prefetchDistance;
 272            _currentBlock = 0;
 273            _currentOffset = 1;
 274            _remaining = storage->Count;
 275
 276            // 在首次开始遍历前先预取一小段后续块。
 277            PrefetchUpcoming();
 278        }
 279
 280        /// <summary>
 281        /// 获取下一块数据,并在成功返回后继续预取更靠后的块。
 282        /// </summary>
 283        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 284        public bool NextBlock(out EntityRef* entities, out T* components, out int count)
 285        {
 286            ValidateVersion();
 287
 288            while (_currentBlock < _storage->BlockCount && _remaining > 0)
 289            {
 290                int itemsInBlock = _blockCapacity - _currentOffset;
 291                if (itemsInBlock > 0)
 292                {
 293                    count = System.Math.Min(_remaining, itemsInBlock);
 294                    entities = _storage->GetBlockEntityRefs(_currentBlock) + _currentOffset;
 295                    components = _storage->GetBlockData(_currentBlock) + _currentOffset;
 296
 297                    _remaining -= count;
 298                    _currentOffset += count;
 299
 300                    // 当前块返回后,立刻尝试预取后续块。
 301                    PrefetchUpcoming();
 302
 303                    return true;
 304                }
 305
 306                _currentBlock++;
 307                _currentOffset = 0;
 308            }
 309
 310            entities = default;
 311            components = default;
 312            count = 0;
 313            return false;
 314        }
 315
 316        /// <summary>
 317        /// 预取后续若干块的实体引用与组件数据。
 318        /// 该优化仅在顺序遍历、大容量存储场景下才更容易带来收益。
 319        /// </summary>
 320        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 321        private void PrefetchUpcoming()
 322        {
 323            for (int i = 1; i <= _prefetchDistance; i++)
 324            {
 325                int prefetchBlock = _currentBlock + i;
 326                if (prefetchBlock >= _storage->BlockCount)
 327                {
 328                    break;
 329                }
 330
 331                SIMDUtils.PrefetchL2(_storage->GetBlockEntityRefs(prefetchBlock));
 332                SIMDUtils.PrefetchL2(_storage->GetBlockData(prefetchBlock));
 333            }
 334        }
 335
 336        /// <summary>
 337        /// 在 DEBUG 模式下校验预取迭代器绑定的存储版本。
 338        /// </summary>
 339        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 340        private void ValidateVersion()
 341        {
 342#if DEBUG
 343            if (_storage->Version != _version)
 344            {
 345                throw new InvalidOperationException(
 346                    $"Cannot modify Storage<{typeof(T).Name}> while iterating over it.");
 347            }
 348#endif
 349        }
 350    }
 351}