-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorldAnimatorSync.cs
More file actions
491 lines (408 loc) · 18.5 KB
/
Copy pathWorldAnimatorSync.cs
File metadata and controls
491 lines (408 loc) · 18.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
using MelonLoader;
using Steamworks;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace GetToReWorked.Core
{
// ─────────────────────────────────────────────────────────────────────────
// Packet layout for PacketType.AnimatorSync (0x12):
//
// [0] byte – PacketType.AnimatorSync
// [1..4] int32 – number of animator entries (N)
// For each entry:
// [+0..3] int32 – stable path hash (GetStableHash of scene-relative path)
// [+4..7] int32 – Animator state hash (layer 0, shortNameHash)
// [+8..11] float – normalized time within state (layer 0)
// [+12] byte – number of float parameters (P, capped at 16)
// For each float param:
// [+0..3] int32 – parameter name hash (Animator.StringToHash)
// [+4..7] float – current value
//
// Sent by the host on a fixed interval (default 100 ms).
// Only Animators whose scene-relative path is known to WorldAnimatorSync
// are tracked, so proxies / DontDestroyOnLoad objects are never included.
// ─────────────────────────────────────────────────────────────────────────
/// <summary>
/// Attach to the same GameObject as MultiplayerManager / SteamP2PManager.
/// Call <see cref="OnSceneReady"/> after each level finishes loading so the
/// component can (re-)discover world animators.
/// </summary>
public class WorldAnimatorSync : MonoBehaviour
{
// ── singleton ──────────────────────────────────────────────────────
public static WorldAnimatorSync Instance { get; private set; }
// ── tuning ─────────────────────────────────────────────────────────
/// <summary>Seconds between host broadcasts. Lower = smoother but more traffic.</summary>
public float BroadcastInterval = 0.10f;
/// <summary>
/// Name substrings used to filter which Animators are world objects.
/// Animators whose GameObject name contains any of these are included.
/// Add more as you find them.
/// </summary>
public static readonly string[] TrackedNameSubstrings = new[]
{
"Pendulum",
"Obstacle",
"Platform",
"Door",
"Elevator",
"Lift",
"Gear",
"Wheel",
"Fan",
"Crusher",
"Spike",
"Saw",
"Rotating",
"Moving",
"Anim",
"Slingshot",
"Catapult",
"Launcher",
};
// ── internal state ─────────────────────────────────────────────────
private struct TrackedAnimator
{
public Animator Animator;
public int PathHash; // stable ID sent over the wire
public string DebugPath; // full path kept only for logging
}
private readonly List<TrackedAnimator> _tracked = new();
private float _broadcastTimer;
private bool _isHost;
// client-side lookup: pathHash → Animator
private readonly Dictionary<int, Animator> _clientLookup = new();
// scratch buffer reused every broadcast (avoids per-frame alloc on host)
private byte[] _sendBuf = new byte[65536];
// ── lifecycle ──────────────────────────────────────────────────────
private void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(this);
return;
}
Instance = this;
SceneManager.sceneLoaded += OnSceneLoaded;
SceneManager.activeSceneChanged += OnActiveSceneChanged;
MelonLogger.Msg("[WAS] WorldAnimatorSync awake.");
}
private void OnDestroy()
{
if (Instance == this)
Instance = null;
SceneManager.sceneLoaded -= OnSceneLoaded;
SceneManager.activeSceneChanged -= OnActiveSceneChanged;
}
private void OnEnable()
{
if (SteamP2PManager.Instance != null)
SteamP2PManager.Instance.OnMessage += OnP2PMessage;
}
private void OnDisable()
{
if (SteamP2PManager.Instance != null)
SteamP2PManager.Instance.OnMessage -= OnP2PMessage;
}
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
MelonLogger.Msg($"[WAS] Scene loaded: {scene.name}");
StartCoroutine(RediscoverAfterSceneLoad());
}
private void OnActiveSceneChanged(Scene oldScene, Scene newScene)
{
MelonLogger.Msg($"[WAS] Active scene changed: {newScene.name}");
StartCoroutine(RediscoverAfterSceneLoad());
}
private IEnumerator RediscoverAfterSceneLoad()
{
// wait a couple frames because many games instantiate
// scene objects after sceneLoaded fires
yield return null;
yield return null;
DiscoverAnimators();
}
// ── public API ─────────────────────────────────────────────────────
/// <summary>
/// Call this (e.g. from MultiplayerManager) once the game scene is fully
/// loaded and <see cref="MultiplayerManager.IsHost"/> is known.
/// </summary>
public void OnSceneReady(bool isHost)
{
_isHost = isHost;
_broadcastTimer = 0f;
MelonLogger.Msg($"[WAS] OnSceneReady – isHost={isHost}");
StartCoroutine(RediscoverAfterSceneLoad());
}
// ── discovery ──────────────────────────────────────────────────────
private void DiscoverAnimators()
{
_tracked.Clear();
_clientLookup.Clear();
int skipped = 0;
for (int si = 0; si < SceneManager.sceneCount; si++)
{
Scene scene = SceneManager.GetSceneAt(si);
if (!scene.isLoaded) continue;
// Skip DontDestroyOnLoad scene (build index –1)
// We check by name; DDOL scene is typically named "DontDestroyOnLoad"
if (scene.name == "DontDestroyOnLoad") continue;
foreach (GameObject root in scene.GetRootGameObjects())
{
// Exclude our own mod objects
if (root.name.StartsWith("RemotePlayer_") ||
root.name.StartsWith("LocalPlayer_") ||
root.name == "MultiplayerManager")
{
skipped++;
continue;
}
CollectAnimatorsRecursive(root.transform, root.name);
}
}
MelonLogger.Msg(
$"[WAS] Discovery complete – tracking {_tracked.Count} animators, " +
$"skipped {skipped} mod-root objects.");
}
private void CollectAnimatorsRecursive(Transform t, string pathSoFar)
{
Animator anim = t.GetComponent<Animator>();
if (anim != null && anim.runtimeAnimatorController != null && ShouldTrack(t.gameObject))
{
int hash = GetStableHash(pathSoFar);
// Duplicate hash guard (extremely unlikely but worth logging)
bool duplicate = false;
foreach (var existing in _tracked)
{
if (existing.PathHash == hash)
{
MelonLogger.Warning(
$"[WAS] Hash collision! '{pathSoFar}' and '{existing.DebugPath}' " +
$"share hash {hash}. The duplicate will be skipped.");
duplicate = true;
break;
}
}
if (!duplicate)
{
_tracked.Add(new TrackedAnimator
{
Animator = anim,
PathHash = hash,
DebugPath = pathSoFar,
});
// Client lookup populated on both sides so client can apply data
_clientLookup[hash] = anim;
}
}
foreach (Transform child in t)
CollectAnimatorsRecursive(child, pathSoFar + "/" + child.name);
}
private static bool ShouldTrack(GameObject go)
{
string name = go.name;
foreach (string sub in TrackedNameSubstrings)
{
if (name.IndexOf(sub, StringComparison.OrdinalIgnoreCase) >= 0)
return true;
}
return false;
}
/// <summary>
/// Stable, deterministic string hash that doesn't depend on runtime
/// object IDs. Both host and client must produce the same value for the
/// same scene-relative path string.
/// </summary>
private static int GetStableHash(string s)
{
// FNV-1a 32-bit – deterministic across runs / platforms
unchecked
{
uint hash = 2166136261u;
foreach (char c in s)
{
hash ^= (uint)c;
hash *= 16777619u;
}
return (int)hash;
}
}
// ── host: send ─────────────────────────────────────────────────────
private void Update()
{
if (!_isHost) return;
if (SteamP2PManager.Instance == null) return;
if (SteamP2PManager.Instance.Peers.Count == 0) return;
if (_tracked.Count == 0) return;
_broadcastTimer -= Time.deltaTime;
if (_broadcastTimer > 0f) return;
_broadcastTimer = BroadcastInterval;
BroadcastAnimatorStates();
}
private void BroadcastAnimatorStates()
{
// Build packet into _sendBuf
int o = 0;
_sendBuf[o++] = PacketType.AnimatorSync;
// Reserve 4 bytes for entry count; fill after the loop
int countOffset = o;
o += 4;
int validEntries = 0;
foreach (var entry in _tracked)
{
if (entry.Animator == null || !entry.Animator.gameObject.activeInHierarchy)
continue;
AnimatorStateInfo info;
try { info = entry.Animator.GetCurrentAnimatorStateInfo(0); }
catch (Exception ex)
{
MelonLogger.Warning($"[WAS] Failed to get state for '{entry.DebugPath}': {ex.Message}");
continue;
}
// Collect float parameters (cap at 16)
AnimatorControllerParameter[] allParams;
try { allParams = entry.Animator.parameters; }
catch { allParams = Array.Empty<AnimatorControllerParameter>(); }
var floatParams = new List<(int hash, float value)>(allParams.Length);
foreach (var p in allParams)
{
if (p.type == AnimatorControllerParameterType.Float)
{
try
{
floatParams.Add((p.nameHash, entry.Animator.GetFloat(p.nameHash)));
}
catch { /* skip bad param */ }
}
if (floatParams.Count >= 16) break;
}
int entrySize = 4 + 4 + 4 + 1 + floatParams.Count * 8;
if (o + entrySize > _sendBuf.Length)
{
MelonLogger.Warning("[WAS] Send buffer full – truncating animator broadcast.");
break;
}
WriteInt(_sendBuf, ref o, entry.PathHash);
WriteInt(_sendBuf, ref o, info.shortNameHash);
float wrappedTime =
info.normalizedTime - Mathf.Floor(info.normalizedTime);
WriteFloat(_sendBuf, ref o, wrappedTime);
_sendBuf[o++] = (byte)floatParams.Count;
foreach (var (pHash, pValue) in floatParams)
{
WriteInt(_sendBuf, ref o, pHash);
WriteFloat(_sendBuf, ref o, pValue);
}
validEntries++;
}
if (validEntries == 0) return;
// Write entry count back
int tempO = countOffset;
WriteInt(_sendBuf, ref tempO, validEntries);
byte[] packet = new byte[o];
Array.Copy(_sendBuf, packet, o);
SteamP2PManager.Instance.Broadcast(packet, EP2PSend.k_EP2PSendUnreliable);
// Verbose: log once every ~2 s to avoid spam (20 ticks * 100 ms = 2 s)
_verboseLogCounter = (_verboseLogCounter + 1) % 20;
if (_verboseLogCounter == 0)
{
MelonLogger.Msg(
$"[WAS] Broadcast {validEntries}/{_tracked.Count} animators " +
$"({packet.Length} bytes) to {SteamP2PManager.Instance.Peers.Count} peer(s).");
}
}
private int _verboseLogCounter;
// ── client: receive ────────────────────────────────────────────────
private void OnP2PMessage(object sender, P2PMessageEventArgs e)
{
if (e.Type != PacketType.AnimatorSync) return;
if (_isHost) return; // host never applies its own sync
ApplyAnimatorSync(e.Data);
}
private void ApplyAnimatorSync(byte[] data)
{
if (data.Length < 5) return; // 1 type + 4 count minimum
int o = 1; // skip packet type byte
int entryCount = ReadInt(data, ref o);
if (entryCount <= 0 || entryCount > 1024)
{
MelonLogger.Warning($"[WAS] Received malformed AnimatorSync: entryCount={entryCount}");
return;
}
int applied = 0;
int missing = 0;
for (int i = 0; i < entryCount; i++)
{
if (o + 13 > data.Length) break; // need at least pathHash+stateHash+normalizedTime+paramCount
int pathHash = ReadInt(data, ref o);
int stateHash = ReadInt(data, ref o);
float normalizedTime = ReadFloat(data, ref o);
int paramCount = data[o++];
// Read params regardless of whether we find the animator
var floatParams = new (int hash, float value)[paramCount];
for (int p = 0; p < paramCount; p++)
{
if (o + 8 > data.Length) break;
floatParams[p] = (ReadInt(data, ref o), ReadFloat(data, ref o));
}
if (!_clientLookup.TryGetValue(pathHash, out Animator anim) || anim == null)
{
missing++;
if (missing == 1)
{
StartCoroutine(RediscoverAfterSceneLoad());
}
continue;
}
try
{
// Every packet forces the animator into exactly the same
// state and time as the host.
anim.Play(stateHash, 0, normalizedTime);
anim.Update(0f);
// Apply float parameters after forcing state/time.
foreach (var (pHash, pValue) in floatParams)
{
try
{
anim.SetFloat(pHash, pValue);
}
catch
{
// Parameter may not exist client-side.
}
}
applied++;
}
catch (Exception ex)
{
MelonLogger.Warning($"[WAS] Apply failed for hash={pathHash}: {ex.Message}");
}
}
// Log only occasionally to stay readable
_clientLogCounter = (_clientLogCounter + 1) % 20;
if (_clientLogCounter == 0 || missing > 0)
{
MelonLogger.Msg(
$"[WAS] AnimatorSync applied={applied}, missing={missing} " +
$"(of {entryCount} entries). " +
(missing > 0
? "Missing animators may appear after re-discovery."
: ""));
}
}
private int _clientLogCounter;
// ── helpers ────────────────────────────────────────────────────────
private static void WriteInt(byte[] b, ref int o, int v)
{ Array.Copy(BitConverter.GetBytes(v), 0, b, o, 4); o += 4; }
private static void WriteFloat(byte[] b, ref int o, float v)
{ Array.Copy(BitConverter.GetBytes(v), 0, b, o, 4); o += 4; }
private static int ReadInt(byte[] b, ref int o)
{ int v = BitConverter.ToInt32(b, o); o += 4; return v; }
private static float ReadFloat(byte[] b, ref int o)
{ float v = BitConverter.ToSingle(b, o); o += 4; return v; }
}
}