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
|
#include "client.hh"
namespace {
std::queue<proto::chunk> received_chunks;
} // namespace
namespace client {
static shared::net::connection make_connection(const std::string_view address,
const std::string_view port) {
constexpr addrinfo hints = {.ai_flags = AI_PASSIVE,
.ai_family = AF_INET,
.ai_socktype = SOCK_STREAM};
const auto info = shared::net::get_addr_info(address, port, &hints);
const auto sock = shared::net::make_socket(info.get());
shared::net::connect_socket(sock, info.get());
return shared::net::connection(sock);
}
static proto::packet
make_request_chunk_packet(const shared::math::coords& coords) noexcept {
proto::packet packet;
const auto chunk_packet = packet.mutable_request_chunk_packet();
shared::net::set_coords(chunk_packet->mutable_chunk_pos(), coords);
return packet;
}
static proto::packet make_auth_packet(const std::string& username,
const std::string& password) noexcept {
proto::packet packet;
const auto auth_packet = packet.mutable_auth_packet();
auth_packet->set_username(username);
auth_packet->set_password(password);
return packet;
}
static proto::packet
make_add_block_packet(const shared::math::coords& coords, const glm::ivec3& pos,
const std::uint32_t& active) noexcept {
proto::packet packet;
const auto add_block_packet = packet.mutable_add_block_packet();
shared::net::set_coords(add_block_packet->mutable_chunk_pos(), coords);
shared::net::set_ivec3(add_block_packet->mutable_block_pos(), pos);
add_block_packet->set_active_item(active);
return packet;
}
static proto::packet
make_remove_block_packet(const shared::math::coords& coords,
const glm::ivec3& pos) noexcept {
proto::packet packet;
const auto remove_block_packet = packet.mutable_remove_block_packet();
shared::net::set_coords(remove_block_packet->mutable_chunk_pos(), coords);
shared::net::set_ivec3(remove_block_packet->mutable_block_pos(), pos);
return packet;
}
[[maybe_unused]] // [[actually_used]]
static proto::packet
make_remove_chunk_packet(const shared::math::coords& coords) noexcept {
proto::packet packet;
const auto remove_chunk_packet = packet.mutable_remove_chunk_packet();
shared::net::set_coords(remove_chunk_packet->mutable_chunk_pos(), coords);
return packet;
}
static proto::packet
make_move_packet(const client::moveable& localplayer) noexcept {
proto::packet packet;
const auto move_packet = packet.mutable_move_packet();
move_packet->set_commands(localplayer.get_commands());
shared::net::set_angles(move_packet->mutable_viewangles(),
localplayer.get_angles());
move_packet->set_active_item(localplayer.get_active_item());
move_packet->set_sequence(localplayer.get_latest_sequence());
return packet;
}
static void handle_init_packet(const proto::init& packet) noexcept {
// Draw distance is the std::min, but we make it more verbose.
if (const auto& wanted = state::draw_distance =
settings::get({"video", "draw_distance"}, 32);
wanted != packet.draw_distance()) {
if (wanted < packet.draw_distance()) {
state::draw_distance = wanted;
} else {
shared::print::warn << shared::print::time
<< "client: server supported draw_distance ("
<< packet.draw_distance()
<< ") less than requested (" << wanted << ")\n";
state::draw_distance = packet.draw_distance();
}
}
state::seed = packet.seed();
state::tickrate = packet.tickrate();
state::tick = packet.tick();
state::delta_ticks = 0.0f; // amount of time passed (in ticks)
const auto& localplayer = packet.localplayer();
const auto& index = localplayer.animate().entity().index();
state::localplayer_index = index;
state::entities.emplace(index, std::make_unique<player>(localplayer));
}
static void
handle_animate_update_packet(const proto::animate_update& packet) noexcept {
const auto& animate = packet.animate();
const auto& index = animate.entity().index();
const auto entity_it = get_entity_it(index);
if (entity_it == std::end(state::entities)) {
state::entities.emplace(index, std::make_unique<player>(animate));
return;
}
const auto animate_ptr = dynamic_cast<class animate*>(&*entity_it->second);
if (animate_ptr == nullptr) {
return;
}
const shared::tick_t tick = packet.tick();
// Localplayer updates time factor and is update is called with the sequence
// number instead of the tick.
if (packet.has_sequence()) {
const shared::tick_t sequence = packet.sequence();
animate_ptr->update_time_factor(sequence, tick);
animate_ptr->notify(animate, sequence, true);
return;
}
animate_ptr->notify(animate, tick, true);
}
// Remove the client whose element is equal to pkt.index.
static void
handle_remove_entity_packet(const proto::remove_entity& packet) noexcept {
const auto entity_it = get_entity_it(packet.index());
if (entity_it == std::end(state::entities)) {
return;
}
state::entities.erase(entity_it);
}
static void handle_hear_packet(const proto::hear_player& packet) noexcept {
const auto entity_it = get_entity_it(packet.index());
if (entity_it == std::end(state::entities)) {
return;
}
const auto player_ptr = dynamic_cast<player*>(&*entity_it->second);
if (player_ptr == nullptr) {
return;
}
player_ptr->message.emplace(packet.text());
}
static void handle_chunk_packet(proto::chunk& packet) noexcept {
// Ratelimited parsing, moved into a vector.
::received_chunks.push(std::move(packet));
}
static void
handle_server_message_packet(const proto::server_message& packet) noexcept {
const bool fatal = packet.fatal();
const std::string message =
"client: received " + std::string{fatal ? "fatal" : ""} +
" message from the server \"" + packet.message() + "\"\n";
if (!fatal) {
shared::print::notify << shared::print::time << message;
return;
}
shared::print::warn << shared::print::time << message;
shared::should_exit = true;
}
static void parse_packet(proto::packet&& packet) noexcept {
if (packet.has_init_packet()) {
handle_init_packet(packet.init_packet());
} else if (packet.has_animate_update_packet()) {
handle_animate_update_packet(packet.animate_update_packet());
} else if (packet.has_remove_entity_packet()) {
handle_remove_entity_packet(packet.remove_entity_packet());
} else if (packet.has_hear_player_packet()) {
handle_hear_packet(packet.hear_player_packet());
} else if (packet.has_chunk_packet()) {
handle_chunk_packet(*packet.mutable_chunk_packet());
} else if (packet.has_server_message_packet()) {
handle_server_message_packet(packet.server_message_packet());
}
#ifndef NDEBUG
else {
shared::print::warn << shared::print::time
<< "client: unhandled packet type\n";
}
#endif
}
static void regenerate_surrounding_chunks(const shared::math::coords& pos) {
// Force the surrounding chunks to regenerate their vbos.
// It's possible we could only generate the ones that we actually need
// to generate, but that's not really a priority atm.
for (auto x = -1; x <= 1; ++x) {
for (auto z = -1; z <= 1; ++z) {
if (std::abs(x) == 1 && std::abs(z) == 1) {
continue;
}
const auto find_update_it =
state::chunks.find(pos + shared::math::coords{x, z});
if (find_update_it == std::end(state::chunks)) {
continue;
}
if (!find_update_it->second.has_value()) {
continue;
}
find_update_it->second->should_regenerate_vbo = true;
}
}
}
static void parse_new_chunks() {
// Add new chunks. We have to ratelimit these because the server responds
// so quickly that our frametime dives as it parses these new chunk packets.
constexpr int CHUNKS_PER_FRAME = 1;
for (int i = 0; i < CHUNKS_PER_FRAME && !::received_chunks.empty();
++i, ::received_chunks.pop()) {
const proto::chunk& packet = ::received_chunks.front();
const shared::math::coords pos{packet.chunk_pos().x(),
packet.chunk_pos().z()};
const auto find_it = state::chunks.find(pos);
if (find_it == std::end(state::chunks)) {
continue;
}
find_it->second.emplace(state::seed, packet);
regenerate_surrounding_chunks(pos);
}
}
static void erase_bad_chunks(const shared::math::coords& lp_pos) {
const auto draw_distance = state::draw_distance;
std::erase_if(state::chunks, [&](const auto& chunk) {
const bool should_erase = !shared::math::coords::is_inside_draw(
chunk.first, lp_pos, draw_distance);
if (should_erase) {
state::connection->rsend_packet(
make_remove_chunk_packet(chunk.first));
}
return should_erase;
});
}
static void request_new_chunks(const shared::math::coords& lp_pos) {
for (int dist = 0; dist <= state::draw_distance; ++dist) {
const auto draw_distance = state::draw_distance;
const auto maybe_add_chunk = [&](const int x, const int z) -> bool {
const auto pos = shared::math::coords{x + lp_pos.x, z + lp_pos.z};
if (!shared::math::coords::is_inside_draw(pos, lp_pos,
draw_distance)) {
return false;
}
if (state::chunks.contains(pos)) {
return false;
}
state::connection->rsend_packet(make_request_chunk_packet(pos));
state::chunks.emplace(pos, std::nullopt);
return true;
};
int x = -dist;
int z = dist;
for (int i = 0; i < dist * 2 + 1; ++i) {
if (maybe_add_chunk(x, z)) {
return;
}
x += (i < dist * 2);
}
for (int i = 0; i < dist * 2; ++i) {
--z;
if (maybe_add_chunk(x, z)) {
return;
}
}
for (int i = 0; i < dist * 2; ++i) {
--x;
if (maybe_add_chunk(x, z)) {
return;
}
}
for (int i = 0; i < dist * 2 - 1; ++i) {
++z;
if (maybe_add_chunk(x, z)) {
return;
}
}
}
}
static void update_chunks() {
parse_new_chunks();
const shared::math::coords& lp_pos = get_localplayer().get_chunk_pos();
erase_bad_chunks(lp_pos);
request_new_chunks(lp_pos);
}
static void handle_button_input() noexcept {
// Don't build our movement commands if we're inputting text.
if (input::state.typing) {
return;
}
using spm = shared::player::mask;
auto& commands = get_localplayer().get_mutable_commands();
commands |= spm::forward * input::is_key_pressed(SDLK_w);
commands |= spm::left * input::is_key_pressed(SDLK_a);
commands |= spm::backward * input::is_key_pressed(SDLK_s);
commands |= spm::right * input::is_key_pressed(SDLK_d);
commands |= spm::jump * input::is_key_pressed(SDLK_SPACE);
commands |= spm::crouch * input::is_key_pressed(SDLK_LCTRL);
commands |= spm::sprint * input::is_key_pressed(SDLK_LSHIFT);
commands |= spm::attack * input::is_key_pressed(SDL_BUTTON_LEFT);
}
static void update_input() noexcept {
input::update();
if (input::is_key_pressed(SDLK_z)) {
render::camera::get_xfov() = 30.0f;
} else {
render::camera::get_xfov() = settings::get({"gameplay", "fov"}, 100.0f);
}
if (!window::is_open()) {
handle_button_input();
}
if (input::state.quit) {
shared::should_exit = true;
}
}
static void update_delta_ticks() noexcept {
static shared::time_point_t last = std::chrono::steady_clock::now();
const auto now = std::chrono::steady_clock::now();
const auto delta_ticks =
shared::get_duration_seconds(now - last) /
shared::get_duration_seconds(state::get_time_per_tick());
state::delta_ticks += state::time_factor * delta_ticks;
last = now;
}
static void update_pre_move() {
state::player_count = state::entities.size();
state::requested_chunk_count = static_cast<std::uint32_t>(
std::ranges::count_if(state::chunks, [](const auto& c) {
return !c.second.has_value();
}));
state::networked_chunk_count =
std::size(state::chunks) - state::requested_chunk_count;
update_delta_ticks();
update_input();
update_chunks();
}
static void interp_entities() {
for (auto& [index, entity] : state::entities) {
const auto animate_ptr = dynamic_cast<animate*>(&*entity);
if (animate_ptr == nullptr) {
continue;
}
animate_ptr->interpolate();
}
}
static void remove_bad_entities() {
const auto lp_index = *state::localplayer_index;
// pvs, remove clients outside of chunks we own
std::erase_if(state::entities, [&](const auto& pair) {
const auto& [idx, entity] = pair;
const auto player_ptr = dynamic_cast<const player*>(&*entity);
if (player_ptr == nullptr) {
return false;
}
if (player_ptr->get_index() == lp_index) {
return false;
}
// Players should be removed if the chunk can't draw.
const auto chunk_it = state::chunks.find(player_ptr->get_chunk_pos());
if (chunk_it == std::end(state::chunks)) {
return true;
}
const auto& chunk = chunk_it->second;
if (chunk.has_value() && !chunk->can_draw()) {
return true;
}
return false;
});
}
static void update_entities() noexcept {
interp_entities();
remove_bad_entities();
}
static void update_post_move() { update_entities(); }
static void maybe_send_move() noexcept {
// An unknown amount of time has passed since we last rendered and this may
// be more than one tick. We do nothing if it's less than one tick.
const auto num_ticks_passed = static_cast<unsigned>(state::delta_ticks);
if (num_ticks_passed <= 0) {
return;
}
// Extrapolate for the number of ticks passed.
auto& localplayer = get_localplayer();
for (auto i = 0u; i < num_ticks_passed; ++i) {
++state::tick; // possibly after?
state::delta_ticks -= 1.0f;
localplayer.extrapolate();
++localplayer.get_mutable_latest_sequence();
state::connection->usend_packet(make_move_packet(localplayer));
}
// reset all commands except for flying, more later probably
const auto retained = shared::animate::flying;
localplayer.get_mutable_commands() &= retained;
}
// requires SDL_MOUSEMOTION
static void handle_mousemotion(const SDL_Event& event) noexcept {
const float sens =
settings::get<float>({"gameplay", "mouse_sensitivity"}, 0.0235f);
auto& lp = get_localplayer();
auto& angles = lp.get_mutable_angles();
const float pitch_offset = static_cast<float>(event.motion.yrel) * sens;
const float yaw_offset = static_cast<float>(event.motion.xrel) * sens;
angles.pitch -= glm::radians(pitch_offset);
angles.yaw += glm::radians(yaw_offset);
angles.normalise();
angles.clamp();
}
// requires SDL_MOUSEBUTTONDOWN
static void handle_mousebuttons(const SDL_Event& event) noexcept {
if (event.button.button != SDL_BUTTON_LEFT &&
event.button.button != SDL_BUTTON_RIGHT) {
return;
}
auto& lp = get_localplayer();
const auto mode = event.button.button == SDL_BUTTON_LEFT
? movement::interact_mode::remove
: movement::interact_mode::add;
const auto position = movement::interact(lp, mode, state::chunks);
if (!position.has_value()) {
return;
}
const auto& [chunk_pos, block_pos] = *position;
auto& block = state::chunks.find(chunk_pos)->second->get_block(block_pos);
if (mode == movement::interact_mode::remove) {
lp.inventory.maybe_add(shared::item::block::get_type(block.type), 1,
client::item::make_item);
block.type = shared::world::block::type::air;
state::connection->rsend_packet(
make_remove_block_packet(chunk_pos, block_pos));
} else {
// Adding is more complicated, needs the active item.
const auto& active = lp.get_active_item();
auto& item = lp.inventory.contents[active];
if (item == nullptr) {
return;
}
const auto block_ptr = dynamic_cast<const shared::item::block*>(&*item);
if (block_ptr == nullptr) {
return;
}
lp.inventory.decrement(active);
block.type = block_ptr->type;
state::connection->rsend_packet(
make_add_block_packet(chunk_pos, block_pos, active));
}
regenerate_surrounding_chunks(chunk_pos);
}
static void handle_space(const SDL_Event& event) noexcept {
if (event.type == SDL_KEYUP) {
return;
}
auto& commands = get_localplayer().get_mutable_commands();
commands |= shared::animate::mask::jump;
if (event.key.repeat) {
return;
}
constexpr auto JUMP_FLY_DELAY = std::chrono::milliseconds(250);
static std::optional<shared::time_point_t> prev = std::nullopt;
const auto now = std::chrono::steady_clock::now();
if (prev.has_value() && now < *prev + JUMP_FLY_DELAY) {
commands ^= shared::animate::mask::flying;
prev.reset();
return;
}
prev.emplace(now);
}
static void handle_keys(const SDL_Event& event) noexcept {
switch (event.key.keysym.sym) {
case SDLK_SPACE:
handle_space(event);
break;
default:
break;
}
}
static void handle_events(const SDL_Event& event) noexcept {
if (window::is_open()) {
return;
}
if (!state::localplayer_index.has_value()) {
return;
}
switch (event.type) {
case SDL_KEYDOWN:
case SDL_KEYUP:
handle_keys(event);
break;
case SDL_MOUSEBUTTONDOWN:
handle_mousebuttons(event);
break;
case SDL_MOUSEMOTION:
handle_mousemotion(event);
break;
default:
break;
}
}
static std::string get_username() {
const settings::setting_pair_t loc = {"gameplay", "username"};
if (const auto username = settings::maybe_get_setting_str(loc);
username.has_value()) {
return *username;
}
shared::print::notify << shared::print::time
<< "first launch detected, username required\n";
std::string ret;
while (ret.empty() || !std::ranges::all_of(ret, isalnum)) {
std::cin.clear();
std::cout << "enter a valid username: ";
std::getline(std::cin, ret);
}
settings::set_setting_str(loc, ret);
return ret;
}
static std::string get_password(const std::string_view& address) {
const settings::setting_pair_t loc = {
"auth", std::string{address == "0.0.0.0" ? "localhost" : address}};
if (const auto password = settings::maybe_get_setting_str(loc);
password.has_value()) {
return *password;
}
// We generate a random string as our password. Our password has decent
// complexitity but considering we don't use any encryption it is worthless
// to any real attacker and just basic authentication.
std::string ret;
std::random_device rand{};
std::uniform_int_distribution<char> uniform{'a', 'z'};
for (int i = 0; i < 256; ++i) {
const char random_char = uniform(rand);
ret.push_back(random_char);
}
settings::set_setting_str(loc, ret);
return ret;
}
static void send_auth_packet(const std::string_view& address,
shared::net::connection& connection) {
const std::string username = get_username();
const std::string password = get_password(address);
connection.rsend_packet(make_auth_packet(username, password));
}
static bool should_do_loop(shared::net::connection& connection) noexcept {
if (shared::should_exit) {
return false;
}
if (!connection.good()) {
shared::print::notify << shared::print::time
<< "client: disconnected for \""
<< connection.get_bad_reason() << "\"\n";
shared::should_exit = true; // cleanup server if necessary
return false;
}
return true;
}
static void do_client_loop(shared::net::connection& connection) {
while (should_do_loop(connection)) {
connection.poll();
while (auto packet = connection.recv_packet()) {
parse_packet(std::move(*packet));
}
if (!state::has_initialised()) {
continue;
}
update_pre_move();
maybe_send_move();
update_post_move();
render::draw(state::entities, state::chunks);
}
}
static void init_client(const std::string_view& address,
const std::string_view& port,
shared::net::connection& connection) {
// Setup client state, some vars should be cleaned up later (raii lol).
state::address = address;
state::port = port;
state::connection = &connection;
input::register_event_handler(&handle_events);
send_auth_packet(address, connection);
render::init();
}
static void cleanup_client() {
state::connection = nullptr;
state::localplayer_index.reset();
state::chunks.clear();
state::entities.clear();
render::quit();
settings::save();
}
void main(const std::string_view address, const std::string_view port) {
shared::net::connection connection = make_connection(address, port);
init_client(address, port, connection);
shared::print::notify << shared::print::time << "client: connected to "
<< address << ':' << port << '\n';
do_client_loop(connection);
shared::print::notify << shared::print::time
<< "client: disconnecting from server\n";
cleanup_client();
}
} // namespace client
|