6internal sealed class FixedStepAccumulator
8 private long _lastDriverTick;
9 private long _accumulatedTicks;
12 internal long SimulationTick {
get;
private set; }
16 internal void Reset(
long tick)
18 _lastDriverTick = tick;
19 _accumulatedTicks = 0;
20 SimulationTick = tick;
32 internal FixedStepBatch Advance(
long driverTick,
int updatesPerSecond,
int maxSteps)
34 if (updatesPerSecond <= 0)
35 throw new ArgumentOutOfRangeException(nameof(updatesPerSecond));
38 throw new ArgumentOutOfRangeException(nameof(maxSteps));
40 long stepTicks = Math.Max(1, HighResTimer.TicksPerSecond / updatesPerSecond);
42 long elapsedTicks = driverTick > _lastDriverTick
43 ? driverTick - _lastDriverTick
46 if (driverTick > _lastDriverTick)
47 _lastDriverTick = driverTick;
49 long maxAccumulatedTicks = stepTicks > long.MaxValue / maxSteps
51 : stepTicks * maxSteps;
53 _accumulatedTicks = elapsedTicks >= maxAccumulatedTicks - _accumulatedTicks
55 : _accumulatedTicks + elapsedTicks;
57 int stepCount = (int)Math.Min(maxSteps, _accumulatedTicks / stepTicks);
58 _accumulatedTicks -= stepCount * stepTicks;
60 long firstStepTick = SimulationTick + stepTicks;
61 SimulationTick += stepCount * stepTicks;
63 return new FixedStepBatch(firstStepTick, stepTicks, stepCount);
71internal readonly record
struct FixedStepBatch(long FirstStepTick, long StepTicks, int StepCount)
76 internal long GetStepTick(
int index)
78 if ((uint)index >= (uint)StepCount)
79 throw new ArgumentOutOfRangeException(nameof(index));
81 return FirstStepTick + (index * StepTicks);