-
-
Notifications
You must be signed in to change notification settings - Fork 138
Expand file tree
/
Copy pathTickPatch.cs
More file actions
328 lines (263 loc) · 10.5 KB
/
TickPatch.cs
File metadata and controls
328 lines (263 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using HarmonyLib;
using LudeonTK;
using Multiplayer.Client.AsyncTime;
using Multiplayer.Common;
using RimWorld.Planet;
using UnityEngine;
using Verse;
namespace Multiplayer.Client
{
[HarmonyPatch(typeof(TickManager), nameof(TickManager.TickManagerUpdate))]
public static class TickPatch
{
public static int Timer { get; private set; }
public static int ticksToRun;
public static int tickUntil; // Ticks < tickUntil can be simulated
public static int workTicks;
public static bool currentExecutingCmdIssuedBySelf;
public static CommandType? currentExecutingCmdType;
public static bool serverFrozen;
public static int frozenAt;
public const float StandardTimePerFrame = 1000.0f / 60.0f;
// Time is in milliseconds
private static float realTime;
public static float avgFrameTime = StandardTimePerFrame;
public static float serverTimePerTick;
private static float frameTimeSentAt;
public static TimeSpeed replayTimeSpeed;
public static SimulatingData simulating;
public static bool ShouldHandle => LongEventHandler.currentEvent == null && !Multiplayer.session.desynced;
public static bool Simulating => simulating?.target != null;
public static bool Frozen => serverFrozen && Timer >= frozenAt && !Simulating && ShouldHandle;
public static IEnumerable<ITickable> AllTickables
{
get
{
yield return Multiplayer.AsyncWorldTime;
var maps = Find.Maps;
for (int i = maps.Count - 1; i >= 0; i--)
yield return maps[i].AsyncTime();
}
}
static Stopwatch updateTimer = Stopwatch.StartNew();
public static Stopwatch tickTimer = Stopwatch.StartNew();
[TweakValue("Multiplayer")]
public static bool doSimulate = true;
static bool Prefix()
{
if (Multiplayer.Client == null) return true;
if (!ShouldHandle) return false;
if (Frozen) return false;
int ticksBehind = tickUntil - Timer;
realTime += Time.deltaTime * 1000f;
// Slow down when few ticksBehind to accumulate a buffer
// Try to speed up when many ticksBehind
// Else run at the speed from the server
float stpt = ticksBehind <= 3 ? serverTimePerTick * 1.2f : ticksBehind >= 7 ? serverTimePerTick * 0.8f : serverTimePerTick;
if (Multiplayer.IsReplay)
stpt = StandardTimePerFrame * ReplayMultiplier();
if (Timer >= tickUntil)
{
ticksToRun = 0;
}
else if (realTime > 0 && stpt > 0)
{
avgFrameTime = (avgFrameTime + Time.deltaTime * 1000f) / 2f;
ticksToRun = Multiplayer.IsReplay ? Mathf.CeilToInt(realTime / stpt) : 1;
realTime -= ticksToRun * stpt;
}
if (realTime > 0)
realTime = 0;
if (Time.time - frameTimeSentAt > 32f/1000f)
{
Multiplayer.Client.Send(Packets.Client_FrameTime, avgFrameTime);
frameTimeSentAt = Time.time;
}
if (Multiplayer.IsReplay && replayTimeSpeed == TimeSpeed.Paused || !doSimulate)
ticksToRun = 0;
if (simulating is { targetIsTickUntil: true })
simulating.target = tickUntil;
CheckFinishSimulating();
if (MpVersion.IsDebug)
SimpleProfiler.Start();
RunCmds();
if (LongEventHandler.eventQueue.Count == 0)
{
DoUpdate(out var worked);
if (worked) workTicks++;
}
if (MpVersion.IsDebug)
SimpleProfiler.Pause();
CheckFinishSimulating();
return false;
}
private static void CheckFinishSimulating()
{
if (simulating?.target != null && Timer >= simulating.target)
{
simulating.onFinish?.Invoke();
ClearSimulating();
}
}
public static void SetSimulation(int ticks = 0, bool toTickUntil = false, Action onFinish = null, Action onCancel = null, string cancelButtonKey = null, bool canEsc = false, string simTextKey = null)
{
simulating = new SimulatingData
{
target = ticks,
targetIsTickUntil = toTickUntil,
onFinish = onFinish,
onCancel = onCancel,
canEsc = canEsc,
cancelButtonKey = cancelButtonKey ?? "CancelButton",
simTextKey = simTextKey ?? "MpSimulating"
};
}
static ITickable CurrentTickable()
{
if (WorldRendererUtility.WorldSelected)
return Multiplayer.AsyncWorldTime;
if (Find.CurrentMap != null)
return Find.CurrentMap.AsyncTime();
return null;
}
static void Postfix()
{
if (Multiplayer.Client == null || Find.CurrentMap == null) return;
Shader.SetGlobalFloat(ShaderPropertyIDs.GameSeconds, Find.CurrentMap.AsyncTime().mapTicks.TicksToSeconds());
}
private static bool RunCmds()
{
int curTimer = Timer;
foreach (ITickable tickable in AllTickables)
{
while (tickable.Cmds.Count > 0 && tickable.Cmds.Peek().ticks == curTimer)
{
ScheduledCommand cmd = tickable.Cmds.Dequeue();
// Minimal code impact fix for #733. Having all the commands be added to a single queue gets rid of
// the out-of-order execution problem. With a proper fix, this can be reverted to tickable.ExecuteCmd
var target = TickableById(cmd.mapId);
if (target == null)
{
Log.Error($"!!! Tickable of {cmd.mapId} not found! {cmd}");
} else target.ExecuteCmd(cmd);
if (LongEventHandler.eventQueue.Count > 0) return true; // Yield to e.g. join-point creation
}
}
return false;
}
public static void DoUpdate(out bool worked)
{
worked = false;
updateTimer.Restart();
while (Simulating ? (Timer < simulating.target && updateTimer.ElapsedMilliseconds < 25) : (ticksToRun > 0))
{
if (RunCmds())
return;
if (DoTick(ref worked))
return;
}
}
public static void DoTicks(int ticks)
{
for (int i = 0; i < ticks; i++)
{
bool worked = false;
DoTick(ref worked);
}
}
// Returns whether the tick loop should stop
public static bool DoTick(ref bool worked)
{
tickTimer.Restart();
foreach (ITickable tickable in AllTickables)
{
if (tickable.TimePerTick(tickable.DesiredTimeSpeed) == 0) continue;
tickable.TimeToTickThrough += 1f;
worked = true;
TickTickable(tickable);
}
ConstantTicker.Tick();
ticksToRun -= 1;
Timer += 1;
tickTimer.Stop();
if (Multiplayer.session.desynced || Timer >= tickUntil || LongEventHandler.eventQueue.Count > 0)
{
ticksToRun = 0;
return true;
}
return false;
}
private static void TickTickable(ITickable tickable)
{
while (tickable.TimeToTickThrough >= 0)
{
float timePerTick = tickable.TimePerTick(tickable.DesiredTimeSpeed);
if (timePerTick == 0) break;
tickable.TimeToTickThrough -= timePerTick;
try
{
tickable.Tick();
}
catch (Exception e)
{
Log.Error($"Exception during ticking {tickable}: {e}");
}
}
}
private static float ReplayMultiplier()
{
if (!Multiplayer.IsReplay || Simulating) return 1f;
if (replayTimeSpeed == TimeSpeed.Paused)
return 0f;
ITickable tickable = CurrentTickable();
if (tickable.TimePerTick(tickable.DesiredTimeSpeed) == 0f)
return 1 / 100f; // So paused sections of the timeline are skipped through
return tickable.ActualRateMultiplier(tickable.DesiredTimeSpeed) / tickable.ActualRateMultiplier(replayTimeSpeed);
}
public static float TimePerTick(this ITickable tickable, TimeSpeed speed)
{
if (tickable.ActualRateMultiplier(speed) == 0f)
return 0f;
return 1f / tickable.ActualRateMultiplier(speed);
}
public static float ActualRateMultiplier(this ITickable tickable, TimeSpeed speed)
{
if (Multiplayer.GameComp.asyncTime)
return tickable.TickRateMultiplier(speed);
var rate = Multiplayer.AsyncWorldTime.TickRateMultiplier(speed);
foreach (var map in Find.Maps)
rate = Math.Min(rate, map.AsyncTime().TickRateMultiplier(speed));
return rate;
}
public static void ClearSimulating() => simulating = null;
public static void Reset()
{
ClearSimulating();
Timer = 0;
tickUntil = 0;
ticksToRun = 0;
serverFrozen = false;
workTicks = 0;
serverTimePerTick = 0;
avgFrameTime = StandardTimePerFrame;
realTime = 0;
TimeControlPatch.prePauseTimeSpeed = null;
}
public static void SetTimer(int value) => Timer = value;
public static ITickable TickableById(int tickableId) => AllTickables.FirstOrDefault(t => t.TickableId == tickableId);
}
public class SimulatingData
{
public int? target;
public bool targetIsTickUntil; // When true, the target field is always up-to-date with TickPatch.tickUntil
public Action onFinish;
public bool canEsc;
public Action onCancel;
public string cancelButtonKey;
public string simTextKey;
}
}