-
Notifications
You must be signed in to change notification settings - Fork 20
/
scene_synchronizer.cpp
5082 lines (4185 loc) · 197 KB
/
scene_synchronizer.cpp
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
#include "scene_synchronizer.h"
#include "core/core.h"
#include "core/data_buffer.h"
#include "core/ensure.h"
#include "core/net_math.h"
#include "core/net_utilities.h"
#include "core/object_data.h"
#include "core/peer_networked_controller.h"
#include "core/snapshot.h"
#include "core/var_data.h"
#include <limits>
#include <string>
#include <vector>
NS_NAMESPACE_BEGIN
void (*SceneSynchronizerBase::var_data_encode_func)(DataBuffer &r_buffer, const NS::VarData &p_val) = nullptr;
void (*SceneSynchronizerBase::var_data_decode_func)(NS::VarData &r_val, DataBuffer &p_buffer, std::uint8_t p_variable_type) = nullptr;
bool (*SceneSynchronizerBase::var_data_compare_func)(const VarData &p_A, const VarData &p_B) = nullptr;
std::string (*SceneSynchronizerBase::var_data_stringify_func)(const VarData &p_var_data, bool p_verbose) = nullptr;
void (*SceneSynchronizerBase::print_line_func)(const std::string &p_str) = nullptr;
void (*SceneSynchronizerBase::print_code_message_func)(const char *p_function, const char *p_file, int p_line, const std::string &p_error, const std::string &p_message, NS::PrintMessageType p_type) = nullptr;
void (*SceneSynchronizerBase::print_flush_stdout_func)() = nullptr;
SceneSynchronizerBase::SceneSynchronizerBase(NetworkInterface *p_network_interface, bool p_pedantic_checks, bool p_disable_client_sub_ticks) :
#ifdef NS_DEBUG_ENABLED
pedantic_checks(p_pedantic_checks),
disable_client_sub_ticks(p_disable_client_sub_ticks),
#endif
network_interface(p_network_interface),
objects_data_storage(*this) {
// Avoid too much useless re-allocations.
changes_listeners.reserve(100);
}
SceneSynchronizerBase::~SceneSynchronizerBase() {
clear();
uninit_synchronizer();
network_interface = nullptr;
}
void SceneSynchronizerBase::install_synchronizer(
void (*p_var_data_encode_func)(DataBuffer &r_buffer, const VarData &p_val),
void (*p_var_data_decode_func)(NS::VarData &r_val, DataBuffer &p_buffer, std::uint8_t p_variable_type),
bool (*p_var_data_compare_func)(const VarData &p_A, const VarData &p_B),
std::string (*p_var_data_stringify_func)(const VarData &p_var_data, bool p_verbose),
void (*p_print_line_func)(const std::string &p_str),
void (*p_print_code_message_func)(const char *p_function, const char *p_file, int p_line, const std::string &p_error, const std::string &p_message, PrintMessageType p_type),
void (*p_print_flush_stdout_func)()) {
var_data_encode_func = p_var_data_encode_func;
var_data_decode_func = p_var_data_decode_func;
var_data_compare_func = p_var_data_compare_func;
var_data_stringify_func = p_var_data_stringify_func;
print_line_func = p_print_line_func;
print_code_message_func = p_print_code_message_func;
print_flush_stdout_func = p_print_flush_stdout_func;
}
void SceneSynchronizerBase::setup(SynchronizerManager &p_synchronizer_interface) {
reset();
// These can't be triggered because the interface and the debugger are
// initialized by this class during the constructor.
NS_ASSERT_COND(network_interface);
synchronizer_manager = &p_synchronizer_interface;
synchronizer_manager->set_scene_synchronizer(this);
network_interface->start_listening_peer_connection(
[this](int p_peer) {
on_peer_connected(p_peer);
},
[this](int p_peer) {
on_peer_disconnected(p_peer);
});
rpc_handler_state =
network_interface->rpc_config(
std::function<void(DataBuffer &)>(std::bind(&SceneSynchronizerBase::rpc_receive_state, this, std::placeholders::_1)),
true,
false);
rpc_handler_notify_need_full_snapshot =
network_interface->rpc_config(
std::function<void()>(std::bind(&SceneSynchronizerBase::rpc__notify_need_full_snapshot, this)),
true,
false);
rpc_handler_set_network_enabled =
network_interface->rpc_config(
std::function<void(bool)>(std::bind(&SceneSynchronizerBase::rpc_set_network_enabled, this, std::placeholders::_1)),
true,
false);
rpc_handler_notify_peer_status =
network_interface->rpc_config(
std::function<void(bool)>(std::bind(&SceneSynchronizerBase::rpc_notify_peer_status, this, std::placeholders::_1)),
true,
false);
rpc_handler_trickled_sync_data =
network_interface->rpc_config(
std::function<void(const std::vector<std::uint8_t> &)>(std::bind(&SceneSynchronizerBase::rpc_trickled_sync_data, this, std::placeholders::_1)),
false,
false);
rpc_handle_notify_netstats =
network_interface->rpc_config(
std::function<void(DataBuffer &)>(std::bind(&SceneSynchronizerBase::rpc_notify_netstats, this, std::placeholders::_1)),
false,
false);
rpc_handle_notify_scheduled_procedure_start =
network_interface->rpc_config(
std::function<void(ObjectNetId p_object_id, ScheduledProcedureId p_scheduled_procedure_id, GlobalFrameIndex p_frame_index, const DataBuffer &p_data)>(std::bind(&SceneSynchronizerBase::rpc_notify_scheduled_procedure_start, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4)),
false,
false);
rpc_handle_notify_scheduled_procedure_stop =
network_interface->rpc_config(
std::function<void(ObjectNetId p_object_id, ScheduledProcedureId p_scheduled_procedure_id)>(std::bind(&SceneSynchronizerBase::rpc_notify_scheduled_procedure_stop, this, std::placeholders::_1, std::placeholders::_2)),
false,
false);
rpc_handle_notify_scheduled_procedure_pause =
network_interface->rpc_config(
std::function<void(ObjectNetId p_object_id, ScheduledProcedureId p_scheduled_procedure_id, GlobalFrameIndex p_pause_frame)>(std::bind(&SceneSynchronizerBase::rpc_notify_scheduled_procedure_pause, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)),
false,
false);
rpc_handle_receive_input =
network_interface->rpc_config(
std::function<void(int, const std::vector<std::uint8_t> &)>(std::bind(&SceneSynchronizerBase::rpc_receive_inputs, this, std::placeholders::_1, std::placeholders::_2)),
false,
false);
reset_synchronizer_mode();
// Fetch the peers connected from the Network Interface and ini them.
std::vector<int> peer_ids;
network_interface->fetch_connected_peers(peer_ids);
for (int peer_id : peer_ids) {
on_peer_connected(peer_id);
}
}
void SceneSynchronizerBase::conclude() {
network_interface->stop_listening_peer_connection();
network_interface->reset();
clear_peers();
clear();
uninit_synchronizer();
// Make sure to reset all the assigned controllers.
reset_controllers();
synchronizer_manager->set_scene_synchronizer(nullptr);
synchronizer_manager = nullptr;
rpc_handler_state.reset();
rpc_handler_notify_need_full_snapshot.reset();
rpc_handler_set_network_enabled.reset();
rpc_handler_notify_peer_status.reset();
rpc_handler_trickled_sync_data.reset();
rpc_handle_notify_netstats.reset();
rpc_handle_notify_scheduled_procedure_start.reset();
rpc_handle_notify_scheduled_procedure_stop.reset();
rpc_handle_notify_scheduled_procedure_pause.reset();
rpc_handle_receive_input.reset();
time_bank = 0.0;
}
void SceneSynchronizerBase::process(float p_delta) {
NS_PROFILE
if (settings_changed) {
event_settings_changed.broadcast(settings);
settings_changed = false;
}
#ifdef NS_DEBUG_ENABLED
NS_ASSERT_COND_MSG(synchronizer, "Never execute this function unless this synchronizer is ready.");
synchronizer_manager->debug_only_validate_objects();
#endif
try_fetch_unnamed_objects_data_names();
synchronizer->process(p_delta);
event_app_process_end.broadcast(p_delta);
}
void SceneSynchronizerBase::on_app_object_removed(ObjectHandle p_app_object_handle) {
unregister_app_object(find_object_local_id(p_app_object_handle));
}
void SceneSynchronizerBase::var_data_encode(DataBuffer &r_buffer, const NS::VarData &p_val, std::uint8_t p_variable_type) {
NS_PROFILE
#ifdef NS_DEBUG_ENABLED
NS_ASSERT_COND_MSG(p_variable_type == p_val.type, "The variable_type differ from the VarData type passed during the encoding. This cause major problems. Please ensure your encoding and decoding properly set the variable type.");
#endif
var_data_encode_func(r_buffer, p_val);
}
void SceneSynchronizerBase::var_data_decode(VarData &r_val, DataBuffer &p_buffer, std::uint8_t p_variable_type) {
NS_PROFILE
var_data_decode_func(r_val, p_buffer, p_variable_type);
#ifdef NS_DEBUG_ENABLED
NS_ASSERT_COND_MSG(p_variable_type == r_val.type, "The variable_type differ from the VarData type passed during the decoding. This cause major problems. Please ensure your encoding and decoding properly set the variable type.");
#endif
}
bool SceneSynchronizerBase::var_data_compare(const VarData &p_A, const VarData &p_B) {
NS_PROFILE
return var_data_compare_func(p_A, p_B);
}
std::string SceneSynchronizerBase::var_data_stringify(const VarData &p_var_data, bool p_verbose) {
NS_PROFILE
return var_data_stringify_func(p_var_data, p_verbose);
}
void SceneSynchronizerBase::__print_line(const std::string &p_str) {
if (print_line_func) {
print_line_func(p_str);
}
}
void SceneSynchronizerBase::print_code_message(SceneSynchronizerDebugger *p_debugger, const char *p_function, const char *p_file, int p_line, const std::string &p_error, const std::string &p_message, NS::PrintMessageType p_type) {
const std::string log_level_str = get_log_level_txt(p_type);
std::string msg = log_level_str + " The condition " + p_error + " evaluated to false: " + p_message + "\n";
msg += std::string() + "At: " + p_file + "::" + p_file + "::" + std::to_string(p_line);
if (p_debugger) {
p_debugger->__add_message(msg, "SceneSync");
}
if (print_code_message_func) {
print_code_message_func(p_function, p_file, p_line, p_error, p_message, p_type);
}
}
void SceneSynchronizerBase::print_flush_stdout() {
if (print_flush_stdout_func) {
print_flush_stdout_func();
}
}
void SceneSynchronizerBase::set_frames_per_seconds(int p_fps) {
frames_per_seconds = std::max(p_fps, 1);
fixed_frame_delta = 1.0f / frames_per_seconds;
}
int SceneSynchronizerBase::get_frames_per_seconds() const {
return frames_per_seconds;
}
float SceneSynchronizerBase::get_fixed_frame_delta() const {
return fixed_frame_delta;
}
void SceneSynchronizerBase::set_max_sub_process_per_frame(std::uint8_t p_max_sub_process_per_frame) {
max_sub_process_per_frame = p_max_sub_process_per_frame;
}
std::uint8_t SceneSynchronizerBase::get_max_sub_process_per_frame() const {
return max_sub_process_per_frame;
}
void SceneSynchronizerBase::set_min_server_input_buffer_size(int p_val) {
min_server_input_buffer_size = p_val;
}
int SceneSynchronizerBase::get_min_server_input_buffer_size() const {
return min_server_input_buffer_size;
}
void SceneSynchronizerBase::set_max_server_input_buffer_size(int p_val) {
max_server_input_buffer_size = p_val;
}
int SceneSynchronizerBase::get_max_server_input_buffer_size() const {
return max_server_input_buffer_size;
}
void SceneSynchronizerBase::set_negligible_packet_loss(float p_val) {
negligible_packet_loss = p_val;
}
float SceneSynchronizerBase::get_negligible_packet_loss() const {
return negligible_packet_loss;
}
void SceneSynchronizerBase::set_worst_packet_loss(float p_val) {
worst_packet_loss = std::clamp(p_val, 0.0001f, 1.0f);
}
float SceneSynchronizerBase::get_worst_packet_loss() const {
return worst_packet_loss;
}
void SceneSynchronizerBase::set_max_fps_acceleration_percentage(float p_percentage) {
max_fps_acceleration_percentage = std::max(p_percentage, 0.0f);
}
float SceneSynchronizerBase::get_max_fps_acceleration_percentage() const {
return max_fps_acceleration_percentage;
}
void SceneSynchronizerBase::set_netstats_update_interval_sec(float p_delay_seconds) {
netstats_update_interval_sec = p_delay_seconds;
}
float SceneSynchronizerBase::get_netstats_update_interval_sec() const {
return netstats_update_interval_sec;
}
void SceneSynchronizerBase::set_max_trickled_objects_per_update(int p_rate) {
max_trickled_objects_per_update = p_rate;
}
int SceneSynchronizerBase::get_max_trickled_objects_per_update() const {
return max_trickled_objects_per_update;
}
void SceneSynchronizerBase::set_max_trickled_interpolation_alpha(float p_int_alpha) {
max_trickled_interpolation_alpha = std::max(p_int_alpha, 1.0f);
}
float SceneSynchronizerBase::get_max_trickled_interpolation_alpha() const {
return max_trickled_interpolation_alpha;
}
void SceneSynchronizerBase::set_frame_confirmation_timespan(float p_interval) {
frame_confirmation_timespan = p_interval;
}
float SceneSynchronizerBase::get_frame_confirmation_timespan() const {
return frame_confirmation_timespan;
}
void SceneSynchronizerBase::set_max_predicted_intervals(float p_max_predicted_intevals) {
max_predicted_intervals = std::max(p_max_predicted_intevals, 1.5f);
}
float SceneSynchronizerBase::get_max_predicted_intervals() const {
return max_predicted_intervals;
}
void SceneSynchronizerBase::set_objects_relevancy_update_time(float p_time) {
objects_relevancy_update_time = p_time;
}
float SceneSynchronizerBase::get_objects_relevancy_update_time() const {
return objects_relevancy_update_time;
}
void SceneSynchronizerBase::set_latency_update_rate(float p_rate_seconds) {
latency_update_rate = p_rate_seconds;
}
float SceneSynchronizerBase::get_latency_update_rate() const {
return latency_update_rate;
}
bool SceneSynchronizerBase::is_variable_registered(ObjectLocalId p_id, const std::string &p_variable) const {
const ObjectData *od = objects_data_storage.get_object_data(p_id);
if (od != nullptr) {
return od->find_variable_id(p_variable) != VarId::NONE;
}
return false;
}
void SceneSynchronizerBase::set_debug_rewindings_enabled(bool p_enabled) {
debug_rewindings_enabled = p_enabled;
}
void SceneSynchronizerBase::set_debug_server_speedup(bool p_enabled) {
debug_server_speedup = p_enabled;
}
void SceneSynchronizerBase::set_debug_log_nodes_relevancy_update(bool p_enabled) {
debug_log_nodes_relevancy_update = p_enabled;
}
void SceneSynchronizerBase::set_settings(Settings &p_settings) {
settings = p_settings;
settings_changed = true;
}
Settings &SceneSynchronizerBase::get_settings_mutable() {
settings_changed = true;
return settings;
}
const Settings &SceneSynchronizerBase::get_settings() const {
return settings;
}
void SceneSynchronizerBase::register_app_object(ObjectHandle p_app_object_handle, ObjectLocalId *out_id) {
NS_ENSURE(p_app_object_handle != ObjectHandle::NONE);
ObjectLocalId id = objects_data_storage.find_object_local_id(p_app_object_handle);
if (out_id) {
*out_id = id;
}
if (id == ObjectLocalId::NONE) {
ObjectData *od = objects_data_storage.allocate_object_data();
id = od->get_local_id();
if (out_id) {
*out_id = id;
}
od->set_net_id(ObjectNetId::NONE);
od->debug_object_id = synchronizer_manager->debug_only_get_object_id(p_app_object_handle);
od->set_object_name(synchronizer_manager->fetch_object_name(p_app_object_handle), true);
od->app_object_handle = p_app_object_handle;
if (generate_id) {
#ifdef NS_DEBUG_ENABLED
// When generate_id is true, the id must always be undefined.
NS_ASSERT_COND(od->get_net_id() == ObjectNetId::NONE);
#endif
od->set_net_id(objects_data_storage.generate_net_id());
}
if (od->has_registered_process_functions()) {
process_functions__clear();
}
synchronizer_manager->setup_synchronizer_for(p_app_object_handle, id);
if (synchronizer) {
synchronizer->on_object_data_added(*od);
}
synchronizer_manager->on_add_object_data(*od);
get_debugger().print(INFO, "New object registered" + (generate_id ? " #ID: " + std::to_string(od->get_net_id().id) : "") + " : " + od->get_object_name(), network_interface->get_owner_name());
}
NS_ASSERT_COND(id != ObjectLocalId::NONE);
}
void SceneSynchronizerBase::unregister_app_object(ObjectLocalId p_id) {
if (p_id == ObjectLocalId::NONE) {
// Nothing to do.
return;
}
ObjectData *od = objects_data_storage.get_object_data(p_id, false);
if (!od) {
// Nothing to do.
return;
}
drop_object_data(*od);
}
void SceneSynchronizerBase::setup_controller(
ObjectLocalId p_id,
std::function<void(float /*delta*/, DataBuffer & /*r_data_buffer*/)> p_collect_input_func,
std::function<bool(DataBuffer & /*p_data_buffer_A*/, DataBuffer & /*p_data_buffer_B*/)> p_are_inputs_different_func,
std::function<void(float /*delta*/, DataBuffer & /*p_data_buffer*/)> p_process_func) {
NS_ENSURE_MSG(p_id != ObjectLocalId::NONE, "The passed object_id is not valid.");
NS::ObjectData *object_data = get_object_data(p_id);
NS_ENSURE(object_data != nullptr);
object_data->setup_controller(p_collect_input_func, p_are_inputs_different_func, p_process_func);
}
void SceneSynchronizerBase::set_controlled_by_peer(
ObjectLocalId p_id,
int p_peer) {
NS_ENSURE_MSG(p_id != ObjectLocalId::NONE, "The passed object_id is not valid.");
ObjectData *object_data = get_object_data(p_id);
NS_ENSURE(object_data != nullptr);
object_data->set_controlled_by_peer(*this, p_peer);
}
void SceneSynchronizerBase::register_variable(ObjectLocalId p_id, const std::string &p_variable_name, const NS_VarDataSetFunc &p_set_func, const NS_VarDataGetFunc &p_get_func) {
NS_ENSURE(p_id != ObjectLocalId::NONE);
NS_ENSURE(!p_variable_name.empty());
NS_ENSURE(p_set_func);
NS_ENSURE(p_get_func);
ObjectData *object_data = get_object_data(p_id);
NS_ENSURE(object_data);
VarId var_id = object_data->find_variable_id(p_variable_name);
if (var_id == VarId::NONE) {
// The variable is not yet registered.
VarData old_val;
p_get_func(
*synchronizer_manager,
object_data->app_object_handle,
p_variable_name.data(),
old_val);
var_id = VarId{ { VarId::IdType(object_data->vars.size()) } };
object_data->vars.push_back(
VarDescriptor(
var_id,
p_variable_name,
old_val.type,
std::move(old_val),
p_set_func,
p_get_func,
false,
true));
} else {
// Make sure the var is active.
object_data->vars[var_id.id].enabled = true;
}
#ifdef NS_DEBUG_ENABLED
for (VarId v = VarId{ { 0 } }; v < VarId{ { VarId::IdType(object_data->vars.size()) } }; v += 1) {
// This can't happen, because the IDs are always consecutive, or NONE.
NS_ASSERT_COND(object_data->vars[v.id].id == v);
}
#endif
get_debugger().print(INFO, "[" + object_data->get_object_name() + "] variable registered ID `" + std::to_string(var_id.id) + "`, name `" + p_variable_name + "`.");
if (synchronizer) {
synchronizer->on_variable_added(object_data, p_variable_name);
}
}
void SceneSynchronizerBase::unregister_variable(ObjectLocalId p_id, const std::string &p_variable) {
NS_ENSURE(p_id != ObjectLocalId::NONE);
NS_ENSURE(!p_variable.empty());
NS::ObjectData *od = objects_data_storage.get_object_data(p_id);
NS_ENSURE(od);
const VarId var_id = od->find_variable_id(p_variable);
NS_ENSURE(var_id != VarId::NONE);
// Never remove the variable values, because the order of the vars matters.
od->vars[var_id.id].enabled = false;
// Remove this var from all the changes listeners.
for (ChangesListener *cl : od->vars[var_id.id].changes_listeners) {
for (ListeningVariable lv : cl->watching_vars) {
if (lv.node_data == od && lv.var_id == var_id) {
// We can't change the var order, so just invalidate this.
lv.node_data = nullptr;
lv.var_id = VarId::NONE;
}
}
}
// So, clear the changes listener list for this var.
od->vars[var_id.id].changes_listeners.clear();
}
ObjectNetId SceneSynchronizerBase::get_app_object_net_id(ObjectLocalId p_local_id) const {
const ObjectData *nd = objects_data_storage.get_object_data(p_local_id);
if (nd) {
return nd->get_net_id();
} else {
return ObjectNetId::NONE;
}
}
ObjectNetId SceneSynchronizerBase::get_app_object_net_id(ObjectHandle p_app_object_handle) const {
return get_app_object_net_id(objects_data_storage.find_object_local_id(p_app_object_handle));
}
ObjectHandle SceneSynchronizerBase::get_app_object_from_id(ObjectNetId p_id, bool p_expected) {
ObjectData *object_data = get_object_data(p_id, p_expected);
if (p_expected) {
NS_ENSURE_V_MSG(object_data, ObjectHandle::NONE, "The ID " + p_id + " is not assigned to any object.");
return object_data->app_object_handle;
} else {
return object_data ? object_data->app_object_handle : ObjectHandle::NONE;
}
}
ObjectHandle SceneSynchronizerBase::get_app_object_from_id_const(ObjectNetId p_id, bool p_expected) const {
const ObjectData *object_data = get_object_data(p_id, p_expected);
if (p_expected) {
NS_ENSURE_V_MSG(object_data, ObjectHandle::NONE, "The ID " + p_id + " is not assigned to any object.");
return object_data->app_object_handle;
} else {
return object_data ? object_data->app_object_handle : ObjectHandle::NONE;
}
}
const std::vector<ObjectData *> &SceneSynchronizerBase::get_sorted_objects_data() const {
return objects_data_storage.get_sorted_objects_data();
}
const std::vector<ObjectData *> &SceneSynchronizerBase::get_all_object_data() const {
return objects_data_storage.get_objects_data();
}
const std::vector<ObjectData *> *SceneSynchronizerBase::get_peer_controlled_objects_data(int p_peer) const {
return objects_data_storage.get_peer_controlled_objects_data(p_peer);
}
VarId SceneSynchronizerBase::get_variable_id(ObjectLocalId p_id, const std::string &p_variable) {
NS_ENSURE_V(p_variable != "", VarId::NONE);
NS::ObjectData *od = get_object_data(p_id);
NS_ENSURE_V_MSG(od, VarId::NONE, "This object " + p_id + "is not registered.");
return od->find_variable_id(p_variable);
}
void SceneSynchronizerBase::set_skip_rewinding(ObjectLocalId p_id, const std::string &p_variable, bool p_skip_rewinding) {
NS::ObjectData *od = get_object_data(p_id);
NS_ENSURE(od);
const VarId id = od->find_variable_id(p_variable);
NS_ENSURE(id != VarId::NONE);
od->vars[id.id].skip_rewinding = p_skip_rewinding;
}
ListenerHandle SceneSynchronizerBase::track_variable_changes(
ObjectLocalId p_id,
const std::string &p_variable,
std::function<void(const std::vector<VarData> &p_old_values)> p_listener_func,
NetEventFlag p_flags) {
std::vector<ObjectLocalId> object_ids;
std::vector<std::string> variables;
object_ids.push_back(p_id);
variables.push_back(p_variable);
return track_variables_changes(object_ids, variables, p_listener_func, p_flags);
}
ListenerHandle SceneSynchronizerBase::track_variables_changes(
const std::vector<ObjectLocalId> &p_object_ids,
const std::vector<std::string> &p_variables,
std::function<void(const std::vector<VarData> &p_old_values)> p_listener_func,
NetEventFlag p_flags) {
NS_ENSURE_V_MSG(p_object_ids.size() == p_variables.size(), nulllistenerhandle, "object_ids and variables should have the exact same size.");
NS_ENSURE_V_MSG(p_object_ids.size() != 0, nulllistenerhandle, "object_ids can't be of size 0");
NS_ENSURE_V_MSG(p_variables.size() != 0, nulllistenerhandle, "object_ids can't be of size 0");
bool is_valid = true;
// TODO allocate into a buffer instead of using `new`?
ChangesListener *listener = new ChangesListener;
listener->listener_func = p_listener_func;
listener->flag = p_flags;
listener->watching_vars.resize(p_object_ids.size());
listener->old_values.resize(p_object_ids.size());
for (int i = 0; i < int(p_object_ids.size()); i++) {
ObjectLocalId id = p_object_ids[i];
const std::string &variable_name = p_variables[i];
NS::ObjectData *od = objects_data_storage.get_object_data(id);
if (!od) {
get_debugger().print(ERROR, "The passed ObjectHandle `" + std::to_string(id.id) + "` is not pointing to any valid NodeData. Make sure to register the variable first.");
is_valid = false;
break;
}
const VarId vid = od->find_variable_id(variable_name);
if (vid == VarId::NONE) {
get_debugger().print(ERROR, "The passed variable `" + variable_name + "` doesn't exist under this object `" + od->get_object_name() + "`.");
is_valid = false;
break;
}
listener->watching_vars[i].node_data = od;
listener->watching_vars[i].var_id = vid;
}
if (is_valid) {
// Now we are sure that everything passed by the user is valid
// we can connect the other NodeData to this listener.
for (auto wv : listener->watching_vars) {
NS::ObjectData *nd = wv.node_data;
nd->vars[wv.var_id.id].changes_listeners.push_back(listener);
}
changes_listeners.push_back(listener);
return ListenerHandle::to_handle(listener);
} else {
delete listener;
return nulllistenerhandle;
}
}
void SceneSynchronizerBase::untrack_variable_changes(ListenerHandle p_handle) {
// Find the listener
const ChangesListener *unsafe_handle = ListenerHandle::from_handle(p_handle);
auto it = VecFunc::find(changes_listeners, unsafe_handle);
if (it == changes_listeners.end()) {
// Nothing to do.
return;
}
ChangesListener *listener = *it;
// Before droplatency this listener, make sure to clear the NodeData.
for (auto &wv : listener->watching_vars) {
if (wv.node_data) {
if (wv.node_data->vars.size() > wv.var_id.id) {
auto wv_cl_it = VecFunc::find(wv.node_data->vars[wv.var_id.id].changes_listeners, unsafe_handle);
if (wv_cl_it != wv.node_data->vars[wv.var_id.id].changes_listeners.end()) {
wv.node_data->vars[wv.var_id.id].changes_listeners.erase(wv_cl_it);
}
}
}
}
changes_listeners.erase(it);
// Now it's time to clear the pointer.
delete listener;
}
PHandler SceneSynchronizerBase::register_process(ObjectLocalId p_id, ProcessPhase p_phase, std::function<void(float)> p_func) {
NS_ENSURE_V(p_id != NS::ObjectLocalId::NONE, NS::NullPHandler);
NS_ENSURE_V(p_func, NS::NullPHandler);
ObjectData *od = get_object_data(p_id);
NS_ENSURE_V(od, NS::NullPHandler);
const PHandler EFH = od->functions[p_phase].bind(p_func);
process_functions__clear();
return EFH;
}
void SceneSynchronizerBase::unregister_process(ObjectLocalId p_id, ProcessPhase p_phase, NS::PHandler p_func_handler) {
NS_ENSURE(p_id != NS::ObjectLocalId::NONE);
ObjectData *od = get_object_data(p_id);
if (od) {
od->functions[p_phase].unbind(p_func_handler);
process_functions__clear();
}
}
ScheduledProcedureId SceneSynchronizerBase::register_scheduled_procedure(
ObjectLocalId p_id,
const NS_ScheduledProcedureFunc &p_func) {
ScheduledProcedureId Id = ScheduledProcedureId::NONE;
NS_ENSURE_V(p_id != NS::ObjectLocalId::NONE, Id);
ObjectData *od = get_object_data(p_id);
NS_ENSURE_V(od, Id);
return od->scheduled_procedure_add(p_func);
}
void SceneSynchronizerBase::unregister_scheduled_procedure(
ObjectLocalId p_id,
ScheduledProcedureId p_procedure_id) {
NS_ENSURE(p_id != NS::ObjectLocalId::NONE);
NS_ENSURE(p_procedure_id != NS::ScheduledProcedureId::NONE);
ObjectData *od = get_object_data(p_id);
if (od) {
od->scheduled_procedure_remove(p_procedure_id);
}
}
GlobalFrameIndex SceneSynchronizerBase::scheduled_procedure_start(
ObjectLocalId p_id,
ScheduledProcedureId p_procedure_id,
float p_execute_in_seconds) {
NS_PROFILE
NS_ENSURE_V_MSG(is_server() || is_no_network(), GlobalFrameIndex{0}, "The procedure can be scheduled only by the server.");
NS_ENSURE_V(p_id != NS::ObjectLocalId::NONE, GlobalFrameIndex{0});
NS_ENSURE_V(p_procedure_id != NS::ScheduledProcedureId::NONE, GlobalFrameIndex{0});
ObjectData *od = get_object_data(p_id);
NS_ENSURE_V(od, GlobalFrameIndex{0});
NS_ENSURE_V(od->scheduled_procedure_exist(p_procedure_id), GlobalFrameIndex{0});
const GlobalFrameIndex execute_on_frame{ std::max(GlobalFrameIndex::IdType(1), global_frame_index.id + GlobalFrameIndex::IdType(std::round(p_execute_in_seconds * float(get_frames_per_seconds())))) };
od->scheduled_procedure_fetch_args(p_procedure_id, get_synchronizer_manager(), get_debugger());
od->scheduled_procedure_start(p_procedure_id, execute_on_frame);
sync_group_notify_scheduled_procedure_changed(*od, p_procedure_id);
if (is_server()) {
// Notify all the peers right away, without waiting for the snapshot.
std::vector<int> peers;
static_cast<ServerSynchronizer *>(synchronizer)->sync_group_fetch_object_simulating_peers(*od, peers);
for (int peer : peers) {
if (peer != network_interface->get_server_peer()) {
const PeerNetworkedController *peer_controller = get_controller_for_peer(peer);
if (peer_controller) {
rpc_handle_notify_scheduled_procedure_start.rpc(
get_network_interface(),
peer,
od->get_net_id(),
p_procedure_id,
execute_on_frame,
od->scheduled_procedure_get_args(p_procedure_id));
}
}
}
}
return execute_on_frame;
}
void SceneSynchronizerBase::scheduled_procedure_stop(
ObjectLocalId p_id,
ScheduledProcedureId p_procedure_id) {
NS_PROFILE
NS_ENSURE_MSG(is_server() || is_no_network(), "The procedure can be scheduled only by the server.");
NS_ENSURE(p_id != NS::ObjectLocalId::NONE);
NS_ENSURE(p_procedure_id != NS::ScheduledProcedureId::NONE);
ObjectData *od = get_object_data(p_id);
NS_ENSURE(od);
NS_ENSURE(od->scheduled_procedure_exist(p_procedure_id));
od->scheduled_procedure_stop(p_procedure_id);
sync_group_notify_scheduled_procedure_changed(*od, p_procedure_id);
if (is_server()) {
// Notify all the peers right away, without waiting for the snapshot.
std::vector<int> peers;
static_cast<ServerSynchronizer *>(synchronizer)->sync_group_fetch_object_simulating_peers(*od, peers);
for (int peer : peers) {
if (peer != network_interface->get_server_peer()) {
const PeerNetworkedController *peer_controller = get_controller_for_peer(peer);
if (peer_controller) {
rpc_handle_notify_scheduled_procedure_stop.rpc(
get_network_interface(),
peer,
od->get_net_id(),
p_procedure_id);
}
}
}
}
}
void SceneSynchronizerBase::scheduled_procedure_pause(
ObjectLocalId p_id,
ScheduledProcedureId p_procedure_id) {
NS_PROFILE
NS_ENSURE_MSG(is_server() || is_no_network(), "The procedure can be scheduled only by the server.");
NS_ENSURE(p_id != NS::ObjectLocalId::NONE);
NS_ENSURE(p_procedure_id != NS::ScheduledProcedureId::NONE);
ObjectData *od = get_object_data(p_id);
NS_ENSURE(od);
NS_ENSURE(od->scheduled_procedure_exist(p_procedure_id));
od->scheduled_procedure_pause(p_procedure_id, global_frame_index);
sync_group_notify_scheduled_procedure_changed(*od, p_procedure_id);
if (is_server()) {
// Notify all the peers right away, without waiting for the snapshot.
std::vector<int> peers;
static_cast<ServerSynchronizer *>(synchronizer)->sync_group_fetch_object_simulating_peers(*od, peers);
for (int peer : peers) {
if (peer != network_interface->get_server_peer()) {
const PeerNetworkedController *peer_controller = get_controller_for_peer(peer);
if (peer_controller) {
rpc_handle_notify_scheduled_procedure_pause.rpc(
get_network_interface(),
peer,
od->get_net_id(),
p_procedure_id,
global_frame_index);
}
}
}
}
}
GlobalFrameIndex SceneSynchronizerBase::scheduled_procedure_unpause(
ObjectLocalId p_id,
ScheduledProcedureId p_procedure_id) {
NS_PROFILE
NS_ENSURE_V_MSG(is_server() || is_no_network(), GlobalFrameIndex{0}, "The procedure can be scheduled only by the server.");
NS_ENSURE_V(p_id != NS::ObjectLocalId::NONE, GlobalFrameIndex{0});
NS_ENSURE_V(p_procedure_id != NS::ScheduledProcedureId::NONE, GlobalFrameIndex{0});
ObjectData *od = get_object_data(p_id);
NS_ENSURE_V(od, GlobalFrameIndex{0});
NS_ENSURE_V(od->scheduled_procedure_exist(p_procedure_id), GlobalFrameIndex{0});
NS_ENSURE_V(od->scheduled_procedure_is_paused(p_procedure_id), GlobalFrameIndex{0});
const std::uint32_t remaining_frames = od->scheduled_procedure_remaining_frames(p_procedure_id, global_frame_index);
const GlobalFrameIndex execute_on_frame = global_frame_index + remaining_frames;
od->scheduled_procedure_start(p_procedure_id, global_frame_index + remaining_frames);
sync_group_notify_scheduled_procedure_changed(*od, p_procedure_id);
if (is_server()) {
// Notify all the peers right away, without waiting for the snapshot.
std::vector<int> peers;
static_cast<ServerSynchronizer *>(synchronizer)->sync_group_fetch_object_simulating_peers(*od, peers);
for (int peer : peers) {
if (peer != network_interface->get_server_peer()) {
const PeerNetworkedController *peer_controller = get_controller_for_peer(peer);
if (peer_controller) {
rpc_handle_notify_scheduled_procedure_start.rpc(
get_network_interface(),
peer,
od->get_net_id(),
p_procedure_id,
execute_on_frame,
od->scheduled_procedure_get_args(p_procedure_id));
}
}
}
}
return execute_on_frame;
}
float SceneSynchronizerBase::scheduled_procedure_get_remaining_seconds(
ObjectLocalId p_id,
ScheduledProcedureId p_procedure_id) const {
NS_PROFILE
const ObjectData *od = get_object_data(p_id);
NS_ENSURE_V(od, -1.f);
NS_ENSURE_V(od->scheduled_procedure_exist(p_procedure_id), -1.f);
return float(od->scheduled_procedure_remaining_frames(p_procedure_id, global_frame_index)) * fixed_frame_delta;
}
bool SceneSynchronizerBase::scheduled_procedure_is_paused(
ObjectLocalId p_id,
ScheduledProcedureId p_procedure_id) const {
NS_PROFILE
const ObjectData *od = get_object_data(p_id);
NS_ENSURE_V(od, true);
NS_ENSURE_V(od->scheduled_procedure_exist(p_procedure_id), true);
return od->scheduled_procedure_is_paused(p_procedure_id);
}
void SceneSynchronizerBase::setup_trickled_sync(
ObjectLocalId p_id,
std::function<void(DataBuffer & /*out_buffer*/, float /*update_rate*/)> p_func_trickled_collect,
std::function<void(float /*delta*/, float /*interpolation_alpha*/, DataBuffer & /*past_buffer*/, DataBuffer & /*future_buffer*/)> p_func_trickled_apply) {
NS_ENSURE(p_id != ObjectLocalId::NONE);
ObjectData *od = get_object_data(p_id);
NS_ENSURE(od);
od->func_trickled_collect = p_func_trickled_collect;
od->func_trickled_apply = p_func_trickled_apply;
get_debugger().print(INFO, "Setup trickled sync functions for: `" + od->get_object_name() + "`.", network_interface->get_owner_name());
}
int SceneSynchronizerBase::get_peer_latency_ms(int p_peer) const {
const PeerData *pd = MapFunc::get_or_null(peer_data, p_peer);
if (pd) {
return (int)pd->get_latency();
} else {
return -1;
}
}
int SceneSynchronizerBase::get_peer_latency_jitter_ms(int p_peer) const {
const PeerData *pd = MapFunc::get_or_null(peer_data, p_peer);
if (pd) {
return (int)pd->get_latency_jitter_ms();
} else {
return 0;
}
}
float SceneSynchronizerBase::get_peer_packet_loss_percentage(int p_peer) const {
const PeerData *pd = MapFunc::get_or_null(peer_data, p_peer);
if (pd) {
return pd->get_out_packet_loss_percentage();
} else {
return 0.0;
}