< Summary

Information
Class: Lattice.ECS.Session.SessionRuntime
Assembly: Lattice
File(s): /home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Session/Session.cs
Line coverage
95%
Covered lines: 344
Uncovered lines: 16
Coverable lines: 360
Total lines: 940
Line coverage: 95.5%
Branch coverage
85%
Covered branches: 97
Total branches: 114
Branch coverage: 85%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
get_RuntimeOptions()100%11100%
get_Context()100%11100%
get_DataBoundary()100%11100%
get_TickPipeline()100%11100%
get_InputBoundary()100%11100%
get_RuntimeKind()100%11100%
get_DeltaTime()100%11100%
get_LocalPlayerId()100%11100%
get_CurrentTick()100%11100%
get_CurrentTickStage()100%11100%
get_VerifiedFrame()100%11100%
get_PredictedFrame()100%11100%
get_PreviousFrame()100%11100%
get_IsRollingBack()100%11100%
get_IsRunning()100%11100%
.ctor(...)50%22100%
.ctor(...)100%11100%
Start()50%22100%
Stop()100%44100%
Update()50%2290%
RegisterSystem(...)100%22100%
UnregisterSystem(...)100%22100%
UpdateSystems(...)100%11100%
CleanupFrame(...)100%11100%
CaptureHistory(...)100%11100%
SetPlayerInput(...)100%11100%
GetPlayerInput(...)100%11100%
CollectInputSet(...)100%11100%
ApplyInputSet(...)100%11100%
ApplyInputs(...)100%11100%
ExecuteTickPipeline(...)100%11100%
EnterTickStage(...)100%11100%
VerifyFrame(...)58.33%121288.88%
RollbackTo(...)80%101091.66%
Resimulate(...)100%22100%
GetHistoricalFrame(...)87.5%8890%
UpdateHistory(...)100%11100%
Rewind(...)100%22100%
CreateCheckpoint()100%11100%
RestoreFromCheckpoint(...)100%44100%
CreateFrame(...)100%11100%
AdvanceFrame(...)100%11100%
ApplyCorrectedInput(...)100%210%
ValidateInputIdentity(...)100%44100%
ResetFrameState(...)100%1010100%
Dispose()50%2287.5%
EnsureRunning(...)100%22100%
EnsureFrameState(...)100%44100%
EnsureCapability(...)100%22100%
ThrowIfDisposed()100%22100%
BindContextRunnerName(...)100%11100%
SetVerifiedFrame(...)100%11100%
SetPredictedFrame(...)100%11100%
SetPreviousFrame(...)100%11100%
DisposeFrameIfDetached(...)100%1010100%
TryMaterializeHistoricalFrame(...)81.81%272278.94%
CopyFrameState(...)100%11100%
RestoreFrame(...)100%11100%
ReplayHistoricalTicksInPlace(...)100%22100%
InvalidateHistoricalMaterializeCache()100%11100%
CanReplayHistoricalFramesInPlace()50%22100%

File(s)

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

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Reflection;
 4using System.Runtime.CompilerServices;
 5using Lattice.ECS.Core;
 6using Lattice.ECS.Framework;
 7using Lattice.Math;
 8
 9namespace Lattice.ECS.Session
 10{
 11    /// <summary>
 12    /// 共享 Session 运行时内核。
 13    /// 该类型承载固定帧推进、系统驱动、输入缓冲、历史帧、检查点与回滚相关的通用机制,
 14    /// 具体运行模式通过派生类决定,不直接假定自己就是唯一的正式 Session 形态。
 15    /// </summary>
 16    public abstract class SessionRuntime : IDisposable
 17    {
 118        private static readonly SessionRuntimeDataBoundary DefaultDataBoundary = new(
 119            SessionInputStorageKind.PlayerTickFixedWindow,
 120            SessionHistoryStorageKind.BoundedLiveFramesWithSampledSnapshots,
 121            SessionCheckpointStorageKind.PackedSnapshot,
 122            SessionRuntimeDataCapability.PlayerTickInputLookup |
 123            SessionRuntimeDataCapability.BoundedInputRetention |
 124            SessionRuntimeDataCapability.TickAddressableHistory |
 125            SessionRuntimeDataCapability.SampledHistoryMaterialization |
 126            SessionRuntimeDataCapability.ExplicitCheckpointRestore |
 127            SessionRuntimeDataCapability.PackedCheckpointStorage,
 128            UnsupportedSessionRuntimeDataCapability.ConfigurableInputRetention |
 129            UnsupportedSessionRuntimeDataCapability.ConfigurableHistoryRetention |
 130            UnsupportedSessionRuntimeDataCapability.ConfigurableSnapshotSampling |
 131            UnsupportedSessionRuntimeDataCapability.PluggableHistoryStore |
 132            UnsupportedSessionRuntimeDataCapability.AlternativeCheckpointFormats |
 133            UnsupportedSessionRuntimeDataCapability.UnboundedPerTickRetention);
 34
 135        private static readonly SessionTickPipelineBoundary DefaultTickPipeline = new(
 136            SessionTickPipelineKind.PhasedStructuralCommit,
 137            SessionTickPipelineCapability.ExplicitStageExposure |
 138            SessionTickPipelineCapability.DeferredStructuralChanges |
 139            SessionTickPipelineCapability.StructuralCommitStage |
 140            SessionTickPipelineCapability.CleanupAndHistoryStages |
 141            SessionTickPipelineCapability.ImmediateComponentMutationDuringSimulation,
 142            UnsupportedSessionTickPipelineCapability.ImmediateStructuralVisibilityDuringSimulation |
 143            UnsupportedSessionTickPipelineCapability.RuntimeReorderedStages |
 144            UnsupportedSessionTickPipelineCapability.PerSystemStructuralCommit);
 45
 146        private static readonly SessionRuntimeInputBoundary DefaultInputBoundary = new(
 147            SessionInputContractKind.TickScopedPlayerInputSet,
 148            SessionMissingInputPolicy.OmitMissingPlayers,
 149            SessionInputWritePolicy.LatestWriteWins,
 150            SessionInputOrder.PlayerIdAscending,
 151            SessionRuntimeInputCapability.TickScopedInputAggregation |
 152            SessionRuntimeInputCapability.SparsePlayerInput |
 153            SessionRuntimeInputCapability.StablePlayerOrdering |
 154            SessionRuntimeInputCapability.LatestWriteWins |
 155            SessionRuntimeInputCapability.TransportDecoupledInputModel,
 156            UnsupportedSessionRuntimeInputCapability.ImplicitPreviousInputCarryForward |
 157            UnsupportedSessionRuntimeInputCapability.BuiltInDefaultInputSynthesis |
 158            UnsupportedSessionRuntimeInputCapability.ConfigurableInputAggregation |
 159            UnsupportedSessionRuntimeInputCapability.ConfigurableMissingInputPolicy |
 160            UnsupportedSessionRuntimeInputCapability.BuiltInTransportSerialization);
 61
 62        #region 字段
 63
 64        /// <summary>运行时配置。</summary>
 865        public SessionRuntimeOptions RuntimeOptions { get; }
 66
 67        /// <summary>
 68        /// 当前运行时上下文。
 69        /// 用于承载运行期共享对象与稳定公开的运行元信息。
 70        /// </summary>
 20871        public SessionRuntimeContext Context { get; }
 72
 73        /// <summary>
 74        /// 当前 Session 的正式运行边界描述。
 75        /// 用于明确当前主干承诺的能力面,而不是把 Session 误读为完整联机会话产品层。
 76        /// </summary>
 77        public abstract SessionRuntimeBoundary RuntimeBoundary { get; }
 78
 79        /// <summary>
 80        /// 当前运行时的输入 / 历史 / checkpoint 数据策略边界。
 81        /// 用于明确哪些是稳定公开契约,哪些 sizing 仍属于内部实现。
 82        /// </summary>
 3283        public virtual SessionRuntimeDataBoundary DataBoundary => DefaultDataBoundary;
 84
 85        /// <summary>
 86        /// 当前运行时的 Tick 管线边界。
 87        /// 用于明确 Tick 阶段与结构性修改的正式语义,而不是继续依赖系统注册顺序和调用约定。
 88        /// </summary>
 189        public virtual SessionTickPipelineBoundary TickPipeline => DefaultTickPipeline;
 90
 91        /// <summary>
 92        /// 当前运行时的正式输入契约边界。
 93        /// 用于明确输入按什么模型聚合、缺失输入如何处理、重复写入如何收敛,以及输入模型是否与传输序列化解耦。
 94        /// </summary>
 3395        public virtual SessionRuntimeInputBoundary InputBoundary => DefaultInputBoundary;
 96
 97        /// <summary>
 98        /// 当前运行时类型。
 99        /// </summary>
 7100        public SessionRuntimeKind RuntimeKind => RuntimeBoundary.RuntimeKind;
 101
 102        /// <summary>固定时间步长</summary>
 103        public FP DeltaTime
 104        {
 1352105            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1352106            get;
 107        }
 108
 109        /// <summary>本地玩家 ID</summary>
 1348110        public int LocalPlayerId { get; protected set; }
 111
 112        /// <summary>当前帧号(Verified 帧号)</summary>
 1077113        public int CurrentTick { get; protected set; }
 114
 115        /// <summary>
 116        /// 当前 Tick 正在执行的阶段。
 117        /// 正常空闲态为 `Idle`;运行中的单步推进、回滚重模拟与历史 materialize 都会复用同一套阶段语义。
 118        /// </summary>
 3965119        public SessionTickStage CurrentTickStage { get; private set; }
 120
 121        /// <summary>最新验证帧(服务器确认)</summary>
 2594122        public Frame? VerifiedFrame { get; protected set; }
 123
 124        /// <summary>预测帧(本地模拟)</summary>
 6628125        public Frame? PredictedFrame { get; protected set; }
 126
 127        /// <summary>上一帧(用于插值)</summary>
 3332128        public Frame? PreviousFrame { get; protected set; }
 129
 130        /// <summary>SessionRuntime 内部历史帧与帧池管理。</summary>
 131        private readonly SessionFrameHistory _frameHistory;
 132
 133        private readonly bool _canReplayHistoricalFramesInPlace;
 134
 135        /// <summary>是否正在回滚中</summary>
 214136        public bool IsRollingBack { get; protected set; }
 137
 138        /// <summary>是否已启动</summary>
 1103139        public bool IsRunning { get; protected set; }
 140
 141        /// <summary>系统调度器</summary>
 113142        protected readonly SystemScheduler _systemScheduler = new();
 143
 144        /// <summary>SessionRuntime 内部输入保留与聚合管理。</summary>
 145        private readonly SessionInputStore _inputStore;
 146
 147        /// <summary>SessionRuntime 内部 Tick 管线执行器。</summary>
 113148        private readonly SessionTickProcessor _tickProcessor = new();
 149
 150        private bool _disposed;
 151
 152        #endregion
 153
 154        #region 事件
 155
 156        /// <summary>帧更新事件</summary>
 157        public event Action<Frame, FP>? OnFrameUpdate;
 158
 159        /// <summary>发生回滚事件</summary>
 160        public event Action<int, int>? OnRollback;  // fromTick, toTick
 161
 162        /// <summary>帧验证事件</summary>
 163        public event Action<int, bool>? OnFrameVerified;  // tick, success
 164
 165        #endregion
 166
 167        #region 构造函数
 168
 169        protected SessionRuntime(FP deltaTime, int localPlayerId = 0)
 87170            : this(new SessionRuntimeOptions(deltaTime, localPlayerId))
 171        {
 87172        }
 173
 113174        protected SessionRuntime(SessionRuntimeOptions runtimeOptions)
 175        {
 113176            RuntimeOptions = runtimeOptions ?? throw new ArgumentNullException(nameof(runtimeOptions));
 113177            DeltaTime = runtimeOptions.DeltaTime;
 113178            LocalPlayerId = runtimeOptions.LocalPlayerId;
 113179            Context = new SessionRuntimeContext(this, GetType().Name);
 113180            _frameHistory = new SessionFrameHistory();
 113181            _inputStore = new SessionInputStore(SessionRuntimeDataDefaults.HistorySize);
 113182            _canReplayHistoricalFramesInPlace = CanReplayHistoricalFramesInPlace();
 183
 113184            CurrentTick = 0;
 113185            CurrentTickStage = SessionTickStage.Idle;
 113186        }
 187
 188        #endregion
 189
 190        #region 生命周期
 191
 192        /// <summary>
 193        /// 启动会话。
 194        /// 该方法是幂等的;若会话已在运行,则直接返回。
 195        /// </summary>
 196        public virtual void Start()
 197        {
 67198            ThrowIfDisposed();
 199
 66200            if (IsRunning) return;
 201
 66202            ResetFrameState(disposeFrames: true);
 203
 204            // 先在权威初始帧上做系统初始化,再克隆出预测帧,避免回滚基线缺失初始化状态
 66205            SetVerifiedFrame(CreateFrame(0));
 66206            _systemScheduler.Initialize(VerifiedFrame!);
 66207            SetPredictedFrame(VerifiedFrame!.CloneState());
 66208            SetPreviousFrame(null);
 66209            CurrentTick = 0;
 66210            CurrentTickStage = SessionTickStage.Idle;
 211
 66212            UpdateHistory(VerifiedFrame!);
 213
 66214            IsRunning = true;
 66215        }
 216
 217        /// <summary>
 218        /// 停止会话。
 219        /// 该方法是幂等的;若会话未运行,则直接返回。
 220        /// </summary>
 221        public virtual void Stop()
 222        {
 129223            ThrowIfDisposed();
 224
 190225            if (!IsRunning) return;
 226
 227            // 销毁系统
 66228            if (PredictedFrame != null)
 229            {
 64230                _systemScheduler.Shutdown(PredictedFrame);
 231            }
 232
 66233            IsRunning = false;
 66234            CurrentTickStage = SessionTickStage.Idle;
 66235        }
 236
 237        /// <summary>
 238        /// 单步更新(FixedUpdate)。
 239        /// 这是当前最小本地推进入口:基于已知输入推进 `PredictedFrame`,并写入历史。
 240        /// 只能在会话运行期间调用。
 241        /// </summary>
 242        public virtual void Update()
 243        {
 522244            ThrowIfDisposed();
 521245            EnsureCapability(SessionRuntimeCapability.LocalPredictionStep, nameof(Update));
 521246            EnsureRunning(nameof(Update));
 247
 517248            if (PredictedFrame == null)
 249            {
 0250                throw new InvalidOperationException("PredictedFrame is not available while session is running.");
 251            }
 252
 253            // 保存上一帧
 517254            SetPreviousFrame(PredictedFrame);
 255
 256            // 创建新帧或复用
 517257            SetPredictedFrame(AdvanceFrame(PredictedFrame!));
 517258            CurrentTick = PredictedFrame.Tick;
 259
 517260            ExecuteTickPipeline(PredictedFrame!, raiseFrameUpdateEvent: true, captureHistory: true);
 517261        }
 262
 263        #endregion
 264
 265        #region 系统管理
 266
 267        /// <summary>
 268        /// 注册系统。
 269        /// 运行中的会话不允许动态修改系统集合,避免 Verified / Predicted / History 之间出现不一致。
 270        /// </summary>
 271        public void RegisterSystem(ISystem system)
 272        {
 98273            ThrowIfDisposed();
 97274            ArgumentNullException.ThrowIfNull(system);
 275
 97276            if (IsRunning)
 277            {
 1278                throw new InvalidOperationException("Cannot register systems while session is running. Stop the session 
 279            }
 280
 96281            _systemScheduler.Add(system);
 96282        }
 283
 284        /// <summary>
 285        /// 注销系统。
 286        /// 运行中的会话不允许动态修改系统集合,避免 Verified / Predicted / History 之间出现不一致。
 287        /// </summary>
 288        public void UnregisterSystem(ISystem system)
 289        {
 3290            ThrowIfDisposed();
 2291            ArgumentNullException.ThrowIfNull(system);
 292
 2293            if (IsRunning)
 294            {
 1295                throw new InvalidOperationException("Cannot unregister systems while session is running. Stop the sessio
 296            }
 297
 1298            _systemScheduler.Remove(system);
 1299        }
 300
 301        /// <summary>
 302        /// 执行系统更新
 303        /// </summary>
 304        protected virtual void UpdateSystems(Frame frame, FP deltaTime)
 305        {
 625306            _systemScheduler.Update(frame, deltaTime);
 625307        }
 308
 309        /// <summary>
 310        /// Tick 末尾清理阶段。
 311        /// 当前默认只保留显式阶段语义,不额外引入新的运行逻辑。
 312        /// </summary>
 313        protected virtual void CleanupFrame(Frame frame)
 314        {
 624315        }
 316
 317        /// <summary>
 318        /// Tick 历史写入阶段。
 319        /// 默认把当前帧写入运行时历史;保留显式 hook 仅用于测试与后续边界扩展。
 320        /// </summary>
 321        protected virtual void CaptureHistory(Frame frame)
 322        {
 586323            UpdateHistory(frame);
 586324        }
 325
 326        #endregion
 327
 328        #region 输入管理
 329
 330        /// <summary>
 331        /// 设置玩家输入。
 332        /// 稳定公开契约是按 `(playerId, tick)` 读写输入;
 333        /// 具体窗口大小、ring buffer sizing 与淘汰细节仍属于内部策略,可通过 `DataBoundary` 了解当前承诺的能力边界。
 334        /// </summary>
 335        public virtual void SetPlayerInput(int playerId, int tick, IPlayerInput input)
 336        {
 334337            ThrowIfDisposed();
 333338            ArgumentNullException.ThrowIfNull(input);
 332339            ValidateInputIdentity(playerId, tick, input);
 340
 330341            _inputStore.SetPlayerInput(playerId, tick, input);
 330342        }
 343
 344        /// <summary>
 345        /// 获取玩家输入。
 346        /// 若请求 tick 已超出当前内部保留窗口,则返回 `null`;窗口大小本身不属于稳定公开 API。
 347        /// </summary>
 348        public IPlayerInput? GetPlayerInput(int playerId, int tick)
 349        {
 3350            ThrowIfDisposed();
 2351            return _inputStore.GetPlayerInput(playerId, tick);
 352        }
 353
 354        /// <summary>
 355        /// 为指定 tick 聚合输入集合。
 356        /// 当前正式语义为:
 357        /// - 只聚合实际写入的玩家输入
 358        /// - 缺失玩家不会自动生成默认输入
 359        /// - 遍历顺序按玩家 ID 升序稳定排列
 360        /// </summary>
 361        protected virtual SessionInputSet CollectInputSet(int tick)
 362        {
 625363            return _inputStore.CollectInputSet(tick);
 364        }
 365
 366        /// <summary>
 367        /// 将聚合后的输入集合应用到当前帧。
 368        /// 这是当前正式推荐的输入扩展点,新玩法 Session 默认应优先重写该方法,而不是直接操作底层输入缓冲。
 369        /// </summary>
 370        protected virtual void ApplyInputSet(Frame frame, in SessionInputSet inputSet)
 371        {
 27372        }
 373
 374        /// <summary>
 375        /// 应用输入到帧。
 376        /// 默认实现会先构建正式 `SessionInputSet`,再调用 `ApplyInputSet(frame, inputSet)`。
 377        /// 保留该 hook 仅用于兼容现有派生类;新代码应优先重写 `ApplyInputSet(...)`。
 378        /// </summary>
 379        protected virtual void ApplyInputs(Frame frame)
 380        {
 625381            SessionInputSet inputSet = CollectInputSet(frame.Tick);
 625382            ApplyInputSet(frame, inputSet);
 625383        }
 384
 385        private void ExecuteTickPipeline(Frame frame, bool raiseFrameUpdateEvent, bool captureHistory)
 386        {
 625387            _tickProcessor.Execute(
 625388                frame,
 625389                DeltaTime,
 625390                EnterTickStage,
 625391                ApplyInputs,
 625392                UpdateSystems,
 625393                CleanupFrame,
 625394                CaptureHistory,
 625395                OnFrameUpdate,
 625396                raiseFrameUpdateEvent,
 625397                captureHistory);
 625398        }
 399
 400        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining
 401        private void EnterTickStage(SessionTickStage stage)
 402        {
 3711403            CurrentTickStage = stage;
 3711404        }
 405
 406        #endregion
 407
 408        #region 帧同步(验证/回滚)
 409
 410        /// <summary>
 411        /// 验证帧(服务器确认)。
 412        /// 该接口属于“预测/验证”语义:用于比较某个历史 Tick 的校验和,
 413        /// 不匹配时触发回滚与重模拟;它不是本地单机玩法推进所必需的入口。
 414        /// 只能在会话运行期间调用。
 415        /// </summary>
 416        public virtual void VerifyFrame(int tick, long expectedChecksum, byte[]? inputData = null)
 417        {
 32418            ThrowIfDisposed();
 31419            EnsureCapability(SessionRuntimeCapability.PredictionVerification, nameof(VerifyFrame));
 30420            EnsureRunning(nameof(VerifyFrame));
 26421            ArgumentOutOfRangeException.ThrowIfNegative(tick);
 422
 25423            if (tick > CurrentTick)
 424            {
 1425                throw new ArgumentOutOfRangeException(nameof(tick), "VerifyFrame only accepts historical or current tick
 426            }
 427
 428            // 获取对应历史帧
 24429            var frame = GetHistoricalFrame(tick);
 24430            if (frame == null)
 431            {
 432                // 帧已不在历史中,无法验证
 0433                OnFrameVerified?.Invoke(tick, false);
 0434                return;
 435            }
 436
 24437            long actualChecksum = (long)frame.CalculateChecksum();
 24438            bool success = actualChecksum == expectedChecksum;
 439
 24440            if (success)
 441            {
 442                // 验证通过
 19443                SetVerifiedFrame(frame.CloneState());
 19444                OnFrameVerified?.Invoke(tick, true);
 445            }
 446            else
 447            {
 448                // 校验和不匹配,需要回滚
 5449                OnFrameVerified?.Invoke(tick, false);
 5450                RollbackTo(tick, inputData);
 451            }
 5452        }
 453
 454        /// <summary>
 455        /// 回滚到指定帧。
 456        /// 该接口属于“预测修正”语义:它会把 `PredictedFrame` 回退到历史基线后再重模拟,
 457        /// 主要服务于校验失败后的状态修正,而不是普通本地 rewind 玩法。
 458        /// 只能在会话运行期间调用;该操作只回退帧状态,不重新初始化系统。
 459        /// </summary>
 460        public virtual void RollbackTo(int tick, byte[]? correctedInput = null)
 461        {
 18462            ThrowIfDisposed();
 17463            EnsureCapability(SessionRuntimeCapability.PredictionVerification, nameof(RollbackTo));
 16464            EnsureRunning(nameof(RollbackTo));
 12465            ArgumentOutOfRangeException.ThrowIfNegative(tick);
 466
 11467            if (tick > CurrentTick)
 468            {
 1469                throw new ArgumentOutOfRangeException(nameof(tick), "RollbackTo only accepts historical or current ticks
 470            }
 471
 10472            int targetTick = CurrentTick;
 10473            IsRollingBack = true;
 10474            OnRollback?.Invoke(CurrentTick, tick);
 475
 476            try
 477            {
 478                // 获取历史帧
 10479                var baseFrame = GetHistoricalFrame(tick);
 10480                if (baseFrame == null)
 481                {
 0482                    throw new InvalidOperationException($"Frame {tick} not found in history");
 483                }
 484
 485                // 克隆基础帧作为新的预测起点
 10486                SetPredictedFrame(baseFrame.CloneState());
 10487                SetPreviousFrame(null);
 10488                CurrentTick = tick;
 489
 490                // 如果有修正的输入,应用它
 10491                if (correctedInput != null)
 492                {
 0493                    ApplyCorrectedInput(PredictedFrame!, correctedInput);
 494                }
 495
 10496                UpdateHistory(PredictedFrame!);
 497
 498                // 重新模拟到回滚前的目标时间
 10499                if (targetTick > tick)
 500                {
 10501                    Resimulate(tick, targetTick);
 502                }
 10503            }
 504            finally
 505            {
 10506                IsRollingBack = false;
 10507            }
 10508        }
 509
 510        /// <summary>
 511        /// 重新模拟帧
 512        /// </summary>
 513        protected virtual void Resimulate(int fromTick, int toTick)
 514        {
 158515            for (int tick = fromTick; tick < toTick; tick++)
 516            {
 69517                SetPreviousFrame(PredictedFrame);
 69518                SetPredictedFrame(AdvanceFrame(PredictedFrame!));
 69519                CurrentTick = PredictedFrame!.Tick;
 69520                ExecuteTickPipeline(PredictedFrame!, raiseFrameUpdateEvent: false, captureHistory: true);
 521            }
 10522        }
 523
 524        #endregion
 525
 526        #region 历史帧管理
 527
 528        /// <summary>
 529        /// 获取历史帧。
 530        /// 返回结果可能来自 live history,也可能来自 sampled snapshot 的按需 materialize;
 531        /// 具体保留数量与采样间隔属于内部策略,不作为稳定公开 API 承诺。
 532        /// </summary>
 533        public Frame? GetHistoricalFrame(int tick)
 534        {
 96535            ThrowIfDisposed();
 536
 95537            if (_frameHistory.TryGetLiveFrame(tick, out Frame? frame))
 538            {
 65539                return frame;
 540            }
 541
 30542            if (_frameHistory.TryGetMaterializedFrame(tick, out Frame? cachedFrame))
 543            {
 5544                return cachedFrame;
 545            }
 546
 25547            if (_frameHistory.TryGetScratchFrame(tick, out Frame? scratchFrame))
 548            {
 0549                return scratchFrame;
 550            }
 551
 25552            if (TryMaterializeHistoricalFrame(tick, out Frame? materialized))
 553            {
 22554                return materialized;
 555            }
 556
 3557            return null;
 558        }
 559
 560        /// <summary>
 561        /// 更新历史中的帧
 562        /// </summary>
 563        protected void UpdateHistory(Frame frame)
 564        {
 688565            _frameHistory.UpdateHistory(frame, DisposeFrameIfDetached);
 688566        }
 567
 568        #endregion
 569
 570        #region 时光倒流(单机玩法)
 571
 572        /// <summary>
 573        /// 回退指定帧数(单机时光倒流)。
 574        /// 该接口更偏“本地玩法语义”:直接恢复历史帧,不做额外重模拟,
 575        /// 与 `RollbackTo()` 的预测修正语义不同。
 576        /// 只能在会话运行期间调用。
 577        /// </summary>
 578        public void Rewind(int frameCount)
 579        {
 8580            ThrowIfDisposed();
 7581            EnsureCapability(SessionRuntimeCapability.LocalRewind, nameof(Rewind));
 6582            EnsureRunning(nameof(Rewind));
 2583            ArgumentOutOfRangeException.ThrowIfNegative(frameCount);
 584
 1585            int targetTick = System.Math.Max(0, CurrentTick - frameCount);
 586
 587            // 直接获取历史帧,不重新模拟(与网络回滚不同)
 1588            var baseFrame = GetHistoricalFrame(targetTick);
 1589            if (baseFrame != null)
 590            {
 1591                SetPredictedFrame(baseFrame.CloneState());
 1592                SetPreviousFrame(null);
 1593                CurrentTick = targetTick;
 594            }
 1595        }
 596
 597        /// <summary>
 598        /// 创建检查点。
 599        /// 该接口更偏“本地工具/运行时管理”语义:保存当前 Verified / Predicted 帧状态,
 600        /// 便于显式恢复、热重载或外层玩法工具使用,不负责系统集合装配。
 601        /// 当前公开契约是“可保存并恢复运行态帧状态,并携带正式 checkpoint 协议 metadata”;
 602        /// 底层 packed payload 细节仍通过显式版本号治理,而不是默认承诺永远隐式兼容。
 603        /// 需要当前已经存在有效帧状态。
 604        /// </summary>
 605        public SessionCheckpoint CreateCheckpoint()
 606        {
 19607            ThrowIfDisposed();
 18608            EnsureCapability(SessionRuntimeCapability.CheckpointRestore, nameof(CreateCheckpoint));
 18609            EnsureFrameState(nameof(CreateCheckpoint));
 16610            return SessionCheckpointFactory.Capture(CurrentTick, VerifiedFrame, PredictedFrame, InputBoundary, DataBound
 611        }
 612
 613        /// <summary>
 614        /// 从检查点恢复。
 615        /// 该接口更偏“本地工具/运行时管理”语义:只恢复帧状态,
 616        /// 不重建系统集合,也不切换 Session 的运行模式。
 617        /// 该操作只恢复帧状态,不会重建系统集合,也不会重新初始化系统。
 618        /// 当前会先校验 checkpoint 协议、输入契约和组件 schema,再执行底层 snapshot restore。
 619        /// </summary>
 620        public void RestoreFromCheckpoint(SessionCheckpoint checkpoint)
 621        {
 17622            ThrowIfDisposed();
 16623            EnsureCapability(SessionRuntimeCapability.CheckpointRestore, nameof(RestoreFromCheckpoint));
 16624            ArgumentNullException.ThrowIfNull(checkpoint);
 625
 15626            ResetFrameState(disposeFrames: true);
 627
 15628            CurrentTick = checkpoint.Tick;
 15629            SessionCheckpointFrames restoredFrames = SessionCheckpointFactory.RestoreFrames(checkpoint, InputBoundary, D
 13630            SetVerifiedFrame(restoredFrames.VerifiedFrame);
 13631            SetPredictedFrame(restoredFrames.PredictedFrame);
 13632            SetPreviousFrame(null);
 633
 26634            if (VerifiedFrame != null) UpdateHistory(VerifiedFrame);
 26635            if (PredictedFrame != null) UpdateHistory(PredictedFrame);
 13636        }
 637
 638        #endregion
 639
 640        #region 辅助方法
 641
 642        /// <summary>
 643        /// 创建新帧
 644        /// </summary>
 645        protected virtual Frame CreateFrame(int tick)
 646        {
 66647            var frame = new Frame();
 66648            frame.Tick = tick;
 66649            frame.DeltaTime = DeltaTime;
 66650            return frame;
 651        }
 652
 653        /// <summary>
 654        /// 推进到下一帧
 655        /// </summary>
 656        protected virtual Frame AdvanceFrame(Frame currentFrame)
 657        {
 587658            Frame nextFrame = CopyFrameState(currentFrame);
 587659            nextFrame.Tick = currentFrame.Tick + 1;
 587660            nextFrame.DeltaTime = DeltaTime;
 587661            return nextFrame;
 662        }
 663
 664        /// <summary>
 665        /// 应用修正的输入
 666        /// </summary>
 667        protected virtual void ApplyCorrectedInput(Frame frame, byte[] inputData)
 668        {
 669            // 子类实现
 0670        }
 671
 672        private static void ValidateInputIdentity(int playerId, int tick, IPlayerInput input)
 673        {
 332674            if (input.PlayerId != playerId)
 675            {
 1676                throw new ArgumentException("Input PlayerId must match the playerId argument.", nameof(input));
 677            }
 678
 331679            if (input.Tick != tick)
 680            {
 1681                throw new ArgumentException("Input Tick must match the tick argument.", nameof(input));
 682            }
 330683        }
 684
 685        private void ResetFrameState(bool disposeFrames)
 686        {
 192687            if (disposeFrames)
 688            {
 192689                var frames = new HashSet<Frame>();
 690
 271691                if (VerifiedFrame != null) frames.Add(VerifiedFrame);
 271692                if (PredictedFrame != null) frames.Add(PredictedFrame);
 251693                if (PreviousFrame != null) frames.Add(PreviousFrame);
 192694                _frameHistory.CopyOwnedFramesTo(frames);
 695
 1154696                foreach (Frame frame in frames)
 697                {
 385698                    frame.Dispose();
 699                }
 700            }
 701
 192702            VerifiedFrame = null;
 192703            PredictedFrame = null;
 192704            PreviousFrame = null;
 192705            CurrentTick = 0;
 192706            IsRollingBack = false;
 192707            _frameHistory.Clear();
 192708        }
 709
 710        #endregion
 711
 712        #region IDisposable
 713
 714        public virtual void Dispose()
 715        {
 111716            if (_disposed)
 717            {
 0718                return;
 719            }
 720
 111721            Stop();
 111722            ResetFrameState(disposeFrames: true);
 111723            _inputStore.Clear();
 111724            Context.Dispose();
 111725            _disposed = true;
 111726        }
 727
 728        #endregion
 729
 730        private void EnsureRunning(string methodName)
 731        {
 573732            if (!IsRunning)
 733            {
 16734                throw new InvalidOperationException($"{methodName} requires the session to be running.");
 735            }
 557736        }
 737
 738        private void EnsureFrameState(string methodName)
 739        {
 18740            if (VerifiedFrame == null || PredictedFrame == null)
 741            {
 2742                throw new InvalidOperationException($"{methodName} requires the session to have initialized frame state.
 743            }
 16744        }
 745
 746        private void EnsureCapability(SessionRuntimeCapability capability, string methodName)
 747        {
 610748            if (!RuntimeBoundary.Supports(capability))
 749            {
 3750                throw new NotSupportedException(
 3751                    $"{GetType().Name} does not support {capability} required by {methodName}.");
 752            }
 607753        }
 754
 755        private void ThrowIfDisposed()
 756        {
 1346757            if (_disposed)
 758            {
 13759                throw new ObjectDisposedException(GetType().Name);
 760            }
 1333761        }
 762
 763        internal void BindContextRunnerName(string runnerName)
 764        {
 38765            Context.BindRunnerName(runnerName);
 38766        }
 767
 768        private void SetVerifiedFrame(Frame? frame)
 769        {
 98770            Frame? previous = VerifiedFrame;
 98771            VerifiedFrame = frame;
 98772            DisposeFrameIfDetached(previous);
 98773        }
 774
 775        private void SetPredictedFrame(Frame? frame)
 776        {
 676777            Frame? previous = PredictedFrame;
 676778            PredictedFrame = frame;
 676779            DisposeFrameIfDetached(previous);
 676780        }
 781
 782        private void SetPreviousFrame(Frame? frame)
 783        {
 676784            Frame? previous = PreviousFrame;
 676785            PreviousFrame = frame;
 676786            DisposeFrameIfDetached(previous);
 676787        }
 788
 789        private void DisposeFrameIfDetached(Frame? frame)
 790        {
 2554791            if (frame == null)
 792            {
 1004793                return;
 794            }
 795
 1550796            if (ReferenceEquals(frame, VerifiedFrame) ||
 1550797                ReferenceEquals(frame, PredictedFrame) ||
 1550798                ReferenceEquals(frame, PreviousFrame))
 799            {
 601800                return;
 801            }
 802
 949803            if (_frameHistory.Owns(frame))
 804            {
 515805                return;
 806            }
 807
 434808            _frameHistory.RecycleFrame(frame);
 434809        }
 810
 811        private bool TryMaterializeHistoricalFrame(int tick, out Frame? frame)
 812        {
 25813            frame = null;
 814
 25815            if (!_frameHistory.IsTickWithinRetentionWindow(tick))
 816            {
 3817                return false;
 818            }
 819
 22820            if (_frameHistory.TryGetScratchFrame(tick, out Frame? scratchFrame))
 821            {
 0822                frame = scratchFrame;
 0823                return true;
 824            }
 825
 22826            if (_frameHistory.TryGetMaterializedFrame(tick, out Frame? cachedFrame))
 827            {
 0828                _frameHistory.SetScratchFrame(cachedFrame!, DisposeFrameIfDetached);
 0829                frame = cachedFrame!;
 0830                return true;
 831            }
 832
 22833            int baseTick = -1;
 22834            Frame? baseFrame = null;
 22835            _frameHistory.TryFindClosestLiveFrame(tick, out baseTick, out baseFrame);
 836
 22837            if (_frameHistory.TryFindClosestMaterializedFrame(tick, out int materializedTick, out Frame? materializedBas
 22838                materializedTick > baseTick)
 839            {
 7840                baseTick = materializedTick;
 7841                baseFrame = materializedBase;
 842            }
 843
 22844            if (_frameHistory.TryGetScratchAsBaseFrame(tick, out int scratchTick, out Frame? scratchBase) &&
 22845                scratchTick > baseTick)
 846            {
 0847                baseTick = scratchTick;
 0848                baseFrame = scratchBase;
 849            }
 850
 851            Frame workingFrame;
 22852            if (baseFrame != null)
 853            {
 7854                workingFrame = CopyFrameState(baseFrame);
 855            }
 15856            else if (_frameHistory.TryFindClosestSnapshotTick(tick, out int snapshotTick))
 857            {
 15858                baseTick = snapshotTick;
 15859                workingFrame = RestoreFrame(_frameHistory.GetSnapshot(snapshotTick), ComponentSerializationMode.Predicti
 860            }
 861            else
 862            {
 0863                return false;
 864            }
 865
 22866            if (_canReplayHistoricalFramesInPlace)
 867            {
 21868                ReplayHistoricalTicksInPlace(workingFrame, baseTick, tick);
 869            }
 870            else
 871            {
 4872                for (int currentTick = baseTick; currentTick < tick; currentTick++)
 873                {
 1874                    Frame nextFrame = AdvanceFrame(workingFrame);
 1875                    _frameHistory.RecycleFrame(workingFrame);
 1876                    workingFrame = nextFrame;
 1877                    ExecuteTickPipeline(workingFrame, raiseFrameUpdateEvent: false, captureHistory: false);
 878                }
 879            }
 880
 22881            _frameHistory.StoreMaterializedFrame(workingFrame, DisposeFrameIfDetached);
 22882            _frameHistory.SetScratchFrame(workingFrame, DisposeFrameIfDetached);
 22883            frame = workingFrame;
 22884            return true;
 885        }
 886
 887        private Frame CopyFrameState(Frame source)
 888        {
 594889            Frame frame = _frameHistory.RentFrameBuffer(source.EntityCapacity);
 594890            frame.CopyStateFrom(source);
 594891            return frame;
 892        }
 893
 894        private Frame RestoreFrame(PackedFrameSnapshot snapshot, ComponentSerializationMode mode = ComponentSerializatio
 895        {
 41896            Frame frame = _frameHistory.RentFrameBuffer(snapshot.EntityCapacity);
 41897            frame.RestoreFromPackedSnapshot(snapshot, mode);
 41898            return frame;
 899        }
 900
 901        private void ReplayHistoricalTicksInPlace(Frame frame, int baseTick, int targetTick)
 902        {
 118903            for (int currentTick = baseTick; currentTick < targetTick; currentTick++)
 904            {
 38905                frame.Tick = currentTick + 1;
 38906                frame.DeltaTime = DeltaTime;
 38907                ExecuteTickPipeline(frame, raiseFrameUpdateEvent: false, captureHistory: false);
 908            }
 21909        }
 910
 911        /// <summary>
 912        /// 清空按需重建历史帧使用的临时缓存。
 913        /// 仅供派生类在测试或基准场景下显式控制冷/热路径使用。
 914        /// </summary>
 915        protected void InvalidateHistoricalMaterializeCache()
 916        {
 3917            _frameHistory.InvalidateMaterializedCache(DisposeFrameIfDetached);
 3918        }
 919
 920        private bool CanReplayHistoricalFramesInPlace()
 921        {
 113922            MethodInfo? advanceFrameMethod = GetType().GetMethod(
 113923                nameof(AdvanceFrame),
 113924                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
 925
 113926            return advanceFrameMethod?.DeclaringType == typeof(SessionRuntime);
 927        }
 928    }
 929
 930    /// <summary>
 931    /// 会话检查点
 932    /// </summary>
 933    public class SessionCheckpoint
 934    {
 935        public int Tick;
 936        public SessionCheckpointProtocol Protocol;
 937        public PackedFrameSnapshot? VerifiedSnapshot;
 938        public PackedFrameSnapshot? PredictedSnapshot;
 939    }
 940}

Methods/Properties

.cctor()
get_RuntimeOptions()
get_Context()
get_DataBoundary()
get_TickPipeline()
get_InputBoundary()
get_RuntimeKind()
get_DeltaTime()
get_LocalPlayerId()
get_CurrentTick()
get_CurrentTickStage()
get_VerifiedFrame()
get_PredictedFrame()
get_PreviousFrame()
get_IsRollingBack()
get_IsRunning()
.ctor(Lattice.ECS.Session.SessionRuntimeOptions)
.ctor(Lattice.Math.FP,System.Int32)
Start()
Stop()
Update()
RegisterSystem(Lattice.ECS.Framework.ISystem)
UnregisterSystem(Lattice.ECS.Framework.ISystem)
UpdateSystems(Lattice.ECS.Core.Frame,Lattice.Math.FP)
CleanupFrame(Lattice.ECS.Core.Frame)
CaptureHistory(Lattice.ECS.Core.Frame)
SetPlayerInput(System.Int32,System.Int32,Lattice.ECS.Session.IPlayerInput)
GetPlayerInput(System.Int32,System.Int32)
CollectInputSet(System.Int32)
ApplyInputSet(System.Runtime.InteropServices.InAttribute))
ApplyInputs(Lattice.ECS.Core.Frame)
ExecuteTickPipeline(Lattice.ECS.Core.Frame,System.Boolean,System.Boolean)
EnterTickStage(Lattice.ECS.Session.SessionTickStage)
VerifyFrame(System.Int32,System.Int64,System.Byte[])
RollbackTo(System.Int32,System.Byte[])
Resimulate(System.Int32,System.Int32)
GetHistoricalFrame(System.Int32)
UpdateHistory(Lattice.ECS.Core.Frame)
Rewind(System.Int32)
CreateCheckpoint()
RestoreFromCheckpoint(Lattice.ECS.Session.SessionCheckpoint)
CreateFrame(System.Int32)
AdvanceFrame(Lattice.ECS.Core.Frame)
ApplyCorrectedInput(Lattice.ECS.Core.Frame,System.Byte[])
ValidateInputIdentity(System.Int32,System.Int32,Lattice.ECS.Session.IPlayerInput)
ResetFrameState(System.Boolean)
Dispose()
EnsureRunning(System.String)
EnsureFrameState(System.String)
EnsureCapability(Lattice.ECS.Session.SessionRuntimeCapability,System.String)
ThrowIfDisposed()
BindContextRunnerName(System.String)
SetVerifiedFrame(Lattice.ECS.Core.Frame)
SetPredictedFrame(Lattice.ECS.Core.Frame)
SetPreviousFrame(Lattice.ECS.Core.Frame)
DisposeFrameIfDetached(Lattice.ECS.Core.Frame)
TryMaterializeHistoricalFrame(System.Int32,Lattice.ECS.Core.Frame&)
CopyFrameState(Lattice.ECS.Core.Frame)
RestoreFrame(Lattice.ECS.Core.PackedFrameSnapshot,Lattice.ECS.Core.ComponentSerializationMode)
ReplayHistoricalTicksInPlace(Lattice.ECS.Core.Frame,System.Int32,System.Int32)
InvalidateHistoricalMaterializeCache()
CanReplayHistoricalFramesInPlace()