-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
1708 lines (1512 loc) · 54.2 KB
/
main.c
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
/* main.c
a simple 3D sandbox brick game
Gabriel Campbell
created 2022-07-05 */
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <string.h>
#include <float.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define GL_GLEXT_PROTOTYPES
#include <GL/gl.h>
#include <GL/glext.h>
#include <GLFW/glfw3.h>
const uint32_t vsync = 1;
double cursor_x, cursor_y;
int32_t prev_x, prev_y;
int32_t scroll_x, scroll_y;
int32_t prev_scroll_x, prev_scroll_y;
float window_width = 640, window_height = 480;
float fovy = 60;
float near = 0.1;
float far = 100;
uint8_t enable_physics_draw = 0;
typedef struct vec2 { float x,y; } vec2;
typedef struct vec3 { float x,y,z; } vec3;
typedef struct vec4 { float x,y,z,w; } vec4;
vec3 __sub_vec3(vec3 a, vec3 b);
vec3 __add_vec3(vec3 a, vec3 b);
vec3 __scale_vec3(vec3 v, float s);
typedef struct brick_t brick_t;
typedef struct collision_t collision_t;
typedef struct camera_t camera_t;
void add_brick_collider_aabb(int32_t brick_id);
uint32_t add_collider_aabb(vec3 pos, vec3 scale);
typedef struct camera_t {
vec3 pos;
vec4 quat;
int32_t zoom;
} camera_t;
typedef struct player_t {
uint32_t entity_id;
char* name;
camera_t camera;
uint8_t focused;
int32_t selected_brick_id; // -1 if none
uint8_t selection_mode; // 0 = selected, 1 = scale, 2 = translate, 3 = color
uint8_t selection_colors[3]; // the new color for selected brick
uint8_t n_selection_colors; // which of R, G, B the current color selection is on 0-2
} player_t;
player_t* player;
/*==================================================*/
/* MESH DATA AND MANAGEMENT */
/*==================================================*/
typedef struct mesh_t {
GLuint vbo_id, ibo_id, vao_id;
uint32_t n_indices;
uint32_t vtx_format; // 0 = v3 pos, 1 = v3 pos v3 norm (default mesh), 2 = v3 pos v3 norm v2 tex
uint8_t has_ibo;
} mesh_t;
mesh_t* meshes;
uint32_t n_meshes;
// create a mesh and return the mesh ID
uint32_t create_mesh(float* vtx_data, uint16_t* idx_data, uint32_t vbo_size, uint32_t ibo_size, uint32_t vtx_format) {
uint32_t stride = 0;
switch(vtx_format) {
case 0: stride = 12; break;
case 1: stride = 24; break;
case 2: stride = 32; break;
default: printf("internal error: create_mesh given invalid vtx_format\n"); exit(1);
}
GLuint buffers[2];
glGenBuffers(2,buffers);
glBindBuffer(GL_ARRAY_BUFFER,buffers[0]);
glBufferData(GL_ARRAY_BUFFER, vbo_size, vtx_data, GL_STATIC_DRAW);
if(idx_data) {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,buffers[1]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,ibo_size,idx_data,GL_STATIC_DRAW);
}
GLuint vao_id = 0;
glGenVertexArrays(1,&vao_id);
glBindVertexArray(vao_id);
glBindBuffer(GL_ARRAY_BUFFER,buffers[0]);
if(idx_data) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,buffers[1]);
switch(vtx_format) {
case 0: // v3 pos
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,stride,0);
glEnableVertexAttribArray(0); break;
case 1: // v3 pos, v3 norm
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,stride,0);
glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,stride,(void*)12);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1); break;
case 2: // v3 pos, v3 norm, v2 tex coord
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,stride,0);
glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,stride,(void*)12);
glVertexAttribPointer(2,2,GL_FLOAT,GL_FALSE,stride,(void*)24);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2); break;
}
meshes = realloc(meshes, sizeof(mesh_t)*(n_meshes+1));
meshes[n_meshes].vbo_id = buffers[0];
meshes[n_meshes].ibo_id = buffers[1];
meshes[n_meshes].vao_id = vao_id;
meshes[n_meshes].n_indices = idx_data ? ibo_size/2 : vbo_size/stride;
meshes[n_meshes].vtx_format = vtx_format;
meshes[n_meshes].has_ibo = idx_data ? 1 : 0, meshes[n_meshes].ibo_id = buffers[1];
return n_meshes++;
}
// create the default brick mesh (1x1x1)
void init_mesh() {
// 12 triangles (36 indices)
uint16_t ibo_data[] = {
0, 1, 2, 2, 1, 3,
4, 5, 6, 6, 5, 7,
8, 9, 10, 10, 9, 11,
12, 13, 14, 14, 13, 15,
16, 17, 18, 18, 17, 19,
20, 21, 22, 22, 21, 23 };
// 24 vertices (3 different vertices per corner, as each corner is shared by 3 faces)
float vbo_data[] = {
0, 0, 1, 0, 0, 1, 0, 0, // face 0
1, 0, 1, 0, 0, 1, 0, 1,
0, 1, 1, 0, 0, 1, 1, 0,
1, 1, 1, 0, 0, 1, 1, 1,
0, 1, 1, 0, 1, 0, 0, 0, // face 1
1, 1, 1, 0, 1, 0, 0, 1,
0, 1, 0, 0, 1, 0, 1, 0,
1, 1, 0, 0, 1, 0, 1, 1,
0, 1, 0, 0, 0, -1, 1, 1, // face 2
1, 1, 0, 0, 0, -1, 0, 1,
0, 0, 0, 0, 0, -1, 1, 0,
1, 0, 0, 0, 0, -1, 0, 0,
0, 0, 0, 0, -1, 0, 0, 0, // face 3
1, 0, 0, 0, -1, 0, 0, 1,
0, 0, 1, 0, -1, 0, 1, 0,
1, 0, 1, 0, -1, 0, 1, 1,
1, 0, 1, 1, 0, 0, 0, 0, // face 4
1, 0, 0, 1, 0, 0, 0, 1,
1, 1, 1, 1, 0, 0, 1, 0,
1, 1, 0, 1, 0, 0, 1, 1,
0, 0, 0, -1, 0, 0, 0, 0, // face 5
0, 0, 1, -1, 0, 0, 0, 1,
0, 1, 0, -1, 0, 0, 1, 0,
0, 1, 1, -1, 0, 0, 1, 1
};
create_mesh(vbo_data, ibo_data, sizeof(vbo_data), sizeof(ibo_data), 2);
}
/*==================================================*/
/* TEXTURE LOADING */
/*==================================================*/
GLuint* gl_textures;
uint32_t n_textures;
// return 0 on failure
GLuint load_texture_from_file(char* path) {
uint32_t w, h, comp;
uint8_t* image = stbi_load(path, &w, &h, &comp, 0);
if(!image) {
printf("internal error: failed to load texture from file %s\n", path);
return 0;
}
// create texture
GLuint tbo_id;
glGenTextures(1,&tbo_id);
glBindTexture(GL_TEXTURE_2D, tbo_id);
// upload image to TBO
if(comp == 3)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
else if(comp == 4)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
// return created texture's ID (or 0 on failure)
gl_textures = realloc(gl_textures, sizeof(GLuint)*(n_textures+1));
gl_textures[n_textures++] = tbo_id;
stbi_image_free(image);
return tbo_id;
}
/*==================================================*/
/* WORLD DATA AND MANAGEMENT */
/*==================================================*/
typedef struct collision_t {
vec3 pos; // minimum
vec3 dim;
int32_t brick_id; // -1 if not a brick collider
uint8_t deleted;
} collision_t;
typedef struct brick_t {
uint32_t mesh_id;
vec3 pos, scale;
vec4 quat, color;
GLuint texture_ids[6]; // for each face, the ID of a texture. 0 if untextured.
uint8_t repeat_textures[6];
uint8_t has_gravity, has_collision;
uint8_t deleted;
} brick_t;
typedef struct world_t {
brick_t* bricks;
uint32_t n_bricks;
collision_t* colls;
uint32_t n_colls;
char* name;
} world_t;
world_t* world;
void init_world() {
char* name = "Test World";
world = calloc(1,sizeof(world_t));
world->name = calloc(1,sizeof(name)+1);
strcpy(world->name,name);
}
void add_brick(world_t* world, vec3 pos, vec4 quat, vec3 scale, vec4 color, uint32_t mesh_id,
uint8_t has_gravity, uint8_t has_collision) {
brick_t new_brick;
new_brick.pos = pos;
new_brick.quat = quat;
new_brick.scale = scale;
new_brick.color = color;
new_brick.mesh_id = mesh_id;
new_brick.has_gravity = has_gravity;
new_brick.has_collision = has_collision;
memset(&new_brick.texture_ids,0,sizeof(GLuint)*6);
new_brick.texture_ids[1] = gl_textures[0]; // top
new_brick.texture_ids[3] = gl_textures[1]; // bottom
new_brick.repeat_textures[1] = 1;
new_brick.repeat_textures[3] = 1;
new_brick.deleted = 0;
world->bricks = realloc(world->bricks, sizeof(brick_t)*(world->n_bricks+1));
world->bricks[world->n_bricks++] = new_brick;
if(has_collision) add_brick_collider_aabb(world->n_bricks-1);
}
void delete_brick(uint32_t brick_id) {
if(!world->bricks[brick_id].deleted) {
world->bricks[brick_id].deleted = 1;
for(uint32_t i = 0; i < world->n_colls; i++)
if(world->colls[i].brick_id == brick_id) world->colls[i].deleted = 1;
}
}
void add_brick_texture(uint32_t brick_id, uint8_t face, GLuint texture, uint8_t repeat) {
world->bricks[brick_id].texture_ids[face] = texture;
world->bricks[brick_id].repeat_textures[face] = repeat;
}
/*==================================================*/
/* ENTITIES AND MANAGEMENT */
/*==================================================*/
typedef struct entity_t {
vec3 pos;
vec4 quat;
uint8_t is_humanoid; // whether or not to render as a character
uint32_t mesh_id; // mesh to render as; ignored if is_humanoid
uint32_t coll_id;
// for humanoids
uint32_t jump_state; // 0=able to jump, 1=cannot jump; mid-jump or falling
float fall_distance; // distance fallen without collision
float health; // 0-1
vec4 part_colors[6]; // torso, left arm, right arm, left leg, right leg, head
} entity_t;
entity_t* entities;
uint32_t n_entities;
uint32_t add_humanoid_entity(vec3 pos, vec4 quat, float health, vec4* colors) {
entity_t new_entity;
memset(&new_entity,0,sizeof(entity_t));
new_entity.pos = pos;
new_entity.quat = quat;
new_entity.is_humanoid = 1;
new_entity.health = health;
new_entity.jump_state = 1;
for(uint32_t i = 0; i < 6; i++)
new_entity.part_colors[i] = colors[i];
vec3 aabb_scale = {2,4,2};
vec3 aabb_pos = new_entity.pos;
aabb_pos.x -= 1;
aabb_pos.z -= 1;
aabb_pos.y -= 2;
new_entity.coll_id = add_collider_aabb(aabb_pos, aabb_scale);
entities = realloc(entities, sizeof(entity_t)*(n_entities+1));
entities[n_entities] = new_entity;
return n_entities++;
}
/*==================================================*/
/* PHYSICS */
/*==================================================*/
// given a brick, calc + add a new collider
void add_brick_collider_aabb(int32_t brick_id) {
brick_t brick = world->bricks[brick_id];
if(!brick.mesh_id) { // default mesh has a known bounding box
collision_t coll = { brick.pos, brick.scale, brick_id, 0 };
world->colls = realloc(world->colls,sizeof(collision_t)*(world->n_colls+1));
world->colls[world->n_colls++] = coll;
} else printf("error in add_brick_collider_aabb: auto-calculation of bounding box only implemented for default brick mesh\n");
}
// calc + add a new collider (returns collider ID)
uint32_t add_collider_aabb(vec3 pos, vec3 scale) {
collision_t coll = { pos, scale, -1, 0 };
world->colls = realloc(world->colls,sizeof(collision_t)*(world->n_colls+1));
world->colls[world->n_colls] = coll;
return world->n_colls++;
}
// check for collision between a given AABB and all others
uint8_t check_collision_aabb(uint32_t coll_id) {
collision_t coll = world->colls[coll_id];
vec3 coll_max = __add_vec3(coll.pos,coll.dim);
for(uint32_t i = 0; i < world->n_colls; i++) {
if(i == coll_id || world->colls[i].deleted) continue;
vec3 min = world->colls[i].pos;
vec3 max = __add_vec3(min,world->colls[i].dim);
if((coll.pos.x <= max.x && coll_max.x >= min.x)
&& (coll.pos.y <= max.y && coll_max.y >= min.y)
&& (coll.pos.z <= max.z && coll_max.z >= min.z))
return 1;
}
return 0;
}
typedef struct intersection_t {
float t; // distance from origin to intersection
uint32_t coll_id; // ID of collider intersected with
} intersection_t;
// check if a ray collides with any collider; if so, return ID of the collider, otherwise return -1
// 'intersection' is newly allocated list of collider IDs that the ray intersects with, and set to 0 if there's no intersections
// returns number of intersections (the closest intersection, if closest_hit is non-zero)
uint32_t check_ray_intersection(vec3 ray_pos, vec3 ray_dir, intersection_t** intersections_ret, uint8_t closest_hit) {
if(!intersections_ret) {
printf("internal error at check_ray_intersection: intersections arg is 0.\n");
exit(1);
}
uint32_t n_intersections = 0;
intersection_t* intersections = 0;
for(uint32_t i = 0; i < world->n_colls; i++) {
if(world->colls[i].deleted) continue;
vec3 bmin = world->colls[i].pos;
vec3 bmax = __add_vec3(world->colls[i].pos,world->colls[i].dim);
vec3 dirfrac = { 1.0f/ray_dir.x, 1.0f/ray_dir.y, 1.0f/ray_dir.z };
float t1 = (bmin.x - ray_pos.x)*dirfrac.x;
float t2 = (bmax.x - ray_pos.x)*dirfrac.x;
float t3 = (bmin.y - ray_pos.y)*dirfrac.y;
float t4 = (bmax.y - ray_pos.y)*dirfrac.y;
float t5 = (bmin.z - ray_pos.z)*dirfrac.z;
float t6 = (bmax.z - ray_pos.z)*dirfrac.z;
float tmin = fmaxf(fmaxf(fminf(t1, t2), fminf(t3, t4)), fminf(t5, t6));
float tmax = fminf(fminf(fmaxf(t1, t2), fmaxf(t3, t4)), fmaxf(t5, t6));
if(tmax < 0) continue; // intersection, but AABB is behind ray
if(tmin > tmax) continue; // no intersection
// intersection; add to intersections list
intersection_t new_intersection;
new_intersection.t = tmin; // length of ray until intersection
new_intersection.coll_id = i;
intersections = realloc(intersections, sizeof(intersection_t)*(n_intersections+1));
intersections[n_intersections++] = new_intersection;
}
if(closest_hit && n_intersections) { // return only the closest hit in the 'intersections' array (lowest 't' value)
uint32_t min_idx = 0;
float min_t = FLT_MAX;
for(uint32_t i = 0; i < n_intersections; i++)
if(intersections[i].t < min_t) {
min_idx = i;
min_t = intersections[i].t;
}
intersections[0] = intersections[min_idx];
intersections = realloc(intersections,sizeof(intersection_t));
n_intersections = 1;
}
*intersections_ret = intersections;
return n_intersections;
}
// step the physics simulation
void physics_step() {
float gravity_step = 0.1;
// for each brick collider with gravity, check if going down some is possible
for(uint32_t i = 0; i < world->n_colls; i++)
if(world->colls[i].brick_id != -1 && world->bricks[world->colls[i].brick_id].has_gravity
&& !world->bricks[world->colls[i].brick_id].deleted) {
world->colls[i].pos.y -= gravity_step;
world->bricks[world->colls[i].brick_id].pos.y -= gravity_step;
if(check_collision_aabb(i)) {
world->colls[i].pos.y += gravity_step;
world->bricks[world->colls[i].brick_id].pos.y += gravity_step;
}
}
// for each entity's collider, check if going down some is possible
for(uint32_t i = 0; i < n_entities; i++) {
entity_t* entity = &entities[i];
world->colls[entity->coll_id].pos.y -= gravity_step;
entity->pos.y -= gravity_step;
entity->jump_state = 1;
entity->fall_distance += gravity_step;
if(check_collision_aabb(entity->coll_id)) {
world->colls[i].pos.y += gravity_step;
entity->pos.y += gravity_step;
entity->jump_state = 0; // on the ground; can jump again
entity->fall_distance = 0;
}
}
// for each brick with gravity and no collider, move down some
for(uint32_t i = 0; i < world->n_bricks; i++)
if(world->bricks[i].has_gravity && !world->bricks[i].has_collision && !world->bricks[i].deleted)
world->bricks[i].pos.y -= gravity_step;
}
void translate_brick(int32_t brick_id, vec3 translation) {
brick_t brick = world->bricks[brick_id];
vec3 new_pos = __add_vec3(brick.pos,translation);
if(brick.has_collision) {
for(uint32_t i = 0; i < world->n_colls; i++)
if(world->colls[i].brick_id == brick_id) {
if(check_collision_aabb(i)) return;
else break;
}
for(uint32_t i = 0; i < world->n_colls; i++) {
if(world->colls[i].brick_id == brick_id) {
world->bricks[brick_id].pos = new_pos;
world->colls[i].pos = new_pos;
}
}
} else world->bricks[brick_id].pos = new_pos;
}
void set_brick_pos(uint32_t brick_id, vec3 new_pos) {
brick_t brick = world->bricks[brick_id];
world->bricks[brick_id].pos = new_pos;
if(brick.has_collision)
for(uint32_t i = 0; i < world->n_colls; i++)
if(world->colls[i].brick_id == brick_id)
world->colls[i].pos = new_pos;
}
void set_brick_scale(uint32_t brick_id, vec3 new_scale) {
world->bricks[brick_id].scale = new_scale;
if(world->bricks[brick_id].has_collision)
for(uint32_t i = 0; i < world->n_colls; i++)
if(world->colls[i].brick_id == brick_id)
world->colls[i].dim = new_scale;
}
/*==================================================*/
/* MATHS AND CAMERA */
/*==================================================*/
typedef struct mat4 { // m[row | col] - stored in column-major
float m00, m10, m20, m30;
float m01, m11, m21, m31;
float m02, m12, m22, m32;
float m03, m13, m23, m33;
} mat4;
typedef camera_t camera_t;
mat4 identity() {
mat4 id;
id.m00 = 1.0; id.m01 = 0.0; id.m02 = 0.0; id.m03 = 0.0;
id.m10 = 0.0; id.m11 = 1.0; id.m12 = 0.0; id.m13 = 0.0;
id.m20 = 0.0; id.m21 = 0.0; id.m22 = 1.0; id.m23 = 0.0;
id.m30 = 0.0; id.m31 = 0.0; id.m32 = 0.0; id.m33 = 1.0;
return id;
}
mat4 mat4_mat4(mat4 a, mat4 b) {
mat4 p;
// first row
p.m00 = a.m00*b.m00 + a.m01*b.m10 + a.m02*b.m20 + a.m03*b.m30;
p.m01 = a.m00*b.m01 + a.m01*b.m11 + a.m02*b.m21 + a.m03*b.m31;
p.m02 = a.m00*b.m02 + a.m01*b.m12 + a.m02*b.m22 + a.m03*b.m32;
p.m03 = a.m00*b.m03 + a.m01*b.m13 + a.m02*b.m23 + a.m03*b.m33;
// second row
p.m10 = a.m10*b.m00 + a.m11*b.m10 + a.m12*b.m20 + a.m13*b.m30;
p.m11 = a.m10*b.m01 + a.m11*b.m11 + a.m12*b.m21 + a.m13*b.m31;
p.m12 = a.m10*b.m02 + a.m11*b.m12 + a.m12*b.m22 + a.m13*b.m32;
p.m13 = a.m10*b.m03 + a.m11*b.m13 + a.m12*b.m23 + a.m13*b.m33;
// third row
p.m20 = a.m20*b.m00 + a.m21*b.m10 + a.m22*b.m20 + a.m23*b.m30;
p.m21 = a.m20*b.m01 + a.m21*b.m11 + a.m22*b.m21 + a.m23*b.m31;
p.m22 = a.m20*b.m02 + a.m21*b.m12 + a.m22*b.m22 + a.m23*b.m32;
p.m23 = a.m20*b.m03 + a.m21*b.m13 + a.m22*b.m23 + a.m23*b.m33;
// fourth row
p.m30 = a.m30*b.m00 + a.m31*b.m10 + a.m32*b.m20 + a.m33*b.m30;
p.m31 = a.m30*b.m01 + a.m31*b.m11 + a.m32*b.m21 + a.m33*b.m31;
p.m32 = a.m30*b.m02 + a.m31*b.m12 + a.m32*b.m22 + a.m33*b.m32;
p.m33 = a.m30*b.m03 + a.m31*b.m13 + a.m32*b.m23 + a.m33*b.m33;
return p;
}
vec4 mat4_vec4(mat4 m, vec4 v) {
vec4 prod;
prod.x = m.m00 * v.x + m.m01 * v.y + m.m02 * v.z + m.m03 * v.w;
prod.y = m.m10 * v.x + m.m11 * v.y + m.m12 * v.z + m.m13 * v.w;
prod.z = m.m20 * v.x + m.m21 * v.y + m.m22 * v.z + m.m23 * v.w;
prod.w = m.m30 * v.x + m.m31 * v.y + m.m32 * v.z + m.m33 * v.w;
return prod;
}
// calculate a symmetrical-frustum projection matrix
mat4 perspective(float fovy, float aspect, float near, float far) {
fovy = fovy * 0.0174533; // from degrees to radians
mat4 m = identity();
float f = 1.0/tan(fovy/2.0);
m.m00 = f/aspect;
m.m11 = f;
m.m22 = -((far+near)/(far-near));
m.m23 = -((2*near*far)/(far-near));
m.m32 = -1;
m.m33 = 0;
return m;
}
float __dot_vec3(vec3 a, vec3 b) {
return a.x*b.x + a.y*b.y + a.z*b.z;
}
float __mag_vec3(vec3 v) {
return sqrt((v.x*v.x) + (v.y*v.y) + (v.z*v.z));
}
vec3 __normalize_vec3(vec3 v) {
float length = sqrt((v.x*v.x) + (v.y*v.y) + (v.z*v.z));
vec3 norm;
norm.x = v.x/length;
norm.y = v.y/length;
norm.z = v.z/length;
return norm;
}
vec4 __normalize_vec4(vec4 v) {
float length = sqrt((v.x*v.x) + (v.y*v.y) + (v.z*v.z) + (v.w*v.w));
vec4 norm;
norm.x = v.x/length;
norm.y = v.y/length;
norm.z = v.z/length;
norm.w = v.w/length;
return norm;
}
vec3 __cross_vec3(vec3 a, vec3 b) {
vec3 cross;
cross.x = a.y*b.z - a.z*b.y;
cross.y = a.z*b.x - a.x*b.z;
cross.z = a.x*b.y - a.y*b.x;
return cross;
}
// calculate difference of two vectors
vec3 __sub_vec3(vec3 a, vec3 b) {
vec3 diff;
diff.x = a.x - b.x;
diff.y = a.y - b.y;
diff.z = a.z - b.z;
return diff;
}
vec3 __add_vec3(vec3 a, vec3 b) {
vec3 sum;
sum.x = a.x + b.x;
sum.y = a.y + b.y;
sum.z = a.z + b.z;
return sum;
}
vec3 __scale_vec3(vec3 v, float s) {
vec3 scaled = {v.x*s,v.y*s,v.z*s};
return scaled;
}
vec4 __mult_vec4(vec4 a, vec4 b) {
vec4 v = { a.x*b.x, a.y*b.y, a.z*b.z, a.w*b.w };
return v;
}
vec4 __mult_quat(vec4 a, vec4 b) {
vec4 prod = {
a.x * b.w + a.y * b.z - a.z * b.y + a.w * b.x,
-a.x * b.z + a.y * b.w + a.z * b.x + a.w * b.y,
a.x * b.y - a.y * b.x + a.z * b.w + a.w * b.z,
-a.x * b.x - a.y * b.y - a.z * b.z + a.w * b.w
};
return prod;
}
// calculate a LookAt matrix
mat4 look_at(vec3 eye, vec3 center, vec3 up) {
vec3 f;
f.x = center.x - eye.x;
f.y = center.y - eye.y;
f.z = center.z - eye.z;
f = __normalize_vec3(f);
vec3 u = __normalize_vec3(up);
vec3 s = __cross_vec3(u,f);
u = __cross_vec3(f,s);
mat4 mat = identity();
mat.m00 = s.x; mat.m01 = s.y; mat.m02 = s.z;
mat.m10 = u.x; mat.m11 = u.y; mat.m12 = u.z;
mat.m20 = f.x; mat.m21 = f.y; mat.m22 = f.z;
mat.m03 = -__dot_vec3(s, eye);
mat.m13 = -__dot_vec3(u, eye);
mat.m23 = -__dot_vec3(f, eye);
return mat;
}
// calculate a translation matrix
mat4 translate(vec3 translation) {
mat4 mtranslation = identity();
mtranslation.m03 = translation.x;
mtranslation.m13 = translation.y;
mtranslation.m23 = translation.z;
return mtranslation;
}
// calculate a rotation matrix (rotation in degrees)
mat4 rotate(float angle, vec3 axis) {
angle = fmod(angle,360.0);
angle = angle * 0.0174533; // from degrees to radians
float x = axis.x;
float y = axis.y;
float z = axis.z;
float c = cos(angle);
float s = sin(angle);
float one_sub_c = 1.0 - c;
float zs = z*s;
float ys = y*s;
float xs = x*s;
float xz = x*z;
float yz = y*z;
mat4 mrot = identity();
mrot.m00 = x*x*(one_sub_c)+c;
mrot.m01 = x*y*(one_sub_c)-zs;
mrot.m02 = xz *(one_sub_c)+ys;
mrot.m10 = y*x*(one_sub_c)+zs;
mrot.m11 = y*y*(one_sub_c)+c;
mrot.m12 = yz *(one_sub_c)-xs;
mrot.m20 = xz *(one_sub_c)-ys;
mrot.m21 = yz *(one_sub_c)+xs;
mrot.m22 = z*z*(one_sub_c)+c;
return mrot;
}
// calculate a scale matrix
mat4 scale(vec3 s) {
mat4 mscale = identity();
mscale.m00 = s.x;
mscale.m11 = s.y;
mscale.m22 = s.z;
return mscale;
}
// convert Euler angles (given in degrees) to quaternion
vec4 euler_to_quat(vec3 angles) {
float c1, c2, c3;
float s1, s2, s3;
if(angles.x >= 0) angles.x = fmod(angles.x, 360.0);
else angles.x = 360 - fmod(-angles.x, 360);
if(angles.y >= 0) angles.y = fmod(angles.y, 360.0);
else angles.y = 360 - fmod(-angles.y, 360);
if(angles.z >= 0) angles.z = fmod(angles.z, 360.0);
else angles.z = 360 - fmod(-angles.z, 360);
angles.x = angles.x * 0.0174533;
angles.y = angles.y * 0.0174533;
angles.z = angles.z * 0.0174533;
c1 = cos(angles.y / 2.0);
c2 = cos(angles.z / 2.0);
c3 = cos(angles.x / 2.0);
s1 = sin(angles.y / 2.0);
s2 = sin(angles.z / 2.0);
s3 = sin(angles.x / 2.0);
vec4 quat;
quat.w = c1*c2*c3 - s1*s2*s3;
quat.x = s1*s2*c3 + c1*c2*s3;
quat.y = s1*c2*c3 + c1*s2*s3;
quat.z = c1*s2*c3 - s1*c2*s3;
float n = sqrt(pow(quat.x, 2) + pow(quat.y, 2) + pow(quat.z, 2) + pow(quat.w, 2));
float inv = 1.0/n;
quat.x = quat.x * inv;
quat.y = quat.y * inv;
quat.z = quat.z * inv;
quat.w = quat.w * inv;
return quat;
}
// create quaternion representing rotation around some arbitrary axis
vec4 quat_axis_rotation(vec3 axis, float angle) {
angle *= 0.0174533;
float fac = sinf(angle/2.0f);
vec4 quat; // calc x,y,z of quaternion
quat.x = axis.x * fac;
quat.y = axis.y * fac;
quat.z = axis.z * fac;
quat.w = cosf(angle/2.0f); // calc w value
return __normalize_vec4(quat);
}
vec3 quat_to_euler(vec4 quat) {
float sqw = quat.w*quat.w;
float sqx = quat.x*quat.x;
float sqy = quat.y*quat.y;
float sqz = quat.z*quat.z;
float unit = sqx + sqy + sqz + sqw; // if normalised is one, otherwise is correction factor
float test = quat.x*quat.y + quat.z*quat.w;
vec3 euler;
if(test > 0.499*unit) { // singularity at north pole
euler.y = 2 * atan2(quat.x,quat.w);
euler.z = 3.14159265358979323846/2;
euler.x = 0;
euler.y *= 57.2958; euler.z *= 57.2958;
return euler;
}
if(test < -0.499*unit) { // singularity at south pole
euler.y = -2 * atan2(quat.x,quat.w);
euler.z = -3.14159265358979323846/2;
euler.x = 0;
euler.y *= 57.2958; euler.z *= 57.2958;
return euler;
}
euler.y = atan2(2*quat.y*quat.w-2*quat.x*quat.z , sqx - sqy - sqz + sqw);
euler.z = asin(2*test/unit);
euler.x = atan2(2*quat.x*quat.w-2*quat.y*quat.z , -sqx + sqy - sqz + sqw);
euler.x *= 57.2958; euler.y *= 57.2958; euler.z *= 57.2958;
return euler;
}
// rotate a quaternion
vec4 rotate_quat(vec4 quat, vec3 angles) {
vec4 v = euler_to_quat(angles);
return __mult_quat(v,quat);
}
mat4 quat_to_mat4(vec4 quat) {
float xx = quat.x * quat.x;
float xy = quat.x * quat.y;
float xz = quat.x * quat.z;
float xw = quat.x * quat.w;
float yy = quat.y * quat.y;
float yz = quat.y * quat.z;
float yw = quat.y * quat.w;
float zz = quat.z * quat.z;
float zw = quat.z * quat.w;
mat4 rotation = identity();
rotation.m00 = 1.0 - 2.0*yy - 2.0*zz;
rotation.m01 = 2.0 * xy - 2.0 * zw;
rotation.m02 = 2.0 * xz + 2.0 * yw;
rotation.m10 = 2.0 * xy + 2.0 * zw;
rotation.m11 = 1.0 - 2.0*xx - 2.0*zz;
rotation.m12 = 2.0 * yz - 2.0 * xw;
rotation.m20 = 2.0 * xz - 2.0 * yw;
rotation.m21 = 2.0 * yz + 2.0 * xw;
rotation.m22 = 1.0 - 2.0*xx - 2.0*yy;
return rotation;
}
// return coords of the center point of this camera
vec3 camera_center(camera_t cam) {
vec4 c4 = { 0,0,1,1 };
mat4 rot_matrix = quat_to_mat4(cam.quat);
c4 = mat4_vec4(rot_matrix, c4);
vec3 p;
p.x = cam.pos.x + c4.x;
p.y = cam.pos.y + c4.y;
p.z = cam.pos.z + c4.z;
return p;
}
// move a camera forward (or backward)
void forward(camera_t* cam, float units) {
if(units) {
vec3 c3 = camera_center(*cam);
c3.x = cam->pos.x - c3.x;
c3.y = cam->pos.y - c3.y;
c3.z = cam->pos.z - c3.z;
cam->pos.x = cam->pos.x + c3.x * units;
cam->pos.y = cam->pos.y + c3.y * units;
cam->pos.z = cam->pos.z + c3.z * units;
}
}
// move a camera leftward or rightward
void right(camera_t* cam, float units) {
if(units) {
vec4 c4; c4.x=1; c4.y=0; c4.z=0; c4.w=1; // default: camera looking down -z axis
mat4 rot_matrix = quat_to_mat4(cam->quat);
c4 = mat4_vec4(rot_matrix, c4);
cam->pos.x = cam->pos.x + c4.x * units;
cam->pos.y = cam->pos.y + c4.y * units;
cam->pos.z = cam->pos.z + c4.z * units;
}
}
/*==================================================*/
/* PLAYER CODE */
/*==================================================*/
typedef struct player_t player_t;
player_t init_player(char* name) {
player_t new_player;
memset(&new_player,0,sizeof(player_t));
new_player.name = calloc(1,strlen(name)+1);
strcpy(new_player.name,name);
vec3 pos = {0,0,0}, rot = { 0,0,0 };
vec4 quat = euler_to_quat(rot);
vec4 p_colors[] = {
{0,0,1,1},
{1,1,0,1},
{1,1,0,1},
{0,1,0,1},
{0,1,0,1},
{1,1,0,1}
};
new_player.entity_id = add_humanoid_entity(pos,quat,1,p_colors);
new_player.camera.quat = euler_to_quat(rot);
new_player.camera.zoom = 10;
new_player.selected_brick_id = -1;
return new_player;
}
// sets player position and updates player's AABB
void set_player_pos(vec3 new_pos) {
entity_t* entity = &entities[player->entity_id];
entity->pos = new_pos;
vec3 half_scale = __scale_vec3(world->colls[entity->coll_id].dim, 0.5);
vec3 aabb_pos = __sub_vec3(new_pos, half_scale);
world->colls[entity->coll_id].pos = aabb_pos;
}
void translate_player(vec3 translation) {
entity_t* entity = &entities[player->entity_id];
entity->pos = __add_vec3(entity->pos, translation);
world->colls[entity->coll_id].pos = __add_vec3(world->colls[entity->coll_id].pos, translation);
if(check_collision_aabb(entity->coll_id)) {
// check if small increase in Y would help before resetting (allows stair climbing)
vec3 step = { 0,1.25,0 };
entity->pos = __add_vec3(entity->pos, step);
world->colls[entity->coll_id].pos = __add_vec3(world->colls[entity->coll_id].pos, step);
if(!check_collision_aabb(entity->coll_id)) return;
entity->pos = __sub_vec3(entity->pos, translation);
entity->pos = __sub_vec3(entity->pos, step);
world->colls[entity->coll_id].pos = __sub_vec3(world->colls[entity->coll_id].pos, translation);
world->colls[entity->coll_id].pos = __sub_vec3(world->colls[entity->coll_id].pos, step);
}
}
/*==================================================*/
/* RENDERING */
/*==================================================*/
// render as the global 'player' variable
// a lot of the work was done in init_gl
// shader and program setting, and mesh generation (mesh 0 is our brick)
// these are the main programs:
// program_ids[0] - basic. reads only vec3 pos attribute; solid color (vtx_format >= 0).
// program_ids[1] - reads vec3 pos and vec3 norm attributes (vtx_format >= 1).
GLuint* program_ids;
uint32_t n_programs;
// create a new GL program
GLuint create_program(const char* vtx_shader_src, const char* pxl_shader_src) {
GLuint vtx_shader = glCreateShader(GL_VERTEX_SHADER);
GLuint pxl_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vtx_shader,1,&vtx_shader_src,0);
glShaderSource(pxl_shader,1,&pxl_shader_src,0);
glCompileShader(vtx_shader);
GLint success = 0;
glGetShaderiv(vtx_shader,GL_COMPILE_STATUS,&success);
if(!success) {
printf("failed to compile vertex shader.\n");
GLint max_length = 0;
glGetShaderiv(vtx_shader, GL_INFO_LOG_LENGTH, &max_length);
char* info_log = calloc(1,max_length);
glGetShaderInfoLog(vtx_shader, max_length, &max_length, &info_log[0]);
printf("%s\n", info_log);
exit(1);
}
glCompileShader(pxl_shader);
glGetShaderiv(pxl_shader,GL_COMPILE_STATUS,&success);
if(!success) {
printf("failed to compile pixel shader.\n");
GLint max_length = 0;
glGetShaderiv(pxl_shader, GL_INFO_LOG_LENGTH, &max_length);
char* info_log = calloc(1,max_length);
glGetShaderInfoLog(pxl_shader, max_length, &max_length, &info_log[0]);
printf("%s\n", info_log);
exit(1);
}
program_ids = realloc(program_ids, sizeof(GLuint));
program_ids[n_programs] = glCreateProgram();
glAttachShader(program_ids[n_programs],vtx_shader);
glAttachShader(program_ids[n_programs],pxl_shader);
glLinkProgram(program_ids[n_programs]);
glGetProgramiv(program_ids[n_programs],GL_LINK_STATUS,&success);
if(!success) {
printf("failed to link shaders.\n");
exit(1);
}
glDetachShader(program_ids[n_programs], vtx_shader);
glDetachShader(program_ids[n_programs], pxl_shader);
n_programs++;
}
void init_render() { // setup and set shader program, GL states
// setup depth test, blending
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
const char* vtx_shader_src_1 =
"#version 330 \n"
"layout(location=0) in vec3 vtx_pos; \n"
"uniform mat4 u_model, u_view, u_proj; \n"
"void main() { \n"
" gl_Position = u_proj * u_view * u_model * vec4(vtx_pos,1); \n"
"} ";
const char* pxl_shader_src_1 =
"#version 330 \n"
"layout(location=0) out vec4 final; \n"
"uniform vec4 u_color; \n"
"void main() { \n"
" final = u_color;\n"
"} ";
create_program(vtx_shader_src_1, pxl_shader_src_1);
const char* vtx_shader_src_2 =
"#version 330 \n"
"layout(location=0) in vec3 vtx_pos; \n"
"layout(location=1) in vec3 vtx_norm; \n"
"out vec3 pxl_norm; \n"
"out vec3 pxl_pos; \n"
"uniform mat4 u_model, u_view, u_proj; \n"
"void main() { \n"
" pxl_norm = mat3(transpose(inverse(u_model))) * vtx_norm;\n"
" pxl_pos = vec3(u_model * vec4(vtx_pos,1.0)); \n"
" gl_Position = u_proj * u_view * u_model * vec4(vtx_pos,1);\n"
"} ";