-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1289 lines (1067 loc) · 42.4 KB
/
Copy pathmain.cpp
File metadata and controls
1289 lines (1067 loc) · 42.4 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 <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <vector>
#include <array>
#include <fstream>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include <sstream>
#include <unordered_map>
#include <memory>
#include <cstdint>
#include <optional>
#include <cmath>
//#define DONT_CULL_HIDDEN_FACES
GLuint make_shader_program(const char* vert_src, const char* frag_src, bool& compilation_success) {
GLuint program_handle = 0;
compilation_success = false;
const char* vertex_shader_c_str = vert_src;
const char* fragment_shader_c_str = frag_src;
GLuint vertex_handle = glCreateShader(GL_VERTEX_SHADER);
GLuint fragment_handle = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vertex_handle, 1, &vertex_shader_c_str, nullptr);
glCompileShader(vertex_handle);
// Check compile errors
int success{};
char info_log[1024];
glGetShaderiv(vertex_handle, GL_COMPILE_STATUS, &success);
if(!success) {
glGetShaderInfoLog(vertex_handle, 1024, nullptr, info_log);
std::cerr << "Vertex Shader Compilation Error: " << info_log << "\n";
return program_handle;
}
glShaderSource(fragment_handle, 1, &fragment_shader_c_str, nullptr);
glCompileShader(fragment_handle);
// Check compile errors
success = true;
glGetShaderiv(fragment_handle, GL_COMPILE_STATUS, &success);
if(!success) {
glGetShaderInfoLog(fragment_handle, 1024, nullptr, info_log);
std::cerr << "Fragment Shader Compilation Error: " << info_log << "\n";
return program_handle;
}
program_handle = glCreateProgram();
glAttachShader(program_handle, vertex_handle);
glAttachShader(program_handle, fragment_handle);
glLinkProgram(program_handle);
// Check compile errors
success = true;
glGetProgramiv(program_handle, GL_LINK_STATUS, &success);
if(!success) {
glGetProgramInfoLog(program_handle, 1024, nullptr, info_log);
std::cerr << "Shader Program Linking Error: " << info_log << "\n";
return program_handle;
}
glDeleteShader(vertex_handle);
glDeleteShader(fragment_handle);
compilation_success = true;
return program_handle;
}
GLuint make_shader_program_from_files(const char* vertex_shader_file, const char* fragment_shader_file, bool& success) {
std::ifstream vertex_shader{vertex_shader_file};
std::ifstream fragment_shader{fragment_shader_file};
if(!vertex_shader) { std::cerr << "Vertex shader file failed to load\n"; exit(1); }
if(!fragment_shader) { std::cerr << "Fragment shader file failed to load\n"; exit(1); }
std::stringstream vertex_ss;
std::stringstream fragment_ss;
vertex_ss << vertex_shader.rdbuf();
fragment_ss << fragment_shader.rdbuf();
std::string vertex_src = vertex_ss.str();
std::string fragment_src = fragment_ss.str();
GLuint program = make_shader_program(vertex_src.c_str(), fragment_src.c_str(), success);
return program;
}
struct ShaderCatalog {
std::unordered_map<std::string, GLuint> shader_programs;
GLuint get(const char* name) { return shader_programs[std::string{name}]; }
};
ShaderCatalog shader_catalog{};
void init_shader_catalog() {
bool rect_ok{};
shader_catalog.shader_programs["rect"] = make_shader_program_from_files("rect.vs.glsl", "rect.fs.glsl", rect_ok);
if(!rect_ok) {
std::cerr << "Rect shader loading failed\n";
}
shader_catalog.shader_programs["basic3d"] = make_shader_program_from_files("basic3d.vs.glsl", "basic3d.fs.glsl", rect_ok);
if(!rect_ok) {
std::cerr << "Basic3D shader loading failed\n";
}
shader_catalog.shader_programs["chunk"] = make_shader_program_from_files("chunk.vs.glsl", "chunk.fs.glsl", rect_ok);
if(!rect_ok) {
std::cerr << "Chunk shader loading failed\n";
}
}
struct Rectangle {
GLuint vao, vbo, ebo;
};
Rectangle make_rectangle() {
std::vector<GLfloat> positions = {
0.5f, 0.5f, // top right
0.5f, -0.5f, // bottom right
-0.5f, -0.5f, // bottom left
-0.5f, 0.5f, // top left
1.0f,0.0f,0.0f, // top right color
0.0f,1.0f,0.0f,
0.0f,0.0f,1.0f,
1.0f,1.0f,1.0f
};
std::vector<GLuint> indexes = {
1, 0, 2,
0, 3, 2
};
GLuint vao, vbo, ebo;
glCreateVertexArrays(1, &vao);
glCreateBuffers(1, &vbo);
glCreateBuffers(1, &ebo);
glNamedBufferData(vbo, sizeof(positions[0]) * positions.size(), positions.data(), GL_STATIC_DRAW);
glNamedBufferData(ebo, sizeof(indexes[0]) * indexes.size(), indexes.data(), GL_STATIC_DRAW);
glVertexArrayVertexBuffer(vao, 0, vbo, 0, 2 * sizeof(GLfloat));
glVertexArrayVertexBuffer(vao, 1, vbo, 4 * 2 * sizeof(GLfloat), 3 * sizeof(GLfloat));
glEnableVertexArrayAttrib(vao, 0);
glVertexArrayAttribBinding(vao, 0, 0);
glVertexArrayAttribFormat(vao, 0, 2, GL_FLOAT, GL_FALSE, 0);
glEnableVertexArrayAttrib(vao, 1);
glVertexArrayAttribBinding(vao, 1, 1);
glVertexArrayAttribFormat(vao, 1, 3, GL_FLOAT, false, 0);
glVertexArrayElementBuffer(vao, ebo);
return {.vao=vao, .vbo=vbo, .ebo=ebo};
}
void render(const Rectangle& rect) {
glUseProgram(shader_catalog.get("rect"));
glBindVertexArray(rect.vao);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
}
struct Camera {
glm::vec3 position;
// glm::vec3 look_dir;
float fov_y_rad;
float aspect_ratio;
float yaw_rad, pitch_rad;
};
glm::mat4x4 get_camera_rotation(const Camera& camera);
glm::vec3 get_camera_look_dir(const Camera& camera) {
glm::vec4 look_dir{0,0,-1, 1};
auto rot = get_camera_rotation(camera);
//std::cout << "cam rot: " << glm::to_string(rot) << "\n";
return rot * look_dir;
}
glm::vec3 get_camera_right(const Camera& camera) {
return glm::normalize(glm::cross(get_camera_look_dir(camera), glm::vec3(0,1,0)));
}
glm::mat4x4 get_camera_rotation(const Camera& camera) {
glm::mat4x4 rot = glm::identity<glm::mat4x4>();
rot = glm::rotate(rot, camera.yaw_rad, glm::vec3{0,1,0});
rot = glm::rotate(rot, camera.pitch_rad, glm::vec3{1,0,0});
return rot;
}
glm::mat4x4 get_view_transform(const Camera& camera) {
auto inv_view = glm::identity<glm::mat4x4>();
inv_view = glm::translate(inv_view, camera.position);
inv_view = inv_view * get_camera_rotation(camera);
return glm::inverse(inv_view);
// glm::vec3 up = glm::cross(get_camera_right(camera), camera.look_dir);
// return glm::lookAt(camera.position, camera.position + camera.look_dir, up);
}
glm::mat4x4 get_perspective_transform(const Camera& camera) {
return glm::perspective(camera.fov_y_rad, camera.aspect_ratio, 0.1f, 1000.0f);
}
struct Cube {
GLuint vao, vbo, ebo;
std::vector<float> positions;
std::vector<unsigned int> indexes;
glm::vec3 position;
glm::vec3 scale;
glm::vec3 color;
};
Cube make_cube() {
const std::vector<float> positions {
-0.5f, 0.5f, -0.5f, // front bottom-left
0.5f, 0.5f, -0.5f, // front bottom-right
0.5f, 0.5f, 0.5f, // front top-right
-0.5f, 0.5f, 0.5f, // front top-left
-0.5f, -0.5f, -0.5f, // back bottom-left
0.5f, -0.5f, -0.5f, // back bottom-right
0.5f, -0.5f, 0.5f, // back top-right
-0.5f, -0.5f, 0.5f, // back top-left
};
const std::vector<unsigned int> indexes {
0, 1, 2, 0, 2, 3, // front face
6, 5, 4, 7, 6, 4, // back face
1, 5, 6, 1, 6, 2, // right face
0, 3, 4, 4, 3, 7, // left face
3, 2, 6, 3, 6, 7, // top face
4, 5, 1, 4, 1, 0, // bottom face
};
GLuint vao, vbo, ebo;
glCreateVertexArrays(1, &vao);
glCreateBuffers(1, &vbo);
glCreateBuffers(1, &ebo);
glNamedBufferData(vbo, positions.size() * sizeof(positions[0]), positions.data(), GL_STATIC_DRAW);
glNamedBufferData(ebo, indexes.size() * sizeof(indexes[0]), indexes.data(), GL_STATIC_DRAW);
glVertexArrayElementBuffer(vao, ebo);
glVertexArrayVertexBuffer(vao, 0, vbo, 0, 3 * sizeof(GLfloat));
glEnableVertexArrayAttrib(vao, 0);
glVertexArrayAttribBinding(vao, 0, 0);
glVertexArrayAttribFormat(vao, 0, 3, GL_FLOAT, false, 0);
GLuint tex{};
glCreateTextures(GL_TEXTURE_2D, 1, &tex);
glTextureParameteri(tex, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTextureParameteri(tex, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTextureParameteri(tex, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTextureParameteri(tex, GL_TEXTURE_WRAP_T, GL_REPEAT);
int image_width{}, image_height{}, nr_channels{};
unsigned char *image_data = stbi_load("atlas.jpg", &image_width, &image_height, &nr_channels, 0);
glTextureStorage2D(tex, 1, GL_RGBA8, image_width, image_height);
glTextureSubImage2D(tex, 0, 0, 0, image_width, image_height, GL_RGBA, GL_UNSIGNED_BYTE, image_data);
glGenerateTextureMipmap(tex);
return Cube{.vao=vao, .vbo=vbo, .ebo=ebo, .positions=positions, .indexes=indexes, .position={}, .scale={1,1,1}, .color={1.0,0.0,1.0}};
}
void render(const Cube& cube, const Camera& camera) {
GLuint shader = shader_catalog.get("basic3d");
glUseProgram(shader);
glUniform3fv(glGetUniformLocation(shader, "color"), 1, glm::value_ptr(cube.color));
glm::mat4x4 t_model = glm::identity<glm::mat4x4>();
t_model = glm::translate(t_model, cube.position);
t_model = glm::scale(t_model, cube.scale);
glUniformMatrix4fv(glGetUniformLocation(shader, "t_model"), 1, GL_FALSE, glm::value_ptr(t_model));
glm::mat4x4 t_view = get_view_transform(camera);
glUniformMatrix4fv(glGetUniformLocation(shader, "t_view"), 1, GL_FALSE, glm::value_ptr(t_view));
glm::mat4x4 t_perspective = get_perspective_transform(camera);
glUniformMatrix4fv(glGetUniformLocation(shader, "t_perspective"), 1, GL_FALSE, glm::value_ptr(t_perspective));
glBindVertexArray(cube.vao);
glDrawElements(GL_TRIANGLES, cube.indexes.size(), GL_UNSIGNED_INT, nullptr);
}
enum FaceDir {
PLUS_X, PLUS_Y, PLUS_Z, MINUS_X, MINUS_Y, MINUS_Z
};
const auto dir_to_vec = std::to_array<glm::ivec3>({
{1,0,0}, {0,1,0}, {0,0,1}, {-1,0,0}, {0,-1,0}, {0,0,-1}
});
struct Vertex {
glm::vec3 position;
glm::vec3 color;
};
struct MeshData {
std::vector<Vertex> vertexes;
std::vector<unsigned int> indexes;
};
/// Returns the emitted vertex's index
unsigned int emit_vertex(glm::vec3 position, glm::vec3 color, MeshData& mesh_data) {
mesh_data.vertexes.push_back({position, color});
return mesh_data.vertexes.size() - 1;
}
/*
* +y
* |
* / \
* +z +x
*
* 6----2
* 7----3 |
* | | | |
* | 5--|-1
* 4----0
*/
const auto cube_positions = std::to_array<glm::vec3>({
{1,0,1}, {1,0,0}, {1,1,0}, {1,1,1},
{0,0,1}, {0,0,0}, {0,1,0}, {0,1,1}
});
const auto cube_face_colors = std::to_array<glm::vec3>({
{1,0,0}, {0,1,0}, {0,0,1}, {1,1,0}, {0,1,1}, {0.4,0.2,0.4}
});
const auto face_vertex = std::to_array<unsigned int>({
0, 1, 2, 3,
7, 3, 2, 6,
4, 0, 3, 7,
5, 4, 7, 6,
5, 1, 0, 4,
1, 5, 6, 2
});
const std::array face_indexes = { 0,1,2,0,2,3 };
// x, y and z are coordinates of the block relative to the chunk's origin = (0,0,0)
void emit_cube_face(glm::vec<3, int> block_ints, FaceDir dir, MeshData& mesh_data) {
auto block_pos = glm::vec3{block_ints.x, block_ints.y, block_ints.z};
unsigned int index_offset = mesh_data.vertexes.size();
for(int v = 0; v < 4; ++v) {
emit_vertex(cube_positions[face_vertex[dir * 4 + v]] + block_pos, cube_face_colors[dir], mesh_data);
}
for(int i = 0; i < 6; ++i) {
mesh_data.indexes.push_back(face_indexes[i] + index_offset);
}
}
// constexpr size_t chunk_volume = 16 * 16 * 256;
struct ChunkMesh {
MeshData mesh_data;
GLuint vao, vbo, ebo;
};
//ChunkMesh make_chunk_mesh() {
// MeshData mesh_data;
//// mesh_data.vertexes.reserve(max_num_vertexes);
//// mesh_data.indexes.reserve(max_num_indexes);
//
// auto chunk_origin = glm::vec<3, int>{-4,-4,-4};
//
// emit_cube_face(chunk_origin, FaceDir::PlusX, mesh_data);
// emit_cube_face(chunk_origin, FaceDir::PlusY, mesh_data);
// emit_cube_face(chunk_origin, FaceDir::PlusZ, mesh_data);
// emit_cube_face(chunk_origin, FaceDir::MinusX, mesh_data);
// emit_cube_face(chunk_origin, FaceDir::MinusY, mesh_data);
// emit_cube_face(chunk_origin, FaceDir::MinusZ, mesh_data);
//
// GLuint vao;
// glCreateVertexArrays(1, &vao);
// GLuint vbo;
// glCreateBuffers(1, &vbo);
// GLuint ebo;
// glCreateBuffers(1, &ebo);
//
// glNamedBufferData(vbo,
// mesh_data.vertexes.size() * sizeof(mesh_data.vertexes[0]),
// mesh_data.vertexes.data(),
// GL_DYNAMIC_DRAW
// );
//
// glNamedBufferData(ebo, mesh_data.indexes.size() * sizeof(mesh_data.indexes[0]), mesh_data.indexes.data(), GL_DYNAMIC_DRAW);
//
// glVertexArrayVertexBuffer(vao, 0, vbo, 0, sizeof(Vertex));
//
// glVertexArrayAttribBinding(vao, 0, 0);
// glVertexArrayAttribBinding(vao, 1, 0);
//
// glEnableVertexArrayAttrib(vao, 0);
// glEnableVertexArrayAttrib(vao, 1);
//
// glVertexArrayAttribFormat(vao, 0, 3, GL_FLOAT, false, 0);
// glVertexArrayAttribFormat(vao, 1, 3, GL_FLOAT, false, offsetof(Vertex, color));
//
// glVertexArrayElementBuffer(vao, ebo);
//
// return ChunkMesh{.mesh_data=mesh_data, .vao=vao, .vbo=vbo, .ebo=ebo};
//}
void render_chunk_mesh(const ChunkMesh& mesh, const Camera& camera) {
GLuint shader = shader_catalog.get("chunk");
glUseProgram(shader);
glm::mat4x4 t_view = get_view_transform(camera);
glUniformMatrix4fv(glGetUniformLocation(shader, "t_view"), 1, GL_FALSE, glm::value_ptr(t_view));
glm::mat4x4 t_perspective = get_perspective_transform(camera);
glUniformMatrix4fv(glGetUniformLocation(shader, "t_perspective"), 1, GL_FALSE, glm::value_ptr(t_perspective));
glBindVertexArray(mesh.vao);
glDrawElements(GL_TRIANGLES, mesh.mesh_data.indexes.size(), GL_UNSIGNED_INT, nullptr);
}
enum class BlockType {
Air, Dirt
};
struct Chunk {
static constexpr int chunk_dim_x = 16;
static constexpr int chunk_dim_y = 16;
static constexpr int chunk_dim_z = 16;
static constexpr glm::ivec3 chunk_dim = {chunk_dim_x, chunk_dim_y, chunk_dim_z};
static constexpr int chunk_volume = chunk_dim_x * chunk_dim_y * chunk_dim_z;
static constexpr size_t max_num_faces = 6 * chunk_volume / 2;
static constexpr size_t max_num_vertexes = 4 * max_num_faces;
static constexpr size_t max_num_indexes = 6 * max_num_faces;
std::vector<BlockType> blocks;
glm::vec<3, int16_t> position;
ChunkMesh* mesh;
bool is_dirty{false};
bool chunk_mesh_initialized{false};
Chunk() : blocks{}, position{}, mesh{}, is_dirty{} {
}
void load_default_chunk(glm::vec<3, int16_t> p_position) {
blocks = std::vector<BlockType>(chunk_volume, BlockType::Dirt);
position = p_position;
mesh = new ChunkMesh{};
init_chunk_mesh();
generate_chunk_mesh();
}
explicit Chunk(glm::vec3 position) : blocks(chunk_volume, BlockType::Dirt), position{position}, mesh{nullptr} {
set_block({0,0,0}, BlockType::Dirt);
set_block({1,0,0}, BlockType::Dirt);
set_block({0,0,1}, BlockType::Dirt);
set_block({1,2,3}, BlockType::Dirt);
set_block({1,2,4}, BlockType::Dirt);
set_block({1,3,4}, BlockType::Dirt);
for(int y = 5; y < 8; ++y) {
for(int x = 0; x < chunk_dim_x; ++x) {
for(int z = 0; z < chunk_dim_z; ++z) {
set_block({x,y,z}, BlockType::Air);
}
}
}
for(int x = 0; x < 3; ++x) {
for(int y = 0; y < 3; ++y) {
for(int z = 0; z < 3; ++z) {
set_block(glm::ivec3{x,y,z} + glm::ivec3{5,5,5}, BlockType::Dirt);
}
}
}
mesh = new ChunkMesh{};
init_chunk_mesh();
generate_chunk_mesh();
}
~Chunk() {
if(chunk_mesh_initialized) {
glDeleteBuffers(1, &mesh->vbo);
glDeleteBuffers(1, &mesh->ebo);
glDeleteVertexArrays(1, &mesh->vao);
delete mesh;
}
}
void init_chunk_mesh() {
GLuint vao;
glCreateVertexArrays(1, &vao);
GLuint vbo;
glCreateBuffers(1, &vbo);
GLuint ebo;
glCreateBuffers(1, &ebo);
glVertexArrayVertexBuffer(vao, 0, vbo, 0, sizeof(Vertex));
glVertexArrayAttribBinding(vao, 0, 0);
glVertexArrayAttribBinding(vao, 1, 0);
glEnableVertexArrayAttrib(vao, 0);
glEnableVertexArrayAttrib(vao, 1);
glVertexArrayAttribFormat(vao, 0, 3, GL_FLOAT, false, 0);
glVertexArrayAttribFormat(vao, 1, 3, GL_FLOAT, false, offsetof(Vertex, color));
glVertexArrayElementBuffer(vao, ebo);
mesh->vao = vao;
mesh->vbo = vbo;
mesh->ebo = ebo;
chunk_mesh_initialized = true;
}
// returns -1 if coords are out of chunk bounds
// the input coords are relative to the chunk's local space!!
static int block_coords_to_index(glm::vec<3, int> coords) {
if( coords.x < 0 || coords.x >= chunk_dim_x ||
coords.y < 0 || coords.y >= chunk_dim_y ||
coords.z < 0 || coords.z >= chunk_dim_z
)
{
return -1;
}
return coords.x + chunk_dim_x * coords.y + chunk_dim_x * chunk_dim_y * coords.z;
}
void set_block(glm::vec<3, int> coords, BlockType block) {
int index = block_coords_to_index(coords);
if(index == -1) {
std::cout << "WARNING: Attempted to set block outside chunk\n";
return;
}
blocks.at(index) = block;
is_dirty = true;
}
// coords is relative to the chunk's local frame!!
BlockType get_block(glm::vec<3, int> coords) {
int index = block_coords_to_index(coords);
if(index == -1) return BlockType::Air;
return blocks[index];
}
void generate_chunk_mesh() {
if(!mesh) return;
mesh->mesh_data.vertexes.clear();
mesh->mesh_data.indexes.clear();
// vector::clear() doesn't free the memory, so these reserves are probably redundant right now
mesh->mesh_data.vertexes.reserve(max_num_vertexes);
mesh->mesh_data.indexes.reserve(max_num_indexes);
for(int x = 0; x < chunk_dim_x; ++x) {
for(int y = 0; y < chunk_dim_y; ++y) {
for(int z = 0; z < chunk_dim_z; ++z) {
auto cube_pos = glm::ivec3{x,y,z};
if(get_block(cube_pos) == BlockType::Air) {
continue;
}
for(int dir = PLUS_X; dir <= MINUS_Z; dir++) {
#ifdef DONT_CULL_HIDDEN_FACES
emit_cube_face(cube_pos, (FaceDir)dir, mesh->mesh_data);
#else
if(get_block(cube_pos + dir_to_vec[dir]) == BlockType::Air) {
emit_cube_face(cube_pos, (FaceDir)dir, mesh->mesh_data);
}
#endif
}
}
}
}
glNamedBufferData(mesh->vbo,
mesh->mesh_data.vertexes.size() * sizeof(mesh->mesh_data.vertexes[0]),
mesh->mesh_data.vertexes.data(),
GL_DYNAMIC_DRAW
);
glNamedBufferData(mesh->ebo,
mesh->mesh_data.indexes.size() * sizeof(mesh->mesh_data.indexes[0]),
mesh->mesh_data.indexes.data(),
GL_DYNAMIC_DRAW);
}
void render(const Camera& camera) {
if(is_dirty) {
generate_chunk_mesh();
is_dirty = false;
}
GLuint shader = shader_catalog.get("chunk");
glUseProgram(shader);
glm::vec3 abs_position{};
for(int a = 0; a < 3; ++a) {
abs_position[a] = (float)position[a] * (float)chunk_dim[a];
}
glm::mat4x4 t_model = glm::translate(glm::mat4x4{1}, abs_position);
glUniformMatrix4fv(glGetUniformLocation(shader, "t_model"), 1, GL_FALSE, glm::value_ptr(t_model));
glm::mat4x4 t_view = get_view_transform(camera);
glUniformMatrix4fv(glGetUniformLocation(shader, "t_view"), 1, GL_FALSE, glm::value_ptr(t_view));
glm::mat4x4 t_perspective = get_perspective_transform(camera);
glUniformMatrix4fv(glGetUniformLocation(shader, "t_perspective"), 1, GL_FALSE, glm::value_ptr(t_perspective));
glBindVertexArray(mesh->vao);
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDrawElements(GL_TRIANGLES, mesh->mesh_data.indexes.size(), GL_UNSIGNED_INT, nullptr);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
};
template< typename T > // add template parameter to strongly type the handles
struct PoolHandle {
int index;
uint32_t generation;
};
template< typename T >
bool operator==(PoolHandle<T> first, PoolHandle<T> second) {
return first.index == second.index && first.generation == second.generation;
}
template< typename T, int MaxNumElements >
struct Pool {
alignas(T) unsigned char buf[sizeof(T) * MaxNumElements];
uint32_t generations[MaxNumElements];
int free_indexes_stack[MaxNumElements];
int free_indexes_sp; // points to the top element of the stack
Pool() : buf{}, generations{}, free_indexes_stack{}, free_indexes_sp{} {
for(int i = 0; i < MaxNumElements; ++i) {
free_indexes_stack[i] = i;
}
free_indexes_sp = 0;
}
int size() const {
return free_indexes_sp;
}
int capacity() const {
return MaxNumElements;
}
// returns -1 if stack is empty
int free_indexes_stack_pop() {
if(free_indexes_sp >= MaxNumElements) {
return -1;
}
int result = free_indexes_stack[free_indexes_sp];
free_indexes_sp += 1;
return result;
}
T* element_at(int index) {
return reinterpret_cast<T*>(&buf[index * sizeof(T)]);
}
PoolHandle<T> alloc() {
int index = free_indexes_stack_pop();
if(index == -1) { std::cerr << "Pool::alloc failed: the pool is full\n"; exit(1); }
new(element_at(index)) T{};
// TODO: what if generation overflows?
// generations[index] += 1;
return {.index=index, .generation=generations[index]};
}
// Returns true if handle is valid, false otherwise
bool check_handle_validity(PoolHandle<T> handle) {
if(handle.index >= MaxNumElements || handle.index < 0) {
return false;
}
if( generations[handle.index] != handle.generation ) {
return false;
}
return true;
}
void free(PoolHandle<T> handle) {
if( !check_handle_validity(handle) ) {
std::cerr << "Pool::free tried to free expired handle (double free)\n";
exit(1);
}
element_at(handle.index)->~T();
free_indexes_sp -= 1;
assert(free_indexes_sp >= 0);
free_indexes_stack[free_indexes_sp] = handle.index;
// TODO: what if generation overflows?
generations[handle.index] += 1;
}
// Returns nullptr if handle not valid
T* get(PoolHandle<T> handle) {
if( !check_handle_validity(handle) ) {
return nullptr;
}
return element_at(handle.index);
}
};
struct ChunkLRUStackNode {
PoolHandle<Chunk> chunk{};
std::optional<PoolHandle<ChunkLRUStackNode>> next{std::nullopt};
std::optional<PoolHandle<ChunkLRUStackNode>> prev{std::nullopt};
};
template< size_t max_loaded_chunks >
struct ChunkLRUStack {
Pool<ChunkLRUStackNode, max_loaded_chunks> nodes{};
// top of the stack is MRU, bottom is the LRU chunk
std::optional<PoolHandle<ChunkLRUStackNode>> bottom{std::nullopt};
std::optional<PoolHandle<ChunkLRUStackNode>> top{std::nullopt};
ChunkLRUStack() : nodes{}, bottom{std::nullopt}, top{std::nullopt} {}
PoolHandle<ChunkLRUStackNode> push_mru(PoolHandle<Chunk> chunk) {
auto new_node_h = nodes.alloc();
nodes.get(new_node_h)->next = std::nullopt;
nodes.get(new_node_h)->prev = std::nullopt;
nodes.get(new_node_h)->chunk = chunk;
if(!top.has_value()) {
// top (and bottom) is null => stack is empty
assert(!bottom.has_value());
top = bottom = new_node_h;
return new_node_h;
}
auto top_node = nodes.get(*top);
top_node->next = new_node_h;
nodes.get(new_node_h)->prev = top;
top = new_node_h;
return new_node_h;
}
// Gets and removes the LRU chunk from the bottom of the stack.
// Returns std::nullopt when lru stack is empty
std::optional<PoolHandle<Chunk>> get_and_remove_lru_chunk() {
if(!bottom.has_value()) {
return std::nullopt;
}
ChunkLRUStackNode* bottom_node = nodes.get(*bottom);
auto result = bottom_node->chunk;
auto new_bottom = bottom_node->next;
nodes.free(*bottom);
if(new_bottom) {
ChunkLRUStackNode *new_bottom_node = nodes.get(*new_bottom);
new_bottom_node->prev = std::nullopt;
bottom = new_bottom;
check_consistency_node(*bottom);
check_consistency_node(*top);
}
else {
// stack only contains one node (top==bottom)
top = bottom = std::nullopt;
}
return result;
}
void promote_to_mru(PoolHandle<ChunkLRUStackNode> chunk) {
ChunkLRUStackNode* chunk_node = nodes.get(chunk);
if(!chunk_node) {
std::cerr << "ChunkLRUStack::promote_to_mru: given chunk handle is invalid\n";
exit(1);
}
if(chunk == *top) {
// chunk is already at the top
return;
}
// link chunk_node.next and chunk_node.prev together
ChunkLRUStackNode* next_node = nodes.get(*(chunk_node->next));
next_node->prev = chunk_node->prev;
if(chunk_node->prev) {
ChunkLRUStackNode* prev_node = nodes.get(*(chunk_node->prev));
prev_node->next = chunk_node->next;
} else {
// chunk was the bottom, set new bottom to chunk_node->next
bottom = chunk_node->next;
}
// put chunk at the top
// but first clear chunk's next and prev pointers
chunk_node->next = chunk_node->prev = std::nullopt;
ChunkLRUStackNode* top_node = nodes.get(*top);
top_node->next = chunk;
chunk_node->prev = top;
top = chunk;
}
void check_consistency() {
auto cur = bottom;
while(cur != std::nullopt) {
ChunkLRUStackNode* cur_node = nodes.get(*cur);
if(cur_node->prev.has_value()) {
assert(nodes.check_handle_validity(*cur_node->prev));
}
if(cur_node->next.has_value()) {
assert(nodes.check_handle_validity(*cur_node->next));
}
cur = cur_node->next;
}
}
void check_consistency_node(PoolHandle<ChunkLRUStackNode> node) {
ChunkLRUStackNode* the_node = nodes.get(node);
if(the_node->prev.has_value()) {
assert(nodes.check_handle_validity(*the_node->prev));
}
if(the_node->next.has_value()) {
assert(nodes.check_handle_validity(*the_node->next));
}
}
};
struct LoadedChunkInfo {
PoolHandle<Chunk> chunk;
PoolHandle<ChunkLRUStackNode> lru_node;
};
struct World {
Chunk chunk;
static constexpr int max_loaded_chunks = 30;
Pool<Chunk, max_loaded_chunks> chunk_pool{};
// LoadedChunkInfo loaded_chunks_sorted[max_loaded_chunks]{};
// int loaded_chunks_sorted_size = 0;
std::unordered_map<uint64_t, LoadedChunkInfo> loaded_chunks{};
ChunkLRUStack<max_loaded_chunks> lru_stack{};
World() : chunk{{0,0,0}}, chunk_pool{}, loaded_chunks{}, lru_stack{} {
}
// TODO: find a good name for this modulo function
static inline int my_mod(int a, int b) {
return ((a % b) + b) % b;
}
static inline int my_div(int a, int b) {
int m = my_mod(a,b);
return (a - m) / b;
}
struct GetChunkAndBlockResult {
Chunk* chunk;
glm::ivec3 block_coord;
};
GetChunkAndBlockResult get_chunk_and_block(glm::ivec3 coords) {
glm::vec<3, int16_t> chunk_coord{};
for(int a = 0; a < 3; ++a) {
chunk_coord[a] = my_div(coords[a], Chunk::chunk_dim[a]);
}
glm::ivec3 block_coord{};
for(int a = 0; a < 3; ++a) {
block_coord[a] = my_mod(coords[a], Chunk::chunk_dim[a]);
}
auto search_result = search_loaded_chunk(chunk_coord);
if(!search_result.found) {
return {.chunk=nullptr, .block_coord={}};
}
Chunk* the_chunk = chunk_pool.get(search_result.chunk_info->chunk);
return {.chunk=the_chunk, .block_coord=block_coord};
}
BlockType get_block(glm::ivec3 coords) {
auto chunk_and_block = get_chunk_and_block(coords);
if(!chunk_and_block.chunk) {
return BlockType::Air;
}
return chunk_and_block.chunk->get_block(chunk_and_block.block_coord);
}
void set_block(glm::ivec3 coords, BlockType block_type) {
auto chunk_and_block = get_chunk_and_block(coords);
if(!chunk_and_block.chunk) {
return;
}
chunk_and_block.chunk->set_block(chunk_and_block.block_coord, block_type);
}
struct BlockHitInfo {
glm::ivec3 block;
FaceDir face;
glm::vec3 hit_position;
bool is_hit;
};
BlockHitInfo hit_block(glm::vec3 ray_origin, glm::vec3 ray_dir, int max_ray_length_in_blocks) {
ray_dir = glm::normalize(ray_dir);
glm::ivec3 cur;
for(int a = 0; a < 3; ++a) {
cur[a] = (int)ray_origin[a];
}
glm::ivec3 step;
for(int a = 0; a < 3; ++a) {
step[a] = ray_dir[a] > 0 ? 1 : (ray_dir[a] < 0 ? -1 : 0);
}
glm::vec3 t_max;
for(int a = 0; a < 3; ++a) {
if(ray_dir[a] != 0) {
float dim_a_intersect = step[a] > 0 ? (int)(ray_origin[a] + (float)step[a]) : (int)ray_origin[a];
t_max[a] = (dim_a_intersect - ray_origin[a]) / (ray_dir[a]);
} else {
t_max[a] = std::numeric_limits<float>::max();
}
}
glm::vec3 t_delta;
for(int a = 0; a < 3; ++a) {
t_delta[a] = 1 / abs(ray_dir[a]); // voxel size == 1
}
int blocks_traversed = 0;
while(blocks_traversed < max_ray_length_in_blocks) {
++blocks_traversed;
FaceDir face{};
glm::vec3 hit_position{};
if(t_max.x < t_max.y && t_max.x < t_max.z) {
hit_position = ray_origin + t_max.x * ray_dir;
cur.x += step.x;
t_max.x += t_delta.x;
face = step.x > 0 ? MINUS_X : PLUS_X;
}
else if(t_max.y < t_max.z) {
hit_position = ray_origin + t_max.y * ray_dir;
cur.y += step.y;
t_max.y += t_delta.y;
face = step.y > 0 ? MINUS_Y : PLUS_Y;
}
else {
hit_position = ray_origin + t_max.z * ray_dir;
cur.z += step.z;
t_max.z += t_delta.z;
face = step.z > 0 ? MINUS_Z : PLUS_Z;
}
if(get_block(cur) != BlockType::Air) {
return {.block=cur, .face=face, .hit_position=hit_position, .is_hit=true};
}
}
// no block was hit within the given block distance
return {.block={}, .face={}, .hit_position={}, .is_hit=false};
}
void render(const Camera& camera) {
chunk.render(camera);
for(auto& c : loaded_chunks ) {
auto chunk_handle = c.second.chunk;
auto the_chunk = chunk_pool.get(chunk_handle);
the_chunk->render(camera);
}
}
// // Performs a binary search on loaded_chunks_sorted array (sorted in increasing values)
// // Returns the index in the array where to_search was found
// // If to_search is not present in the array then the index where to_search should be inserted is returned
// int binary_search(uint64_t to_search, bool& found) {
// int first = 0;
// int last = loaded_chunks_sorted_size-1;
// while(first <= last) {
// int m = (last + first) / 2;
// uint64_t m_val = loaded_chunks_sorted_get_hash(m);
// if(m_val == to_search) {
// found = true;
// return m;
// }