-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkPhysicsComponent.cpp
More file actions
4494 lines (3887 loc) · 198 KB
/
Copy pathNetworkPhysicsComponent.cpp
File metadata and controls
4494 lines (3887 loc) · 198 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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Epic Games, Inc. All Rights Reserved.
#include "Physics/NetworkPhysicsComponent.h"
#include "Components/PrimitiveComponent.h"
#include "EngineLogs.h"
#include "EngineUtils.h"
#include "GameFramework/Pawn.h"
#include "GameFramework/PlayerController.h"
#include "PBDRigidsSolver.h"
#include "Net/UnrealNetwork.h"
#include "PhysicsProxy/SingleParticlePhysicsProxy.h"
#include "Chaos/PhysicsObjectInternalInterface.h"
#include "Net/Core/PushModel/PushModel.h"
#include "Iris/ReplicationState/PropertyNetSerializerInfoRegistry.h"
#include "Iris/ReplicationState/ReplicationStateDescriptor.h"
#include "Iris/ReplicationSystem/ReplicationOperations.h"
#include "Iris/ReplicationSystem/ObjectReplicationBridge.h"
#include "Net/Iris/ReplicationSystem/EngineReplicationBridge.h"
#include "Net/Iris/ReplicationSystem/ReplicationSystemUtil.h"
#include "Iris/ReplicationSystem/NetRefHandle.h"
#include "Misc/Crc.h"
#if UE_WITH_REMOTE_OBJECT_HANDLE
#include "UObject/UObjectMigrationContext.h"
#endif
#include UE_INLINE_GENERATED_CPP_BY_NAME(NetworkPhysicsComponent)
namespace UE::Net
{
FReplicationFragment* CreateAndRegisterNetworkPhysicsRewindDataProxyReplicationFragment(UObject* Owner, const FReplicationStateDescriptor* Descriptor, FFragmentRegistrationContext& Context)
{
if (FNetworkPhysicsRewindDataProxyReplicationFragment* Fragment = new FNetworkPhysicsRewindDataProxyReplicationFragment(
Context.GetFragmentTraits() | EReplicationFragmentTraits::DeleteWithInstanceProtocol, Owner, Descriptor))
{
Fragment->Register(Context);
return Fragment;
}
return nullptr;
}
FNetworkPhysicsRewindDataProxyReplicationFragment::FNetworkPhysicsRewindDataProxyReplicationFragment(EReplicationFragmentTraits InTraits, UObject* InOwner, const FReplicationStateDescriptor* InDescriptor)
: FReplicationFragment(InTraits)
, ReplicationStateDescriptor(InDescriptor)
, Owner(InOwner)
{
// We don't want to create temporary states when applying replicated state as we want to update the replicated fields.
Traits |= EReplicationFragmentTraits::HasPersistentTargetStateBuffer;
if (EnumHasAnyFlags(InTraits, EReplicationFragmentTraits::CanReplicate))
{
SrcReplicationState = MakeUnique<FPropertyReplicationState>(InDescriptor);
// We mark the property as dirty via overriding PollReplicatedState
Traits |= EReplicationFragmentTraits::NeedsPoll;
}
#if WITH_PUSH_MODEL
if (EnumHasAnyFlags(InDescriptor->Traits, EReplicationStateTraits::HasPushBasedDirtiness))
{
Traits |= EReplicationFragmentTraits::HasPushBasedDirtiness;
if (EnumHasAnyFlags(InDescriptor->Traits, EReplicationStateTraits::HasFullPushBasedDirtiness))
{
Traits |= EReplicationFragmentTraits::HasFullPushBasedDirtiness;
}
}
#endif
if (EnumHasAnyFlags(InTraits, EReplicationFragmentTraits::CanReceive))
{
if (EnumHasAnyFlags(InDescriptor->Traits, EReplicationStateTraits::HasRepNotifies))
{
ensureMsgf(!EnumHasAnyFlags(InDescriptor->Traits, EReplicationStateTraits::KeepPreviousState), TEXT("FNetworkPhysicsRewindDataProxyReplicationFragment doesn't support OnRep calls with previous value."));
}
// We do custom callbacks in CallRepNotifies rather than in ApplyReplicatedState.
Traits |= EReplicationFragmentTraits::HasRepNotifies | EReplicationFragmentTraits::NeedsLegacyCallbacks;
}
}
void FNetworkPhysicsRewindDataProxyReplicationFragment::Register(FFragmentRegistrationContext& Context)
{
FPropertyReplicationState* ReplicationState = SrcReplicationState.Get();
Context.RegisterReplicationFragment(this, ReplicationStateDescriptor.GetReference(), (ReplicationState ? ReplicationState->GetStateBuffer() : nullptr));
}
void FNetworkPhysicsRewindDataProxyReplicationFragment::ApplyReplicatedState(FReplicationStateApplyContext& ApplyContext) const
{
uint8* ExternalStatePointer = reinterpret_cast<uint8*>(Owner) + ReplicationStateDescriptor->MemberProperties[0]->GetOffset_ForGC();
// Get struct instance from owner and assign owner pointer
FNetworkPhysicsRewindDataProxy* ExternalSourceState = reinterpret_cast<FNetworkPhysicsRewindDataProxy*>(ExternalStatePointer);
ExternalSourceState->Owner = static_cast<UNetworkPhysicsComponent*>(Owner);
// Dequantize replicated members to external struct instance
// Need to call the serializer directly with the appropriate arguments as the external state doesn't have a ReplicationStateHeader in front of it.
FNetDequantizeArgs DequantizeArgs = {};
DequantizeArgs.Source = NetSerializerValuePointer(ApplyContext.StateBufferData.RawStateBuffer);
DequantizeArgs.Target = NetSerializerValuePointer(ExternalSourceState);
DequantizeArgs.NetSerializerConfig = ReplicationStateDescriptor->MemberSerializerDescriptors[0].SerializerConfig;
const FNetSerializer* Serializer = ReplicationStateDescriptor->MemberSerializerDescriptors[0].Serializer;
Serializer->Dequantize(*ApplyContext.NetSerializationContext, DequantizeArgs);
}
bool FNetworkPhysicsRewindDataProxyReplicationFragment::PollReplicatedState(EReplicationFragmentPollFlags PollOption)
{
if (!SrcReplicationState)
{
return true;
}
// We can early out if we are pushbased and not dirty for polling
const bool bPoll = EnumHasAnyFlags(PollOption, EReplicationFragmentPollFlags::PollAllState) ||
(EnumHasAnyFlags(PollOption, EReplicationFragmentPollFlags::PollDirtyState) && (!EnumHasAnyFlags(EReplicationFragmentTraits::HasPushBasedDirtiness, Traits) || SrcReplicationState->IsDirtyForPolling()));
if (bPoll)
{
return SrcReplicationState->PollPropertyReplicationState(Owner);
}
return SrcReplicationState->IsDirty(0);
}
void FNetworkPhysicsRewindDataProxyReplicationFragment::CallRepNotifies(FReplicationStateApplyContext& Context)
{
if (const UFunction* RepNotifyFunction = ReplicationStateDescriptor->MemberPropertyDescriptors[0].RepNotifyFunction)
{
if (Context.bIsInit)
{
const uint8* ReceivedState = Context.StateBufferData.RawStateBuffer;
const uint8* DefaultState = ReplicationStateDescriptor->DefaultStateBuffer;
if (FReplicationStateOperations::IsEqualQuantizedState(*Context.NetSerializationContext, ReceivedState, DefaultState, ReplicationStateDescriptor))
{
return;
}
}
Owner->ProcessEvent(const_cast<UFunction*>(RepNotifyFunction), nullptr);
}
}
void FNetworkPhysicsRewindDataProxyReplicationFragment::CollectOwner(FReplicationStateOwnerCollector* Owners) const
{
Owners->AddOwner(Owner);
}
}
namespace PhysicsReplicationCVars
{
namespace ResimulationCVars
{
int32 RedundantInputs = 2;
static FAutoConsoleVariableRef CVarResimRedundantInputs(TEXT("np2.Resim.RedundantInputs"), RedundantInputs, TEXT("How many extra inputs to send with each unreliable network message, to account for packetloss. From owning client to server and back to owning client. NOTE: This is disabled while np2.Resim.DynamicInputReplicationScaling.Enabled is enabled. Clamped by NetworkPhysicsComponentConstants::MaxNumberOfElementsToNetwork."));
int32 RedundantRemoteInputs = 1;
static FAutoConsoleVariableRef CVarResimRedundantRemoteInputs(TEXT("np2.Resim.RedundantRemoteInputs"), RedundantRemoteInputs, TEXT("How many extra inputs to send with each unreliable network message, to account for packetloss. From server to remote clients. Clamped by NetworkPhysicsComponentConstants::MaxNumberOfElementsToNetwork."));
int32 RedundantStates = 0;
static FAutoConsoleVariableRef CVarResimRedundantStates(TEXT("np2.Resim.RedundantStates"), RedundantStates, TEXT("How many extra states to send with each unreliable network message, to account for packetloss. Clamped by NetworkPhysicsComponentConstants::MaxNumberOfElementsToNetwork."));
bool bDynamicInputReplicationScalingEnabled = true;
static FAutoConsoleVariableRef CVarDynamicInputReplicationScalingEnabled(TEXT("np2.Resim.DynamicInputReplicationScaling.Enabled"), bDynamicInputReplicationScalingEnabled, TEXT("Enable dynmic scaling of number of inputs sent from owning client to the server to account for packet loss. The server will control the value based on how often the server has a hole in its input buffer. NOTE: This overrides np2.Resim.RedundantInputs. Clamped by NetworkPhysicsComponentConstants::MaxNumberOfElementsToNetwork."));
float DynamicInputReplicationScalingMaxInputsPercent = 0.1f;
static FAutoConsoleVariableRef CVarDynamicInputReplicationScalingMaxInputsPercent(TEXT("np2.Resim.DynamicInputReplicationScaling.MaxInputsPercent"), DynamicInputReplicationScalingMaxInputsPercent, TEXT("Default 0.1 (= 10%, value in percent as multiplier). Sets the max scalable number of inputs to network from owning client to server as a percentage of the physics fixed tick-rate. 10% of 30Hz = 3 inputs at max. Clamped by NetworkPhysicsComponentConstants::MaxNumberOfElementsToNetwork."));
int32 DynamicInputReplicationScalingMinInputs = 2;
static FAutoConsoleVariableRef CVarDynamicInputReplicationScalingMinInputs(TEXT("np2.Resim.DynamicInputReplicationScaling.MinInputs"), DynamicInputReplicationScalingMinInputs, TEXT("Default 2. Sets the minimum scalable number of inputs to network from owning client to server."));
float DynamicInputReplicationScalingIncreaseAverageMultiplier = 0.2f;
static FAutoConsoleVariableRef CVarDynamicInputReplicationScalingIncreaseAverageMultiplier(TEXT("np2.Resim.DynamicInputReplicationScaling.IncreaseAverageMultiplier"), DynamicInputReplicationScalingIncreaseAverageMultiplier, TEXT("Default 0.2 (= 20%). Multiplier for how fast the average input scaling value increases. NOTE it's recommended to have a higher value than np2.Resim.DynamicInputReplicationScaling.DecreaseAverageMultiplier so the average can grow quick when network conditions gets worse."));
float DynamicInputReplicationScalingDecreaseAverageMultiplier = 0.1f;
static FAutoConsoleVariableRef CVarDynamicInputReplicationScalingDecreaseAverageMultiplier(TEXT("np2.Resim.DynamicInputReplicationScaling.DecreaseAverageMultiplier"), DynamicInputReplicationScalingDecreaseAverageMultiplier, TEXT("Default 0.1 (= 10%). Multiplier for how fast the average input scaling value decreases. NOTE it's recommended to have a lower value than np2.Resim.DynamicInputReplicationScaling.IncreaseAverageMultiplier so the average doesn't try to decrease too quickly which can cause repeated desyncs."));
float DynamicInputReplicationScalingIncreaseTimeInterval = 2.0f;
static FAutoConsoleVariableRef CVarDynamicInputReplicationScalingIncreaseTimeInterval(TEXT("np2.Resim.DynamicInputReplicationScaling.IncreaseTimeInterval"), DynamicInputReplicationScalingIncreaseTimeInterval, TEXT("Default 2.0 (value in seconds). How often dynamic scaling can increase the number of inputs to send." ));
float DynamicInputReplicationScalingDecreaseTimeInterval = 10.0f;
static FAutoConsoleVariableRef CVarDynamicInputReplicationScalingDecreaseTimeInterval(TEXT("np2.Resim.DynamicInputReplicationScaling.DecreaseTimeInterval"), DynamicInputReplicationScalingDecreaseTimeInterval, TEXT("Default 10.0 (value in seconds). How often dynamic scaling can decrease the number of inputs to send."));
bool bDynamicInputBufferScalingEnabled = true;
static FAutoConsoleVariableRef CVarDynamicInputBufferScalingEnabled(TEXT("np2.Resim.DynamicInputBufferScaling.Enabled"), bDynamicInputBufferScalingEnabled, TEXT("Enable dynmic scaling of input buffer on the server."));
float DynamicInputBufferScalingMinBufferMs = 30.0f;
static FAutoConsoleVariableRef CVarDynamicInputBufferScalingMinBufferMs(TEXT("np2.Resim.DynamicInputBufferScaling.MinBufferTime"), DynamicInputBufferScalingMinBufferMs, TEXT("Time in milliseconds for the lowest allowed input buffer size, when below this the buffer will scale up over time."));
float DynamicInputBufferScalingMaxBufferMs = 90.0f;
static FAutoConsoleVariableRef CVarDynamicInputBufferScalingMaxBufferMs(TEXT("np2.Resim.DynamicInputBufferScaling.MaxBufferTime"), DynamicInputBufferScalingMaxBufferMs, TEXT("Time in milliseconds to cap out the input buffer size."));
float DynamicInputBufferScalingAverageTime = 0.5f;
static FAutoConsoleVariableRef CVarDynamicInputBufferScalingAverageTime(TEXT("np2.Resim.DynamicInputBufferScaling.AverageTime"), DynamicInputBufferScalingAverageTime, TEXT("Time in seconds to keep a running average of the input buffer size over."));
float DynamicInputBufferScalingBumpUpMultiplier = 1.0f;
static FAutoConsoleVariableRef CVarDynamicInputBufferScalingBumpUpMultiplier(TEXT("np2.Resim.DynamicInputBufferScaling.BumpUpMultiplier"), DynamicInputBufferScalingBumpUpMultiplier, TEXT("Multiplier for how much of a fixed delta time should be added to the target input buffer size instantly."));
float DynamicInputBufferScalingScaleUpMultiplier = 1.0f;
static FAutoConsoleVariableRef CVarDynamicInputBufferScalingScaleUpMultiplier(TEXT("np2.Resim.DynamicInputBufferScaling.ScaleUpMultiplier"), DynamicInputBufferScalingScaleUpMultiplier, TEXT("How fast the input buffer scales up when too low. Default 1.0 = one fixed delta time per second."));
float DynamicInputBufferScalingScaleDownMinMultiplier = 0.01f;
static FAutoConsoleVariableRef CVarDynamicInputBufferScalingScaleDownMinMultiplier(TEXT("np2.Resim.DynamicInputBufferScaling.ScaleDownMinMultiplier"), DynamicInputBufferScalingScaleDownMinMultiplier, TEXT("How fast the input buffer scales down when buffer is slightly too large."));
float DynamicInputBufferScalingScaleDownMaxMultiplier = 0.1f;
static FAutoConsoleVariableRef CVarDynamicInputBufferScalingScaleDownMaxMultiplier(TEXT("np2.Resim.DynamicInputBufferScaling.ScaleDownMaxMultiplier"), DynamicInputBufferScalingScaleDownMaxMultiplier, TEXT("How fast the input buffer scales down when buffer is slightly too large."));
bool bDynamicInputBufferScalingDebugLogs = false;
static FAutoConsoleVariableRef CVarDynamicInputBufferScalingDebugLogs(TEXT("np2.Resim.DynamicInputBufferScaling.DebugLogs"), bDynamicInputBufferScalingDebugLogs, TEXT("Print logs for debugging."));
bool bAllowRewindToClosestState = true;
static FAutoConsoleVariableRef CVarResimAllowRewindToClosestState(TEXT("np2.Resim.AllowRewindToClosestState"), bAllowRewindToClosestState, TEXT("When rewinding to a specific frame, if the client doens't have state data for that frame, use closest data available. Only affects the first rewind frame, when FPBDRigidsEvolution is set to Reset."));
bool bCompareStateToTriggerRewind = false;
static FAutoConsoleVariableRef CVarResimCompareStateToTriggerRewind(TEXT("np2.Resim.CompareStateToTriggerRewind"), bCompareStateToTriggerRewind, TEXT("When true, cache local FNetworkPhysicsData state in rewind history and compare the predicted state with incoming server state to trigger resimulations if they differ, comparison done through FNetworkPhysicsData::CompareData. Only applies if IsLocallyControlled, to enable this for simulated proxies, where IsLocallyControlled is false, also enable np2.Resim.CompareStateToTriggerRewind.IncludeSimProxies)"));
bool bCompareStateToTriggerRewindIncludeSimProxies = false;
static FAutoConsoleVariableRef CVarResimCompareStateToTriggerRewindIncludeSimProxies(TEXT("np2.Resim.CompareStateToTriggerRewind.IncludeSimProxies"), bCompareStateToTriggerRewindIncludeSimProxies, TEXT("When true, include simulated proxies when np2.Resim.CompareStateToTriggerRewind is enabled."));
bool bCompareInputToTriggerRewind = false;
static FAutoConsoleVariableRef CVarResimCompareInputToTriggerRewind(TEXT("np2.Resim.CompareInputToTriggerRewind"), bCompareInputToTriggerRewind, TEXT("When true, compare local predicted FNetworkPhysicsData input with incoming server inputs to trigger resimulations if they differ, comparison done through FNetworkPhysicsData::CompareData."));
bool bEnableUnreliableFlow = true;
static FAutoConsoleVariableRef CVarResimEnableUnreliableFlow(TEXT("np2.Resim.EnableUnreliableFlow"), bEnableUnreliableFlow, TEXT("When true, allow data to be sent unreliably. Also sends FNetworkPhysicsData not marked with FNetworkPhysicsData::bimportant unreliably over the network."));
bool bEnableReliableFlow = false;
static FAutoConsoleVariableRef CVarResimEnableReliableFlow(TEXT("np2.Resim.EnableReliableFlow"), bEnableReliableFlow, TEXT("EXPERIMENTAL -- When true, allow data to be sent reliably. Also send FNetworkPhysicsData marked with FNetworkPhysicsData::bimportant reliably over the network."));
bool bApplyDataInsteadOfMergeData = false;
static FAutoConsoleVariableRef CVarResimApplyDataInsteadOfMergeData(TEXT("np2.Resim.ApplyDataInsteadOfMergeData"), bApplyDataInsteadOfMergeData, TEXT("When true, call ApplyData for each data instead of MergeData when having to use multiple data entries in one frame."));
bool bAllowInputExtrapolation = true;
static FAutoConsoleVariableRef CVarResimAllowInputExtrapolation(TEXT("np2.Resim.AllowInputExtrapolation"), bAllowInputExtrapolation, TEXT("When true, allow inputs to be extrapolated from last known on the server and if there is a gap allow interpolation between two known inputs."));
bool bValidateDataOnGameThread = false;
static FAutoConsoleVariableRef CVarResimValidateDataOnGameThread(TEXT("np2.Resim.ValidateDataOnGameThread"), bValidateDataOnGameThread, TEXT("When true, perform server-side input validation through FNetworkPhysicsData::ValidateData on the Game Thread, note that LocalFrame will be the same as ServerFrame on Game Thread. If false, perform the call on the Physics Thread."));
bool bApplySimProxyStateAtRuntime = false;
static FAutoConsoleVariableRef CVarResimApplySimProxyStateAtRuntime(TEXT("np2.Resim.ApplySimProxyStateAtRuntime"), bApplySimProxyStateAtRuntime, TEXT("When true, call ApplyData on received states for simulated proxies at runtime."));
bool bApplySimProxyInputAtRuntime = true;
static FAutoConsoleVariableRef CVarResimApplySimProxyInputAtRuntime(TEXT("np2.Resim.ApplySimProxyInputAtRuntime"), bApplySimProxyInputAtRuntime, TEXT("When true, call ApplyData on received inputs for simulated proxies at runtime."));
bool bTriggerResimOnInputReceive = false;
static FAutoConsoleVariableRef CVarTriggerResimOnInputReceive(TEXT("np2.Resim.TriggerResimOnInputReceive"), bTriggerResimOnInputReceive, TEXT("When true, a resim will be requested to the frame of the latest frame of received inputs this frame"));
bool bEnableInputDecay = true;
static FAutoConsoleVariableRef CVarEnableInputDecay(TEXT("np2.Resim.EnableInputDecay"), bEnableInputDecay, TEXT("When true, apply the Input Decay on predicted inputs."));
bool bApplyInputDecayOverSetTime = false;
static FAutoConsoleVariableRef CVarApplyInputDecayOverSetTime(TEXT("np2.Resim.ApplyInputDecayOverSetTime"), bApplyInputDecayOverSetTime, TEXT("When true, apply the Input Decay Curve over a set amount of time instead of over the start of input prediction and end of resim which is variable each resimulation"));
float InputDecaySetTime = 0.15f;
static FAutoConsoleVariableRef CVarInputDecaySetTime(TEXT("np2.Resim.InputDecaySetTime"), InputDecaySetTime, TEXT("Applied when np2.Resim.ApplyInputDecayOverSetTime is true, read there for more info. Set time to apply Input Decay Curve over while predicting inputs during resimulation"));
bool bEnableLagScalingInputDecay = false;
static FAutoConsoleVariableRef CVarEnableLagScaledInputDecay(TEXT("np2.Resim.EnableLagScalingInputDecay"), bEnableLagScalingInputDecay, TEXT("If true, scales input decay as a proportion of measured input lag compared to the reference input lag (np2.Resim.InputDecayReferenceLagMs)"));
float InputDecayReferenceLagMs = 100.0f;
static FAutoConsoleVariableRef CVarInputDecayReferenceLagMs(TEXT("np2.Resim.InputDecayReferenceLagMs"), InputDecayReferenceLagMs, TEXT("The reference input lag in milliseconds used to scale input decay. Only applies if np2.Resim.EnableLagScalingInputDecay is true"));
bool bApplyInputDecaySimProxyInputAtRuntime = false;
static FAutoConsoleVariableRef CVarApplyInputDecaySimProxyInputAtRuntime(TEXT("np2.Resim.ApplyInputDecaySimProxyInputAtRuntime"), bApplyInputDecaySimProxyInputAtRuntime, TEXT("When true, apply input decay on inputs applied on simulated proxies at runtime (outside of resimulation)"));
float InputDecaySimProxyInputAtRuntime = 0.25f;
static FAutoConsoleVariableRef CVarInputDecaySimProxyInputAtRuntime(TEXT("np2.Resim.InputDecaySimProxyInputAtRuntime"), InputDecaySimProxyInputAtRuntime, TEXT("The amount of input decay to apply on simulated proxy inputs at runtime (outside of resim), if np2.Resim.ApplyInputDecaySimProxyInputAtRuntime is true"));
bool bEnableLagScalingSimProxyRuntimeInputDecay = false;
static FAutoConsoleVariableRef CVarEnableLagScalingSimProxyRuntimeInputDecay(TEXT("np2.Resim.EnableLagScalingSimProxyRuntimeInputDecay"), bEnableLagScalingSimProxyRuntimeInputDecay, TEXT("When true, scale 'runtime' simulated proxy input decay with measured lag, just like resim input decay"));
bool bActionsEnableDebugLogs = false;
static FAutoConsoleVariableRef CVarNetworkedActionsEnableDebugLogs(TEXT("np2.Resim.NetworkedActions.EnableDebugLogs"), bActionsEnableDebugLogs, TEXT("Enable logs for the networked Actions flow in non-shipping builds."));
int32 bActionsEquivalenceFrameWindow = 1;
static FAutoConsoleVariableRef CVarNetworkedActionsEquivalenceFrameWindow(TEXT("np2.Resim.NetworkedActions.EquivalenceFrameWindow"), bActionsEquivalenceFrameWindow, TEXT("Number of frames to look forward and behind when looking for equivalent actions in proposals when server produces an action or client re-produces an acton during resim, as well as in predicted actions when receiving a confirmed action from the server. A value of N means look at (CurrentFrame - N), CurrentFrame and (CurrentFrame + N)."));
bool bSimDecayNetPhysicsCompEnable = false;
static FAutoConsoleVariableRef CVarSimDecayNetPhysicsCompEnable(TEXT("np2.Resim.SimulationDecay.NetPhysicsComp.Enable"), bSimDecayNetPhysicsCompEnable, TEXT("Enable SimulationDecay for for sim-proxies running the NetworkPhysicsComponent."));
bool bSimDecayNetPhysicsCompApplyAtRuntime = false;
static FAutoConsoleVariableRef CVarSimDecayNetPhysicsCompApplyAtRuntime(TEXT("np2.Resim.SimulationDecay.NetPhysicsComp.ApplyAtRuntime"), bSimDecayNetPhysicsCompApplyAtRuntime, TEXT("Apply SimulationDecay during regular (non-resim) frames in addition to resim frames, for sim-proxies running this component. Only active when the particle is in EPhysicsReplicationMode::Resimulation."));
bool bSimDecayNetPhysicsCompUseDynamic = true;
static FAutoConsoleVariableRef CVarSimDecayNetPhysicsCompUseDynamic(TEXT("np2.Resim.SimulationDecay.NetPhysicsComp.UseDynamic"), bSimDecayNetPhysicsCompUseDynamic, TEXT("When true, compute the clamp from the NetworkPhysicsComponent's running-average input-prediction depth. When false, use StaticTimeScale."));
float SimDecayNetPhysicsCompStaticTimeScale = 0.9f;
static FAutoConsoleVariableRef CVarSimDecayNetPhysicsCompStaticTimeScale(TEXT("np2.Resim.SimulationDecay.NetPhysicsComp.StaticTimeScale"), SimDecayNetPhysicsCompStaticTimeScale, TEXT("Static clamp value used when UseDynamic is false."));
float SimDecayNetPhysicsCompDynamicBase = 0.1f;
static FAutoConsoleVariableRef CVarSimDecayNetPhysicsCompDynamicBase(TEXT("np2.Resim.SimulationDecay.NetPhysicsComp.DynamicBase"), SimDecayNetPhysicsCompDynamicBase, TEXT("Base value added to the dynamic clamp formula."));
float SimDecayNetPhysicsCompDynamicMin = 0.25f;
static FAutoConsoleVariableRef CVarSimDecayNetPhysicsCompDynamicMin(TEXT("np2.Resim.SimulationDecay.NetPhysicsComp.DynamicMin"), SimDecayNetPhysicsCompDynamicMin, TEXT("Minimum clamp value allowed when the dynamic formula is in use, clamped 0-1."));
float SimDecayNetPhysicsCompDynamicMax = 1.0f;
static FAutoConsoleVariableRef CVarSimDecayNetPhysicsCompDynamicMax(TEXT("np2.Resim.SimulationDecay.NetPhysicsComp.DynamicMax"), SimDecayNetPhysicsCompDynamicMax, TEXT("Maximum clamp value (per-NetworkPhysicsComponent ceiling), clamped 0-1."));
float SimDecayNetPhysicsCompAverageOverTime = 2.0f;
static FAutoConsoleVariableRef CVarSimDecayNetPhysicsCompAverageOverTime(TEXT("np2.Resim.SimulationDecay.NetPhysicsComp.AverageOverTime"), SimDecayNetPhysicsCompAverageOverTime, TEXT("Time in seconds the NetworkPhysicsComponent running-average of input-prediction depth smooths over - the signal that drives the dynamic clamp formula."));
bool bEnableStatefulDeltaSerialization = true;
static FAutoConsoleVariableRef CVarResimEnableStatefulDeltaSerialization(TEXT("np2.Resim.StatefulDeltaSerialization.Enable"), bEnableStatefulDeltaSerialization, TEXT("Enables stateful delta serialization for FNetworkPhysicsData derived inputs and states. During FNetworkPhysicsData::NetSerialize there will be a valid pointer to a previous FNetworkPhysicsData which can be used for delta serialization, FNetworkPhysicsData::DeltaSourceData. NOTE: Switching this during gameplay might cause disconnections."));
bool bUseDefaultDeltaForDeltaSourceReplication = true;
static FAutoConsoleVariableRef CVarResimUseDefaultForDeltaSourceReplication(TEXT("np2.Resim.StatefulDeltaSerialization.UseDefaultForDeltaSourceReplication"), bUseDefaultDeltaForDeltaSourceReplication, TEXT("When false delta sources will use standard serialization when being replicated. When true there will be a valid delta source pointer to default data which can be used for delta serialization when replicating delta sources."));
float TimeToSyncStatefulDeltaSource = 5.0f;
static FAutoConsoleVariableRef CVarResimTimeToSyncStatefulDeltaSource(TEXT("np2.Resim.StatefulDeltaSerialization.TimeToSyncStatefulDeltaSource"), TimeToSyncStatefulDeltaSource, TEXT("The time in seconds between synchronizing the stateful delta source from server to clients."));
bool bApplyPredictiveInterpolationWhenBehindServer = true;
static FAutoConsoleVariableRef CVarResimApplyPredictiveInterpolationWhenBehindServer(TEXT("np2.Resim.ApplyPredictiveInterpolationWhenBehindServer"), bApplyPredictiveInterpolationWhenBehindServer, TEXT("When true, switch over to replicating with Predictive Interpolation temporarily, when the client receive target states from the server for frames that have not yet simulated on the client. When false apply the received target via a resimulation when the client has caught up and simulated the corresponding frame."));
bool bRecordStatePostSolve = true;
static FAutoConsoleVariableRef CVarResimRecordStatePostSolve(TEXT("np2.Resim.RecordStatePostSolve"), bRecordStatePostSolve, TEXT("When true, cache custom state in PostSolve_Internal (and mark it for current frame + 1) instead of between ProcessInputs_Internal and OnPreSimulate_Internal. This makes clients receive states 1 frame earlier, reducing number of frames needed to resimulate."));
int32 bDebugTriggerResimEveryNFrames = 0;
static FAutoConsoleVariableRef CVarDebugTriggerResimEveryNFrames(TEXT("np2.Resim.Debug.TriggerResimEveryNFrames"), bDebugTriggerResimEveryNFrames, TEXT("When above 0, trigger a resim at an interval of the set value, as long as we receive a state or input on that frame."));
}
}
namespace Chaos
{
extern CHAOS_API int32 RewindBeforeAdvance;
}
bool FNetworkPhysicsRewindDataProxy::NetSerializeBase(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess
, TUniqueFunction<TUniquePtr<Chaos::FBaseRewindHistory> ()> CreateHistoryFunction
, TUniqueFunction<const uint32 ()> GetLatestDeltaSourceIndex
, TUniqueFunction<FNetworkPhysicsData* (const int32)> GetDeltaSourceData)
{
bDeltaSerializationIssue = false;
bool bHasData = false;
if (Ar.IsSaving())
{
if (History.IsValid())
{
bHasData = History->GetHistorySize() > 0;
}
Ar.SerializeBits(&bHasData, 1);
if (bHasData)
{
History->NetSerialize(Ar, Map, [&](void* Data, const int32 DataIndex)
{
if (FNetworkPhysicsData* NetData = static_cast<FNetworkPhysicsData*>(Data))
{
if (Owner)
{
// Set the component pointer to the implementation that uses this data
NetData->SetImplementationComponent(Owner.Get()->ActorComponent.Get());
NetData->bIsUsingDeltaSerialization = false;
// Only use stateful delta source for the first entry in history, the following entries will use the previous entry as delta source
if (PhysicsReplicationCVars::ResimulationCVars::bEnableStatefulDeltaSerialization && DataIndex == 0 && GetLatestDeltaSourceIndex && GetDeltaSourceData)
{
// Stateful Delta Serialization
{
uint32 DeltaSourceIndex = GetLatestDeltaSourceIndex();
if (FNetworkPhysicsData* DeltaSourceData = GetDeltaSourceData(DeltaSourceIndex))
{
NetData->SetDeltaSourceData(DeltaSourceData);
}
else
{
ensureMsgf(false, TEXT("Delta Serialization failed to get the latest delta source when sending, should not happen. On the first send the latest index should be populated with a default value, not null."));
NetData->SetDeltaSourceData(GetDeltaSourceData(/*Default*/ -2));
// Set "index" to the buffer size, meaning it's invalid
DeltaSourceIndex = NetworkPhysicsComponentConstants::DeltaSourceBufferSize;
}
Ar.SerializeBits(&NetData->bIsUsingDeltaSerialization, 1);
if (NetData->bIsUsingDeltaSerialization)
{
constexpr uint32 NumBitsDeltaBufferSize = FMath::CeilLogTwo(NetworkPhysicsComponentConstants::DeltaSourceBufferSize);
Ar.SerializeBits(&DeltaSourceIndex, NumBitsDeltaBufferSize);
}
}
}
else
{
Ar.SerializeBits(&NetData->bIsUsingDeltaSerialization, 1);
}
}
}
});
}
}
else // IsLoading
{
if (!History.IsValid())
{
if (ensureMsgf(Owner, TEXT("FNetRewindDataBase::NetSerialize: owner is null")))
{
History = CreateHistoryFunction();
if (!ensureMsgf(History.IsValid(), TEXT("FNetRewindDataBase::NetSerialize: failed to create history. Owner: %s"), *GetFullNameSafe(Owner)))
{
Ar.SetError();
bOutSuccess = false;
return true;
}
}
else
{
Ar.SetError();
bOutSuccess = false;
return true;
}
}
Ar.SerializeBits(&bHasData, 1);
if (bHasData)
{
History->NetSerialize(Ar, Map, [&](void* Data, const int32 DataIndex)
{
if (FNetworkPhysicsData* NetData = static_cast<FNetworkPhysicsData*>(Data))
{
if (Owner)
{
// Set the component pointer to the implementation that uses this data
NetData->SetImplementationComponent(Owner.Get()->ActorComponent.Get());
Ar.SerializeBits(&NetData->bIsUsingDeltaSerialization, 1);
// Stateful Delta Serialization
if (NetData->bIsUsingDeltaSerialization)
{
uint32 DeltaSourceIndex = 0;
constexpr uint32 NumBitsDeltaBufferSize = FMath::CeilLogTwo(NetworkPhysicsComponentConstants::DeltaSourceBufferSize);
Ar.SerializeBits(&DeltaSourceIndex, NumBitsDeltaBufferSize);
// Only use stateful delta source for the first entry in history, the following entries will use the previous entry as delta source
if (PhysicsReplicationCVars::ResimulationCVars::bEnableStatefulDeltaSerialization && GetDeltaSourceData)
{
FNetworkPhysicsData* DeltaSourceData = nullptr;
if (DeltaSourceIndex < NetworkPhysicsComponentConstants::DeltaSourceBufferSize)
{
DeltaSourceData = GetDeltaSourceData(static_cast<int32>(DeltaSourceIndex));;
}
else
{
// Sender used default as delta source
DeltaSourceData = GetDeltaSourceData(/*Default*/ -2);
}
if (!DeltaSourceData)
{
#if DEBUG_NETWORK_PHYSICS_DELTASERIALIZATION
UE_LOGF(LogChaos, Warning, "[DEBUG Delta Serialization] %ls ISSUE, did not find delta source at index: %d -- Name: %ls"
, (Owner->HasServerWorld() ? TEXT("[SERVER] ") : (Owner->IsLocallyControlled() ? TEXT("[AUTONOMOUS]") : TEXT("[SIMULATED] "))), DeltaSourceIndex, *AActor::GetDebugName(Owner->GetOwner()));
#endif
bDeltaSerializationIssue = true;
DeltaSourceData = GetDeltaSourceData(/*Default*/ -2);
}
// Don't use the SetDeltaSourceData API since it also override bIsUsingDeltaSerialization depending on if delta source is null or not, but here we know delta was used even if we can't find a valid delta source.
NetData->DeltaSourceData = DeltaSourceData;
}
}
}
}
});
}
}
return true;
}
FNetworkPhysicsRewindDataProxy& FNetworkPhysicsRewindDataProxy::operator=(const FNetworkPhysicsRewindDataProxy& Other)
{
if (&Other != this)
{
Owner = Other.Owner;
History = Other.History ? Other.History->Clone() : nullptr;
}
return *this;
}
FNetworkPhysicsRewindDataProxyRPC& FNetworkPhysicsRewindDataProxyRPC::operator=(const FNetworkPhysicsRewindDataProxyRPC& Other)
{
if (&Other != this)
{
Owner = Other.Owner;
History = Other.History ? Other.History->Clone() : nullptr;
}
return *this;
}
// Replicated Properties, register ReplicationFragment to inject Owner (without replicating it) into FNetworkPhysicsRewindDataProxy
UE_NET_IMPLEMENT_NAMED_STRUCT_LASTRESORT_NETSERIALIZER_AND_REGISTRY_DELEGATES(NetworkPhysicsRewindDataOwnerInputProxy, { .CreateAndRegisterReplicationFragmentFunction = UE::Net::CreateAndRegisterNetworkPhysicsRewindDataProxyReplicationFragment })
UE_NET_IMPLEMENT_NAMED_STRUCT_LASTRESORT_NETSERIALIZER_AND_REGISTRY_DELEGATES(NetworkPhysicsRewindDataRemoteInputProxy, { .CreateAndRegisterReplicationFragmentFunction = UE::Net::CreateAndRegisterNetworkPhysicsRewindDataProxyReplicationFragment })
UE_NET_IMPLEMENT_NAMED_STRUCT_LASTRESORT_NETSERIALIZER_AND_REGISTRY_DELEGATES(NetworkPhysicsRewindDataStateProxy, { .CreateAndRegisterReplicationFragmentFunction = UE::Net::CreateAndRegisterNetworkPhysicsRewindDataProxyReplicationFragment })
UE_NET_IMPLEMENT_NAMED_STRUCT_LASTRESORT_NETSERIALIZER_AND_REGISTRY_DELEGATES(NetworkPhysicsRewindDataDeltaSourceInputProxy, { .CreateAndRegisterReplicationFragmentFunction = UE::Net::CreateAndRegisterNetworkPhysicsRewindDataProxyReplicationFragment });
UE_NET_IMPLEMENT_NAMED_STRUCT_LASTRESORT_NETSERIALIZER_AND_REGISTRY_DELEGATES(NetworkPhysicsRewindDataDeltaSourceStateProxy, { .CreateAndRegisterReplicationFragmentFunction = UE::Net::CreateAndRegisterNetworkPhysicsRewindDataProxyReplicationFragment });
// Replicated RPC Parameters, doesn't support ReplicationFragment so they replicate Owner via FNetworkPhysicsRewindDataProxyRPC
UE_NET_IMPLEMENT_NAMED_STRUCT_LASTRESORT_NETSERIALIZER_AND_REGISTRY_DELEGATES(NetworkPhysicsRewindDataInputProxy);
UE_NET_IMPLEMENT_NAMED_STRUCT_LASTRESORT_NETSERIALIZER_AND_REGISTRY_DELEGATES(NetworkPhysicsRewindDataImportantInputProxy);
UE_NET_IMPLEMENT_NAMED_STRUCT_LASTRESORT_NETSERIALIZER_AND_REGISTRY_DELEGATES(NetworkPhysicsRewindDataImportantStateProxy);
bool FNetworkPhysicsRewindDataInputProxy::NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess)
{
const bool bSuccess = NetSerializeBase(Ar, Map, bOutSuccess
/*CreateHistoryFunction*/, [this]() { return Owner->InputHelper->CreateUniqueRewindHistory(0); }
/*GetLatestDeltaSourceIndex*/, [this]() -> const uint32 { return Owner->GetLatestAcknowledgedDeltaSourceInputIndex(); }
/*GetDeltaSourceData*/, [this](const int32 Value) -> FNetworkPhysicsData* { return Owner->GetDeltaSourceInput(Value, /*bValueIsIndex*/ true); });
#if DEBUG_NETWORK_PHYSICS_DELTASERIALIZATION
if (bDeltaSerializationIssue)
{
UE_LOGF(LogChaos, Warning, " [DEBUG Delta Serialization] INPUT RPC");
}
#endif
return bSuccess;
}
bool FNetworkPhysicsRewindDataOwnerInputProxy::NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess)
{
const bool bSuccess = NetSerializeBase(Ar, Map, bOutSuccess
/*CreateHistoryFunction*/, [this]() { return Owner->InputHelper->CreateUniqueRewindHistory(0); }
/*GetLatestDeltaSourceIndex*/, [this]() -> const uint32 { return Owner->GetLatestAcknowledgedDeltaSourceInputIndex(); }
/*GetDeltaSourceData*/, [this](const int32 Value) -> FNetworkPhysicsData* { return Owner->GetDeltaSourceInput(Value, /*bValueIsIndex*/ true); });
#if DEBUG_NETWORK_PHYSICS_DELTASERIALIZATION
if (bDeltaSerializationIssue)
{
UE_LOGF(LogChaos, Warning, " [DEBUG Delta Serialization] OWNER INPUT");
}
#endif
return bSuccess;
}
bool FNetworkPhysicsRewindDataRemoteInputProxy::NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess)
{
const bool bSuccess = NetSerializeBase(Ar, Map, bOutSuccess
/*CreateHistoryFunction*/, [this]() { return Owner->InputHelper->CreateUniqueRewindHistory(0); }
/*GetLatestDeltaSourceIndex*/, [this]() -> const uint32 { return Owner->GetLatestAcknowledgedDeltaSourceInputIndex(); }
/*GetDeltaSourceData*/, [this](const int32 Value) -> FNetworkPhysicsData* { return Owner->GetDeltaSourceInput(Value, /*bValueIsIndex*/ true); });
#if DEBUG_NETWORK_PHYSICS_DELTASERIALIZATION
if (bDeltaSerializationIssue) { UE_LOGF(LogChaos, Warning, " [DEBUG Delta Serialization] REMOTE INPUT"); }
#endif
return bSuccess;
}
bool FNetworkPhysicsRewindDataStateProxy::NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess)
{
const bool bSuccess = NetSerializeBase(Ar, Map, bOutSuccess
/*CreateHistoryFunction*/, [this]() { return Owner->StateHelper->CreateUniqueRewindHistory(0); }
/*GetLatestDeltaSourceIndex*/, [this]() -> const uint32 { return Owner->GetLatestAcknowledgedDeltaSourceStateIndex(); }
/*GetDeltaSourceData*/, [this](const int32 Value) -> FNetworkPhysicsData* { return Owner->GetDeltaSourceState(Value, /*bValueIsIndex*/ true); });
#if DEBUG_NETWORK_PHYSICS_DELTASERIALIZATION
if (bDeltaSerializationIssue) { UE_LOGF(LogChaos, Warning, " [DEBUG Delta Serialization] STATE"); }
#endif
return bSuccess;
}
bool FNetworkPhysicsRewindDataImportantInputProxy::NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess)
{
const bool bSuccess = NetSerializeBase(Ar, Map, bOutSuccess
/*CreateHistoryFunction*/, [this]() { return Owner->InputHelper->CreateUniqueRewindHistory(0); }
/*GetLatestDeltaSourceIndex*/, [this]() -> const uint32 { return Owner->GetLatestAcknowledgedDeltaSourceInputIndex(); }
/*GetDeltaSourceData*/, [this](const int32 Value) -> FNetworkPhysicsData* { return Owner->GetDeltaSourceInput(Value, /*bValueIsIndex*/ true); });
#if DEBUG_NETWORK_PHYSICS_DELTASERIALIZATION
if (bDeltaSerializationIssue) { UE_LOGF(LogChaos, Warning, " [DEBUG Delta Serialization] IMPORTANT INPUT RPC"); }
#endif
return bSuccess;
}
bool FNetworkPhysicsRewindDataImportantStateProxy::NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess)
{
const bool bSuccess = NetSerializeBase(Ar, Map, bOutSuccess
/*CreateHistoryFunction*/, [this]() { return Owner->StateHelper->CreateUniqueRewindHistory(0); }
/*GetLatestDeltaSourceIndex*/, [this]() -> const uint32 { return Owner->GetLatestAcknowledgedDeltaSourceStateIndex(); }
/*GetDeltaSourceData*/, [this](const int32 Value) -> FNetworkPhysicsData* { return Owner->GetDeltaSourceState(Value, /*bValueIsIndex*/ true); });
#if DEBUG_NETWORK_PHYSICS_DELTASERIALIZATION
if (bDeltaSerializationIssue) { UE_LOGF(LogChaos, Warning, " [DEBUG Delta Serialization] IMPORTANT STATE RPC"); }
#endif
return bSuccess;
}
bool FNetworkPhysicsRewindDataDeltaSourceInputProxy::NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess)
{
bool bSuccess = true;
constexpr uint32 NumBitsDeltaBufferSize = FMath::CeilLogTwo(NetworkPhysicsComponentConstants::DeltaSourceBufferSize);
Ar.SerializeBits(&Index, NumBitsDeltaBufferSize);
if (PhysicsReplicationCVars::ResimulationCVars::bUseDefaultDeltaForDeltaSourceReplication)
{
// Use default as base for delta serialization when sending delta source
bSuccess = NetSerializeBase(Ar, Map, bOutSuccess
/*CreateHistoryFunction*/, [this]() { return Owner->InputHelper->CreateUniqueRewindHistory(0); }
/*GetLatestDeltaSourceIndex*/, [this]() -> const uint32 { return Owner->GetLatestAcknowledgedDeltaSourceInputIndex(); }
/*GetDeltaSourceData*/, [this](const int32 Value) -> FNetworkPhysicsData* { return Owner->GetDeltaSourceInput(/*Default*/ -2, /*bValueIsIndex*/ true); });
}
else
{
// Standard serialization for delta source
bSuccess = NetSerializeBase(Ar, Map, bOutSuccess
/*CreateHistoryFunction*/, [this]() { return Owner->InputHelper->CreateUniqueRewindHistory(0); }
/*GetLatestDeltaSourceIndex*/, nullptr
/*GetDeltaSourceData*/, nullptr);
}
#if DEBUG_NETWORK_PHYSICS_DELTASERIALIZATION
if (bDeltaSerializationIssue) { UE_LOGF(LogChaos, Warning, " [DEBUG Delta Serialization] DELTA INPUT"); }
#endif
return bSuccess;
}
bool FNetworkPhysicsRewindDataDeltaSourceStateProxy::NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess)
{
bool bSuccess = true;
constexpr uint32 NumBitsDeltaBufferSize = FMath::CeilLogTwo(NetworkPhysicsComponentConstants::DeltaSourceBufferSize);
Ar.SerializeBits(&Index, NumBitsDeltaBufferSize);
if (PhysicsReplicationCVars::ResimulationCVars::bUseDefaultDeltaForDeltaSourceReplication)
{
// Use default as base for delta serialization when sending delta source
bSuccess = NetSerializeBase(Ar, Map, bOutSuccess
/*CreateHistoryFunction*/, [this]() { return Owner->StateHelper->CreateUniqueRewindHistory(0); }
/*GetLatestDeltaSourceIndex*/, [this]() -> const uint32 { return Owner->GetLatestAcknowledgedDeltaSourceStateIndex(); }
/*GetDeltaSourceData*/, [this](const int32 Value) -> FNetworkPhysicsData* { return Owner->GetDeltaSourceState(/*Default*/ -2, /*bValueIsIndex*/ true); });
}
else
{
// Standard serialization for delta source
bSuccess = NetSerializeBase(Ar, Map, bOutSuccess
/*CreateHistoryFunction*/, [this]() { return Owner->StateHelper->CreateUniqueRewindHistory(0); }
/*GetLatestDeltaSourceIndex*/, nullptr
/*GetDeltaSourceData*/, nullptr);
}
#if DEBUG_NETWORK_PHYSICS_DELTASERIALIZATION
if (bDeltaSerializationIssue) { UE_LOGF(LogChaos, Warning, " [DEBUG Delta Serialization] DELTA STATE"); }
#endif
return bSuccess;
}
// --------------------------- Network Physics Callback ---------------------------
void FNetworkPhysicsCallback::InjectInputs_External(int32 PhysicsStep, int32 NumSteps)
{
InjectInputsExternal.Broadcast(PhysicsStep, NumSteps);
}
void FNetworkPhysicsCallback::ProcessInputs_External(int32 PhysicsStep, const TArray<Chaos::FSimCallbackInputAndObject>& SimCallbackInputs)
{
for (const Chaos::FSimCallbackInputAndObject& SimCallbackObject : SimCallbackInputs)
{
if (SimCallbackObject.CallbackObject
&& SimCallbackObject.CallbackObject->HasOption(Chaos::ESimCallbackOptions::Rewind) == true
&& SimCallbackObject.CallbackObject->HasOption(Chaos::ESimCallbackOptions::ProcessInputsExternal) == false) // Only call from here if not already listening to the native callback
{
SimCallbackObject.CallbackObject->ProcessInputs_External(PhysicsStep);
}
}
}
void FNetworkPhysicsCallback::PreProcessInputs_Internal(int32 PhysicsStep)
{
PreProcessInputsInternal.Broadcast(PhysicsStep);
}
void FNetworkPhysicsCallback::ProcessInputs_Internal(int32 PhysicsStep, const TArray<Chaos::FSimCallbackInputAndObject>& SimCallbacks)
{
for (Chaos::ISimCallbackObject* SimCallbackObject : RewindableCallbackObjects)
{
if (SimCallbackObject->HasOption(Chaos::ESimCallbackOptions::ProcessInputsInternal) == false) // Only call from here if not already listening to the native callback
{
SimCallbackObject->ProcessInputs_Internal(PhysicsStep);
}
}
}
void FNetworkPhysicsCallback::PostProcessInputs_Internal(int32 PhysicsStep)
{
PostProcessInputsInternal.Broadcast(PhysicsStep);
}
void FNetworkPhysicsCallback::PreResimStep_Internal(int32 PhysicsStep, bool bFirst)
{
if (bFirst)
{
for (Chaos::ISimCallbackObject* SimCallbackObject : RewindableCallbackObjects)
{
SimCallbackObject->FirstPreResimStep_Internal(PhysicsStep);
}
}
}
void FNetworkPhysicsCallback::PostResimStep_Internal(int32 PhysicsStep)
{
}
void FNetworkPhysicsCallback::AddResimulationRequest_Internal(const int32 PhysicsStep, const float DeltaSeconds)
{
if (FPhysScene* PhysScene = World->GetPhysicsScene())
{
if (Chaos::FPhysicsSolver* PhysicsSolver = PhysScene->GetSolver())
{
// Add resimulation request from physics state replication
if (IPhysicsReplicationAsync* ReplicationCallback = PhysicsSolver->GetPhysicsReplication_Internal())
{
ReplicationCallback->AddResimulationRequest_Internal(DeltaSeconds);
}
}
}
AddResimulationRequestInternal.Broadcast(PhysicsStep);
}
int32 FNetworkPhysicsCallback::TriggerRewindIfNeeded_Internal(int32 LatestStepCompleted)
{
int32 ResimFrame = INDEX_NONE;
for (Chaos::ISimCallbackObject* SimCallbackObject : RewindableCallbackObjects)
{
const int32 CallbackFrame = SimCallbackObject->TriggerRewindIfNeeded_Internal(LatestStepCompleted);
ResimFrame = (ResimFrame == INDEX_NONE) ? CallbackFrame : FMath::Min(CallbackFrame, ResimFrame);
}
if (RewindData)
{
int32 TargetStateComparisonFrame = INDEX_NONE;
if (!PhysicsReplicationCVars::ResimulationCVars::bApplyPredictiveInterpolationWhenBehindServer)
{
TargetStateComparisonFrame = RewindData->CompareTargetsToLastFrame();
ResimFrame = (ResimFrame == INDEX_NONE) ? TargetStateComparisonFrame : (TargetStateComparisonFrame == INDEX_NONE) ? ResimFrame : FMath::Min(TargetStateComparisonFrame, ResimFrame);
}
const int32 ReplicationFrame = RewindData->GetResimFrame();
ResimFrame = (ResimFrame == INDEX_NONE) ? ReplicationFrame : (ReplicationFrame == INDEX_NONE) ? ResimFrame : FMath::Min(ReplicationFrame, ResimFrame);
if (ResimFrame != INDEX_NONE)
{
const int32 ValidFrame = RewindData->FindValidResimFrame(ResimFrame);
#if DEBUG_NETWORK_PHYSICS || DEBUG_REWIND_DATA
UE_LOGF(LogChaos, Log, "CLIENT | PT | TriggerRewindIfNeeded_Internal | Requested Resim Frame = %d (%d / %d) | Valid Resim Frame = %d", ResimFrame, TargetStateComparisonFrame, ReplicationFrame, ValidFrame);
#endif
ResimFrame = ValidFrame;
}
}
return ResimFrame;
}
// --------------------------- Network Physics System ---------------------------
UNetworkPhysicsSystem::UNetworkPhysicsSystem()
{}
void UNetworkPhysicsSystem::Initialize(FSubsystemCollectionBase& Collection)
{
UWorld* World = GetWorld();
check(World);
if (World->WorldType == EWorldType::PIE || World->WorldType == EWorldType::Game)
{
FWorldDelegates::OnPostWorldInitialization.AddUObject(this, &UNetworkPhysicsSystem::OnWorldPostInit);
}
}
void UNetworkPhysicsSystem::Deinitialize()
{}
void UNetworkPhysicsSystem::OnWorldPostInit(UWorld* World, const UWorld::InitializationValues)
{
if (World != GetWorld())
{
return;
}
if (UPhysicsSettings::Get()->PhysicsPrediction.bEnablePhysicsPrediction || UPhysicsSettings::Get()->PhysicsPrediction.bEnablePhysicsHistoryCapture)
{
if (FPhysScene* PhysScene = World->GetPhysicsScene())
{
if (Chaos::FPhysicsSolver* Solver = PhysScene->GetSolver())
{
if (Solver->GetRewindCallback() == nullptr)
{
Solver->SetRewindCallback(MakeUnique<FNetworkPhysicsCallback>(World));
}
if (UPhysicsSettings::Get()->PhysicsPrediction.bEnablePhysicsHistoryCapture)
{
if (Solver->GetRewindData() == nullptr)
{
Solver->EnableRewindCapture();
}
}
}
}
}
}
// --------------------------- GameThread Network Physics Component ---------------------------
UNetworkPhysicsComponent::UNetworkPhysicsComponent(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
InitPhysics();
}
UNetworkPhysicsComponent::UNetworkPhysicsComponent() : Super()
{
InitPhysics();
}
void UNetworkPhysicsComponent::InitPhysics()
{
if (const IConsoleVariable* CVarRedundantInputs = IConsoleManager::Get().FindConsoleVariable(TEXT("np2.Resim.RedundantInputs")))
{
SetNumberOfInputsToNetwork(CVarRedundantInputs->GetInt() + 1);
}
if (const IConsoleVariable* CVarRedundantRemoteInputs = IConsoleManager::Get().FindConsoleVariable(TEXT("np2.Resim.RedundantRemoteInputs")))
{
SetNumberOfRemoteInputsToNetwork(CVarRedundantRemoteInputs->GetInt() + 1);
}
if (const IConsoleVariable* CVarRedundantStates = IConsoleManager::Get().FindConsoleVariable(TEXT("np2.Resim.RedundantStates")))
{
SetNumberOfStatesToNetwork(CVarRedundantStates->GetInt() + 1);
}
if (const IConsoleVariable* CVarCompareStateToTriggerRewind = IConsoleManager::Get().FindConsoleVariable(TEXT("np2.Resim.CompareStateToTriggerRewind")))
{
bCompareStateToTriggerRewind = CVarCompareStateToTriggerRewind->GetBool();
}
if (const IConsoleVariable* CVarCompareStateToTriggerRewind = IConsoleManager::Get().FindConsoleVariable(TEXT("np2.Resim.CompareStateToTriggerRewind.IncludeSimProxies")))
{
bCompareStateToTriggerRewindIncludeSimProxies = CVarCompareStateToTriggerRewind->GetBool();
}
if (const IConsoleVariable* CVarCompareInputToTriggerRewind = IConsoleManager::Get().FindConsoleVariable(TEXT("np2.Resim.CompareInputToTriggerRewind")))
{
bCompareInputToTriggerRewind = CVarCompareInputToTriggerRewind->GetBool();
}
/** NOTE:
* If the NetworkPhysicsComponent is added as a SubObject after the actor has processed bAutoActivate
* SetActive(true) and RegisterComponent() needs to be called manually for the component to function properly. */
PrimaryComponentTick.bCanEverTick = true;
PrimaryComponentTick.TickGroup = TG_PostPhysics;
bAutoActivate = true;
// Request InitializeComponent so the normal init path runs after all sibling components have
// called their own OnRegister (ensuring NetworkPhysicsSettingsComponent data is available).
// The seamless travel case is handled separately in OnRegister via bActorSeamlessTraveled.
bWantsInitializeComponent = true;
SetIsReplicatedByDefault(true);
}
void UNetworkPhysicsComponent::OnRegister()
{
Super::OnRegister();
// During seamless travel the actor skips the normal initialization path, so
// InitializeComponent will NOT be called. We must initialize here instead.
// For all other cases (normal spawn, level load, dynamic component addition)
// we defer to InitializeComponent which runs after all sibling components have
// completed their OnRegister, guaranteeing NetworkPhysicsSettingsComponent data
// is available when we look for it.
if (AActor* Owner = GetOwner())
{
if (Owner->bActorSeamlessTraveled)
{
InitializePhysicsReplication();
}
}
}
void UNetworkPhysicsComponent::InitializeComponent()
{
Super::InitializeComponent();
// All sibling components have called OnRegister by the time InitializeComponent runs,
// so any NetworkPhysicsSettingsComponent data is guaranteed to be available here.
InitializePhysicsReplication();
}
void UNetworkPhysicsComponent::InitializePhysicsReplication()
{
// Cache CVar values
bEnableUnreliableFlow = PhysicsReplicationCVars::ResimulationCVars::bEnableUnreliableFlow;
bEnableReliableFlow = PhysicsReplicationCVars::ResimulationCVars::bEnableReliableFlow;
bValidateDataOnGameThread = PhysicsReplicationCVars::ResimulationCVars::bValidateDataOnGameThread;
if (AActor* Owner = GetOwner())
{
Owner->SetCallPreReplication(true);
// Get settings from NetworkPhysicsSettingsComponent, if there is one
UNetworkPhysicsSettingsComponent* SettingsComponent = Owner->FindComponentByClass<UNetworkPhysicsSettingsComponent>();
if (SettingsComponent)
{
const FNetworkPhysicsSettingsData& SettingsData = SettingsComponent->GetSettings();
SetNumberOfInputsToNetwork(SettingsData.NetworkPhysicsComponentSettings.GetRedundantInputs() + 1);
SetNumberOfRemoteInputsToNetwork(SettingsData.NetworkPhysicsComponentSettings.GetRedundantRemoteInputs() + 1);
SetNumberOfStatesToNetwork(SettingsData.NetworkPhysicsComponentSettings.GetRedundantStates() + 1);
bEnableUnreliableFlow = SettingsData.NetworkPhysicsComponentSettings.GetEnableUnreliableFlow();
bEnableReliableFlow = SettingsData.NetworkPhysicsComponentSettings.GetEnableReliableFlow();
bValidateDataOnGameThread = SettingsData.NetworkPhysicsComponentSettings.GetValidateDataOnGameThread();
if (ReplicatedOwnerInputs.History)
{
ReplicatedOwnerInputs.History->ResizeDataHistory(InputsToNetwork_OwnerDefault);
}
if (ReplicatedRemoteInputs.History)
{
ReplicatedRemoteInputs.History->ResizeDataHistory(InputsToNetwork_Simulated);
}
if (ReplicatedStates.History)
{
ReplicatedStates.History->ResizeDataHistory(StatesToNetwork);
}
}
if (!PhysicsObject)
{
if (UPrimitiveComponent* RootPrimComp = Cast<UPrimitiveComponent>(Owner->GetRootComponent()))
{
SetPhysicsObject(RootPrimComp->GetPhysicsObjectByName(NAME_None));
}
}
}
if (UWorld* World = GetWorld())
{
if (FPhysScene* PhysScene = World->GetPhysicsScene())
{
if (Chaos::FPhysicsSolver* Solver = PhysScene->GetSolver())
{
// Create async component to run on Physics Thread
NetworkPhysicsComponent_Internal = Solver->CreateAndRegisterSimCallbackObject_External<FAsyncNetworkPhysicsComponent>();
NetworkPhysicsComponent_Internal->PhysicsObject = PhysicsObject;
NetworkPhysicsComponent_Internal->InputsToNetwork_OwnerDefault = InputsToNetwork_OwnerDefault;
NetworkPhysicsComponent_Internal->InputsToNetwork_Simulated = InputsToNetwork_Simulated;
NetworkPhysicsComponent_Internal->StatesToNetwork = StatesToNetwork;
NetworkPhysicsComponent_Internal->bCompareStateToTriggerRewind = bCompareStateToTriggerRewind;
NetworkPhysicsComponent_Internal->bCompareStateToTriggerRewindIncludeSimProxies = bCompareStateToTriggerRewindIncludeSimProxies;
NetworkPhysicsComponent_Internal->bCompareInputToTriggerRewind = bCompareInputToTriggerRewind;
CreateAsyncDataHistory();
UpdateAsyncComponent(true);
// If a NetworkPhysicsSettingsComponent exists but its internal (physics thread) data
// is not yet initialized, it means the settings component has not yet called its own
// OnRegister (registration order race). The UpdateAsyncComponent call above therefore
// could not set the physics thread SettingsComponent pointer. Flag a deferred full
// update so it is re-sent on the first tick, by which time all sibling components
// will have completed their OnRegister and InitializeInternalSettings will have run.
if (AActor* SettingsOwner = GetOwner())
{
if (UNetworkPhysicsSettingsComponent* SettingsComp = SettingsOwner->FindComponentByClass<UNetworkPhysicsSettingsComponent>())
{
if (!SettingsComp->GetSettings_Internal().IsValid())
{
bNeedsFullAsyncComponentUpdate = true;
}
}
}
/** Run OnInitialize_Internal on the ISimCallbackObject first thing on the next physics thread frame */
FAsyncNetworkPhysicsComponent* AsyncNetworkPhysicsComponent = NetworkPhysicsComponent_Internal;
Solver->EnqueueCommandImmediate(
[AsyncNetworkPhysicsComponent]()
{
if (AsyncNetworkPhysicsComponent)
{
AsyncNetworkPhysicsComponent->OnInitialize_Internal();
}
}
);
}
}
}
}
void UNetworkPhysicsComponent::OnUnregister()
{
Super::OnUnregister();
UninitializePhysicsReplication();
}
void UNetworkPhysicsComponent::UninitializePhysicsReplication()
{
if (NetworkPhysicsComponent_Internal)
{
if (FAsyncNetworkPhysicsComponentInput* AsyncInput = NetworkPhysicsComponent_Internal->GetProducerInputData_External())
{
AsyncInput->ActorComponent = nullptr;
AsyncInput->PhysicsObject = nullptr;
AsyncInput->ImplementationInterface_Internal = nullptr;
AsyncInput->ActionHandler_Internal = nullptr;
}
if (UWorld* World = GetWorld())
{
if (FPhysScene* PhysScene = World->GetPhysicsScene())
{
if (Chaos::FPhysicsSolver* Solver = PhysScene->GetSolver())
{
/* Run OnUninitialize_Internal on the ISimCallbackObject as a way to unregister input / state history, unsubscribe from delegates etc.
* After UnregisterAndFreeSimCallbackObject_External the ISimCallbackObject will not get any callbacks anymore, use this as the last safe place to use the cached FPhysicsObject for example */
FAsyncNetworkPhysicsComponent* AsyncNetworkPhysicsComponent = NetworkPhysicsComponent_Internal;
Solver->EnqueueCommandImmediate(
[AsyncNetworkPhysicsComponent]()
{
if (AsyncNetworkPhysicsComponent)
{
AsyncNetworkPhysicsComponent->OnUninitialize_Internal();
}
}
);
// Clear async component from Physics Thread and memory
Solver->UnregisterAndFreeSimCallbackObject_External(NetworkPhysicsComponent_Internal);
}
}
}
}
NetworkPhysicsComponent_Internal = nullptr;
PhysicsObject = nullptr;
}
void UNetworkPhysicsComponent::BeginPlay()
{