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
use std::{
clone::Clone,
collections::{HashMap, HashSet, VecDeque},
hash::Hash,
};
use crate::{
messages::channels::senders::indexed_message_writer::IndexedMessageWriter,
world::{
entity::entity_converters::GlobalWorldManagerType, host::host_world_manager::CommandId,
local::local_world_manager::LocalWorldManager,
},
BitWrite, BitWriter, ComponentKind, ComponentKinds,
EntityAndGlobalEntityConverter, EntityCommand, EntityMessage, EntityMessageType, GlobalEntity,
Instant, MessageIndex, PacketIndex, Serde, WorldRefType,
};
pub struct WorldWriter;
impl WorldWriter {
fn write_command_id(
writer: &mut dyn BitWrite,
last_id_opt: &mut Option<CommandId>,
current_id: &CommandId,
) {
IndexedMessageWriter::write_message_index(writer, last_id_opt, current_id);
*last_id_opt = Some(*current_id);
}
#[allow(clippy::too_many_arguments)]
pub fn write_into_packet<E: Copy + Eq + Hash + Send + Sync, W: WorldRefType<E>>(
component_kinds: &ComponentKinds,
now: &Instant,
writer: &mut BitWriter,
packet_index: &PacketIndex,
world: &W,
entity_converter: &dyn EntityAndGlobalEntityConverter<E>,
global_world_manager: &dyn GlobalWorldManagerType,
world_manager: &mut LocalWorldManager,
has_written: &mut bool,
world_events: &mut VecDeque<(CommandId, EntityCommand)>,
update_events: &mut HashMap<GlobalEntity, HashSet<ComponentKind>>,
entity_priority_order: Option<&[GlobalEntity]>,
) {
// write entity updates
Self::write_updates(
component_kinds,
now,
writer,
packet_index,
world,
entity_converter,
global_world_manager,
world_manager,
has_written,
update_events,
entity_priority_order,
);
// write entity commands
Self::write_commands(
component_kinds,
now,
writer,
packet_index,
world,
entity_converter,
global_world_manager,
world_manager,
has_written,
world_events,
);
}
#[allow(clippy::too_many_arguments)]
fn write_commands<E: Copy + Eq + Hash + Send + Sync, W: WorldRefType<E>>(
component_kinds: &ComponentKinds,
now: &Instant,
writer: &mut BitWriter,
packet_index: &PacketIndex,
world: &W,
entity_converter: &dyn EntityAndGlobalEntityConverter<E>,
global_world_manager: &dyn GlobalWorldManagerType,
world_manager: &mut LocalWorldManager,
has_written: &mut bool,
next_send_commands: &mut VecDeque<(CommandId, EntityCommand)>,
) {
let mut last_counted_id: Option<MessageIndex> = None;
let mut last_written_id: Option<MessageIndex> = None;
loop {
if next_send_commands.is_empty() {
break;
}
// check that we can write the next message
let mut counter = writer.counter();
// write CommandContinue bit
true.ser(&mut counter);
// write data
Self::write_command(
component_kinds,
world,
entity_converter,
global_world_manager,
world_manager,
packet_index,
&mut counter,
&mut last_counted_id,
false,
next_send_commands,
);
if counter.overflowed() {
// if nothing useful has been written in this packet yet,
// send warning about size of component being too big
if !*has_written {
Self::warn_overflow_command(
component_kinds,
counter.bits_needed(),
writer.bits_free(),
next_send_commands,
);
}
break;
}
*has_written = true;
// optimization
world_manager.insert_sent_command_packet(packet_index, now.clone());
// write CommandContinue bit
true.ser(writer);
// write data
Self::write_command(
component_kinds,
world,
entity_converter,
global_world_manager,
world_manager,
packet_index,
writer,
&mut last_written_id,
true,
next_send_commands,
);
// pop command we've written
next_send_commands.pop_front();
}
// Finish commands by writing false CommandContinue bit
writer.release_bits(1);
false.ser(writer);
}
#[allow(clippy::too_many_arguments)]
fn write_command<E: Copy + Eq + Hash + Send + Sync, W: WorldRefType<E>>(
component_kinds: &ComponentKinds,
world: &W,
entity_converter: &dyn EntityAndGlobalEntityConverter<E>,
global_world_manager: &dyn GlobalWorldManagerType,
world_manager: &mut LocalWorldManager,
packet_index: &PacketIndex,
writer: &mut dyn BitWrite,
last_written_id: &mut Option<CommandId>,
is_writing: bool,
next_send_commands: &mut VecDeque<(CommandId, EntityCommand)>,
) {
let (command_id, command) = next_send_commands.front().unwrap();
// info!("Writing (command_id: {:?}), command {:?} into packet {:?}", command_id, command, packet_index);
// write command id
Self::write_command_id(writer, last_written_id, command_id);
match command {
EntityCommand::Spawn(global_entity) => {
EntityMessageType::Spawn.ser(writer);
// get host entity
let host_entity = world_manager
.entity_converter()
.global_entity_to_host_entity(global_entity)
.unwrap();
// write host entity
host_entity.ser(writer);
// if we are writing to this packet, add it to record
if is_writing {
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::Spawn(host_entity.copy_to_owned()),
);
}
}
EntityCommand::SpawnWithComponents(global_entity, comp_kind_list) => {
let Some(world_entity) =
entity_converter.global_entity_to_entity(global_entity).ok()
else {
EntityMessageType::Noop.ser(writer);
if is_writing {
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::Noop,
);
}
return;
};
let all_present = comp_kind_list
.iter()
.all(|k| world.has_component_of_kind(&world_entity, k));
let has_global = world_manager.has_global_entity(global_entity);
if !has_global || !all_present {
EntityMessageType::Noop.ser(writer);
if is_writing {
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::Noop,
);
}
return;
}
EntityMessageType::SpawnWithComponents.ser(writer);
let host_entity = world_manager
.entity_converter()
.global_entity_to_host_entity(global_entity)
.unwrap();
host_entity.copy_to_owned().ser(writer);
let count = comp_kind_list.len() as u8;
count.ser(writer);
{
let mut converter =
world_manager.entity_converter_mut(global_world_manager);
for component_kind in comp_kind_list.iter() {
world
.component_of_kind(&world_entity, component_kind)
.expect("Component does not exist in World")
.write(component_kinds, writer, &mut converter);
}
}
if is_writing {
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::SpawnWithComponents(
host_entity.copy_to_owned(),
comp_kind_list.clone(),
),
);
}
}
EntityCommand::Despawn(global_entity) => {
EntityMessageType::Despawn.ser(writer);
// get local entity
let local_entity = world_manager
.entity_converter()
.global_entity_to_owned_entity(global_entity)
.unwrap();
// write local entity
local_entity.ser(writer);
// if we are writing to this packet, add it to record
if is_writing {
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::Despawn(local_entity),
);
}
}
EntityCommand::InsertComponent(global_entity, component_kind) => {
// get world entity
let Some(world_entity) =
entity_converter.global_entity_to_entity(global_entity).ok()
else {
EntityMessageType::Noop.ser(writer);
if is_writing {
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::Noop,
);
}
return;
};
if !world_manager.has_global_entity(global_entity)
|| !world.has_component_of_kind(&world_entity, component_kind)
{
EntityMessageType::Noop.ser(writer);
// if we are actually writing this packet
if is_writing {
// add it to command record
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::Noop,
);
}
} else {
EntityMessageType::InsertComponent.ser(writer);
// get local entity
let local_entity = world_manager
.entity_converter()
.global_entity_to_owned_entity(global_entity)
.unwrap();
// write local entity
local_entity.ser(writer);
let mut converter = world_manager.entity_converter_mut(global_world_manager);
// write component payload
world
.component_of_kind(&world_entity, component_kind)
.expect("Component does not exist in World")
.write(component_kinds, writer, &mut converter);
// if we are actually writing this packet
if is_writing {
// add it to command record
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::InsertComponent(local_entity, *component_kind),
);
}
}
}
EntityCommand::RemoveComponent(global_entity, component_kind) => {
if !world_manager.has_global_entity(global_entity) {
EntityMessageType::Noop.ser(writer);
// if we are actually writing this packet
if is_writing {
// add it to command record
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::Noop,
);
}
} else {
EntityMessageType::RemoveComponent.ser(writer);
// get local entity
let local_entity = world_manager
.entity_converter()
.global_entity_to_owned_entity(global_entity)
.unwrap();
// write local entity
local_entity.ser(writer);
// write component kind
component_kind.ser(component_kinds, writer);
// if we are writing to this packet, add it to record
if is_writing {
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::RemoveComponent(local_entity, *component_kind),
);
}
}
}
EntityCommand::Publish(sub_id_opt, global_entity) => {
// get subcommand id
let Some(sub_id) = sub_id_opt else {
panic!("Publish command must have a CommandId");
};
// write message type
EntityMessageType::Publish.ser(writer);
// write subcommand id
sub_id.ser(writer);
// get local entity
let local_entity = world_manager
.entity_converter()
.global_entity_to_owned_entity(global_entity)
.unwrap();
// write local entity
local_entity.ser(writer);
// if we are writing to this packet, add it to record
if is_writing {
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::Publish(*sub_id, local_entity),
);
}
}
EntityCommand::Unpublish(sub_id_opt, global_entity) => {
// get subcommand id
let Some(sub_id) = sub_id_opt else {
panic!("Unpublish command must have a CommandId");
};
// write message type
EntityMessageType::Unpublish.ser(writer);
// write subcommand id
sub_id.ser(writer);
// get local entity
let local_entity = world_manager
.entity_converter()
.global_entity_to_owned_entity(global_entity)
.unwrap();
// write local entity
local_entity.ser(writer);
// if we are writing to this packet, add it to record
if is_writing {
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::Unpublish(*sub_id, local_entity),
);
}
}
EntityCommand::EnableDelegation(sub_id_opt, global_entity) => {
// get subcommand id
let Some(sub_id) = sub_id_opt else {
panic!("EnableDelegation command must have a CommandId");
};
// write message type
EntityMessageType::EnableDelegation.ser(writer);
// write subcommand id
sub_id.ser(writer);
// get local entity
let local_entity = world_manager
.entity_converter()
.global_entity_to_owned_entity(global_entity)
.unwrap();
local_entity.ser(writer);
// if we are writing to this packet, add it to record
if is_writing {
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::EnableDelegation(*sub_id, local_entity),
);
}
}
EntityCommand::DisableDelegation(sub_id_opt, global_entity) => {
// this command is only ever sent by the server, regarding server-owned entities, to clients
// get subcommand id
let Some(sub_id) = sub_id_opt else {
panic!("DisableDelegation command must have a CommandId");
};
// write message type
EntityMessageType::DisableDelegation.ser(writer);
// write subcommand id
sub_id.ser(writer);
// get host entity
let host_entity = world_manager
.entity_converter()
.global_entity_to_host_entity(global_entity)
.unwrap();
// write host entity
host_entity.ser(writer);
// if we are writing to this packet, add it to record
if is_writing {
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::DisableDelegation(*sub_id, host_entity.copy_to_owned()),
);
}
}
EntityCommand::SetAuthority(sub_id_opt, global_entity, auth_status) => {
// this command is sent by the server to clients (for both server-owned and client-owned entities)
// get subcommand id
let Some(sub_id) = sub_id_opt else {
panic!("SetAuthority command must have a CommandId");
};
// write message type
EntityMessageType::SetAuthority.ser(writer);
// write subcommand id
sub_id.ser(writer);
// get remote entity (client always reads SetAuthority as RemoteEntity)
// Try RemoteEntity first (for client-owned entities on server), fall back to HostEntity if needed
let remote_entity = world_manager
.entity_converter()
.global_entity_to_remote_entity(global_entity)
.or_else(|_| {
// Fallback: if it's a HostEntity, convert it to RemoteEntity
// This handles the case where server-owned entities are sent as SetAuthority
world_manager
.entity_converter()
.global_entity_to_host_entity(global_entity)
.map(|he| he.to_remote())
})
.unwrap_or_else(|_| {
panic!(
"SetAuthority: Cannot convert GlobalEntity {:?} to RemoteEntity or HostEntity",
global_entity
);
});
// write remote entity
remote_entity.ser(writer);
// write auth status
auth_status.ser(writer);
// if we are writing to this packet, add it to record
if is_writing {
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::SetAuthority(
*sub_id,
remote_entity.copy_to_owned(),
*auth_status,
),
);
}
}
// below are response-type commands
EntityCommand::RequestAuthority(sub_id_opt, global_entity) => {
// this command is only ever sent by clients, regarding server-owned entities, to server
// get subcommand id
let Some(sub_id) = sub_id_opt else {
panic!("RequestAuthority command must have a CommandId");
};
// write message type
EntityMessageType::RequestAuthority.ser(writer);
// write subcommand id
sub_id.ser(writer);
// get remote entity
let remote_entity = world_manager
.entity_converter()
.global_entity_to_remote_entity(global_entity)
.unwrap();
// write remote entity
remote_entity.ser(writer);
// if we are writing to this packet, add it to record
if is_writing {
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::RequestAuthority(*sub_id, remote_entity.copy_to_owned()),
);
}
}
EntityCommand::ReleaseAuthority(sub_id_opt, global_entity) => {
// this command is only ever sent by clients, regarding server-owned entities, to server
// get subcommand id
let Some(sub_id) = sub_id_opt else {
panic!("ReleaseAuthority command must have a CommandId");
};
// write message type
EntityMessageType::ReleaseAuthority.ser(writer);
// write subcommand id
sub_id.ser(writer);
// get local entity
// NOTE: this is actually valid because it should be possible to ReleaseAuthority right after EnableDelegation, so that auth isn't automatically set to Granted
let local_entity = world_manager
.entity_converter()
.global_entity_to_owned_entity(global_entity)
.unwrap();
// write local entity
local_entity.ser(writer);
// if we are writing to this packet, add it to record
if is_writing {
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::ReleaseAuthority(*sub_id, local_entity),
);
}
}
EntityCommand::EnableDelegationResponse(sub_id_opt, global_entity) => {
// this command is only ever sent by clients, regarding server-owned entities, to server
// get subcommand id
let Some(sub_id) = sub_id_opt else {
panic!("EnableDelegationResponse command must have a CommandId");
};
// write message type
EntityMessageType::EnableDelegationResponse.ser(writer);
// write subcommand id
sub_id.ser(writer);
// get remote entity
let remote_entity = world_manager
.entity_converter()
.global_entity_to_remote_entity(global_entity)
.unwrap();
// write remote entity
remote_entity.ser(writer);
// if we are writing to this packet, add it to record
if is_writing {
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::EnableDelegationResponse(
*sub_id,
remote_entity.copy_to_owned(),
),
);
}
}
EntityCommand::MigrateResponse(
sub_id_opt,
_global_entity,
old_remote_entity,
new_host_entity_value,
) => {
// this command is only ever sent by the server, regarding newly delegated server-owned entities, to clients
// get subcommand id
let Some(sub_id) = sub_id_opt else {
panic!("MigrateResponse command must have a CommandId");
};
// write message type
EntityMessageType::MigrateResponse.ser(writer);
// write subcommand id
sub_id.ser(writer);
// Convert server's RemoteEntity to client's HostEntity (same value, different type)
// The client can look this up in its entity_map!
let client_host_entity = old_remote_entity.to_host();
client_host_entity.ser(writer);
// write new remote entity (what the client will create)
let new_remote_entity = new_host_entity_value.to_remote();
new_remote_entity.ser(writer);
// if we are writing to this packet, add it to record
if is_writing {
world_manager.record_command_written(
packet_index,
command_id,
EntityMessage::MigrateResponse(
*sub_id,
client_host_entity.copy_to_owned(),
new_remote_entity,
),
);
}
}
}
}
fn warn_overflow_command(
component_kinds: &ComponentKinds,
bits_needed: u32,
bits_free: u32,
next_send_commands: &VecDeque<(CommandId, EntityCommand)>,
) {
let (_command_id, command) = next_send_commands.front().unwrap();
match command {
EntityCommand::Spawn(_entity) => {
panic!(
"Packet Write Error: Blocking overflow detected! Entity Spawn message requires {bits_needed} bits, but packet only has {bits_free} bits available! Recommend slimming down these Components."
)
}
EntityCommand::SpawnWithComponents(_entity, _kinds) => {
panic!(
"Packet Write Error: Blocking overflow detected! SpawnWithComponents message requires {bits_needed} bits, but packet only has {bits_free} bits available! Recommend slimming down these Components."
)
}
EntityCommand::InsertComponent(_entity, component_kind) => {
let component_name = component_kinds.kind_to_name(component_kind);
panic!(
"Packet Write Error: Blocking overflow detected! Component Insertion message of type `{component_name}` requires {bits_needed} bits, but packet only has {bits_free} bits available! This condition should never be reached, as large Messages should be Fragmented in the Reliable channel"
)
}
EntityCommand::Publish(_, _)
| EntityCommand::Unpublish(_, _)
| EntityCommand::EnableDelegation(_, _)
| EntityCommand::EnableDelegationResponse(_, _)
| EntityCommand::DisableDelegation(_, _)
| EntityCommand::RequestAuthority(_, _)
| EntityCommand::ReleaseAuthority(_, _)
| EntityCommand::SetAuthority(_, _, _)
| EntityCommand::MigrateResponse(_, _, _, _) => {
panic!(
"Packet Write Error: Blocking overflow detected! Authority/delegation command requires {bits_needed} bits, but packet only has {bits_free} bits available! These messages should be small and not cause overflow."
)
}
_ => {
panic!(
"Packet Write Error: Blocking overflow detected! Command requires {bits_needed} bits, but packet only has {bits_free} bits available! This message should never display..."
)
}
}
}
#[allow(clippy::too_many_arguments)]
fn write_updates<E: Copy + Eq + Hash + Send + Sync, W: WorldRefType<E>>(
component_kinds: &ComponentKinds,
now: &Instant,
writer: &mut BitWriter,
packet_index: &PacketIndex,
world: &W,
converter: &dyn EntityAndGlobalEntityConverter<E>,
global_world_manager: &dyn GlobalWorldManagerType,
world_manager: &mut LocalWorldManager,
has_written: &mut bool,
next_send_updates: &mut HashMap<GlobalEntity, HashSet<ComponentKind>>,
entity_priority_order: Option<&[GlobalEntity]>,
) {
// When a priority order is supplied, iterate entities in that order
// (filtered to those with pending updates this cycle). This is the
// intra-section k-way merge ordering for priority-sorted entity bundles.
// Without priority guidance we fall back to HashMap iteration order.
let all_update_entities: Vec<GlobalEntity> = match entity_priority_order {
Some(order) => order
.iter()
.copied()
.filter(|e| next_send_updates.contains_key(e))
.collect(),
None => next_send_updates.keys().copied().collect(),
};
for global_entity in all_update_entities {
// get LocalEntity
let local_entity = world_manager
.entity_converter()
.global_entity_to_owned_entity(&global_entity)
.unwrap();
// get World Entity
let world_entity = converter.global_entity_to_entity(&global_entity).unwrap();
// check that we can at least write a LocalEntity and a ComponentContinue bit
let mut counter = writer.counter();
// reserve ComponentContinue bit
counter.write_bit(true);
// write UpdateContinue bit
counter.write_bit(true);
// write LocalEntity
local_entity.ser(&mut counter);
if counter.overflowed() {
break;
}
// reserve ComponentContinue bit
writer.reserve_bits(1);
// write UpdateContinue bit
true.ser(writer);
// write LocalEntity
local_entity.ser(writer);
// for component_kind in next_send_updates.get(&global_entity).unwrap() {
// info!("Writing update for global_entity: {:?}, local_entity {:?}, component kind {:?}", global_entity, local_entity, component_kinds.kind_to_name(component_kind));
// }
// write Components
Self::write_update(
component_kinds,
now,
world,
global_world_manager,
world_manager,
packet_index,
writer,
&global_entity,
&world_entity,
has_written,
next_send_updates,
);
// write ComponentContinue finish bit, release
writer.release_bits(1);
false.ser(writer);
}
// write EntityContinue finish bit, release
writer.release_bits(1);
false.ser(writer);
}
/// For a given entity, write component value updates into a packet
/// Only component values that changed in the internal (naia's) host world will be written
#[allow(clippy::too_many_arguments)]
fn write_update<E: Copy + Eq + Hash + Send + Sync, W: WorldRefType<E>>(
component_kinds: &ComponentKinds,
now: &Instant,
world: &W,
global_world_manager: &dyn GlobalWorldManagerType,
world_manager: &mut LocalWorldManager,
packet_index: &PacketIndex,
writer: &mut BitWriter,
global_entity: &GlobalEntity,
world_entity: &E,
has_written: &mut bool,
next_send_updates: &mut HashMap<GlobalEntity, HashSet<ComponentKind>>,
) {
let mut written_component_kinds = Vec::new();
let component_kind_set = next_send_updates.get(global_entity).unwrap();
for component_kind in component_kind_set {
// get diff mask
let diff_mask = world_manager.get_diff_mask(global_entity, component_kind);
let mut converter = world_manager.entity_converter_mut(global_world_manager);
// check that we can write the next component update
let mut counter = writer.counter();
// write ComponentContinue bit
true.ser(&mut counter);
// write component kind (variable-length encoding — count the
// actual bits this kind will take rather than a const upper
// bound)
component_kind.ser(component_kinds, &mut counter);
// write data
world
.component_of_kind(world_entity, component_kind)
.expect("Component does not exist in World")
.write_update(&diff_mask, &mut counter, &mut converter);
if counter.overflowed() {
// if nothing useful has been written in this packet yet,
// send warning about size of component being too big
if !*has_written {
let component_name = component_kinds.kind_to_name(component_kind);
Self::warn_overflow_update(
component_name,
counter.bits_needed(),
writer.bits_free(),
);
}
break;
}
*has_written = true;
// write ComponentContinue bit
true.ser(writer);
// write component kind
component_kind.ser(component_kinds, writer);
// write data
world
.component_of_kind(world_entity, component_kind)
.expect("Component does not exist in World")
.write_update(&diff_mask, writer, &mut converter);
written_component_kinds.push(*component_kind);
world_manager.record_update(
now,
packet_index,
global_entity,
component_kind,
diff_mask,
);
}
let update_kinds = next_send_updates.get_mut(global_entity).unwrap();
for component_kind in &written_component_kinds {
update_kinds.remove(component_kind);
}
if update_kinds.is_empty() {
next_send_updates.remove(global_entity);
}
}
fn warn_overflow_update(component_name: String, bits_needed: u32, bits_free: u32) {
panic!(
"Packet Write Error: Blocking overflow detected! Data update of Component `{component_name}` requires {bits_needed} bits, but packet only has {bits_free} bits available! Recommended to slim down this Component"
)
}
}