< Summary

Information
Class: Lattice.ECS.Session.SimulationSession<T>
Assembly: Lattice
File(s): /home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Session/SimulationSession.cs
Line coverage
89%
Covered lines: 136
Uncovered lines: 16
Coverable lines: 152
Total lines: 351
Line coverage: 89.4%
Branch coverage
63%
Covered branches: 38
Total branches: 60
Branch coverage: 63.3%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)50%6682.35%
get_Scheduler()100%210%
get_Commands()100%11100%
get_VerifiedFrame()100%11100%
get_PredictedFrame()100%11100%
get_VerifiedTick()50%22100%
get_PredictedTick()0%620%
get_IsRunning()100%11100%
Add(...)100%11100%
AddRange(...)0%620%
Start(...)75%4490%
SetPredictedInput(...)100%11100%
SetVerifiedInput(...)100%11100%
AdvanceVerifiedTo(...)75%4490%
AdvancePredictedTo(...)75%4492.3%
CalculateVerifiedChecksum()100%11100%
CalculatePredictedChecksum()100%11100%
Dispose()91.66%121294.11%
CreateFrame(...)100%11100%
SimulateNext(...)50%22100%
PrepareCommandBuffer(...)100%11100%
DisposeCommandBuffer()100%11100%
ResolveVerifiedInput(...)50%2266.66%
ResolveBestInput(...)50%5460%
EnsureRunning()50%7666.66%
ThrowIfDisposed()100%11100%
ReplaceVerifiedFrame(...)50%22100%
ReplacePredictedFrame(...)50%22100%
.ctor(...)100%22100%
Set(...)100%11100%
TryGet(...)100%22100%
GetSlot(...)50%22100%

File(s)

/home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Session/SimulationSession.cs

#LineLine coverage
 1// Copyright (c) 2026 Sideline Authors. All rights reserved.
 2// Licensed under GPL-3.0.
 3
 4using System;
 5using Lattice.ECS.Core;
 6using Lattice.ECS.Framework;
 7using Lattice.Math;
 8
 9namespace Lattice.ECS.Session
 10{
 11    /// <summary>
 12    /// 将输入写入帧状态的最小入口。
 13    /// </summary>
 14    public delegate void SimulationInputApplier<TInput>(Frame frame, TInput input) where TInput : unmanaged;
 15
 16    /// <summary>
 17    /// 最小确定性模拟会话。
 18    /// </summary>
 19    public sealed class SimulationSession<TInput> : IDisposable where TInput : unmanaged
 20    {
 21        private readonly SimulationSessionOptions _options;
 22        private readonly SimulationInputApplier<TInput>? _applyInput;
 23        private readonly TickBuffer _predictedInputs;
 24        private readonly TickBuffer _verifiedInputs;
 425        private readonly SystemScheduler _scheduler = new();
 26        private bool _disposed;
 27        private Frame? _verifiedFrame;
 28        private Frame? _predictedFrame;
 29
 430        public SimulationSession(
 431            SimulationSessionOptions options,
 432            SimulationInputApplier<TInput>? applyInput = null)
 33        {
 434            ArgumentNullException.ThrowIfNull(options);
 35
 436            if (options.MaxEntities <= 0)
 37            {
 038                throw new ArgumentOutOfRangeException(nameof(options.MaxEntities));
 39            }
 40
 441            if (options.InputCapacity <= 0)
 42            {
 043                throw new ArgumentOutOfRangeException(nameof(options.InputCapacity));
 44            }
 45
 446            if (options.CommandBufferCapacity <= 0)
 47            {
 048                throw new ArgumentOutOfRangeException(nameof(options.CommandBufferCapacity));
 49            }
 50
 451            _options = options;
 452            _applyInput = applyInput;
 453            _predictedInputs = new TickBuffer(options.InputCapacity);
 454            _verifiedInputs = new TickBuffer(options.InputCapacity);
 455            Commands = new SimulationCommandBufferHost();
 456        }
 57
 58        /// <summary>当前系统调度器。</summary>
 059        public SystemScheduler Scheduler => _scheduler;
 60
 61        /// <summary>当前 tick 命令缓冲宿主。</summary>
 10862        public SimulationCommandBufferHost Commands { get; }
 63
 64        /// <summary>当前权威帧。</summary>
 265        public Frame? VerifiedFrame => _verifiedFrame;
 66
 67        /// <summary>当前预测帧。</summary>
 368        public Frame? PredictedFrame => _predictedFrame;
 69
 70        /// <summary>当前权威 tick。</summary>
 971        public int VerifiedTick => _verifiedFrame?.Tick ?? _options.InitialTick;
 72
 73        /// <summary>当前预测 tick。</summary>
 074        public int PredictedTick => _predictedFrame?.Tick ?? _options.InitialTick;
 75
 76        /// <summary>会话是否已启动。</summary>
 2977        public bool IsRunning { get; private set; }
 78
 79        public void Add(ISystem system)
 80        {
 481            _scheduler.Add(system);
 482        }
 83
 84        public void AddRange(ReadOnlySpan<ISystem> systems)
 85        {
 086            for (int i = 0; i < systems.Length; i++)
 87            {
 088                _scheduler.Add(systems[i]);
 89            }
 090        }
 91
 92        public void Start(Action<Frame>? bootstrap = null)
 93        {
 494            ThrowIfDisposed();
 95
 496            if (IsRunning)
 97            {
 098                throw new InvalidOperationException("SimulationSession 已启动。");
 99            }
 100
 4101            Frame verified = CreateFrame(_options.InitialTick);
 4102            bootstrap?.Invoke(verified);
 103
 4104            _scheduler.Initialize(verified);
 105
 4106            _verifiedFrame = verified;
 4107            _predictedFrame = verified.Clone();
 4108            IsRunning = true;
 4109        }
 110
 111        public void SetPredictedInput(int tick, in TInput input)
 112        {
 9113            ThrowIfDisposed();
 9114            _predictedInputs.Set(tick, input);
 9115        }
 116
 117        public void SetVerifiedInput(int tick, in TInput input)
 118        {
 10119            ThrowIfDisposed();
 10120            _verifiedInputs.Set(tick, input);
 10121        }
 122
 123        public void AdvanceVerifiedTo(int targetTick)
 124        {
 4125            ThrowIfDisposed();
 4126            EnsureRunning();
 127
 4128            if (targetTick < VerifiedTick)
 129            {
 0130                throw new InvalidOperationException("目标 verified tick 不能回退。");
 131            }
 132
 14133            while (_verifiedFrame!.Tick < targetTick)
 134            {
 10135                int nextTick = _verifiedFrame.Tick + 1;
 10136                TInput input = ResolveVerifiedInput(nextTick);
 10137                Frame next = SimulateNext(_verifiedFrame, nextTick, input);
 10138                ReplaceVerifiedFrame(next);
 139            }
 4140        }
 141
 142        public void AdvancePredictedTo(int targetTick)
 143        {
 5144            ThrowIfDisposed();
 5145            EnsureRunning();
 146
 5147            if (targetTick < VerifiedTick)
 148            {
 0149                targetTick = VerifiedTick;
 150            }
 151
 5152            Frame current = _verifiedFrame!.Clone();
 15153            while (current.Tick < targetTick)
 154            {
 10155                int nextTick = current.Tick + 1;
 10156                TInput input = ResolveBestInput(nextTick);
 10157                Frame next = SimulateNext(current, nextTick, input);
 10158                current.Dispose();
 10159                current = next;
 160            }
 161
 5162            ReplacePredictedFrame(current);
 5163        }
 164
 165        public ulong CalculateVerifiedChecksum()
 166        {
 2167            ThrowIfDisposed();
 2168            EnsureRunning();
 2169            return _verifiedFrame!.CalculateChecksum();
 170        }
 171
 172        public ulong CalculatePredictedChecksum()
 173        {
 2174            ThrowIfDisposed();
 2175            EnsureRunning();
 2176            return _predictedFrame!.CalculateChecksum();
 177        }
 178
 179        public void Dispose()
 180        {
 4181            if (_disposed)
 182            {
 0183                return;
 184            }
 185
 186            try
 187            {
 4188                if (IsRunning && _verifiedFrame != null)
 189                {
 4190                    _scheduler.Shutdown(_verifiedFrame);
 191                }
 4192            }
 193            finally
 194            {
 4195                DisposeCommandBuffer();
 196
 4197                Frame? verified = _verifiedFrame;
 4198                Frame? predicted = _predictedFrame;
 199
 4200                _verifiedFrame = null;
 4201                _predictedFrame = null;
 4202                IsRunning = false;
 203
 4204                verified?.Dispose();
 4205                if (!ReferenceEquals(predicted, verified))
 206                {
 4207                    predicted?.Dispose();
 208                }
 209
 4210                _disposed = true;
 4211            }
 4212        }
 213
 214        private Frame CreateFrame(int tick)
 215        {
 4216            return new Frame(_options.MaxEntities)
 4217            {
 4218                Tick = tick,
 4219                DeltaTime = _options.DeltaTime
 4220            };
 221        }
 222
 223        private Frame SimulateNext(Frame currentFrame, int nextTick, TInput input)
 224        {
 20225            Frame next = currentFrame.Clone();
 20226            next.Tick = nextTick;
 20227            next.DeltaTime = _options.DeltaTime;
 228
 20229            PrepareCommandBuffer(next);
 230            try
 231            {
 20232                _applyInput?.Invoke(next, input);
 20233                _scheduler.Update(next, _options.DeltaTime);
 20234                Commands.Buffer.Playback(next);
 20235            }
 236            finally
 237            {
 20238                Commands.Buffer.Dispose();
 20239            }
 240
 20241            return next;
 242        }
 243
 244        private void PrepareCommandBuffer(Frame frame)
 245        {
 20246            DisposeCommandBuffer();
 20247            Commands.Buffer.Initialize(frame, _options.CommandBufferCapacity);
 20248        }
 249
 250        private void DisposeCommandBuffer()
 251        {
 24252            Commands.Buffer.Dispose();
 24253            Commands.Buffer = default;
 24254        }
 255
 256        private TInput ResolveVerifiedInput(int tick)
 257        {
 10258            if (_verifiedInputs.TryGet(tick, out TInput input))
 259            {
 10260                return input;
 261            }
 262
 0263            throw new InvalidOperationException($"缺少 tick={tick} 的 verified 输入。");
 264        }
 265
 266        private TInput ResolveBestInput(int tick)
 267        {
 10268            if (_verifiedInputs.TryGet(tick, out TInput verified))
 269            {
 0270                return verified;
 271            }
 272
 10273            if (_predictedInputs.TryGet(tick, out TInput predicted))
 274            {
 10275                return predicted;
 276            }
 277
 0278            return default;
 279        }
 280
 281        private void EnsureRunning()
 282        {
 13283            if (!IsRunning || _verifiedFrame == null || _predictedFrame == null)
 284            {
 0285                throw new InvalidOperationException("SimulationSession 尚未启动。");
 286            }
 13287        }
 288
 289        private void ThrowIfDisposed()
 290        {
 36291            ObjectDisposedException.ThrowIf(_disposed, this);
 36292        }
 293
 294        private void ReplaceVerifiedFrame(Frame next)
 295        {
 10296            Frame? previous = _verifiedFrame;
 10297            _verifiedFrame = next;
 10298            previous?.Dispose();
 10299        }
 300
 301        private void ReplacePredictedFrame(Frame next)
 302        {
 5303            Frame? previous = _predictedFrame;
 5304            _predictedFrame = next;
 5305            previous?.Dispose();
 5306        }
 307
 308        private sealed class TickBuffer
 309        {
 310            private readonly int[] _ticks;
 311            private readonly TInput[] _values;
 312
 8313            public TickBuffer(int capacity)
 314            {
 8315                _ticks = new int[capacity];
 8316                _values = new TInput[capacity];
 317
 528318                for (int i = 0; i < _ticks.Length; i++)
 319                {
 256320                    _ticks[i] = int.MinValue;
 321                }
 8322            }
 323
 324            public void Set(int tick, TInput value)
 325            {
 19326                int index = GetSlot(tick);
 19327                _ticks[index] = tick;
 19328                _values[index] = value;
 19329            }
 330
 331            public bool TryGet(int tick, out TInput value)
 332            {
 30333                int index = GetSlot(tick);
 30334                if (_ticks[index] == tick)
 335                {
 20336                    value = _values[index];
 20337                    return true;
 338                }
 339
 10340                value = default;
 10341                return false;
 342            }
 343
 344            private int GetSlot(int tick)
 345            {
 49346                int index = tick % _ticks.Length;
 49347                return index < 0 ? index + _ticks.Length : index;
 348            }
 349        }
 350    }
 351}