-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathphysics.h
1618 lines (1395 loc) · 58.7 KB
/
physics.h
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 "terragen.h"
#include <algorithm>
#include <boost/align/aligned_allocator.hpp>
#include <chrono>
#include <deque>
#include <iostream>
#include <mutex>
#include <vector>
#include <cassert>
#include <cstdarg>
#include <cstdint>
#include <cstring>
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/norm.hpp>
#define nil nullptr
#define takeoff_memcpy memcpy
/*
void *takeoff_memcpy(void *dest, const void *src, size_t n) {
size_t i = 0;
while((i + 1) * sizeof(uint64_t) <= n){
((uint64_t*)dest)[i] = ((uint64_t*)src)[i];
i++;
}
while(i * sizeof(uint8_t) < n){
((uint8_t*)dest)[i] = ((uint8_t*)src)[i];
i++;
}
return dest;
}
*/
using std::isnan;
using std::mutex;
using std::string;
auto now = std::chrono::high_resolution_clock::now;
using glm::dvec3;
using glm::vec3;
using glm::vec4;
using glm::dmat4;
using glm::dmat3;
using glm::dquat;
bool verbose = false;
bool POTATO_MODE = false;
bool LOW_MEMORY_MODE = false;
uint32_t frame_counter = 0;
float PI = 3.14159265359f;
enum terrain_upload_status_enum {
idle,
should_exit,
generating,
done_generating,
done_generating_first_time,
uploading,
done_uploading
};
enum vertex_type_id {
VERTEX_TYPE_NONE,
VERTEX_TYPE_TERRAIN,
VERTEX_TYPE_FARTERRAIN,
VERTEX_TYPE_TREETRUNK,
VERTEX_TYPE_LEAF
};
size_t min(size_t a, size_t b) {
return a > b ? b : a;
}
size_t max(size_t a, size_t b) {
return a < b ? b : a;
}
uint32_t min(uint32_t a, uint32_t b) {
return a > b ? b : a;
}
uint32_t max(uint32_t a, uint32_t b) {
return a < b ? b : a;
}
double min(double a, double b) {
return a > b ? b : a;
}
double max(double a, double b) {
return a < b ? b : a;
}
namespace nonstd {
template <typename T> struct vector {
T* data;
size_t count;
size_t capacity;
vector() { bzero(this, sizeof(vector<T>)); }
void destroy() {
for(size_t i = 0; i < count; ++i){
data[i].~T();
}
free(data);
bzero(this, sizeof(vector<T>));
}
vector<T> copy() {
vector<T> tmp;
tmp.data = (T*)malloc(sizeof(T) * count);
takeoff_memcpy(tmp.data, data, sizeof(T) * count);
tmp.count = count;
tmp.capacity = count;
return tmp;
}
size_t size() { return count; }
void reserve(size_t new_capacity) {
assert(new_capacity >= count);
data = (T*)realloc(data, sizeof(T) * new_capacity);
capacity = new_capacity;
}
// starting with 4 capacity is not optimal for performance, but it's nice to start with a low number so bugs are discovered early.
void push_back(const T& val) {
if(count == capacity) reserve(max(4, capacity) * 2);
takeoff_memcpy(&data[count++], &val, sizeof(T));
}
void push_back(T&& val) {
if(count == capacity) reserve(max(4, capacity) * 2);
takeoff_memcpy(&data[count++], &val, sizeof(T));
}
template <typename... Args> constexpr T& emplace_back(Args&&... args) {
if(count == capacity) reserve(max(4, capacity) * 2);
return *new(&data[count++]) T(std::forward<Args>(args)...);
}
T pop_back() { return data[--count]; }
T& operator[](size_t idx) { return data[idx]; }
T* begin() { return data; }
T* end() { return &data[count]; }
T& back() { return data[count-1]; }
};
};
std::string fstr(const char* format, ...) {
va_list args;
va_start(args, format);
std::vector<char> buf(1 + std::vsnprintf(nil, 0, format, args));
va_end(args);
va_start(args, format);
std::vsnprintf(buf.data(), buf.size(), format, args);
va_end(args);
return std::string(buf.data());
}
std::string str(dvec3 in) {
return fstr("(%f, %f, %f)", in.x, in.y, in.z);
}
// right now (2024) Intel and AMD cpus have 64 byte cache lines and Apple's M series have 128 bytes.
// Apple can suck a dick because opengl is deprecated on macos and their ios app store policies are anticompetitive.
struct cacheline {
void *ptr[8];
};
struct mempool {
nonstd::vector<cacheline*> data;
nonstd::vector<cacheline*> recycler;
uint64_t data_idx;
~mempool() { data.destroy(); recycler.destroy(); }
cacheline* alloc();
void free(cacheline *line);
};
cacheline* mempool::alloc() {
if(recycler.size() > 0) {
return recycler.pop_back();
} else {
if( ! data_idx){
data.push_back((cacheline *)calloc(4096, sizeof(cacheline)));
uint64_t misalignment = (uint64_t)data.back() % sizeof(cacheline);
if(misalignment != 0){
if(verbose) std::cout << "pool allocator adjusted misaligned memory: off by " << misalignment <<" bytes\n";
data[data.size()-1] -= misalignment;
++data_idx;
} else {
if(verbose) std::cout << "pool allocator got memory that was already aligned, nothing to adjust\n";
}
}
cacheline* rax = &data.back()[data_idx];
data_idx = (data_idx + 1) % 4096;
return rax;
}
}
void mempool::free(cacheline *line) {
recycler.push_back(line);
}
struct unionvec3 {
union {
float radio;
float r;
float red;
float uv;
float x;
};
union {
float microwave;
float g;
float green;
float xray;
float y;
};
union {
float ir;
float b;
float blue;
float gamma;
float z;
};
};
struct vec9 {
unionvec3 lo; // frequencies below the visible spectrum
unionvec3 mid;// visible light
unionvec3 hi; // frequencies above the visible spectrum
};
struct hvec3 {
int16_t x;
int16_t y;
int16_t z;
hvec3();
hvec3(int16_t in);
constexpr hvec3(int16_t px, int16_t py, int16_t pz) : x(px), y(py), z(pz) {};
hvec3(dvec3 in);
static hvec3 max(hvec3 lhs, hvec3 rhs);
static hvec3 min(hvec3 lhs, hvec3 rhs);
dvec3 todvec3() { return dvec3(x, y, z); }
};
int16_t d2hi(double in) {
if(in > 0.0) return (int16_t)(in + 0.5);
if(in < 0.0) return (int16_t)(in - 0.5);
return 0;
}
hvec3::hvec3() { x = 0; y = 0; z = 0; }
hvec3::hvec3(int16_t in) { x = in; y = in; z = in; }
hvec3::hvec3(dvec3 in) {
x = d2hi(in.x);
y = d2hi(in.y);
z = d2hi(in.z);
}
hvec3 hvec3::max(hvec3 lhs, hvec3 rhs) {
return hvec3{
glm::max(lhs.x, rhs.x),
glm::max(lhs.y, rhs.y),
glm::max(lhs.z, rhs.z)};
}
hvec3 hvec3::min(hvec3 lhs, hvec3 rhs) {
return hvec3{
glm::min(lhs.x, rhs.x),
glm::min(lhs.y, rhs.y),
glm::min(lhs.z, rhs.z)};
}
constexpr hvec3 operator*(const hvec3 lhs, const int16_t rhs) {
return hvec3(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs);
}
constexpr hvec3 operator/(const hvec3 lhs, const int16_t rhs) {
assert(rhs != 0);
return hvec3(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs);
}
constexpr hvec3 operator+(const hvec3 lhs, const int16_t rhs) {
return hvec3(lhs.x + rhs, lhs.y + rhs, lhs.z + rhs);
}
constexpr hvec3 operator-(const hvec3 lhs, const int16_t rhs) {
return hvec3(lhs.x - rhs, lhs.y - rhs, lhs.z - rhs);
}
constexpr hvec3 operator+(const hvec3 lhs, const hvec3 rhs) {
return hvec3(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z);
}
constexpr hvec3 operator-(const hvec3 lhs, const hvec3 rhs) {
return hvec3(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z);
}
constexpr dvec3 operator*(const dvec3 lhs, const double rhs) {
return dvec3(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs);
}
constexpr dvec3 operator/(const dvec3 lhs, const double rhs) {
assert(rhs != 0.0);
double factor = 1.0 / rhs;
return dvec3(lhs.x * factor, lhs.y * factor, lhs.z * factor);
}
constexpr dvec3 operator+(const dvec3 lhs, const double rhs) {
return dvec3(lhs.x + rhs, lhs.y + rhs, lhs.z + rhs);
}
constexpr dvec3 operator-(const dvec3 lhs, const double rhs) {
return dvec3(lhs.x - rhs, lhs.y - rhs, lhs.z - rhs);
}
constexpr dvec3 operator+(const dvec3 lhs, const vec3 rhs) {
return dvec3(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z);
}
constexpr dvec3 operator-(const dvec3 lhs, const vec3 rhs) {
return dvec3(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z);
}
double length(dvec3 a) {
dvec3 s = a * a;
return sqrt(s.x + s.y + s.z);
}
dvec3 normalize(dvec3 a) {
return glm::normalize(a);
/* double length = ::length(a);
assert(length != 0);
if(length == 0){
return a * length;
}
return a / length;*/
}
struct dTri {
uint32_t verts[3];
float elevations[3];
glm::dvec3 normal;
int32_t type_id;
float foliage_density[3];
dTri() {}
dTri(uint32_t pverts[3], dvec3* vertData, dvec3 center, int32_t ptype_id) {
verts[0] = pverts[0];
verts[1] = pverts[1];
verts[2] = pverts[2];
normal = normalize(glm::cross((vertData[verts[0]] - vertData[verts[1]]), (vertData[verts[0]] - vertData[verts[2]])));
double dotProduct = glm::dot(normal, vertData[verts[0]] - center);
if(dotProduct < 0.0){
normal = -normal;
}
type_id = ptype_id;
foliage_density[0] = 0.0f;
foliage_density[1] = 0.0f;
foliage_density[2] = 0.0f;
}
};
struct dMesh {
dvec3 *verts;
dTri *tris;
uint32_t num_verts;
uint32_t num_tris;
dMesh() { bzero(this, sizeof(dMesh)); }
dMesh(dvec3* pverts, uint32_t pnumVerts, dTri* ptris, uint32_t pnumTris) {
verts = pverts;
num_verts = pnumVerts;
tris = ptris;
num_tris = pnumTris;
}
void destroy() {
if(verts)
free(verts);
verts = 0;
tris = 0;
num_verts = 0;
num_tris = 0;
}
// TODO: create a cylinder mesh and remember to make a function that produces the correct texture coordinates for
// the mesh upload function
static dMesh createBox(dvec3 center, double width, double height, double depth) {
assert(width > 0);
assert(height > 0);
assert(depth > 0);
const int numVertices = 8;
const int numTriangles = 12;
dvec3 *vertices = (dvec3*)malloc(numVertices * sizeof(dvec3) + numTriangles * sizeof(dTri));
dTri *triangles = (dTri*)&vertices[numVertices];
double halfwidth = width / 2.0;
double halfheight = height / 2.0;
double halfdepth = depth / 2.0;
int vertexIndex = 0;
for (int i = 0; i < 8; ++i) {
double xCoord = i & 1 ? halfwidth : -halfwidth;
double yCoord = i & 4 ? halfheight : -halfheight;
double zCoord = i & 2 ? halfdepth : -halfdepth;
vertices[vertexIndex++] = center + dvec3(xCoord, yCoord, zCoord);
}
uint32_t faces[6 * 4] =
{0, 1, 2, 3, // top
0, 1, 4, 5, // front
0, 2, 4, 6, // left
7, 5, 3, 1, // right
7, 6, 3, 2, // back
7, 6, 5, 4}; // bottom
for(int i = 0; i < 6; i++) {
uint32_t tri1[3] = {faces[i * 4], faces[i * 4 + 1], faces[i * 4 + 2]};
uint32_t tri2[3] = {faces[i * 4 + 1], faces[i * 4 + 2], faces[i * 4 + 3]};
triangles[i * 2] = dTri(tri1, vertices, center, VERTEX_TYPE_NONE);
triangles[i * 2 + 1] = dTri(tri2, vertices, center, VERTEX_TYPE_NONE);
}
return dMesh(vertices, numVertices, triangles, numTriangles);
}
};
struct texvert {
glm::vec4 xyz;
// int32_t type_id; (opengl clobbered this when I passed it as int so I packed it into the w component of xyz as a workaround)
glm::vec3 uvw;
texvert(glm::vec3 a, int32_t ptype_id, glm::vec3 b) { xyz = glm::vec4(a.x, a.y, a.z, *(float*)(&ptype_id)); uvw = b; }
// yes mr. pcie customs officer that is definitely a float. if the bit pattern looks like an integer that's just a coincidence. how are your wife and kids?
};
// foliage geometry quad, no relation to quadtrees
void mktreequad(nonstd::vector<texvert> *dest, glm::vec3 a, glm::vec3 b, glm::vec3 c, glm::vec3 d, glm::vec3 uvw, int32_t type_id){
dest->push_back({a, type_id, uvw});
dest->push_back({b, type_id, uvw});
dest->push_back({c, type_id, uvw});
dest->push_back({c, type_id, uvw});
dest->push_back({b, type_id, uvw});
dest->push_back({d, type_id, uvw});
}
// foliage, not data structure
void mktree(nonstd::vector<texvert> *dest, float h_trunk, float r_trunk, float h_canopy, float r_canopy, glm::vec3 origin){
float h_root = -0.5;
// trunk, should be at least 4 quads
mktreequad(dest,
glm::vec3(-r_trunk, h_root, -r_trunk) + origin,
glm::vec3(r_trunk, h_root, -r_trunk) + origin,
glm::vec3(-r_trunk, h_trunk, -r_trunk) + origin,
glm::vec3(r_trunk, h_trunk, -r_trunk) + origin,
glm::vec3(0.0f), VERTEX_TYPE_TREETRUNK);
mktreequad(dest,
glm::vec3(r_trunk, h_root, r_trunk) + origin,
glm::vec3(-r_trunk, h_root, r_trunk) + origin,
glm::vec3(r_trunk, h_trunk, r_trunk) + origin,
glm::vec3(-r_trunk, h_trunk, r_trunk) + origin,
glm::vec3(0.333333f), VERTEX_TYPE_TREETRUNK);
mktreequad(dest,
glm::vec3(r_trunk, h_root, -r_trunk) + origin,
glm::vec3(r_trunk, h_root, r_trunk) + origin,
glm::vec3(r_trunk, h_trunk, -r_trunk) + origin,
glm::vec3(r_trunk, h_trunk, r_trunk) + origin,
glm::vec3(0.666667f), VERTEX_TYPE_TREETRUNK);
mktreequad(dest,
glm::vec3(-r_trunk, h_root, -r_trunk) + origin,
glm::vec3(-r_trunk, h_root, r_trunk) + origin,
glm::vec3(-r_trunk, h_trunk, -r_trunk) + origin,
glm::vec3(-r_trunk, h_trunk, r_trunk) + origin,
glm::vec3(1.0f), VERTEX_TYPE_TREETRUNK);
// canopy, should be at least 4 triangles
mktreequad(dest,
glm::vec3(-r_canopy, h_trunk, -r_canopy) + origin,
glm::vec3(-r_canopy, h_trunk, r_canopy) + origin,
glm::vec3(0.0, h_trunk + h_canopy, 0.0) + origin,
glm::vec3(r_canopy, h_trunk, r_canopy) + origin,
glm::vec3(0.0f), VERTEX_TYPE_LEAF);
mktreequad(dest,
glm::vec3(r_canopy, h_trunk, r_canopy) + origin,
glm::vec3(r_canopy, h_trunk, -r_canopy) + origin,
glm::vec3(0.0, h_trunk + h_canopy, 0.0) + origin,
glm::vec3(-r_canopy, h_trunk, -r_canopy) + origin,
glm::vec3(1.0f), VERTEX_TYPE_LEAF);
}
struct Motor {
double max_force;
double min_force; // negative values for motors that can produce power in both directions
double max_braking_force;
double max_power; // both positive and negative if applicable
};
struct Joint {
dvec3 pos;
dvec3 axis;
Motor motor;
};
struct JointHinge: Joint {
double target_angle;
double angle;
double max_angle;
double min_angle;
};
struct JointSlide: Joint {
double target_extension;
double extension;
double max_extension;
double min_extension;
};
struct Joint6dof: Joint {
dvec3 target_angle;
dvec3 angle;
};
enum physics_state {
active,
sleeping, // the forces acting on it are in equilibrium and it's not moving
immovable, // immovable objects are things like terrain and buildings. They can become active in dire circumstances.
ghost // can be attached to other objects but does not collide with anything and is not affected by any forces
};
// mesh vertices should be expressed in the main object's coordinate space, which means that they will have to be
// recalculated when a component detaches from the main object
// the benefit is that when collision testing a small object against a large object we don't have to transform the
// vertices of the large object, only transform the small object into the large object's coordinate space.
// limbs attached to joints should be exeptions to this because they need to rotate around the joint
// so for every joint we have to calculate a combined transformation matrix of the parent and the joint
// impacts that cause damage should create a new, recessed vertex at the impact point with depth proportional
// to the damage. For damage that would cause a dent deeper than the component the component can be destroyed.
struct RenderObject;
mempool collision_pool;
struct PhysicsObject {
PhysicsObject *parent;
RenderObject *ro;
Joint *joint; // joint can only represent the connection to parent. directed acyclic graph is the only valid topology.
PhysicsObject *limbs; // limbs are subassemblies connected via joints
int num_limbs;
PhysicsObject *components; // components are rigidly attached to the object
int num_components;
cacheline *active_collisions; // I will use this later to implement multi-body collisions
dMesh mesh;
double radius; // radius of the bounding sphere for early elimination
enum physics_state state;
double mass;
dmat3 inertia_tensor;
uint64_t zone;
dvec3 pos; // center of the coordinate system (and therefore the bounding sphere), not center of mass
dvec3 vel;
dquat rot;
dquat spin;
double temperature;
PhysicsObject() {
bzero(this, sizeof(PhysicsObject));
active_collisions = collision_pool.alloc();
rot = glm::dquat(1.0, 0.0, 0.0, 0.0);
spin = glm::dquat(1.0, 0.0, 0.0, 0.0);
state = active;
}
PhysicsObject(dMesh pmesh, PhysicsObject *pparent) {
bzero(this, sizeof(PhysicsObject));
parent = pparent;
active_collisions = collision_pool.alloc();
mesh = pmesh;
radius = calculateRadius();
state = active;
mass = 1.0;
rot = glm::dquat(1.0, 0.0, 0.0, 0.0);
}
~PhysicsObject() {
if(active_collisions) {
collision_pool.free(active_collisions);
active_collisions = 0;
}
mesh.destroy();
}
// this just assumes that pos is at the center, of course in practice it will often not be
double calculateRadius() {
double greatestRsquared = 0.0;
for(int i = 0; i < mesh.num_verts; i++){
dvec3 lvalue = mesh.verts[i] - pos;
double rSquared = glm::length2(lvalue);
greatestRsquared = glm::max(greatestRsquared, rSquared);
}
return sqrt(greatestRsquared);
}
glm::vec3 zoneSpacePosition() {
dvec3 sum_pos = pos;
PhysicsObject *next = parent;
while(next){
sum_pos += parent->pos;
next = parent->parent;
}
return glm::vec3(sum_pos.x, sum_pos.y, sum_pos.z);
}
};
struct unit_order {
string command_type;
dvec3 target_pos;
uint64_t target_id;
};
uint64_t unit_next_uid = 1;
struct Unit {
string name;
uint64_t id;
uint64_t owner_id;
PhysicsObject body;
nonstd::vector<PhysicsObject> limbs;
nonstd::vector<PhysicsObject> components;
bool limbs_dirty;
bool components_dirty;
std::deque<unit_order> order_queue;
Unit() {
bzero(this, sizeof(Unit));
name = "prototype";
id = unit_next_uid++;
owner_id = 0;
new(&body) PhysicsObject();
limbs_dirty = false;
components_dirty = false;
}
void addLimb(dMesh pmesh) {
limbs.emplace_back(pmesh, &body);
limbs_dirty = true;
}
void addComponent(dMesh pmesh) {
components.emplace_back(pmesh, &body);
components_dirty = true;
}
void bake() {
if(limbs_dirty){
body.limbs = &limbs[0];
body.num_limbs = limbs.size();
limbs_dirty = false;
}
if(components_dirty){
body.mesh.destroy();
uint64_t num_tris = 0;
uint64_t num_verts = 0;
for(int i = 0; i < components.size(); i++){
num_tris += components[i].mesh.num_tris;
num_verts += components[i].mesh.num_verts;
}
dvec3 *verts = (dvec3 *)malloc(num_verts * sizeof(dvec3) + num_tris * sizeof(dTri));
uint64_t tri_idx = 0;
uint64_t vert_idx = 0;
for(int i = 0; i < components.size(); i++){
takeoff_memcpy(&verts[vert_idx], components[i].mesh.verts, components[i].mesh.num_verts * sizeof(dvec3));
vert_idx += components[i].mesh.num_verts;
}
dTri *tris = (dTri*)&verts[vert_idx];
for(int i = 0; i < components.size(); i++){
takeoff_memcpy(&tris[tri_idx], components[i].mesh.tris, components[i].mesh.num_tris * sizeof(dTri));
tri_idx += components[i].mesh.num_tris;
}
body.mesh = dMesh(verts, num_verts, tris, num_tris);
body.components = &components[0];
body.num_components = components.size();
body.radius = body.calculateRadius();
components_dirty = false;
}
}
};
// Thoughts on convex/concave hull
//
// We should separately collision test anything connected to a joint, and also anything protruding from the main hull.
// The final authority on whether a component collides with something should be its hull mesh. Each component should
// have a very simple hull mesh and the main body can have a hull mesh that combines the outer surface into one mesh
// except protruding and jointed features since they will be tested separately.
// 1. physics objects move, rotate, appear and disappear
// 2. we calculate a transformation matrix from the object's new rotation
// 3. we transform each point in the collision shape's mesh to calculate a new bounding box (but leave the mesh
// untransformed)
// 3b. we may consider caching a transformed copy of the mesh for faster collision detection
// 4. we add the physics object's position to the bounding box's
// 5. we update the BVH
// 6. we can now read from the BVH and write to the physics objects to our heart's content for the rest of the tick
struct ctleaf {
// 8 bytes
PhysicsObject *object;
// axis-aligned bounding box
hvec3 hi; // 6 bytes (total 14)
hvec3 lo; // 6 bytes (total 20)
ctleaf(PhysicsObject *o){
object = o;
hi = hvec3(o->pos + o->radius + 0.5);
lo = hvec3(o->pos - o->radius - 0.5);
}
};
struct AABB {
hvec3 max;
hvec3 min;
};
AABB calculateBounds(ctleaf* p, uint32_t first, uint32_t last) {
AABB bounds;
bounds.min = hvec3(32767);
bounds.max = hvec3(-32768);
for (uint32_t i = first; i <= last; ++i) {
bounds.min = hvec3::min(bounds.min, p[i].lo);
bounds.max = hvec3::max(bounds.max, p[i].hi);
}
return bounds;
}
struct ctnode {
hvec3 hi; // 6 bytes
hvec3 lo; // 6 bytes (total 12)
uint32_t count; // 4 bytes (total 16)
union{ // 4 bytes (total 20)
uint32_t left_child;
uint32_t first_leaf;
};
void setBounds(AABB bounds) { hi = bounds.max; lo = bounds.min; }
void subdivide(ctnode* nodes, uint32_t* poolPtr, ctleaf* primitives, uint32_t first, uint32_t last) {
if (first == last) {
this->first_leaf = first;
this->count = 1;
return;
}
this->left_child = *poolPtr;
*poolPtr += 2;
ctnode *left = &nodes[left_child];
ctnode *right = &nodes[left_child + 1];
// sort the primitives
hvec3 size = hi - lo;
if(size.y > size.x && size.y > size.z) {
std::sort(primitives + first, primitives + last + 1, [](const ctleaf& a, const ctleaf& b) -> bool {
return (int32_t)a.lo.x + (int32_t)a.hi.x < (int32_t)b.hi.x + (int32_t)b.lo.x;
});
}
else if (size.y > size.x && size.y > size.z) {
std::sort(primitives + first, primitives + last + 1, [](const ctleaf& a, const ctleaf& b) -> bool {
return (int32_t)a.lo.y + (int32_t)a.hi.y < (int32_t)b.hi.y + (int32_t)b.lo.y;
});
}
else {
std::sort(primitives + first, primitives + last + 1, [](const ctleaf& a, const ctleaf& b) -> bool {
return (int32_t)a.lo.z + (int32_t)a.hi.z < (int32_t)b.hi.z + (int32_t)b.lo.z;
});
}
// split them in a dumb way that is not optimal but better than worst case
// here we could instead do a binary search to find the geometric middle or even search for the biggest gap
uint32_t split = (first + last) >> 1;
left->setBounds(calculateBounds(primitives, first, split));
right->setBounds(calculateBounds(primitives, split + 1, last));
left->subdivide(nodes, poolPtr, primitives, first, split);
right->subdivide(nodes, poolPtr, primitives, split + 1, last);
this->count = last - first + 1;
}
};
#define MAX_MAX_DEPTH 16
struct CollisionTree {
dvec3 pos;
ctnode *root = 0;
ctleaf *leaves = 0;
void destroy() {
if(root){
free(root);
root = 0;
}
leaves = 0;
}
CollisionTree(dvec3 origo) {
pos = origo;
root = 0;
}
CollisionTree(dvec3 origo, ctleaf* pleaves, int N) {
pos = origo;
leaves = pleaves;
ctnode* nodes = (ctnode*) malloc(sizeof(ctnode) * (2 * N));
root = &nodes[0];
root->count = N;
AABB globalBounds = calculateBounds(pleaves, 0, N);
root->setBounds(globalBounds);
uint32_t poolPtr = 1;
root->subdivide(nodes, &poolPtr, leaves, 0, N - 1);
// glBindBuffer(GL_SHADER_STORAGE_BUFFER, TLASBuffer);
// glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(ctnode) * poolPtr, nodes, GL_STATIC_DRAW);
}
};
struct ttnode {
uint64_t path;
uint32_t first_child;
uint32_t triangle;
uint32_t neighbors[3];
uint32_t rendered_at_level; // number of subdivisions to reach this node, if it was rendered. otherwise 0.
double elevations[3]; // elevation of the node's 3 corners above the planet's spheroid
double roughnesses[3]; // terrain roughness at the node's 3 corners
dvec3 verts[3]; // vertices (node space (octahedron with manhattan distance to center = r everywhere on the surface))
uint32_t last_used_at_frame;
float foliage_density[3];
nonstd::vector<texvert> vegetation;
vec3 wind_velocity;
float pressure;
vec3 fluid_velocity;
float fluid_depth;
float temperature;
float snow_depth;
// add more stuff like temperature, moisture, vegetation
std::string str(){
return fstr("node: 0x%llx elevation: %f verts: %s, %s, %s", path, elevation(), ::str(verts[0]).c_str(), ::str(verts[1]).c_str(), ::str(verts[2]).c_str());
}
dvec3 spheroidPosition(dvec3 vert, double radius) {
double length = glm::length(vert);
return vert * (radius / length);
}
dvec3 globalPosition(double radius, int i) {
double length = glm::length(verts[i]);
return verts[i] * ((radius + elevations[i]) / length);
}
// position of 0th vertex transformed to zone space (LOD space)
vec3 zone_space_position(dvec3 location, double radius, int i) {
glm::vec3 point = verts[i];
double length = glm::length(point);
point = point * (radius / length); // scaled from node space to spheroid
point = point + (elevations[i] * (point / length)) - location; // subtracting location.. adding -gravnorm * elevations
return point; // sounds about right, yeah?
}
// node space center
dvec3 center() {
dvec3 pos(0.0);
for(int i = 0; i < 3; i++) {
pos += verts[i];
}
pos /= 3.0;
return pos;
}
double elevation() {
double elevation = 0.0;
for(int i = 0; i < 3; i++) {
elevation += elevations[i];
}
elevation /= 3.0;
return elevation;
}
double player_altitude(dvec3 pos, dMesh* mesh, dvec3 gravity_dir) {
dTri *tri = &mesh->tris[triangle];
dvec3 a = mesh->verts[tri->verts[0]];
dvec3 b = mesh->verts[tri->verts[1]];
dvec3 c = mesh->verts[tri->verts[2]];
dvec3 ab = b - a;
dvec3 ac = c - a;
dvec3 norm = normalize(glm::cross(ab, ac));
double divisor = dot(norm, gravity_dir);
for(int i = 0; i < 9; i++){
assert(!isnan(((double*)(&mesh->verts[tri->verts[i/3]]))[i % 3])); // fight me
}
assert(divisor != 0.0);
double d = dot(norm, (a - pos)) / divisor;
return d;
}
};
glm::vec3 calculate_center(uint64_t level, uint64_t address, glm::vec3 v0, glm::vec3 v1, glm::vec3 v2, uint64_t wiggle) {
assert(level < 32);
for(int i = 0; i < level; i++){
glm::vec3 mid0 = (v0 + v1) * 0.5f;
glm::vec3 mid1 = (v1 + v2) * 0.5f;
glm::vec3 mid2 = (v2 + v0) * 0.5f;
switch ((address >> (2 * i)) & 3) {
case 0: // Center triangle
v0 = mid0;
v1 = mid1;
v2 = mid2;
break;
case 1: // First corner triangle
v1 = mid0;
v2 = mid2;
break;
case 2: // Second corner triangle
v2 = mid1;
v0 = mid0;
break;
case 3: // Third corner triangle
v0 = mid2;
v1 = mid1;
break;
}
}
if(wiggle) {
float r1 = sqrt((wiggle % 10000000) / 10000000.0f);
float r2 = (wiggle % 9000000) / 9000000.0f;
float a = 1 - r1;
float b = r1 * (1 - r2);
float c = r1 * r2;
return a * v0 + b * v1 + c * v2;
} else {
glm::vec3 center = (v0 + v1 + v2) / 3.0f;
return center;
}
}
struct TerrainTree {
uint64_t seed;
double radius;
double noise_yscaling;
double LOD_DISTANCE_SCALE;
int MAX_LOD;
float highest_point = 0.0f;
float lowest_point = 0.0f;
TerrainGenerator *generator;
nonstd::vector<ttnode> nodes;
void destroy() {
for(int i = 0; i > nodes.count; i++){
nodes[i].vegetation.destroy();
}
nodes.destroy();
}
~TerrainTree() {
}
TerrainTree() {
bzero(this, sizeof(TerrainTree));
}
TerrainTree copy() {
TerrainTree tmp;
takeoff_memcpy(&tmp, this, sizeof(TerrainTree));
tmp.nodes = nodes.copy();
if(LOW_MEMORY_MODE) {
for(int i = 0; i < tmp.nodes.count; i++) {