-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
591 lines (481 loc) · 18.7 KB
/
main.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
#include "main.h"
#include "UI/GUI.h"
#include "./Network/Client.h"
#include "./Network/NetworkPacket.h"
#include "ServerMain.cpp"
#include "ConfigReader.h"
#include <filesystem>
#include "Model.h"
#include <thread>
#include <atomic>
#include <chrono>
#include <map>
#include "SoundEngine.h"
namespace fs = std::filesystem;
bool GUI::show_loading;
void error_callback(int error, const char* description)
{
// Print error.
std::cerr << description << std::endl;
}
void setup_callbacks(GLFWwindow* window)
{
// Set the error callback.
glfwSetErrorCallback(error_callback);
// Set the window resize callback.
glfwSetWindowSizeCallback(window, Window::resizeCallback);
// Set the key callback.
glfwSetKeyCallback(window, InputManager::keyCallback);
// Set cursor callback
glfwSetCursorPosCallback(window, InputManager::CursorCallback);
}
void setup_opengl_settings()
{
// Enable depth buffering.
glEnable(GL_DEPTH_TEST);
// Related to shaders and z value comparisons for the depth buffer.
glDepthFunc(GL_LEQUAL);
// Set polygon drawing mode to fill front and back of each polygon.
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// Enable transparency for meshes
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBlendEquation(GL_FUNC_ADD);
// Set clear color to black.
glClearColor(212.f/255, 242.f/255, 148.f/255, 1.0);
}
void print_versions()
{
// Get info of GPU and supported OpenGL version.
std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl;
std::cout << "OpenGL version supported: " << glGetString(GL_VERSION)
<< std::endl;
//If the shading language symbol is defined.
#ifdef GL_SHADING_LANGUAGE_VERSION
std::cout << "Supported GLSL version is: " <<
glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
#endif
}
void preload_texture_files() {
std::cout << "Start pre-loading... " << std::endl;
const char* load_dir = "models";
int i = 0;
for (auto& entry : fs::recursive_directory_iterator(load_dir)) {
std::cout << entry.path() << std::endl;
int width, height, nrComponents;
unsigned char* data = stbi_load(entry.path().string().c_str(), &width, &height, &nrComponents, 0);
stbi_image_free(data);
i++;
}
GUI::show_loading = false;
}
void timing(std::chrono::time_point<std::chrono::steady_clock> &begin_time, std::string msg){
//auto begin_time = std::chrono::steady_clock::now();
auto end_time = std::chrono::steady_clock::now();
long long elapsed_time = std::chrono::duration_cast<std::chrono::microseconds>(end_time - begin_time).count();
printf("%s: %f ms\n", msg.c_str(), elapsed_time/1000.f);
begin_time = end_time;
}
void preload_assets(GLFWwindow* window)
{
Model tmp;
int size = SENTINEL_END - SENTINEL_BEGIN + 1; // implicit + 2 from (progress = 1) and excess (progress++)
float progress = 1;
bool flip_image = true; // variable use to flip the image
std::atomic_bool spawned(false);
std::atomic_bool done(false);
for (ModelEnum i = static_cast<ModelEnum>(SENTINEL_BEGIN + 1); i < SENTINEL_END;) {
auto begin_time = std::chrono::steady_clock::now();
flip_image = GUI::renderProgressBar(progress / size, window, flip_image);
if (!spawned.load(std::memory_order_relaxed))
{
spawned.store(true, std::memory_order_relaxed);
std::thread worker([&]()
{
Model::load_scene(i);
done.store(true, std::memory_order_relaxed);
});
worker.detach();
}
if (done.load(std::memory_order_relaxed))
{
tmp = Model(i);
progress++;
i = static_cast<ModelEnum>(i + 1);
spawned.store(false, std::memory_order_relaxed);
done.store(false, std::memory_order_relaxed);
}
auto end_time = std::chrono::steady_clock::now();
int elapsed_time = static_cast<int>(std::chrono::duration_cast<std::chrono::milliseconds>(end_time - begin_time).count());
Sleep(std::max(130 - elapsed_time, 0));
}
flip_image = GUI::renderProgressBar(progress / size, window, flip_image);
GUI::initializeImage();
progress++;
flip_image = GUI::renderProgressBar(progress / size, window, flip_image);
}
int main(int argc, char* argv[])
{
if (argc > 1 && (std::string(argv[1]) == "server-build")) { //TODO Add Seperate Project
ServerMain();
return 0;
}
// Create the GLFW window.
GLFWwindow* window = Window::createWindow(1920, 1080);
if (!window)
exit(EXIT_FAILURE);
// Print OpenGL and GLSL versions.
print_versions();
// Setup callbacks.
setup_callbacks(window);
// Setup OpenGL settings.
setup_opengl_settings();
// Initialize the shader program; exit if initialization fails.
if (!Window::initializeProgram())
exit(EXIT_FAILURE);
// Initialize objects/pointers for rendering; exit if initialization fails.
if (!Window::initializeObjects())
exit(EXIT_FAILURE);
// display loading bar
GUI::show_loading = true;
// initialize IMGUI
GUI::initializeGUI(window);
GUI::initializeLoadingImage();
// preload models and other assets
preload_assets(window);
// Initialize network client interface
static std::unordered_map<std::string, std::string> client_config = ConfigReader::readConfigFile("client.cfg");
Client* client = new Client(client_config["server_address"].c_str(), DEFAULT_PORT);
// Initialize sound engine
SoundEngine sound_engine{};
sound_engine.Init(client_config["audio"] == "true");
// client-side wait until all clients are connected
sound_engine.PlayMusic(MUSIC_MENU);
GUI::renderWaitingClient(1, 1);
int num_clients = 4;
client->syncGameReadyToStart([&](ClientWaitPacket cw_packet)
{
num_clients = cw_packet.max_client;
fprintf(stderr, "%d of %d players joined\n", cw_packet.client_joined, cw_packet.max_client);
GUI::renderWaitingClient(cw_packet.client_joined, cw_packet.max_client);
});
fprintf(stderr, "All players connected, starting character selection\n");
// character selection
GUI::char_selections = client->syncCharacterSelection(num_clients,[&](ServerCharacterPacket recv_packet)
{
std::unordered_map<ModelEnum, int> char_selections;
for (int i = 0; i < num_clients; i++) {
char_selections[recv_packet.current_char_selections[i]] = i;
}
ModelEnum res = GUI::renderCharacterSelection(char_selections, recv_packet.client_idx);
ClientCharacterPacket out_packet;
out_packet.character = res;
return out_packet;
});
fprintf(stderr, "All players selected character, starting game\n");
// butter butter magic
Window::postprocessing = new FBO(-200.0f, 7500.0f);
Window::bloom = new FBO(Window::width, Window::height);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// "globals" for the duration of the client main loop
int status = 1;
std::map<uintptr_t, Model*> model_map;
glm::vec3 eye_offset = glm::vec3(0,30,30); //TODO no magic number :,(
glm::vec3 winning_camera = glm::vec3(0, 0, -100);
glm::vec3 winning_view = glm::vec3(0, 0, 0);
sound_engine.Play(SFX_AMBIENCE);
// Loop while GLFW window should stay open and server hasn't closed connection
bool day_1_started = false;
bool night_started = false;
bool day_2_started = false;
bool two_minute_started = false;
bool victory_started = false;
while (!glfwWindowShouldClose(window) && status > 0)
{
// adjust camera direction (player's forward direction depends on camera)
const glm::vec2 mouse_delta = InputManager::GetCursorDelta();
glm::mat3 rot_x = util_RotateAroundAxis(-mouse_delta[0] * InputManager::camera_speed, glm::vec3{0,1,0});
auto rot_y = glm::mat3(1);
if (eye_offset[1] < 40.f || mouse_delta[1] <= 0) { //TODO no magic numbers :^(
const glm::vec3 right_axis = -glm::cross(glm::vec3{0,1,0},eye_offset);
rot_y = util_RotateAroundAxis(mouse_delta[1] * InputManager::camera_speed, glm::normalize(right_axis));
}
eye_offset = rot_x * rot_y * eye_offset;
eye_offset = glm::normalize(eye_offset) * InputManager::camera_dist;
if (eye_offset[1] < 15) eye_offset[1] = 15;
eye_offset = eye_offset * (eye_offset[1]/30.f);
// after moving camera, move the player
ClientPacket out_packet;
const glm::vec2 movement = InputManager::getLastMovement();
const float degrees = atan2f(eye_offset[0], eye_offset[2]);
const glm::mat2 trans = util_Rotate2D(degrees);
out_packet.movement = trans * movement;
out_packet.lastCommand = InputManager::getLastCommand();
InputManager::reset();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
status = client->syncWithServer(&out_packet, sizeof(out_packet), [&](char* recv_buf, size_t recv_len) {
// deserialize incoming packet into structs
ServerHeader* sheader;
ModelInfo* model_arr;
SoundInfo* sound_arr;
PendingDeleteInfo* pending_arr;
serverDeserialize(recv_buf, &sheader, &model_arr, &sound_arr, &pending_arr);
// reorder particle (to be rendered last)
std::vector<ModelInfo> model_vec;
std::vector<ModelInfo> particles;
for (int i = 0; i < sheader->num_models; i++) {
ModelInfo& model_info = model_arr[i];
if (model_info.model >= PARTICLE_GLOW && model_info.model <= PARTICLE_FIREFLIES_WHITE) {
particles.push_back(model_info);
} else {
model_vec.push_back(model_info);
}
}
model_vec.insert(model_vec.end(), particles.begin(), particles.end());
//Rendering Code
const glm::mat4 player_transform = sheader->player_transform;
const glm::vec3 player_pos = glm::vec3(player_transform[3][0], player_transform[3][1], player_transform[3][2]) / player_transform[3][3];
glm::vec3 eye_pos = player_pos + eye_offset; // TODO implement angle.
glm::vec3 look_at_point = player_pos; // The point we are looking at.
std::vector<glm::vec3> point_light_pos; // TODO ask cynthia <--- used to get players positions for point lights in night phase -cynthia
// check if need to trigger client-side winning sequence
// Camera Code I
if (false && sheader->time_remaining_seconds <= 0){
GUI::GUI_show_winning = true;
if (sheader->time_remaining_seconds < -0.1) {
if (sheader->time_remaining_seconds > -5) {
if (sheader->time_remaining_seconds > -1) {
winning_camera = winning_camera + glm::vec3(0, 0, 0.3);
}
else if (sheader->time_remaining_seconds > -3) {
winning_camera = winning_camera + glm::vec3(0, 0, 0.3);
winning_view = winning_view + glm::vec3(0, 0.1, 0);
}
else {
winning_camera = winning_camera + glm::vec3(0, 0.1, 0.2);
winning_view = winning_view + glm::vec3(0, 0.1, 0);
}
}
}
if (winning_camera.y > 4)
winning_camera[1] = 4;
if (winning_camera.z > -40)
winning_camera[2] = -40;
if (look_at_point.y > 11)
winning_view[1] = 5;
eye_pos = winning_camera;
look_at_point = winning_view;
}
//Camera Code II
if (sheader->time_remaining_seconds <= -3) {
double x = sheader->time_remaining_seconds + 11;
winning_view = glm::vec3{ 0, 1, 0 };
if (x >= 0) {
winning_camera[0] = cosf(7 * sqrtf(x)) * sqrt(x) * 10;
winning_camera[1] = powf(2.7182f,-x+3);
winning_camera[2] = ((x / 8) * -200) - 50;
}
eye_pos = winning_camera;
look_at_point = winning_view;
}
const glm::mat4 view = glm::lookAt(eye_pos, look_at_point, Window::upVector);
if (!day_1_started && sheader->time_remaining_seconds > 8.5f * 60) {
sound_engine.PlayMusic(MUSIC_DAY_1, false);
day_1_started = true;
}
if (!night_started && sheader->time_remaining_seconds <= 8.5f * 60
&& sheader->time_remaining_seconds > 3.5f * 60) {
sound_engine.PlayMusic(MUSIC_NIGHT, true);
night_started = true;
}
if (!day_2_started && sheader->time_remaining_seconds <= 3.5f * 60
&& sheader->time_remaining_seconds > 120) {
sound_engine.PlayMusic(MUSIC_DAY_1, false);
day_2_started = true;
}
if (!two_minute_started && sheader->time_remaining_seconds <= 120
&& sheader->time_remaining_seconds > 0) {
sound_engine.PlayMusic(MUSIC_TWO_MINUTES, false);
two_minute_started = true;
}
if (!victory_started && sheader->time_remaining_seconds <= -3) {
sound_engine.PlayMusic(MUSIC_VICTORY, false);
victory_started = true;
GUI::GUI_show_winning = true;
}
// update scoreboard
for (int i = 0; i < num_clients; i++) {
GUI::scoreboard_data[i] = sheader->balance[i];
}
// update stamina
GUI::stamina_percent = sheader->stamina_bar;
// update timer
GUI::setTimer(static_cast<float>(1 - (sheader->time_remaining_seconds / sheader->time_max_seconds)), sheader->time_remaining_seconds);
char strbuf[16];
int rem_s = static_cast<int>(sheader->time_remaining_seconds);
if (sheader->time_remaining_seconds < 0) {
rem_s = 0;
}
sprintf(strbuf, "%02d:%02d", rem_s / 60, rem_s % 60);
GUI::GUI_timer_string = std::string(strbuf);
// show NPC UI page
GUI::ShowGUI(sheader->ui_open);
GUI::setHoldingModel(sheader->holding_veggie);
GUI::setShowSaleUI(sheader->sale_confirm_ui_open);
//if (sheader->holding_veggie != -1 && sheader->sale_confirm_ui_open) {
//fprintf(stderr, "player is holding vegetable: %d", sheader->holding_veggie);
//}
// UI for glue and soju
if (sheader->isGlued) GUI::setShowGlueSign(true);
else GUI::setShowGlueSign(false);
if (sheader->isDrunk) GUI::setShowSojuSign(true);
else GUI::setShowSojuSign(false);
// play sounds
for (int i = 0; i < sheader->num_sounds; i++) {
const SoundInfo sound_info = sound_arr[i];
//TODO Add location of sound so we have panning
sound_engine.Play(sound_info.sound);
}
Window::postprocessing->draw(Window::width, Window::height, sheader->time_remaining_seconds, Window::view);
for (int i = 0; i < sheader->num_models; i++)
{
ModelInfo& model_info = model_vec[i];
// insert new model into map
if (model_map.count(model_info.model_id) == 0) {
model_map[model_info.model_id] = new Model(model_info.model);
}
else if (model_info.model != model_map[model_info.model_id]->getModelEnum()) {
delete model_map[model_info.model_id];
model_map[model_info.model_id] = new Model(model_info.model);
}
Model& curr_model = *model_map[model_info.model_id];
// FBO and minimap needs player data
if (model_info.is_player) {
GUI::player_pos[model_info.model - CHAR_BUMBUS] = ImVec2(
model_info.parent_transform[3][0],
model_info.parent_transform[3][2]);
point_light_pos.push_back(glm::vec3(model_info.parent_transform[3]) + glm::vec3(0.0f, 3.0f, 0.0f));
}
// set player animation speed
//TODO Get rid of this lol, maybe make AnimSpeeds sent back from server?
if (curr_model.hasAni) {
if (model_info.modelAnim == WALK || model_info.modelAnim == IDLE_WALK) {
if (sheader->player_sprinting) {
curr_model.anim_speed = 3.0f;
}
else {
curr_model.anim_speed = 1.5f;
}
}
else {
curr_model.anim_speed = 1.0f;
}
}
curr_model.setAnimationMode(model_info.modelAnim);
// get light for NPC and golden eggplant
if (model_info.model == CHAR_NPC) {
glm::vec3 pos = glm::vec3(model_info.parent_transform[3]) + glm::vec3(0.0f, 6.0f, 0.0f);
point_light_pos.push_back(pos);
}
//trigger the golden eggplant spawn sign if not trigger before
else if (model_info.model == VEG_GOLDEN_EGGPLANT) {
GUI::setShowGoldenEggplantSign(true);
if (glm::vec3(model_info.parent_transform[3]).y == -1) {
glm::vec3 pos = glm::vec3(model_info.parent_transform[3]) + glm::vec3(0.0f, 6.0f, 0.0f);
std::cout << glm::to_string(pos) << std::endl;
point_light_pos.push_back(pos);
}
}
// rotating particles towards players
else if (model_info.model == INDICATOR_WATER || model_info.model == INDICATOR_FERTILIZER || model_info.model == PARTICLE_GLOW) {
glm::mat4 tempTransform = model_info.parent_transform;
glm::vec3 plot_pos = glm::vec3(tempTransform[3][0], tempTransform[3][1], tempTransform[3][2]);
glm::mat4 rotation;
if (model_info.model == PARTICLE_GLOW)
{
rotation = glm::mat4(1);
}
else
{
rotation = glm::lookAt(glm::vec3(plot_pos.x, 0, -plot_pos.z), glm::vec3(eye_pos.x, 0, -eye_pos.z), glm::vec3(0, 1, 0));
}
//CONCAT CODE
rotation[3][0] = tempTransform[3][0];
rotation[3][1] = tempTransform[3][1];
rotation[3][2] = tempTransform[3][2];
model_info.parent_transform = rotation;
}
// rotating the woooorrrllllddd
else if (model_info.model == WORLD_DOME) {
float degrees = glm::clamp(FBO::timePassed / 720.0f, 0.0f, 1.0f);
glm::mat4 rotation = glm::rotate(glm::mix(0.0f, 6.28f, degrees), glm::vec3(0.0f, 1.0f, 0.0f));
model_info.parent_transform = rotation * glm::translate(glm::vec3(model_info.parent_transform[3]));
}
// Do not draw shadow for the big sky dome
if (model_info.model != WORLD_DOME) {
curr_model.draw(model_info.parent_transform, Window::shadowShaderProgram);
}
}
// for point lights in night phase
FBO::playerPos = point_light_pos;
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, Window::width, Window::height);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindFramebuffer(GL_FRAMEBUFFER, Window::bloom->sceneFBO);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glCullFace(GL_BACK);
for (int i = 0; i < sheader->num_models; i++) // TODO ask Danica planting bandaid nani
{
ModelInfo model_info = model_vec[i];
if (model_map.count(model_info.model_id) == 0) {
model_map[model_info.model_id] = new Model(model_info.model);
}
else if (model_info.model != model_map[model_info.model_id]->getModelEnum()) {
delete model_map[model_info.model_id];
model_map[model_info.model_id] = new Model(model_info.model);
}
model_map[model_info.model_id]->setAnimationMode(model_info.modelAnim);
model_map[model_info.model_id]->draw(view, Window::projection, model_info.parent_transform, Window::modelShader[model_info.model]);
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
FBO::bloomBlur(Window::blurShaderProgram);
FBO::finalDraw(Window::finalShaderProgram);
for (int i = 0; i < sheader->num_pending_delete; i++) {
const uintptr_t pending_delete_id = pending_arr[i].model_id;
fprintf(stderr, "Client: deleting model with ID %lld\n", pending_delete_id);
Model* model_to_delete = model_map[pending_delete_id];
model_map.erase(pending_delete_id);
delete model_to_delete;
}
free(sheader);
free(model_arr);
free(sound_arr);
free(pending_arr);
});
// Gets events, including input such as keyboard and mouse or window resizing
glfwPollEvents();
//IMGUI rendering
if (GUI::GUI_show_winning) {
GUI::renderWinningScene();
} else {
GUI::renderUI();
}
// Swap buffers.
glfwSwapBuffers(window);
}
sound_engine.DeInit();
// destroy objects created
Window::cleanUp();
for (auto iter = model_map.begin(); iter != model_map.end(); iter++) {
free(iter->second);
//delete iter->second;
}
// Cleanup ImGui
GUI::cleanUp();
// Destroy the window.
glfwDestroyWindow(window);
// Terminate GLFW.
glfwTerminate();
delete client;
exit(EXIT_SUCCESS);
}