Repository navigation
Expand file tree
/
Copy pathserver_game.cpp
More file actions
1153 lines (1060 loc) · 46.1 KB
/
Copy pathserver_game.cpp
File metadata and controls
1153 lines (1060 loc) · 46.1 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
#include "game/server/server_game.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <limits>
#include <utility>
#include "engine/core/log.h"
#include "game/shared/hitscan.h"
#include "game/shared/rng.h"
namespace game {
namespace {
constexpr int kMaxInputPacketsPerSecond = 200;
constexpr int kMaxBadMessages = 10;
// One message per 45 ticks (0.75 s). Slow enough that nobody can flood a
// lobby, fast enough that a real conversation never hits it.
constexpr std::uint32_t kChatCooldownTicks = 45;
constexpr int kStarvationJumpTicks = 6;
// One shot reports one zone, but a shotgun's pellets can land in several.
// Head beats body beats limb, so a spray that catches a head still reads as
// a headshot -- which is what the shooter saw and what the damage reflects.
int zone_rank(HitZone zone) {
switch (zone) {
case HitZone::Head:
return 2;
case HitZone::Torso:
return 1;
case HitZone::Arm:
case HitZone::Leg:
break;
}
return 0;
}
template <typename Message>
std::vector<std::uint8_t> encode(const Message& message) {
eng::ByteWriter writer;
write(writer, message);
return {writer.data().begin(), writer.data().end()};
}
} // namespace
ServerGame::ServerGame(std::vector<std::pair<eng::MeshData, glm::mat4>> map_meshes,
std::vector<glm::vec3> spawns, std::string map_name, Arsenal arsenal)
: spawns_(std::move(spawns)), map_name_(std::move(map_name)), arsenal_(std::move(arsenal)) {
for (const auto& [mesh, transform] : map_meshes) {
world_.add_static_mesh(mesh, transform);
}
world_.optimize();
if (spawns_.empty()) {
spawns_.push_back({0.0f, 1.0f, 0.0f});
}
if (arsenal_.empty()) {
arsenal_.weapons.push_back(WeaponConfig{}); // built-in rifle fallback
}
eng::log::info("ServerGame: {} static bodies, {} spawns, {} weapons, map '{}'",
world_.body_count(), spawns_.size(), arsenal_.size(), map_name_);
}
std::size_t ServerGame::player_count() const {
std::size_t count = 0;
for (const auto& player : players_) {
if (player) {
++count;
}
}
return count;
}
std::optional<std::uint8_t> ServerGame::find_player_by_peer(std::uint32_t peer) const {
for (std::uint8_t i = 0; i < kMaxPlayers; ++i) {
if (players_[i] && players_[i]->peer == peer) {
return i;
}
}
return std::nullopt;
}
void ServerGame::handle_event(const eng::NetEvent& event, eng::IServerTransport& net) {
switch (event.type) {
case eng::NetEvent::Type::Connected:
eng::log::info("Peer {} connected (awaiting hello)", event.peer);
break;
case eng::NetEvent::Type::Disconnected: {
if (const auto id = find_player_by_peer(event.peer)) {
eng::log::info("Player {} '{}' disconnected", *id, players_[*id]->name);
drop_player(*id, net);
}
break;
}
case eng::NetEvent::Type::Message: {
eng::ByteReader reader{{event.data.data(), event.data.size()}};
const auto type = read_message_type(reader);
const auto player_id = find_player_by_peer(event.peer);
if (!type) {
if (player_id) {
if (++players_[*player_id]->bad_messages > kMaxBadMessages) {
eng::log::warn("Player {}: too many bad messages, kicking", *player_id);
net.disconnect(event.peer);
}
}
return;
}
if (*type == MessageType::ClientHello) {
handle_hello(event.peer, reader, net);
} else if (*type == MessageType::Input && player_id) {
handle_input(*players_[*player_id], reader, net);
} else if (*type == MessageType::ChatSend && player_id) {
handle_chat(*player_id, reader, net);
}
// Anything else from a client is ignored (and counted).
break;
}
}
}
void ServerGame::handle_hello(std::uint32_t peer, eng::ByteReader& reader,
eng::IServerTransport& net) {
const auto hello = read_client_hello(reader);
if (!hello) {
eng::log::warn("Peer {}: invalid hello (version/name), rejecting", peer);
const auto reject = encode(ServerReject{RejectReason::VersionMismatch});
net.send(peer, reject, eng::NetChannel::Reliable, true);
net.disconnect(peer);
return;
}
if (find_player_by_peer(peer)) {
return; // duplicate hello; ignore
}
std::optional<std::uint8_t> slot;
for (std::uint8_t i = 0; i < kMaxPlayers; ++i) {
if (!players_[i]) {
slot = i;
break;
}
}
if (!slot) {
const auto reject = encode(ServerReject{RejectReason::ServerFull});
net.send(peer, reject, eng::NetChannel::Reliable, true);
net.disconnect(peer);
return;
}
Player player;
player.peer = peer;
player.name = hello->name;
player.team = assign_team();
const glm::vec3 spawn = pick_spawn(player.team);
player.state.position = spawn;
player.controller = std::make_unique<eng::CharacterController>(world_, spawn);
reset_loadout(player.loadout, arsenal_);
players_[*slot] = std::move(player);
recorder_.add_player(*slot, hello->name, spawn);
eng::log::info("Player {} '{}' joined (peer {})", *slot, hello->name, peer);
// Welcome the new player.
ServerWelcome welcome;
welcome.player_id = *slot;
welcome.server_tick = tick_;
welcome.map = map_name_;
welcome.team = players_[*slot]->team;
net.send(peer, encode(welcome), eng::NetChannel::Reliable, true);
send_leaderboard(peer, net);
// Tell them about everyone already here, and everyone about them.
for (std::uint8_t i = 0; i < kMaxPlayers; ++i) {
if (players_[i] && i != *slot) {
net.send(peer, encode(PlayerJoined{i, players_[i]->name, players_[i]->team}),
eng::NetChannel::Reliable, true);
}
}
const auto joined = encode(PlayerJoined{*slot, hello->name, players_[*slot]->team});
for (std::uint8_t i = 0; i < kMaxPlayers; ++i) {
if (players_[i] && i != *slot && !players_[i]->is_bot) {
net.send(players_[i]->peer, joined, eng::NetChannel::Reliable, true);
}
}
// Bring the newcomer up to date: match state, all scores, their weapon.
net.send(peer, encode(match_state()), eng::NetChannel::Reliable, true);
for (std::uint8_t i = 0; i < kMaxPlayers; ++i) {
if (players_[i]) {
net.send(peer, encode(ScoreUpdateMsg{i, players_[i]->kills, players_[i]->deaths}),
eng::NetChannel::Reliable, true);
}
}
send_weapon_status(*players_[*slot], net);
}
// Relays one player's chat to everyone, INCLUDING the sender -- seeing your
// own line appear is how you know it was delivered rather than dropped.
//
// Bots never reach here: they have no peer and no inbound messages at all.
void ServerGame::handle_chat(std::uint8_t sender, eng::ByteReader& reader,
eng::IServerTransport& net) {
Player& player = *players_[sender];
const auto message = read_chat_send(reader);
if (!message) {
if (++player.bad_messages > kMaxBadMessages) {
eng::log::warn("Player {}: too many bad messages, kicking", sender);
net.disconnect(player.peer);
}
return;
}
// Rate limit BEFORE sanitizing: the cost of a dropped message should not
// depend on how long it was.
if (player.has_chatted && tick_ - player.last_chat_tick < kChatCooldownTicks) {
return;
}
// The client sanitizes too, for its own echo. This is the copy that
// matters: the client is not the only thing that can send a ChatSend.
const std::string text = sanitize_chat(message->text);
if (text.empty()) {
return; // nothing printable survived; not worth a line in the log
}
player.has_chatted = true;
player.last_chat_tick = tick_;
eng::log::info("[chat] {}: {}", player.name, text);
eng::ByteWriter writer;
write(writer, ChatMessageMsg{sender, text});
const std::vector<std::uint8_t> bytes{writer.data().begin(), writer.data().end()};
for (std::size_t id = 0; id < players_.size(); ++id) {
if (players_[id] && !players_[id]->is_bot) {
net.send(players_[id]->peer, bytes, eng::NetChannel::Reliable, true);
}
}
}
void ServerGame::handle_input(Player& player, eng::ByteReader& reader, eng::IServerTransport& net) {
if (++player.input_packets_this_second > kMaxInputPacketsPerSecond) {
eng::log::warn("Player '{}': input rate limit exceeded, kicking", player.name);
net.disconnect(player.peer);
return;
}
const auto packet = read_input_packet(reader);
if (!packet) {
if (++player.bad_messages > kMaxBadMessages) {
eng::log::warn("Player '{}': too many malformed inputs, kicking", player.name);
net.disconnect(player.peer);
}
return;
}
// Reject inputs absurdly far ahead of what we've processed.
if (packet->newest_sequence > player.last_processed_input + kMaxInputAhead) {
return;
}
for (const InputCommand& command : packet->commands) {
if (command.sequence > player.last_processed_input &&
!player.pending.contains(command.sequence)) {
player.pending.emplace(command.sequence, command);
}
}
// Newest claimed view tick for lag compensation (monotonic; clamped
// again into the legal rewind window at fire time).
if (packet->view_tick > player.view_tick) {
player.view_tick = packet->view_tick;
}
}
bool ServerGame::add_bot(std::string name) {
std::optional<std::uint8_t> slot;
for (std::uint8_t i = 0; i < kMaxPlayers; ++i) {
if (!players_[i]) {
slot = i;
break;
}
}
if (!slot) {
eng::log::warn("Cannot add bot '{}': server full", name);
return false;
}
Player player;
player.peer = 0; // never used: send() is skipped for bots
player.is_bot = true;
player.name = std::move(name);
player.team = assign_team();
const glm::vec3 spawn = pick_spawn(player.team);
player.state.position = spawn;
player.controller = std::make_unique<eng::CharacterController>(world_, spawn);
reset_loadout(player.loadout, arsenal_);
players_[*slot] = std::move(player);
recorder_.add_player(*slot, players_[*slot]->name, spawn);
eng::log::info("Bot {} '{}' added", *slot, players_[*slot]->name);
return true;
}
// Gathers what a bot can perceive: the nearest living enemy, whether it has
// line of sight, and how much room is ahead. Kept here rather than in
// decide() so the decision layer stays pure and testable.
BotSenses ServerGame::sense_for_bot(std::uint8_t bot_id) const {
const Player& bot = *players_[bot_id];
BotSenses senses;
senses.position = bot.state.position;
senses.yaw = bot.view_yaw;
senses.on_ground = bot.state.on_ground;
// Without this a bot pulls a pin it does not have: decide() would commit
// to a throw, hold the button, and wait forever for a grenade the server
// already refused to give it.
senses.has_grenade = bot.grenades > 0 && !bot.cooking;
const glm::vec3 eye = bot.state.position + glm::vec3{0.0f, 1.6f, 0.0f};
// Target selection is a shared rule, not a loop here: see nearest_enemy
// in bot.h for why it had to leave this function.
std::array<BotTarget, kMaxPlayers> candidates{};
for (std::uint8_t id = 0; id < kMaxPlayers; ++id) {
if (id == bot_id || !players_[id]) {
continue;
}
candidates[id] =
BotTarget{players_[id]->state.position, players_[id]->team, players_[id]->alive};
}
if (const auto target_index = nearest_enemy(bot.state.position, bot.team, candidates)) {
senses.has_target = true;
senses.target_position = candidates[*target_index].position;
// Line of sight: a wall between us closer than the target blocks it.
const glm::vec3 aim = senses.target_position + glm::vec3{0.0f, 1.1f, 0.0f};
const glm::vec3 to_aim = aim - eye;
const float length = glm::length(to_aim);
senses.target_visible = true;
if (length > 0.01f) {
const auto wall = world_.raycast(eye, to_aim / length, length);
senses.target_visible = !wall.has_value();
}
}
const glm::vec3 forward = view_direction(bot.view_yaw, 0.0f);
// Cast from knee height: the floor is not an obstacle, but a crate is.
const glm::vec3 probe = bot.state.position + glm::vec3{0.0f, 0.6f, 0.0f};
if (const auto hit = world_.raycast(probe, forward, 8.0f)) {
senses.forward_clearance = hit->distance;
}
return senses;
}
void ServerGame::start_recording(std::filesystem::path path) {
replay_path_ = std::move(path);
recorder_.begin(map_name_, static_cast<std::uint16_t>(std::lround(1.0f / kTickSeconds)));
eng::log::info("Recording replay to '{}'", replay_path_.string());
}
bool ServerGame::write_replay() const {
if (!recorder_.recording()) {
return true;
}
return write_replay_file(replay_path_, recorder_.replay());
}
void ServerGame::drop_player(std::uint8_t player_id, eng::IServerTransport& net) {
// A match lasts five minutes and a session can end at any point in one,
// so waiting for match end to persist would drop most of what happened.
if (stats_enabled_ && players_[player_id] && !players_[player_id]->is_bot) {
save_stats();
}
players_[player_id].reset();
const auto left = encode(PlayerLeft{player_id});
for (const auto& player : players_) {
if (player && !player->is_bot) {
net.send(player->peer, left, eng::NetChannel::Reliable, true);
}
}
}
void ServerGame::tick(eng::IServerTransport& net) {
++tick_;
update_match(net);
for (std::uint8_t id = 0; id < kMaxPlayers; ++id) {
if (!players_[id]) {
continue;
}
Player& player = *players_[id];
// A bot's command is synthesized; a human's is consumed from the
// network queue. That is the ONLY difference -- everything below runs
// identically for both, so bots exercise the real movement, combat,
// scoring and recording code rather than a parallel imitation of it.
InputCommand command = player.last_command;
if (player.is_bot) {
const BotSenses senses = sense_for_bot(id);
command = decide(player.bot_state, senses, bot_config_, kTickSeconds,
hash_combine(tick_, id));
command.sequence = ++player.last_processed_input;
} else {
// Consume exactly one input per tick, in order. When starved
// (loss or jitter), reuse the last command briefly, then
// fast-forward. Inputs are consumed even while dead so sequence
// acks keep flowing.
const auto next = player.pending.find(player.last_processed_input + 1);
if (next != player.pending.end()) {
command = next->second;
player.pending.erase(next);
player.last_processed_input = command.sequence;
player.starved_ticks = 0;
} else if (!player.pending.empty() && ++player.starved_ticks >= kStarvationJumpTicks) {
const auto first = player.pending.begin();
command = first->second;
player.last_processed_input = first->first;
player.pending.erase(first);
player.starved_ticks = 0;
}
}
player.last_command = command;
// Recorded here, at the point of consumption. Recording arriving
// packets instead would miss the starvation path above, where the
// server reuses the previous command -- and a replay that skipped
// those ticks would diverge.
recorder_.record(tick_, id, command);
player.view_yaw = command.yaw;
player.view_pitch = command.pitch;
if (!player.alive) {
player.respawn_remaining -= kTickSeconds;
if (player.respawn_remaining <= 0.0f) {
respawn_player(id, net);
}
continue;
}
advance_player(player.state, command, kTickSeconds, *player.controller, world_);
player.history.push(tick_, player.state.position);
// At the snapshot rate, not the tick rate: 60 Hz would triple the
// message for motion nobody can see at playback speed.
if (tick_ % kKillCamTickStride == 0) {
player.trail.push(
ViewSample{player.state.position, player.view_yaw, player.view_pitch});
}
// Fell out of the world: counts as an environment death.
if (player.state.position.y < -20.0f) {
kill_player(id, kNoPlayer, net);
continue;
}
// Weapon: entirely authoritative. Fire rate, ammo, and reload come
// from the deterministic shared state machine; a cheating client
// holding Fire every tick still fires at exactly the configured RPM.
if (phase_ == MatchPhase::Playing) {
const bool fire_held = has_button(command, Button::Fire);
const bool reload = has_button(command, Button::Reload);
// The server runs the SAME sights transition the client predicts,
// from the same button and the same sprint state, because the
// cone it rolls below depends on it. Trusting a client-reported
// aim flag would be trusting a client-reported spread.
update_grenade_button(id, command, net);
const bool aim = wants_ads(command, player.state.sprinting);
const WeaponTickResult shot =
update_loadout(player.loadout, arsenal_, command.weapon_slot, fire_held, reload,
kTickSeconds, aim);
if (shot.fired) {
fire_hitscan(id, command, net);
}
if (shot.fired || shot.reload_started || shot.reload_finished || shot.switched) {
send_weapon_status(player, net);
}
}
}
step_grenades(net);
// Reset per-second rate counters.
if (tick_ % 60 == 0) {
for (auto& slot : players_) {
if (slot) {
slot->input_packets_this_second = 0;
}
}
}
if (tick_ % kSnapshotDivisor == 0) {
send_snapshots(net);
}
}
void ServerGame::send_snapshots(eng::IServerTransport& net) {
// Grenades ride the snapshot CADENCE but not the snapshot itself: a
// snapshot is per-player state the client reconciles its own prediction
// against, and a grenade belongs to nobody. Same channel and same rate,
// separate message, so neither has to grow a variable-length list of the
// other's business.
//
// Sent even when empty is deliberately NOT done -- a client that hears
// nothing keeps drawing the last positions for at most one interval, and
// an explosion message removes them anyway.
if (!grenades_.empty()) {
GrenadeStateMsg live;
live.grenades.reserve(grenades_.size());
for (const GrenadeState& g : grenades_) {
live.grenades.push_back({g.id, g.thrower, g.position});
}
const auto bytes = encode(live);
for (const auto& slot : players_) {
if (slot && !slot->is_bot) {
net.send(slot->peer, bytes, eng::NetChannel::Sequenced, false);
}
}
}
// Shared player list; per-recipient last_processed_input header.
std::vector<SnapshotPlayer> everyone;
for (std::uint8_t i = 0; i < kMaxPlayers; ++i) {
if (!players_[i]) {
continue;
}
const Player& p = *players_[i];
SnapshotPlayer sp;
sp.player_id = i;
sp.position = p.state.position;
sp.velocity = p.state.velocity;
sp.yaw = p.view_yaw;
sp.pitch = p.view_pitch;
sp.flags = (p.state.on_ground ? kFlagOnGround : 0u) | (p.alive ? kFlagAlive : 0u) |
(p.state.crouching ? kFlagCrouching : 0u) |
(p.team == Team::B ? kFlagTeamB : 0u);
everyone.push_back(sp);
}
for (const auto& slot : players_) {
if (!slot || slot->is_bot) {
continue; // nothing to send a snapshot to
}
Snapshot snapshot;
snapshot.server_tick = tick_;
snapshot.last_processed_input = slot->last_processed_input;
snapshot.players = everyone;
net.send(slot->peer, encode(snapshot), eng::NetChannel::Sequenced, false);
}
}
// --- combat -----------------------------------------------------------------
void ServerGame::broadcast_reliable(const std::vector<std::uint8_t>& data,
eng::IServerTransport& net) {
for (const auto& player : players_) {
if (player && !player->is_bot) {
net.send(player->peer, data, eng::NetChannel::Reliable, true);
}
}
}
void ServerGame::send_weapon_status(const Player& player, eng::IServerTransport& net) {
if (player.is_bot) {
return;
}
const WeaponState& weapon = player.loadout.weapons[player.loadout.slot];
const WeaponConfig& config = arsenal_.at(player.loadout.slot);
net.send(player.peer,
encode(WeaponStatusMsg{
static_cast<std::uint8_t>(weapon.ammo), weapon.reloading(), player.loadout.slot,
static_cast<std::uint8_t>(config.magazine_size),
player.loadout.switch_remaining_seconds > 0.0f, player.grenades, player.cooking}),
eng::NetChannel::Reliable, true);
}
void ServerGame::set_stats_path(std::filesystem::path path) {
stats_ = StatsStore::open(std::move(path));
stats_enabled_ = true;
}
void ServerGame::save_stats() const {
if (stats_enabled_) {
stats_.save(); // failures are logged by the store, and are not fatal
}
}
LeaderboardMsg ServerGame::leaderboard() const {
LeaderboardMsg message;
for (const PlayerRecord& record : stats_.top(kLeaderboardSize)) {
message.entries.push_back({record.name, record.kills, record.deaths, record.matches});
}
return message;
}
void ServerGame::send_leaderboard(std::uint32_t peer, eng::IServerTransport& net) const {
if (!stats_enabled_) {
return;
}
const LeaderboardMsg message = leaderboard();
if (message.entries.empty()) {
return; // nothing to show on a fresh server
}
net.send(peer, encode(message), eng::NetChannel::Reliable, true);
}
MatchStateMsg ServerGame::match_state() const {
MatchStateMsg m;
m.phase = phase_;
m.seconds_remaining = static_cast<std::uint16_t>(
std::max(0.0f, phase_ == MatchPhase::Playing ? match_remaining_ : restart_remaining_));
m.score_a = team_kills_[static_cast<std::size_t>(Team::A)];
m.score_b = team_kills_[static_cast<std::size_t>(Team::B)];
return m;
}
Team ServerGame::assign_team() const {
int counts[2]{};
for (const auto& slot : players_) {
if (slot) {
++counts[static_cast<std::size_t>(slot->team)];
}
}
// Bots are counted. They are here so the server is never empty, and a
// lone human against four of them is not a team game.
return counts[1] < counts[0] ? Team::B : Team::A;
}
glm::vec3 ServerGame::pick_spawn(Team team) {
// Furthest from the nearest LIVING ENEMY. Not "furthest from everyone":
// spawning next to a teammate is fine and often what you want, and
// measuring against your own side would scatter a team across the map.
float best_score = -1.0f;
const glm::vec3* best = nullptr;
for (const glm::vec3& candidate : spawns_) {
float nearest_enemy = std::numeric_limits<float>::max();
for (const auto& slot : players_) {
if (!slot || !slot->alive || slot->team == team) {
continue;
}
nearest_enemy = std::min(nearest_enemy, glm::distance(candidate, slot->state.position));
}
if (nearest_enemy == std::numeric_limits<float>::max()) {
continue; // no enemy alive to measure against
}
if (nearest_enemy > best_score) {
best_score = nearest_enemy;
best = &candidate;
}
}
if (best != nullptr) {
return *best;
}
// Nobody to avoid. Round-robin, which is exactly what every spawn did
// before teams existed, so a one-team server behaves as it always has.
return spawns_[next_spawn_++ % spawns_.size()];
}
void ServerGame::rebalance_teams() {
// Between matches only. Being teleported onto the other side mid-fight is
// worse than the 3v2 it fixes, so this runs from restart_match and
// nowhere else.
for (;;) {
std::vector<std::uint8_t> members[2];
for (std::uint8_t id = 0; id < kMaxPlayers; ++id) {
if (players_[id]) {
members[static_cast<std::size_t>(players_[id]->team)].push_back(id);
}
}
const std::size_t big = members[0].size() >= members[1].size() ? 0 : 1;
const std::size_t small = 1 - big;
if (members[big].size() <= members[small].size() + 1) {
return; // even, or off by the one a player count of 3 forces
}
// Bots first, so a human is never the one moved while a bot could
// have been. Otherwise the last to join, who has least invested in
// the side they are on.
const auto& pool = members[big];
std::uint8_t move = pool.back();
for (const std::uint8_t id : pool) {
if (players_[id]->is_bot) {
move = id;
break;
}
}
players_[move]->team = static_cast<Team>(small);
eng::log::info("Rebalanced: player {} '{}' -> team {}", move, players_[move]->name,
team_name(players_[move]->team));
}
}
// The pin, and the throw. Both are EDGES of one held button, which is what
// makes cooking a single-button mechanic: press to pull the pin, release to
// throw, and the fuse runs across both.
void ServerGame::update_grenade_button(std::uint8_t player_id, const InputCommand& command,
eng::IServerTransport& net) {
Player& player = *players_[player_id];
const bool held = wants_grenade(command);
if (held && !player.cooking) {
// Pin out. A player with none left presses a button that does nothing,
// which is correct: there is no grenade to pull a pin from.
if (player.grenades == 0 || !player.alive) {
return;
}
--player.grenades;
player.cooking = true;
player.cook_remaining = kGrenadeFuseSeconds;
// The owner is told on BOTH edges. send_weapon_status otherwise only
// fires on a shot, a reload or a switch, so without this the HUD count
// never moved and the pin coming out was invisible -- the one piece of
// feedback the whole mechanic depends on.
send_weapon_status(player, net);
return;
}
if (!held && player.cooking) {
// Released: it leaves the hand with whatever fuse is left. A grenade
// thrown at 0.4 s remaining is a grenade that airbursts, and that is
// the entire point of having cooked it.
const glm::vec3 eye =
player.state.position + glm::vec3{0.0f, eye_height_for(player.state), 0.0f};
const glm::vec3 aim = view_direction(player.view_yaw, player.view_pitch);
GrenadeState g;
g.id = next_grenade_id_++;
if (next_grenade_id_ == 0) {
next_grenade_id_ = 1; // 0 is never a live id
}
g.thrower = player_id;
g.team = player.team;
g.position = eye + aim * kGrenadeThrowOffset;
g.velocity =
grenade_throw_velocity(player.view_yaw, player.view_pitch, player.state.velocity);
g.fuse_remaining = player.cook_remaining;
g.in_hand = false;
grenades_.push_back(g);
player.cooking = false;
player.cook_remaining = 0.0f;
send_weapon_status(player, net);
}
}
// One tick of every grenade in the air, plus the ones that went off.
void ServerGame::step_grenades(eng::IServerTransport& net) {
// A grenade whose thrower is still holding it burns down IN THEIR HAND and
// takes them with it. Handled here rather than in the button edge so a
// player who never releases still gets the blast on the right tick.
for (std::uint8_t id = 0; id < kMaxPlayers; ++id) {
if (!players_[id] || !players_[id]->cooking) {
continue;
}
Player& player = *players_[id];
player.cook_remaining -= kTickSeconds;
if (player.cook_remaining > 0.0f) {
continue;
}
GrenadeState in_hand;
in_hand.id = next_grenade_id_++;
if (next_grenade_id_ == 0) {
next_grenade_id_ = 1;
}
in_hand.thrower = id;
in_hand.team = player.team;
in_hand.position =
player.state.position + glm::vec3{0.0f, eye_height_for(player.state) * 0.6f, 0.0f};
player.cooking = false;
player.cook_remaining = 0.0f;
send_weapon_status(player, net);
detonate(in_hand, net);
}
for (std::size_t i = 0; i < grenades_.size();) {
GrenadeState& g = grenades_[i];
g.fuse_remaining -= kTickSeconds;
g.velocity.y -= kGrenadeGravity * kTickSeconds;
const glm::vec3 step = g.velocity * kTickSeconds;
const float distance = glm::length(step);
if (distance > 1e-5f) {
const glm::vec3 direction = step / distance;
// Raycast rather than a swept sphere: the arena is boxes and a
// 12 cm grenade against a wall does not need more, and this is the
// same primitive lag compensation already trusts.
if (const auto hit = world_.raycast(g.position, direction, distance + kGrenadeRadius)) {
// Land just off the surface, then split the velocity into the
// part that bounces and the part that slides. Without the
// friction term a grenade skates along a floor forever.
g.position =
g.position + direction * std::max(0.0f, hit->distance - kGrenadeRadius);
const glm::vec3 normal = hit->normal;
const glm::vec3 into = normal * glm::dot(g.velocity, normal);
const glm::vec3 along = g.velocity - into;
g.velocity = along * kGrenadeFriction - into * kGrenadeRestitution;
} else {
g.position += step;
}
}
if (g.fuse_remaining <= 0.0f) {
detonate(g, net);
grenades_.erase(grenades_.begin() + static_cast<std::ptrdiff_t>(i));
continue;
}
++i;
}
}
void ServerGame::detonate(const GrenadeState& grenade, eng::IServerTransport& net) {
// Logged for the same reason a kill is: it is a thing that HAPPENED in the
// match, and without a line for it the only way to find out whether
// grenades are being thrown at all is to stand in the arena and watch.
eng::log::info("Grenade {} from player {} detonated at ({:.1f},{:.1f},{:.1f})", grenade.id,
grenade.thrower, grenade.position.x, grenade.position.y, grenade.position.z);
broadcast_reliable(encode(GrenadeExplodedMsg{grenade.id, grenade.thrower, grenade.position}),
net);
for (std::uint8_t id = 0; id < kMaxPlayers; ++id) {
if (!players_[id] || !players_[id]->alive) {
continue;
}
Player& victim = *players_[id];
if (!blast_can_damage(grenade.thrower, grenade.team, id, victim.team)) {
continue;
}
// Measured to the CHEST, not the feet: a blast at head height beside a
// standing player would otherwise be scored from the floor and read as
// a grenade that visibly went off in someone's face for half damage.
const glm::vec3 chest =
victim.state.position + glm::vec3{0.0f, eye_height_for(victim.state) * 0.6f, 0.0f};
const float amount = grenade_damage_at(glm::distance(chest, grenade.position));
if (amount <= 0.0f) {
continue;
}
const bool died = apply_damage(victim.health, amount);
broadcast_reliable(encode(PlayerDamagedMsg{id, grenade.thrower, victim.health.current,
amount, HitZone::Torso}),
net);
if (died) {
kill_player(id, grenade.thrower, net);
}
}
}
void ServerGame::fire_hitscan(std::uint8_t shooter_id, const InputCommand& command,
eng::IServerTransport& net) {
Player& shooter = *players_[shooter_id];
const WeaponConfig& weapon = arsenal_.at(shooter.loadout.slot);
const glm::vec3 eye =
shooter.state.position + glm::vec3{0.0f, eye_height_for(shooter.state), 0.0f};
const glm::vec3 aim = view_direction(command.yaw, command.pitch);
// Lag compensation: test victims where the SHOOTER saw them - their
// positions at the shooter's (bounded) interpolation view tick. A
// hostile view_tick claim can rewind at most kMaxRewindTicks (~250 ms).
const std::uint32_t rewind_tick = clamp_rewind_tick(shooter.view_tick, tick_);
FireEventMsg event;
event.shooter = shooter_id;
event.slot = shooter.loadout.slot;
event.from = eye;
// Damage is accumulated per victim so a shotgun applies one combined hit
// (and can only kill a player once, no matter how many pellets land).
std::array<float, kMaxPlayers> damage_by_victim{};
// The best zone any pellet of this shot reached, per victim.
std::array<HitZone, kMaxPlayers> zone_by_victim{};
std::array<bool, kMaxPlayers> hit_any{};
// The cone the shooter had raised at the moment of the shot, not the
// weapon's hip-fire cone. This is the authoritative half of ADS.
const float spread =
glm::radians(effective_spread_degrees(weapon, shooter.loadout.ads_fraction));
for (int pellet = 0; pellet < weapon.pellets; ++pellet) {
// Deterministic per-pellet spread: a pure hash of tick, shooter and
// pellet index, so a recorded match replays identically (M17).
const std::uint32_t seed =
hash_combine(hash_combine(tick_, shooter_id), static_cast<std::uint32_t>(pellet));
const glm::vec3 dir = spread_direction(aim, spread, seed);
// World geometry bounds each pellet.
float max_t = weapon.range;
if (const auto wall = world_.raycast(eye, dir, weapon.range)) {
max_t = wall->distance;
}
std::uint8_t hit_id = kNoPlayer;
float hit_t = max_t;
// The capsule that won, kept so the impact point can be turned into a
// hit zone below. Recomputing it from players_[hit_id] afterwards
// would silently use the player's CURRENT position rather than the
// rewound one the ray was actually tested against.
glm::vec3 hit_feet{0.0f};
float hit_radius = 0.0f;
float hit_height = 0.0f;
for (std::uint8_t id = 0; id < kMaxPlayers; ++id) {
if (id == shooter_id || !players_[id] || !players_[id]->alive) {
continue;
}
// Friendly fire is OFF, and off at the RAY rather than at the
// damage: a teammate must not stop a bullet either, or a team
// would spend the match blocking each other's shots and calling
// it lag. A pellet passes through a teammate and can still hit
// the enemy behind them.
if (players_[id]->team == shooter.team) {
continue;
}
const glm::vec3 victim_position =
players_[id]->history.at(rewind_tick).value_or(players_[id]->state.position);
// Crouched players present a shorter capsule to shoot at.
const auto& config = players_[id]->controller->config();
const float height =
players_[id]->state.crouching ? config.crouch_height : config.height;
const auto t = ray_vertical_capsule(eye, dir, victim_position, config.radius, height);
if (t && *t < hit_t) {
hit_t = *t;
hit_id = id;
hit_feet = victim_position;
hit_radius = config.radius;
hit_height = height;
}
}
const glm::vec3 impact = eye + dir * hit_t;
event.rays.push_back(FireRay{impact, hit_id});
if (hit_id != kNoPlayer) {
const HitZone zone =
classify_hit_zone(impact, eye, dir, hit_feet, hit_radius, hit_height);
// Falloff first, then the zone multiplier: a head shot doubles
// whatever the range left of the bullet, rather than doubling the
// muzzle damage and then attenuating it. Per pellet at that
// pellet's OWN distance, which is the whole point for a shotgun.
damage_by_victim[hit_id] +=
damage_at_distance(weapon, hit_t) * zone_damage_multiplier(weapon, zone);
// First pellet to reach this victim sets the zone outright; later
// ones only raise it. Without the `!hit_any` term the array's
// value-initialised Torso would outrank a limb, and every leg
// shot would be reported to the client as a body shot.
if (!hit_any[hit_id] || zone_rank(zone) > zone_rank(zone_by_victim[hit_id])) {
zone_by_victim[hit_id] = zone;
}
hit_any[hit_id] = true;
}
}
if (rewind_tick != tick_) {
eng::log::debug("lag comp: shot resolved {} ticks in the past", tick_ - rewind_tick);
}
broadcast_reliable(encode(event), net);
for (std::uint8_t id = 0; id < kMaxPlayers; ++id) {
if (damage_by_victim[id] <= 0.0f || !players_[id]) {
continue;
}
Player& victim = *players_[id];
const bool died = apply_damage(victim.health, damage_by_victim[id]);
broadcast_reliable(encode(PlayerDamagedMsg{id, shooter_id, victim.health.current,
damage_by_victim[id], zone_by_victim[id]}),
net);
if (died) {
kill_player(id, shooter_id, net);
}
}
}
void ServerGame::kill_player(std::uint8_t victim_id, std::uint8_t killer_id,
eng::IServerTransport& net) {
Player& victim = *players_[victim_id];
victim.alive = false;
victim.health.current = 0.0f;
// Shot while cooking: the pin goes with them. A corpse that detonates
// seconds later kills whoever won the fight, from nowhere they can see,
// and reads as a bug however defensible the physics is.
victim.cooking = false;
victim.cook_remaining = 0.0f;
victim.respawn_remaining = kRespawnSeconds;
victim.state.velocity = {0.0f, 0.0f, 0.0f};
++victim.deaths;
if (killer_id != kNoPlayer && players_[killer_id]) {
++players_[killer_id]->kills;
++team_kills_[static_cast<std::size_t>(players_[killer_id]->team)];
broadcast_reliable(encode(ScoreUpdateMsg{killer_id, players_[killer_id]->kills,
players_[killer_id]->deaths}),
net);
}
// Bots are excluded on purpose. They exist so the server is never empty,
// and a career table topped by `bot3` says nothing about anyone.
if (stats_enabled_) {
if (!victim.is_bot) {
stats_.record_death(victim.name);
}
if (killer_id != kNoPlayer && players_[killer_id] && !players_[killer_id]->is_bot) {
stats_.record_kill(players_[killer_id]->name);
}
}
// Unicast to the victim before the death broadcast, so it has arrived by
// the time their client puts up the death overlay. Skipped for bots (they
// have no peer) and for deaths with no killer -- falling out of the world
// has no viewpoint worth showing.
if (!victim.is_bot && killer_id != kNoPlayer && players_[killer_id]) {
KillCamMsg cam;
cam.killer = killer_id;
cam.samples = players_[killer_id]->trail.recent(kKillCamSamples);
if (!cam.samples.empty()) {
net.send(victim.peer, encode(cam), eng::NetChannel::Reliable, true);