-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmath_3d.h
2078 lines (1823 loc) · 72.8 KB
/
math_3d.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
/**
Math 3D v1.0
By Stephan Soller <stephan.soller@helionweb.de> and Tobias Malmsheimer
Licensed under the MIT license
Math 3D is a compact C99 library meant to be used with OpenGL. It provides basic
3D vector and 4x4 matrix operations as well as functions to create transformation
and projection matrices. The OpenGL binary layout is used so you can just upload
vectors and matrices into shaders and work with them without any conversions.
It's an stb style single header file library. Define MATH_3D_IMPLEMENTATION
before you include this file in *one* C file to create the implementation.
QUICK NOTES
- If not explicitly stated by a parameter name all angles are in radians.
- The matrices use column-major indices. This is the same as in OpenGL and GLSL.
The matrix documentation below for details.
- Matrices are passed by value. This is probably a bit inefficient but
simplifies code quite a bit. Most operations will be inlined by the compiler
anyway so the difference shouldn't matter that much. A matrix fits into 4 of
the 16 SSE2 registers anyway. If profiling shows significant slowdowns the
matrix type might change but ease of use is more important than every last
percent of performance.
- When combining matrices with multiplication the effects apply right to left.
This is the convention used in mathematics and OpenGL. Source:
https://en.wikipedia.org/wiki/Transformation_matrix#Composing_and_inverting_transformations
Direct3D does it differently.
- The `m4_mul_pos()` and `m4_mul_dir()` functions do a correct perspective
divide (division by w) when necessary. This is a bit slower but ensures that
the functions will properly work with projection matrices. If profiling shows
this is a bottleneck special functions without perspective division can be
added. But the normal multiplications should avoid any surprises.
- The library consistently uses a right-handed coordinate system. The old
`glOrtho()` broke that rule and `m4_ortho()` has be slightly modified so you
can always think of right-handed cubes that are projected into OpenGLs
normalized device coordinates.
- Special care has been taken to document all complex operations and important
sources. Most code is covered by test cases that have been manually calculated
and checked on the whiteboard. Since indices and math code is prone to be
confusing we used pair programming to avoid mistakes.
FURTHER IDEARS
These are ideas for future work on the library. They're implemented as soon as
there is a proper use case and we can find good names for them.
- bool v3_is_null(vec3_t v, float epsilon)
To check if the length of a vector is smaller than `epsilon`.
- vec3_t v3_length_default(vec3_t v, float default_length, float epsilon)
Returns `default_length` if the length of `v` is smaller than `epsilon`.
Otherwise same as `v3_length()`.
- vec3_t v3_norm_default(vec3_t v, vec3_t default_vector, float epsilon)
Returns `default_vector` if the length of `v` is smaller than `epsilon`.
Otherwise the same as `v3_norm()`.
- mat4_t m4_invert(mat4_t matrix)
Matrix inversion that works with arbitrary matrices. `m4_invert_affine()` can
already invert translation, rotation, scaling, mirroring, reflection and
shearing matrices. So a general inversion might only be useful to invert
projection matrices for picking. But with orthographic and perspective
projection it's probably simpler to calculate the ray into the scene directly
based on the screen coordinates.
VERSION HISTORY
v1.0 2016-02-15 Initial release
Modified by Flix01. Added some structs and functions mostly ported from
the OgreMath library (www.ogre3d.org) - MIT licensed.
Very little testing has been done. Use it at your own risk.
Ported code back to --std=gnu89 [Basically ansi C with single line comments allowed]
**/
#ifndef MATH_3D_HEADER
#define MATH_3D_HEADER
#include <math.h>
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
// Define PI directly because we would need to define the _BSD_SOURCE or
// _XOPEN_SOURCE feature test macros to get it from math.h. That would be a
// rather harsh dependency. So we define it directly if necessary.
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#ifndef M_HALF_PI
#define M_HALF_PI (M_PI/2.0)
#endif
#ifndef M_PIOVER180
#define M_PIOVER180 (3.14159265358979323846/180.0)
#endif
#ifndef M_180OVERPI
#define M_180OVERPI (180.0/3.14159265358979323846)
#endif
//
// 3D vectors
//
// Use the `vec3()` function to create vectors. All other vector functions start
// with the `v3_` prefix.
//
// The binary layout is the same as in GLSL and everything else (just 3 floats).
// So you can just upload the vectors into shaders as they are.
//
typedef union {struct {float x, y, z;};float v[3];} vec3_t;
static __inline vec3_t vec3(float x, float y, float z) { vec3_t v;v.x=x;v.y=y;v.z=z;return v; }
static __inline vec3_t v3_add (vec3_t a, vec3_t b) { return vec3( a.x + b.x, a.y + b.y, a.z + b.z ); }
static __inline vec3_t v3_adds (vec3_t a, float s) { return vec3( a.x + s, a.y + s, a.z + s ); }
static __inline vec3_t v3_sub (vec3_t a, vec3_t b) { return vec3( a.x - b.x, a.y - b.y, a.z - b.z ); }
static __inline vec3_t v3_subs (vec3_t a, float s) { return vec3( a.x - s, a.y - s, a.z - s ); }
static __inline vec3_t v3_mul (vec3_t a, vec3_t b) { return vec3( a.x * b.x, a.y * b.y, a.z * b.z ); }
static __inline vec3_t v3_muls (vec3_t a, float s) { return vec3( a.x * s, a.y * s, a.z * s ); }
static __inline vec3_t v3_div (vec3_t a, vec3_t b) { return vec3( a.x / b.x, a.y / b.y, a.z / b.z ); }
static __inline vec3_t v3_divs (vec3_t a, float s) { return vec3( a.x / s, a.y / s, a.z / s ); }
static __inline float v3_length(vec3_t v) { return sqrt(v.x*v.x + v.y*v.y + v.z*v.z); }
static __inline vec3_t v3_norm (vec3_t v);
static __inline float v3_dot (vec3_t a, vec3_t b) { return a.x*b.x + a.y*b.y + a.z*b.z; }
static __inline vec3_t v3_proj (vec3_t v, vec3_t onto);
static __inline vec3_t v3_cross (vec3_t a, vec3_t b);
static __inline float v3_angle_between(vec3_t a, vec3_t b);
static __inline vec3_t v3_lerp(vec3_t a, vec3_t b,float t) { float ct = 1.f-t;return vec3(a.x*ct+b.x*t,a.y*ct+b.y*t,a.z*ct+b.z*t);}
void v3_print (vec3_t v);
void v3_printp (vec3_t v, int width, int precision);
void v3_fprint (FILE* stream, vec3_t v);
void v3_fprintp (FILE* stream, vec3_t v, int width, int precision);
//
// quaternions
//
// Use the `quat()` function to create vectors. All other vector functions start
// with the `qt_` prefix.
//
typedef union {struct {float x, y, z, w;};float v[4];} quat_t;
static __inline quat_t quat(float x, float y, float z,float w) { quat_t q;q.x=x;q.y=y;q.z=z;q.w=w;return q; }
static __inline float qt_dot (quat_t a, quat_t b) { return a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w; }
static __inline float qt_length2(quat_t q) { return q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w; }
static __inline float qt_length(quat_t q) { return sqrt(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); }
static __inline quat_t qt_norm(quat_t q) { float len=qt_length(q);return quat(q.x/len,q.y/len,q.z/len,q.w/len);}
//static __inline quat_t qt_look_at_YX(vec3_t source_pos,vec3_t target_pos);
quat_t qt_slerp(quat_t qStart,quat_t qEnd,float factor);
void qt_print (quat_t q);
void qt_printp (quat_t q, int width, int precision);
void qt_fprint (FILE* stream, quat_t q);
void qt_fprintp (FILE* stream, quat_t q, int width, int precision);
//
// 3x3 matrices
//
// Use the `mat3()` function to create a matrix. You can write the matrix
// members in the same way as you would write them on paper or on a whiteboard:
//
// mat3_t m = mat3(
// 1, 0, 0
// 0, 1, 0
// 0, 0, 1
// )
//
// This creates an identity matrix. All other
// matrix functions start with the `m3_` prefix.
//
// The matrix is stored in column-major order, just as OpenGL expects. Members
// can be accessed by indices or member names. When you write a matrix on paper
// or on the whiteboard the indices and named members correspond to these
// positions:
//
// | m00 m10 m20 |
// | m01 m11 m21 |
// | m02 m12 m22 |
//
// | m00 m10 m20 |
// | m01 m11 m21 |
// | m02 m12 m22 |
//
// The first index or number in a name denotes the column, the second the row.
// So m[i][j] denotes the member in the ith column and the jth row. This is the
// same as in GLSL (source: GLSL v1.3 specification, 5.6 Matrix Components).
//
typedef union {
// The first index is the column index, the second the row index. The memory
// layout of nested arrays in C matches the memory layout expected by OpenGL.
float m[3][3];
// OpenGL expects the first 3 floats to be the first column of the matrix.
// So we need to define the named members column by column for the names to
// match the memory locations of the array elements.
struct {
float m00, m01, m02;
float m10, m11, m12;
float m20, m21, m22;
};
// When we need to cast it to an array ptr we can just use 'v'
float v[9];
} mat3_t;
static __inline mat3_t mat3(
float m00, float m10, float m20,
float m01, float m11, float m21,
float m02, float m12, float m22
);
static __inline mat3_t mat3_rm(
float m00, float m01, float m02,
float m10, float m11, float m12,
float m20, float m21, float m22
);
static __inline mat3_t m3_identity ();
static __inline vec3_t m3_get_x_axis (const mat3_t* matrix);
static __inline vec3_t m3_get_y_axis (const mat3_t* matrix);
static __inline vec3_t m3_get_z_axis (const mat3_t* matrix);
static __inline mat3_t m3_invert_XZ_axis(const mat3_t* matrix);
static __inline mat3_t m3_scaling (vec3_t scale);
static __inline mat3_t m3_rotation_x (float angle_in_rad);
static __inline mat3_t m3_rotation_y (float angle_in_rad);
static __inline mat3_t m3_rotation_z (float angle_in_rad);
mat3_t m3_rotation (float angle_in_rad, vec3_t axis);
quat_t m3_get_quaternion(const mat3_t* matrix);
void m3_set_quaternion(mat3_t* matrix,quat_t q);
static __inline mat3_t m3_slerp(const mat3_t* T1,const mat3_t* T2,float t);
static __inline mat3_t m3_transpose (mat3_t matrix);
static __inline mat3_t m3_mul (mat3_t a, mat3_t b);
mat3_t m3_invert (mat3_t matrix);
vec3_t m3_mul_dir (mat3_t matrix, vec3_t direction);
mat3_t m3_from_euler_XYZ (const vec3_t YPR);
mat3_t m3_from_euler_XZY (const vec3_t YPR);
mat3_t m3_from_euler_YXZ (const vec3_t YPR);
mat3_t m3_from_euler_YZX (const vec3_t YPR);
mat3_t m3_from_euler_ZXY (const vec3_t YPR);
mat3_t m3_from_euler_ZYX (const vec3_t YPR);
int m3_to_euler_XYZ (const mat3_t* m,vec3_t* YPR);
int m3_to_euler_XZY (const mat3_t* m,vec3_t* YPR);
int m3_to_euler_YXZ (const mat3_t* m,vec3_t* YPR);
int m3_to_euler_YZX (const mat3_t* m,vec3_t* YPR);
int m3_to_euler_ZXY (const mat3_t* m,vec3_t* YPR);
int m3_to_euler_ZYX (const mat3_t* m,vec3_t* YPR);
void m3_print (mat3_t matrix);
void m3_printp (mat3_t matrix, int width, int precision);
void m3_fprint (FILE* stream, mat3_t matrix);
void m3_fprintp (FILE* stream, mat3_t matrix, int width, int precision);
//
// 4x4 matrices
//
// Use the `mat4()` function to create a matrix. You can write the matrix
// members in the same way as you would write them on paper or on a whiteboard:
//
// mat4_t m = mat4(
// 1, 0, 0, 7,
// 0, 1, 0, 5,
// 0, 0, 1, 3,
// 0, 0, 0, 1
// )
//
// This creates a matrix that translates points by vec3(7, 5, 3). All other
// matrix functions start with the `m4_` prefix. Among them functions to create
// identity, translation, rotation, scaling and projection matrices.
//
// The matrix is stored in column-major order, just as OpenGL expects. Members
// can be accessed by indices or member names. When you write a matrix on paper
// or on the whiteboard the indices and named members correspond to these
// positions:
//
// | m00 m10 m20 m30 |
// | m01 m11 m21 m31 |
// | m02 m12 m22 m32 |
// | m03 m13 m23 m33 |
//
// | m00 m10 m20 m30 |
// | m01 m11 m21 m31 |
// | m02 m12 m22 m32 |
// | m03 m13 m23 m33 |
//
// The first index or number in a name denotes the column, the second the row.
// So m[i][j] denotes the member in the ith column and the jth row. This is the
// same as in GLSL (source: GLSL v1.3 specification, 5.6 Matrix Components).
//
typedef union {
// The first index is the column index, the second the row index. The memory
// layout of nested arrays in C matches the memory layout expected by OpenGL.
float m[4][4];
// OpenGL expects the first 4 floats to be the first column of the matrix.
// So we need to define the named members column by column for the names to
// match the memory locations of the array elements.
struct {
float m00, m01, m02, m03;
float m10, m11, m12, m13;
float m20, m21, m22, m23;
float m30, m31, m32, m33;
};
// When we need to cast it to an array ptr we can just use 'v'
float v[16];
} mat4_t;
static __inline mat4_t mat4(
float m00, float m10, float m20, float m30,
float m01, float m11, float m21, float m31,
float m02, float m12, float m22, float m32,
float m03, float m13, float m23, float m33
);
static __inline mat4_t mat4_rm(
float m00, float m01, float m02, float m03,
float m10, float m11, float m12, float m13,
float m20, float m21, float m22, float m23,
float m30, float m31, float m32, float m33
);
static __inline mat4_t mat4_from_array(float m[16]);
static __inline mat4_t m4_identity ();
static __inline void m4_set_identity_mat3(mat4_t* matrix);
static __inline mat3_t m4_get_mat3 (const mat4_t* matrix);
static __inline void m4_set_mat3 (mat4_t* matrix,mat3_t matrix3);
static __inline vec3_t m4_get_x_axis (const mat4_t* matrix);
static __inline vec3_t m4_get_y_axis (const mat4_t* matrix);
static __inline vec3_t m4_get_z_axis (const mat4_t* matrix);
static __inline mat4_t m4_invert_XZ_axis(const mat4_t* matrix);
static __inline vec3_t m4_get_translation(const mat4_t* matrix);
static __inline void m4_set_translation(mat4_t* matrix,vec3_t translation);
quat_t m4_get_quaternion(const mat4_t* matrix);
void m4_set_quaternion(mat4_t* matrix,quat_t q);
static __inline mat4_t m4_translation (vec3_t offset);
static __inline mat4_t m4_scaling (vec3_t scale);
static __inline mat4_t m4_rotation_x (float angle_in_rad);
static __inline mat4_t m4_rotation_y (float angle_in_rad);
static __inline mat4_t m4_rotation_z (float angle_in_rad);
mat4_t m4_rotation (float angle_in_rad, vec3_t axis);
mat4_t m4_ortho_2d (float left,float right, float bottom, float top);
mat4_t m4_ortho (float left,float right, float bottom, float top,float nearVal,float farVal);
mat4_t m4_ortho_3d (float cameraTargetDistance,float degFOV,float aspect,float znear,float zfar);
mat4_t m4_perspective (float fovy,float aspect, float zNear, float zFar);
mat4_t m4_frustum (float left,float right, float bottom, float top,float zNear, float zFar);
mat4_t m4_look_at (float eyex,float eyey,float eyez,float centerx,float centery,float centerz,float upx,float upy,float upz);
static __inline mat4_t m4_transpose (mat4_t matrix);
static __inline mat4_t m4_mul (mat4_t a, mat4_t b);
mat4_t m4_invert (mat4_t matrix);
static __inline mat4_t m4_invert_fast (mat4_t matrix);
vec3_t m4_mul_pos (mat4_t matrix, vec3_t position);
vec3_t m4_mul_dir (mat4_t matrix, vec3_t direction);
void m4_look_at_YX (mat4_t* matrix,vec3_t to,float min_distance_allowed,float max_distance_allowed);
static __inline mat4_t m4_slerp(const mat4_t* T1,const mat4_t* T2,float t);
void m4_print (mat4_t matrix);
void m4_printp (mat4_t matrix, int width, int precision);
void m4_fprint (FILE* stream, mat4_t matrix);
void m4_fprintp (FILE* stream, mat4_t matrix, int width, int precision);
void m4_print_as__array (mat4_t matrix);
void m4_printp_as__array (mat4_t matrix, int width, int precision);
void m4_fprint_as__array (FILE* stream, mat4_t matrix);
void m4_fprintp_as__array (FILE* stream, mat4_t matrix, int width, int precision);
//
// 3D vector functions header implementation
//
static __inline vec3_t v3_norm(vec3_t v) {
float len = v3_length(v);
if (len > 0)
return vec3( v.x / len, v.y / len, v.z / len );
else
return vec3( 0, 0, 0);
}
static __inline vec3_t v3_proj(vec3_t v, vec3_t onto) {
return v3_muls(onto, v3_dot(v, onto) / v3_dot(onto, onto));
}
static __inline vec3_t v3_cross(vec3_t a, vec3_t b) {
return vec3(
a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x
);
}
static __inline float v3_angle_between(vec3_t a, vec3_t b) {
return acosf( v3_dot(a, b) / (v3_length(a) * v3_length(b)) );
}
//
// Quaternion header implementation
//
/*static __inline quat_t qt_look_at_YX(vec3_t source_pos,vec3_t target_pos) {
vec3_t D;float Dxz2,Dxz,AY,AX;
D = target_pos-source_pos;
Dxz2 = D.x*D.x+D.z*D.z;
Dxz = sqrt(Dxz2);
AY = atan2(D.x,D.z);
AX = -atan2(D.y,Dxz);
return qt_mul(qt_from_axis_angle(vec3(0.f,1.f,0.f),AY),qt_from_axis_angle(vec3(1.f,0.f,0.f),AX);
}*/
//
// Matrix3 functions header implementation
//
static __inline mat3_t mat3(
float m00, float m10, float m20,
float m01, float m11, float m21,
float m02, float m12, float m22
) {
mat3_t m;
m.m00=m00; m.m10=m10; m.m20=m20;
m.m01=m01; m.m11=m11; m.m21=m21;
m.m02=m02; m.m12=m12; m.m22=m22;
return m;
}
static __inline mat3_t mat3_rm(
float m00, float m01, float m02,
float m10, float m11, float m12,
float m20, float m21, float m22
) {
mat3_t m;
m.m00=m00; m.m10=m10; m.m20=m20;
m.m01=m01; m.m11=m11; m.m21=m21;
m.m02=m02; m.m12=m12; m.m22=m22;
return m;
}
static __inline mat3_t m3_identity() {
return mat3(
1, 0, 0,
0, 1, 0,
0, 0, 1
);
}
static __inline mat3_t m3_scaling(vec3_t scale) {
float x = scale.x, y = scale.y, z = scale.z;
return mat3(
x, 0, 0,
0, y, 0,
0, 0, z
);
}
static __inline vec3_t m3_get_x_axis(const mat3_t* matrix) {
const mat3_t* m = matrix;
return vec3(m->m00,m->m01,m->m02);
}
static __inline vec3_t m3_get_y_axis(const mat3_t* matrix) {
const mat3_t* m = matrix;
return vec3(m->m10,m->m11,m->m12);
}
static __inline vec3_t m3_get_z_axis(const mat3_t* matrix) {
const mat3_t* m = matrix;
return vec3(m->m20,m->m21,m->m22);
}
static __inline mat3_t m3_invert_XZ_axis(const mat3_t* matrix) {
const mat3_t* m = matrix;
return mat3 (
-m->m00, m->m10, -m->m20,
-m->m01, m->m11, -m->m21,
-m->m02, m->m12, -m->m22
);
}
/*
// BASICALLY I WANT TO PORT THIS CODE I USE WITH BULLET MATH
{
// The "system" modelview matrix is the inverse of m_cameraT, BUT we must be coherent with the axis conventions...
// If we choose +Z to be the "forward" axis, and +X the left axis (like we do), we must "spoil" the camera from its own convention,
// because in openGL, if we assign an identity matrix to the camera, it looks in the -Z direction, and its +X direction
// is "right", instead of left.
// [Note: Having an identity matrix as the camera is like not having a camera at all and just draw on the OpenGL blackboard:
// we look from +Z to 0 -> -Z direction, and we have +X at our RIGHT].
// Many people force this convention (-Z = forward and +X = right) for all the objects, so they don't need to do this hack when
// dealing with the camera, but I strongly advice you not to do so, as most models are modelled with the +Z axis as their
// forward axis, and you'll end up rotating all the objects in the world, when you can just do some "dirty work" on the camera...
//
// P.S. For the ones that are still confused: don't worry, m_cameraT.getBasis().getColumn(2) is still the camera forward axis and that's
// the important thing to remember.
static btTransform m_cameraArrangedT;
m_cameraArrangedT = m_cameraT;
btMatrix3x3& m_cameraArrangedBasis = m_cameraArrangedT.getBasis();
//invert the sign of m_cameraArrangedT.getBasis().getColumn(2); // Z axis
m_cameraArrangedBasis[0].setZ(- m_cameraArrangedBasis[0][2]);
m_cameraArrangedBasis[1].setZ(- m_cameraArrangedBasis[1][2]);
m_cameraArrangedBasis[2].setZ(- m_cameraArrangedBasis[2][2]);
//invert the sign of m_cameraArrangedT.getBasis().getColumn(0); // X axis
m_cameraArrangedBasis[0].setX( - m_cameraArrangedBasis[0][0]);
m_cameraArrangedBasis[1].setX( - m_cameraArrangedBasis[1][0]);
m_cameraArrangedBasis[2].setX( - m_cameraArrangedBasis[2][0]);
// Here m_cameraArrangedT has been cleaned from the "camera convention"
m_cameraArrangedT.inverse().getOpenGLMatrix(m_modelviewMatrix); // very fast (see the implementation of Matrix3x3::inverse())
}
*/
static __inline mat3_t m3_rotation_x(float angle_in_rad) {
float s = sinf(angle_in_rad), c = cosf(angle_in_rad);
return mat3(
1, 0, 0,
0, c, -s,
0, s, c
);
}
static __inline mat3_t m3_rotation_y(float angle_in_rad) {
float s = sinf(angle_in_rad), c = cosf(angle_in_rad);
return mat3(
c, 0, s,
0, 1, 0,
-s, 0, c
);
}
static __inline mat3_t m3_rotation_z(float angle_in_rad) {
float s = sinf(angle_in_rad), c = cosf(angle_in_rad);
return mat3(
c, -s, 0,
s, c, 0,
0, 0, 1
);
}
static __inline mat3_t m3_transpose(mat3_t matrix) {
return mat3(matrix.m00, matrix.m01, matrix.m02,
matrix.m10, matrix.m11, matrix.m12,
matrix.m20, matrix.m21, matrix.m22);
}
static __inline mat3_t m3_slerp(const mat3_t* T1,const mat3_t* T2,float t) {
mat3_t m;
quat_t q = qt_slerp(m3_get_quaternion(T1),m3_get_quaternion(T2),t);
m3_set_quaternion(&m,q);
return m;
}
/**
* Multiplication of two 3x3 matrices.
*
* Implemented by following the row times column rule and illustrating it on a
* whiteboard with the proper indices in mind.
*
* Further reading: https://en.wikipedia.org/wiki/Matrix_multiplication
* But note that the article use the first index for rows and the second for
* columns.
*/
static __inline mat3_t m3_mul(mat3_t a, mat3_t b) {
mat3_t result;int i,j;
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
result.m[i][j] = a.m[0][j]*b.m[i][0] +
a.m[1][j]*b.m[i][1] +
a.m[2][j]*b.m[i][2];
}
}
return result;
}
//
// Matrix4 functions header implementation
//
static __inline mat4_t mat4(
float m00, float m10, float m20, float m30,
float m01, float m11, float m21, float m31,
float m02, float m12, float m22, float m32,
float m03, float m13, float m23, float m33
) {
mat4_t m;
m.m00=m00; m.m10=m10; m.m20=m20; m.m30=m30;
m.m01=m01; m.m11=m11; m.m21=m21; m.m31=m31;
m.m02=m02; m.m12=m12; m.m22=m22; m.m32=m32;
m.m03=m03; m.m13=m13; m.m23=m23; m.m33=m33;
return m;
}
static __inline mat4_t mat4_rm(
float m00, float m01, float m02, float m03,
float m10, float m11, float m12, float m13,
float m20, float m21, float m22, float m23,
float m30, float m31, float m32, float m33
) {
mat4_t m;
m.m00=m00; m.m10=m10; m.m20=m20; m.m30=m30;
m.m01=m01; m.m11=m11; m.m21=m21; m.m31=m31;
m.m02=m02; m.m12=m12; m.m22=m22; m.m32=m32;
m.m03=m03; m.m13=m13; m.m23=m23; m.m33=m33;
return m;
}
static __inline mat4_t mat4_from_array(float m[16]) {
mat4_t mat;
int i;for (i=0;i<16;i++) mat.v[i] = m[i];
return mat;
}
static __inline mat4_t m4_identity() {
return mat4(
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
}
static __inline void m4_set_identity_mat3(mat4_t* matrix) {
mat4_t* m = matrix;
m->m00 = 1; m->m10 = 0; m->m20 = 0;
m->m01 = 0; m->m11 = 1; m->m21 = 0;
m->m02 = 0; m->m12 = 0; m->m22 = 1;
}
static __inline mat3_t m4_get_mat3(const mat4_t* matrix) {
const mat4_t* m = matrix;
return mat3 (
m->m00, m->m10, m->m20,
m->m01, m->m11, m->m21,
m->m02, m->m12, m->m22
);
}
static __inline void m4_set_mat3(mat4_t* matrix,mat3_t matrix3) {
mat4_t* m = matrix;
m->m00 = matrix3.m00; m->m10 = matrix3.m10; m->m20 = matrix3.m20;
m->m01 = matrix3.m01; m->m11 = matrix3.m11; m->m21 = matrix3.m21;
m->m02 = matrix3.m02; m->m12 = matrix3.m12; m->m22 = matrix3.m22;
}
static __inline vec3_t m4_get_x_axis(const mat4_t* matrix) {
const mat4_t* m = matrix;
return vec3(m->m00,m->m01,m->m02);
}
static __inline vec3_t m4_get_y_axis(const mat4_t* matrix) {
const mat4_t* m = matrix;
return vec3(m->m10,m->m11,m->m12);
}
static __inline vec3_t m4_get_z_axis(const mat4_t* matrix) {
const mat4_t* m = matrix;
return vec3(m->m20,m->m21,m->m22);
}
static __inline mat4_t m4_invert_XZ_axis(const mat4_t* matrix) {
const mat4_t* m = matrix;
return mat4 (
-m->m00, m->m10, -m->m20, m->m30,
-m->m01, m->m11, -m->m21, m->m31,
-m->m02, m->m12, -m->m22, m->m32,
m->m03, m->m13, m->m23, m->m33
);
}
static __inline vec3_t m4_get_translation(const mat4_t* matrix) {
const mat4_t* m = matrix;
return vec3(m->m30,m->m31,m->m32);
}
static __inline void m4_set_translation(mat4_t* matrix,vec3_t translation) {
mat4_t* m = matrix;
m->m30 = translation.x;
m->m31 = translation.y;
m->m32 = translation.z;
}
static __inline mat4_t m4_translation(vec3_t offset) {
return mat4(
1, 0, 0, offset.x,
0, 1, 0, offset.y,
0, 0, 1, offset.z,
0, 0, 0, 1
);
}
static __inline mat4_t m4_scaling(vec3_t scale) {
float x = scale.x, y = scale.y, z = scale.z;
return mat4(
x, 0, 0, 0,
0, y, 0, 0,
0, 0, z, 0,
0, 0, 0, 1
);
}
static __inline mat4_t m4_rotation_x(float angle_in_rad) {
float s = sinf(angle_in_rad), c = cosf(angle_in_rad);
return mat4(
1, 0, 0, 0,
0, c, -s, 0,
0, s, c, 0,
0, 0, 0, 1
);
}
static __inline mat4_t m4_rotation_y(float angle_in_rad) {
float s = sinf(angle_in_rad), c = cosf(angle_in_rad);
return mat4(
c, 0, s, 0,
0, 1, 0, 0,
-s, 0, c, 0,
0, 0, 0, 1
);
}
static __inline mat4_t m4_rotation_z(float angle_in_rad) {
float s = sinf(angle_in_rad), c = cosf(angle_in_rad);
return mat4(
c, -s, 0, 0,
s, c, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
}
static __inline mat4_t m4_transpose(mat4_t matrix) {
return mat4(matrix.m00, matrix.m01, matrix.m02, matrix.m03,
matrix.m10, matrix.m11, matrix.m12, matrix.m13,
matrix.m20, matrix.m21, matrix.m22, matrix.m23,
matrix.m30, matrix.m31, matrix.m32, matrix.m33);
}
static __inline mat4_t m4_slerp(const mat4_t* T1,const mat4_t* T2,float t) {
mat4_t m = m4_identity();
quat_t q = qt_slerp(m4_get_quaternion(T1),m4_get_quaternion(T2),t);
vec3_t l = v3_lerp(m4_get_translation(T1),m4_get_translation(T2),t);
m4_set_quaternion(&m,q);
m4_set_translation(&m,l);
return m;
}
/**
* Multiplication of two 4x4 matrices.
*
* Implemented by following the row times column rule and illustrating it on a
* whiteboard with the proper indices in mind.
*
* Further reading: https://en.wikipedia.org/wiki/Matrix_multiplication
* But note that the article use the first index for rows and the second for
* columns.
*/
static __inline mat4_t m4_mul(mat4_t a, mat4_t b) {
mat4_t result;int i,j;
for(i = 0; i < 4; i++) {
for(j = 0; j < 4; j++) {
result.m[i][j] =
a.m[0][j] * b.m[i][0] +
a.m[1][j] * b.m[i][1] +
a.m[2][j] * b.m[i][2] +
a.m[3][j] * b.m[i][3];
}
}
return result;
}
/** Return the inverse of this mat4
It works only for translation + rotation, and only
when rotation can be represented by an unit quaternion
scaling is discarded
*/
static __inline mat4_t m4_invert_fast(mat4_t matrix) {
mat4_t inv;vec3_t tra;
m4_set_mat3(&inv,m3_transpose(m4_get_mat3(&matrix)));
inv.m30=inv.m31=inv.m32=inv.m03=inv.m13=inv.m23=0.f;inv.m33=1.f;
tra = m4_get_translation(&matrix);
tra.x=-tra.x;tra.y=-tra.y;tra.z=-tra.z;
m4_set_translation(&inv,m4_mul_dir(inv,tra));
return inv;
}
#ifdef __cplusplus
}
#endif
#endif // MATH_3D_HEADER
#ifdef MATH_3D_IMPLEMENTATION
#ifdef __cplusplus
extern "C" {
#endif
void v3_print(vec3_t v) {
v3_fprintp(stdout, v, 6, 2);
}
void v3_printp(vec3_t v, int width, int precision) {
v3_fprintp(stdout, v, width, precision);
}
void v3_fprint(FILE* stream, vec3_t v) {
v3_fprintp(stream, v, 6, 2);
}
void v3_fprintp(FILE* stream, vec3_t v, int width, int precision) {
int w = width, p = precision;
fprintf(stream, "( %*.*f %*.*f %*.*f )\n",
w, p, v.x, w, p, v.y, w, p, v.z
);
}
quat_t qt_slerp(quat_t qStart,quat_t qEnd,float factor) {
const int normalizeQOutAfterLerp = 1; // When using Lerp instead of Slerp qOut should be normalized. However some users prefer setting eps small enough so that they can leave the Lerp as it is.
const float eps=0.0001f; // In [0 = 100% Slerp,1 = 100% Lerp] Faster but less precise with bigger epsilon (Lerp is used instead of Slerp more often). Users should tune it to achieve a performance boost.
const int useAcosAndSinInsteadOfAtan2AndSqrt = 0;// Another possible minimal Speed vs Precision tweak (I suggest just changing it here and not in the caller code)
quat_t qOut;
float fCos;
fCos = qStart.x * qEnd.x + qStart.y * qEnd.y + qStart.z * qEnd.z + qStart.w * qEnd.w;
// Do we need to invert rotation?
if(fCos < 0) //Originally it was if(fCos < static_cast < Real >(0.0) && shortestPath)
{fCos = -fCos;qEnd.x = -qEnd.x;qEnd.y = -qEnd.y;qEnd.z = -qEnd.z;qEnd.w = -qEnd.w;}
if( fCos < 1.f - eps) // Originally if was "Ogre::Math::Abs(fCos)" instead of "fCos", but we know fCos>0, because we have hard coded shortestPath=true
{
// Standard case (slerp)
float fSin,fAngle;
if (!useAcosAndSinInsteadOfAtan2AndSqrt) {
// Ogre::Quaternion uses this branch by default
fSin = sqrt(1.f - fCos*fCos);
fAngle = atan2(fSin, fCos);
}
else {
// Possible replacement of the two lines above
// (it's hard to tell if they're faster, but my instinct tells me I should trust atan2 better than acos (geometry geeks needed here...)):
// But probably sin(...) is faster than (sqrt + 1 subtraction and mult)
fAngle = acos(fCos);
fSin = sin(fAngle);
}
{
const float fInvSin = 1.f / fSin;
const float fCoeff0 = sin((1.f - factor) * fAngle) * fInvSin;
const float fCoeff1 = sin(factor * fAngle) * fInvSin;
//qOut = fCoeff0 * qStart + fCoeff1 * qEnd; //Avoided for maximum portability and conversion of the code
qOut.x = (fCoeff0 * qStart.x + fCoeff1 * qEnd.x);
qOut.y = (fCoeff0 * qStart.y + fCoeff1 * qEnd.y);
qOut.z = (fCoeff0 * qStart.z + fCoeff1 * qEnd.z);
qOut.w = (fCoeff0 * qStart.w + fCoeff1 * qEnd.w);
}
} else
{
// There are two situations:
// 1. "qStart" and "qEnd" are very close (fCos ~= +1), so we can do a linear
// interpolation safely.
// 2. "qStart" and "qEnd" are almost inverse of each other (fCos ~= -1), there
// are an infinite number of possibilities interpolation. but we haven't
// have method to fix this case, so just use linear interpolation here.
// IMPORTANT: CASE 2 can't happen anymore because we have hardcoded "shortestPath = true" and now fCos > 0
const float fCoeff0 = 1.f - factor;
const float fCoeff1 = factor;
//qOut = fCoeff0 * qStart + fCoeff1 * qEnd; //Avoided for maximum portability and conversion of the code
qOut.x = (fCoeff0 * qStart.x + fCoeff1 * qEnd.x);
qOut.y = (fCoeff0 * qStart.y + fCoeff1 * qEnd.y);
qOut.z = (fCoeff0 * qStart.z + fCoeff1 * qEnd.z);
qOut.w = (fCoeff0 * qStart.w + fCoeff1 * qEnd.w);
if (normalizeQOutAfterLerp) qOut = qt_norm(qOut);
}
return qOut;
}
void qt_print(quat_t q) {
qt_fprintp(stdout, q, 6, 2);
}
void qt_printp(quat_t q, int width, int precision) {
qt_fprintp(stdout, q, width, precision);
}
void qt_fprint(FILE* stream, quat_t q) {
qt_fprintp(stream, q, 6, 2);
}
void qt_fprintp(FILE* stream, quat_t q, int width, int precision) {
int w = width, p = precision;
fprintf(stream, "( %*.*f %*.*f %*.*f %*.*f )\n",
w, p, q.x, w, p, q.y, w, p, q.z, w, p, q.w
);
}
/**
* Creates a matrix to rotate around an axis by a given angle. The axis doesn't
* need to be normalized.
*
* Sources:
*
* https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
*/
/*mat3_t m3_rotation(float angle_in_rad, vec3_t axis) {
vec3_t normalized_axis = v3_norm(axis);
float x = normalized_axis.x, y = normalized_axis.y, z = normalized_axis.z;
float c = cosf(angle_in_rad), s = sinf(angle_in_rad);
return mat3(
c + x*x*(1-c), x*y*(1-c) - z*s, x*z*(1-c) + y*s,
y*x*(1-c) + z*s, c + y*y*(1-c), y*z*(1-c) - x*s,
z*x*(1-c) - y*s, z*y*(1-c) + x*s, c + z*z*(1-c)
);
}*/
/**
* Implementation details:
*
* - Invert the 3x3 matrix to handle rotation, scaling, etc.
* correctly (see source).
* Sources for 3x3 matrix inversion:
*
* https://www.khanacademy.org/math/precalculus/precalc-matrices/determinants-and-inverses-of-large-matrices/v/inverting-3x3-part-2-determinant-and-adjugate-of-a-matrix
*/
mat3_t m3_invert(mat3_t matrix) {
// Create shorthands to access matrix members
float m00 = matrix.m00, m10 = matrix.m10, m20 = matrix.m20;
float m01 = matrix.m01, m11 = matrix.m11, m21 = matrix.m21;
float m02 = matrix.m02, m12 = matrix.m12, m22 = matrix.m22;
// Calculate cofactor matrix
float c00 = m11*m22 - m12*m21, c10 = -(m01*m22 - m02*m21), c20 = m01*m12 - m02*m11;
float c01 = -(m10*m22 - m12*m20), c11 = m00*m22 - m02*m20, c21 = -(m00*m12 - m02*m10);
float c02 = m10*m21 - m11*m20, c12 = -(m00*m21 - m01*m20), c22 = m00*m11 - m01*m10;
float i00,i10,i20, i01,i11,i21, i02,i12,i22;
// Caclculate the determinant by using the already calculated determinants
// in the cofactor matrix.
// Second sign is already minus from the cofactor matrix.
float det = m00*c00 + m10*c10 + m20 * c20;
if (fabs(det) < 0.00001)
return m3_identity();
// Calcuate inverse by dividing the transposed cofactor matrix by the determinant.
i00 = c00 / det; i10 = c01 / det; i20 = c02 / det;
i01 = c10 / det; i11 = c11 / det; i21 = c12 / det;
i02 = c20 / det; i12 = c21 / det; i22 = c22 / det;
// Combine the inverted R with the inverted translation
return mat3(
i00, i10, i20,
i01, i11, i21,
i02, i12, i22
);
}
/**
* Multiplies a 3x3 matrix with a 3D vector representing a direction in 3D space.
*/
vec3_t m3_mul_dir(mat3_t matrix, vec3_t direction) {
return vec3 (matrix.m00*direction.x + matrix.m10*direction.y + matrix.m20*direction.z,
matrix.m01*direction.x + matrix.m11*direction.y + matrix.m21*direction.z,
matrix.m02*direction.x + matrix.m12*direction.y + matrix.m22*direction.z);
}
// Not sure here if I have to invert m[i][j] with m[j][i]
quat_t m3_get_quaternion(const mat3_t* matrix) {
const mat3_t* m = matrix;
float temp[4];
float trace = m->m00 + m->m11 + m->m22;
if (trace > 0.f) {
float s = sqrt(trace + 1.0f);
temp[3]=(s * 0.5f);s = 0.5f / s;
temp[0]=((m->m12 - m->m21) * s);
temp[1]=((m->m20 - m->m02) * s);
temp[2]=((m->m01 - m->m10) * s);
}
else {
int i = m->m00 < m->m11 ?
(m->m11 < m->m22 ? 2 : 1) :
(m->m00 < m->m22 ? 2 : 0);
int j = (i + 1) % 3;
int k = (i + 2) % 3;
float s = sqrt(m->m[i][i] - m->m[j][j] - m->m[k][k] + 1.0f);
temp[i] = s * 0.5f;s = 0.5f / s;
temp[3] = (m->m[j][k] - m->m[k][j]) * s;
temp[j] = (m->m[i][j] + m->m[j][i]) * s;
temp[k] = (m->m[i][k] + m->m[k][i]) * s;
}
return quat(temp[0],temp[1],temp[2],temp[3]);