-
Notifications
You must be signed in to change notification settings - Fork 3
/
physac.h
2051 lines (1710 loc) · 82.8 KB
/
physac.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
/**********************************************************************************************
*
* Physac v1.0 - 2D Physics library for videogames
*
* DESCRIPTION:
*
* Physac is a small 2D physics engine written in pure C. The engine uses a fixed time-step thread loop
* to simluate physics. A physics step contains the following phases: get collision information,
* apply dynamics, collision solving and position correction. It uses a very simple struct for physic
* bodies with a position vector to be used in any 3D rendering API.
*
* CONFIGURATION:
*
* #define PHYSAC_IMPLEMENTATION
* Generates the implementation of the library into the included file.
* If not defined, the library is in header only mode and can be included in other headers
* or source files without problems. But only ONE file should hold the implementation.
*
* #define PHYSAC_STATIC (defined by default)
* The generated implementation will stay private inside implementation file and all
* internal symbols and functions will only be visible inside that file.
*
* #define PHYSAC_NO_THREADS
* The generated implementation won't include pthread library and user must create a secondary thread to call PhysicsThread().
* It is so important that the thread where PhysicsThread() is called must not have v-sync or any other CPU limitation.
*
* #define PHYSAC_STANDALONE
* Avoid raylib.h header inclusion in this file. Data types defined on raylib are defined
* internally in the library and input management and drawing functions must be provided by
* the user (check library implementation for further details).
*
* #define PHYSAC_DEBUG
* Traces log messages when creating and destroying physics bodies and detects errors in physics
* calculations and reference exceptions; it is useful for debug purposes
*
* #define PHYSAC_MALLOC()
* #define PHYSAC_FREE()
* You can define your own malloc/free implementation replacing stdlib.h malloc()/free() functions.
* Otherwise it will include stdlib.h and use the C standard library malloc()/free() function.
*
*
* NOTE 1: Physac requires multi-threading, when InitPhysics() a second thread is created to manage physics calculations.
* NOTE 2: Physac requires static C library linkage to avoid dependency on MinGW DLL (-static -lpthread)
*
* Use the following code to compile:
* gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static -lraylib -lpthread -lopengl32 -lgdi32 -std=c99
*
* VERY THANKS TO:
* Ramon Santamaria (github: @raysan5)
*
*
* LICENSE: zlib/libpng
*
* Copyright (c) 2016-2018 Victor Fisac (github: @victorfisac)
*
* This software is provided "as-is", without any express or implied warranty. In no event
* will the authors be held liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose, including commercial
* applications, and to alter it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim that you
* wrote the original software. If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented
* as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
**********************************************************************************************/
#if !defined(PHYSAC_H)
#define PHYSAC_H
// #define PHYSAC_STATIC
// #define PHYSAC_NO_THREADS
// #define PHYSAC_STANDALONE
// #define PHYSAC_DEBUG
#if defined(PHYSAC_STATIC)
#define PHYSACDEF static // Functions just visible to module including this file
#else
#if defined(__cplusplus)
#define PHYSACDEF extern "C" // Functions visible from other files (no name mangling of functions in C++)
#else
#define PHYSACDEF extern // Functions visible from other files
#endif
#endif
//----------------------------------------------------------------------------------
// Defines and Macros
//----------------------------------------------------------------------------------
#define PHYSAC_MAX_BODIES 64
#define PHYSAC_MAX_MANIFOLDS 4096
#define PHYSAC_MAX_VERTICES 24
#define PHYSAC_CIRCLE_VERTICES 24
#define PHYSAC_DESIRED_DELTATIME 1.0/60.0
#define PHYSAC_MAX_TIMESTEP 0.02
#define PHYSAC_COLLISION_ITERATIONS 100
#define PHYSAC_PENETRATION_ALLOWANCE 0.05f
#define PHYSAC_PENETRATION_CORRECTION 0.4f
#define PHYSAC_PI 3.14159265358979323846
#define PHYSAC_DEG2RAD (PHYSAC_PI/180.0f)
#define PHYSAC_MALLOC(size) malloc(size)
#define PHYSAC_FREE(ptr) free(ptr)
//----------------------------------------------------------------------------------
// Types and Structures Definition
// NOTE: Below types are required for PHYSAC_STANDALONE usage
//----------------------------------------------------------------------------------
#if defined(PHYSAC_STANDALONE)
// Vector2 type
typedef struct Vector2 {
float x;
float y;
} Vector2;
// Boolean type
#if !defined(_STDBOOL_H)
typedef enum { false, true } bool;
#define _STDBOOL_H
#endif
#endif
typedef enum PhysicsShapeType { PHYSICS_CIRCLE, PHYSICS_POLYGON } PhysicsShapeType;
// Previously defined to be used in PhysicsShape struct as circular dependencies
typedef struct PhysicsBodyData *PhysicsBody;
// Mat2 type (used for polygon shape rotation matrix)
typedef struct Mat2 {
float m00;
float m01;
float m10;
float m11;
} Mat2;
typedef struct PolygonData {
unsigned int vertexCount; // Current used vertex and normals count
Vector2 positions[PHYSAC_MAX_VERTICES]; // Polygon vertex positions vectors
Vector2 normals[PHYSAC_MAX_VERTICES]; // Polygon vertex normals vectors
} PolygonData;
typedef struct PhysicsShape {
PhysicsShapeType type; // Physics shape type (circle or polygon)
PhysicsBody body; // Shape physics body reference
float radius; // Circle shape radius (used for circle shapes)
Mat2 transform; // Vertices transform matrix 2x2
PolygonData vertexData; // Polygon shape vertices position and normals data (just used for polygon shapes)
} PhysicsShape;
typedef struct PhysicsBodyData {
unsigned int id; // Reference unique identifier
bool enabled; // Enabled dynamics state (collisions are calculated anyway)
Vector2 position; // Physics body shape pivot
Vector2 velocity; // Current linear velocity applied to position
Vector2 force; // Current linear force (reset to 0 every step)
float angularVelocity; // Current angular velocity applied to orient
float torque; // Current angular force (reset to 0 every step)
float orient; // Rotation in radians
float inertia; // Moment of inertia
float inverseInertia; // Inverse value of inertia
float mass; // Physics body mass
float inverseMass; // Inverse value of mass
float staticFriction; // Friction when the body has not movement (0 to 1)
float dynamicFriction; // Friction when the body has movement (0 to 1)
float restitution; // Restitution coefficient of the body (0 to 1)
bool useGravity; // Apply gravity force to dynamics
bool isGrounded; // Physics grounded on other body state
bool freezeOrient; // Physics rotation constraint
PhysicsShape shape; // Physics body shape information (type, radius, vertices, normals)
} PhysicsBodyData;
typedef struct PhysicsManifoldData {
unsigned int id; // Reference unique identifier
PhysicsBody bodyA; // Manifold first physics body reference
PhysicsBody bodyB; // Manifold second physics body reference
float penetration; // Depth of penetration from collision
Vector2 normal; // Normal direction vector from 'a' to 'b'
Vector2 contacts[2]; // Points of contact during collision
unsigned int contactsCount; // Current collision number of contacts
float restitution; // Mixed restitution during collision
float dynamicFriction; // Mixed dynamic friction during collision
float staticFriction; // Mixed static friction during collision
} PhysicsManifoldData, *PhysicsManifold;
#if defined(__cplusplus)
extern "C" { // Prevents name mangling of functions
#endif
//----------------------------------------------------------------------------------
// Module Functions Declaration
//----------------------------------------------------------------------------------
PHYSACDEF void InitPhysics(void); // Initializes physics values, pointers and creates physics loop thread
PHYSACDEF bool IsPhysicsEnabled(void); // Returns true if physics thread is currently enabled
PHYSACDEF void SetPhysicsGravity(float x, float y); // Sets physics global gravity force
PHYSACDEF PhysicsBody CreatePhysicsBodyCircle(Vector2 pos, float radius, float density); // Creates a new circle physics body with generic parameters
PHYSACDEF PhysicsBody CreatePhysicsBodyRectangle(Vector2 pos, float width, float height, float density); // Creates a new rectangle physics body with generic parameters
PHYSACDEF PhysicsBody CreatePhysicsBodyPolygon(Vector2 pos, float radius, int sides, float density); // Creates a new polygon physics body with generic parameters
PHYSACDEF void PhysicsAddForce(PhysicsBody body, Vector2 force); // Adds a force to a physics body
PHYSACDEF void PhysicsAddTorque(PhysicsBody body, float amount); // Adds an angular force to a physics body
PHYSACDEF void PhysicsShatter(PhysicsBody body, Vector2 position, float force); // Shatters a polygon shape physics body to little physics bodies with explosion force
PHYSACDEF int GetPhysicsBodiesCount(void); // Returns the current amount of created physics bodies
PHYSACDEF PhysicsBody GetPhysicsBody(int index); // Returns a physics body of the bodies pool at a specific index
PHYSACDEF int GetPhysicsShapeType(int index); // Returns the physics body shape type (PHYSICS_CIRCLE or PHYSICS_POLYGON)
PHYSACDEF int GetPhysicsShapeVerticesCount(int index); // Returns the amount of vertices of a physics body shape
PHYSACDEF Vector2 GetPhysicsShapeVertex(PhysicsBody body, int vertex); // Returns transformed position of a body shape (body position + vertex transformed position)
PHYSACDEF void SetPhysicsBodyRotation(PhysicsBody body, float radians); // Sets physics body shape transform based on radians parameter
PHYSACDEF void DestroyPhysicsBody(PhysicsBody body); // Unitializes and destroy a physics body
PHYSACDEF void ResetPhysics(void); // Destroys created physics bodies and manifolds and resets global values
PHYSACDEF void ClosePhysics(void); // Unitializes physics pointers and closes physics loop thread
#if defined(__cplusplus)
}
#endif
#endif // PHYSAC_H
/***********************************************************************************
*
* PHYSAC IMPLEMENTATION
*
************************************************************************************/
#if defined(PHYSAC_IMPLEMENTATION)
#if !defined(PHYSAC_NO_THREADS)
#include <pthread.h> // Required for: pthread_t, pthread_create()
#endif
#if defined(PHYSAC_DEBUG)
#include <stdio.h> // Required for: printf()
#endif
#include <stdlib.h> // Required for: malloc(), free(), srand(), rand()
#include <math.h> // Required for: cosf(), sinf(), fabs(), sqrtf()
#include <stdint.h> // Required for: uint64_t
#if !defined(PHYSAC_STANDALONE)
#include "raymath.h" // Required for: Vector2Add(), Vector2Subtract()
#endif
// Time management functionality
#if defined(_WIN32)
// Functions required to query time on Windows
int __stdcall QueryPerformanceCounter(unsigned long long int *lpPerformanceCount);
int __stdcall QueryPerformanceFrequency(unsigned long long int *lpFrequency);
#include <time.h>
#elif defined(__linux__)
#if _POSIX_C_SOURCE < 199309L
#undef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 199309L // Required for CLOCK_MONOTONIC if compiled with c99 without gnu ext.
#endif
#include <sys/time.h> // Required for: timespec
#include <time.h> // Required for: clock_gettime()
#elif defined(__APPLE__) // macOS also defines __MACH__
#include <mach/mach_time.h> // Required for: mach_absolute_time()
#endif
//----------------------------------------------------------------------------------
// Defines and Macros
//----------------------------------------------------------------------------------
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
#define PHYSAC_FLT_MAX 3.402823466e+38f
#define PHYSAC_EPSILON 0.000001f
#define PHYSAC_K 1.0f/3.0f
#define PHYSAC_VECTOR_ZERO (Vector2){ 0.0f, 0.0f }
//----------------------------------------------------------------------------------
// Global Variables Definition
//----------------------------------------------------------------------------------
#if !defined(PHYSAC_NO_THREADS)
static pthread_t physicsThreadId; // Physics thread id
#endif
static unsigned int usedMemory = 0; // Total allocated dynamic memory
static bool physicsThreadEnabled = false; // Physics thread enabled state
static double baseTime = 0.0; // Offset time for MONOTONIC clock
static double startTime = 0.0; // Start time in milliseconds
static double deltaTime = 0.0; // Delta time used for physics steps
static double currentTime = 0.0; // Current time in milliseconds
static uint64_t frequency = 0; // Hi-res clock frequency
static double accumulator = 0.0; // Physics time step delta time accumulator
static unsigned int stepsCount = 0; // Total physics steps processed
static Vector2 gravityForce = { 0.0f, 9.81f/1000 }; // Physics world gravity force
static PhysicsBody bodies[PHYSAC_MAX_BODIES]; // Physics bodies pointers array
static unsigned int physicsBodiesCount = 0; // Physics world current bodies counter
static PhysicsManifold contacts[PHYSAC_MAX_MANIFOLDS]; // Physics bodies pointers array
static unsigned int physicsManifoldsCount = 0; // Physics world current manifolds counter
//----------------------------------------------------------------------------------
// Module Internal Functions Declaration
//----------------------------------------------------------------------------------
static int FindAvailableBodyIndex(); // Finds a valid index for a new physics body initialization
static PolygonData CreateRandomPolygon(float radius, int sides); // Creates a random polygon shape with max vertex distance from polygon pivot
static PolygonData CreateRectanglePolygon(Vector2 pos, Vector2 size); // Creates a rectangle polygon shape based on a min and max positions
static void *PhysicsLoop(void *arg); // Physics loop thread function
static void PhysicsStep(void); // Physics steps calculations (dynamics, collisions and position corrections)
static int FindAvailableManifoldIndex(); // Finds a valid index for a new manifold initialization
static PhysicsManifold CreatePhysicsManifold(PhysicsBody a, PhysicsBody b); // Creates a new physics manifold to solve collision
static void DestroyPhysicsManifold(PhysicsManifold manifold); // Unitializes and destroys a physics manifold
static void SolvePhysicsManifold(PhysicsManifold manifold); // Solves a created physics manifold between two physics bodies
static void SolveCircleToCircle(PhysicsManifold manifold); // Solves collision between two circle shape physics bodies
static void SolveCircleToPolygon(PhysicsManifold manifold); // Solves collision between a circle to a polygon shape physics bodies
static void SolvePolygonToCircle(PhysicsManifold manifold); // Solves collision between a polygon to a circle shape physics bodies
static void SolvePolygonToPolygon(PhysicsManifold manifold); // Solves collision between two polygons shape physics bodies
static void IntegratePhysicsForces(PhysicsBody body); // Integrates physics forces into velocity
static void InitializePhysicsManifolds(PhysicsManifold manifold); // Initializes physics manifolds to solve collisions
static void IntegratePhysicsImpulses(PhysicsManifold manifold); // Integrates physics collisions impulses to solve collisions
static void IntegratePhysicsVelocity(PhysicsBody body); // Integrates physics velocity into position and forces
static void CorrectPhysicsPositions(PhysicsManifold manifold); // Corrects physics bodies positions based on manifolds collision information
static float FindAxisLeastPenetration(int *faceIndex, PhysicsShape shapeA, PhysicsShape shapeB); // Finds polygon shapes axis least penetration
static void FindIncidentFace(Vector2 *v0, Vector2 *v1, PhysicsShape ref, PhysicsShape inc, int index); // Finds two polygon shapes incident face
static int Clip(Vector2 normal, float clip, Vector2 *faceA, Vector2 *faceB); // Calculates clipping based on a normal and two faces
static bool BiasGreaterThan(float valueA, float valueB); // Check if values are between bias range
static Vector2 TriangleBarycenter(Vector2 v1, Vector2 v2, Vector2 v3); // Returns the barycenter of a triangle given by 3 points
static void InitTimer(void); // Initializes hi-resolution MONOTONIC timer
static uint64_t GetTimeCount(void); // Get hi-res MONOTONIC time measure in seconds
static double GetCurrentTime(void); // // Get hi-res MONOTONIC time measure in seconds
static int GetRandomNumber(int min, int max); // Returns a random number between min and max (both included)
// Math functions
static void MathClamp(double *value, double min, double max); // Clamp a value in a range
static Vector2 MathCross(float value, Vector2 vector); // Returns the cross product of a vector and a value
static float MathCrossVector2(Vector2 v1, Vector2 v2); // Returns the cross product of two vectors
static float MathLenSqr(Vector2 vector); // Returns the len square root of a vector
static float MathDot(Vector2 v1, Vector2 v2); // Returns the dot product of two vectors
static inline float DistSqr(Vector2 v1, Vector2 v2); // Returns the square root of distance between two vectors
static void MathNormalize(Vector2 *vector); // Returns the normalized values of a vector
#if defined(PHYSAC_STANDALONE)
static Vector2 Vector2Add(Vector2 v1, Vector2 v2); // Returns the sum of two given vectors
static Vector2 Vector2Subtract(Vector2 v1, Vector2 v2); // Returns the subtract of two given vectors
#endif
static Mat2 Mat2Radians(float radians); // Creates a matrix 2x2 from a given radians value
static void Mat2Set(Mat2 *matrix, float radians); // Set values from radians to a created matrix 2x2
static inline Mat2 Mat2Transpose(Mat2 matrix); // Returns the transpose of a given matrix 2x2
static inline Vector2 Mat2MultiplyVector2(Mat2 matrix, Vector2 vector); // Multiplies a vector by a matrix 2x2
//----------------------------------------------------------------------------------
// Module Functions Definition
//----------------------------------------------------------------------------------
// Initializes physics values, pointers and creates physics loop thread
PHYSACDEF void InitPhysics(void)
{
#if !defined(PHYSAC_NO_THREADS)
// NOTE: if defined, user will need to create a thread for PhysicsThread function manually
// Create physics thread using POSIXS thread libraries
pthread_create(&physicsThreadId, NULL, &PhysicsLoop, NULL);
#endif
#if defined(PHYSAC_DEBUG)
printf("[PHYSAC] physics module initialized successfully\n");
#endif
}
// Returns true if physics thread is currently enabled
PHYSACDEF bool IsPhysicsEnabled(void)
{
return physicsThreadEnabled;
}
// Sets physics global gravity force
PHYSACDEF void SetPhysicsGravity(float x, float y)
{
gravityForce.x = x;
gravityForce.y = y;
}
// Creates a new circle physics body with generic parameters
PHYSACDEF PhysicsBody CreatePhysicsBodyCircle(Vector2 pos, float radius, float density)
{
PhysicsBody newBody = CreatePhysicsBodyPolygon(pos, radius, PHYSAC_CIRCLE_VERTICES, density);
return newBody;
}
// Creates a new rectangle physics body with generic parameters
PHYSACDEF PhysicsBody CreatePhysicsBodyRectangle(Vector2 pos, float width, float height, float density)
{
PhysicsBody newBody = (PhysicsBody)PHYSAC_MALLOC(sizeof(PhysicsBodyData));
usedMemory += sizeof(PhysicsBodyData);
int newId = FindAvailableBodyIndex();
if (newId != -1)
{
// Initialize new body with generic values
newBody->id = newId;
newBody->enabled = true;
newBody->position = pos;
newBody->velocity = (Vector2){ 0.0f };
newBody->force = (Vector2){ 0.0f };
newBody->angularVelocity = 0.0f;
newBody->torque = 0.0f;
newBody->orient = 0.0f;
newBody->shape.type = PHYSICS_POLYGON;
newBody->shape.body = newBody;
newBody->shape.radius = 0.0f;
newBody->shape.transform = Mat2Radians(0.0f);
newBody->shape.vertexData = CreateRectanglePolygon(pos, (Vector2){ width, height });
// Calculate centroid and moment of inertia
Vector2 center = { 0.0f, 0.0f };
float area = 0.0f;
float inertia = 0.0f;
for (int i = 0; i < newBody->shape.vertexData.vertexCount; i++)
{
// Triangle vertices, third vertex implied as (0, 0)
Vector2 p1 = newBody->shape.vertexData.positions[i];
int nextIndex = (((i + 1) < newBody->shape.vertexData.vertexCount) ? (i + 1) : 0);
Vector2 p2 = newBody->shape.vertexData.positions[nextIndex];
float D = MathCrossVector2(p1, p2);
float triangleArea = D/2;
area += triangleArea;
// Use area to weight the centroid average, not just vertex position
center.x += triangleArea*PHYSAC_K*(p1.x + p2.x);
center.y += triangleArea*PHYSAC_K*(p1.y + p2.y);
float intx2 = p1.x*p1.x + p2.x*p1.x + p2.x*p2.x;
float inty2 = p1.y*p1.y + p2.y*p1.y + p2.y*p2.y;
inertia += (0.25f*PHYSAC_K*D)*(intx2 + inty2);
}
center.x *= 1.0f/area;
center.y *= 1.0f/area;
// Translate vertices to centroid (make the centroid (0, 0) for the polygon in model space)
// Note: this is not really necessary
for (int i = 0; i < newBody->shape.vertexData.vertexCount; i++)
{
newBody->shape.vertexData.positions[i].x -= center.x;
newBody->shape.vertexData.positions[i].y -= center.y;
}
newBody->mass = density*area;
newBody->inverseMass = ((newBody->mass != 0.0f) ? 1.0f/newBody->mass : 0.0f);
newBody->inertia = density*inertia;
newBody->inverseInertia = ((newBody->inertia != 0.0f) ? 1.0f/newBody->inertia : 0.0f);
newBody->staticFriction = 0.4f;
newBody->dynamicFriction = 0.2f;
newBody->restitution = 0.0f;
newBody->useGravity = true;
newBody->isGrounded = false;
newBody->freezeOrient = false;
// Add new body to bodies pointers array and update bodies count
bodies[physicsBodiesCount] = newBody;
physicsBodiesCount++;
#if defined(PHYSAC_DEBUG)
printf("[PHYSAC] created polygon physics body id %i\n", newBody->id);
#endif
}
#if defined(PHYSAC_DEBUG)
else printf("[PHYSAC] new physics body creation failed because there is any available id to use\n");
#endif
return newBody;
}
// Creates a new polygon physics body with generic parameters
PHYSACDEF PhysicsBody CreatePhysicsBodyPolygon(Vector2 pos, float radius, int sides, float density)
{
PhysicsBody newBody = (PhysicsBody)PHYSAC_MALLOC(sizeof(PhysicsBodyData));
usedMemory += sizeof(PhysicsBodyData);
int newId = FindAvailableBodyIndex();
if (newId != -1)
{
// Initialize new body with generic values
newBody->id = newId;
newBody->enabled = true;
newBody->position = pos;
newBody->velocity = PHYSAC_VECTOR_ZERO;
newBody->force = PHYSAC_VECTOR_ZERO;
newBody->angularVelocity = 0.0f;
newBody->torque = 0.0f;
newBody->orient = 0.0f;
newBody->shape.type = PHYSICS_POLYGON;
newBody->shape.body = newBody;
newBody->shape.transform = Mat2Radians(0.0f);
newBody->shape.vertexData = CreateRandomPolygon(radius, sides);
// Calculate centroid and moment of inertia
Vector2 center = { 0.0f, 0.0f };
float area = 0.0f;
float inertia = 0.0f;
for (int i = 0; i < newBody->shape.vertexData.vertexCount; i++)
{
// Triangle vertices, third vertex implied as (0, 0)
Vector2 position1 = newBody->shape.vertexData.positions[i];
int nextIndex = (((i + 1) < newBody->shape.vertexData.vertexCount) ? (i + 1) : 0);
Vector2 position2 = newBody->shape.vertexData.positions[nextIndex];
float cross = MathCrossVector2(position1, position2);
float triangleArea = cross/2;
area += triangleArea;
// Use area to weight the centroid average, not just vertex position
center.x += triangleArea*PHYSAC_K*(position1.x + position2.x);
center.y += triangleArea*PHYSAC_K*(position1.y + position2.y);
float intx2 = position1.x*position1.x + position2.x*position1.x + position2.x*position2.x;
float inty2 = position1.y*position1.y + position2.y*position1.y + position2.y*position2.y;
inertia += (0.25f*PHYSAC_K*cross)*(intx2 + inty2);
}
center.x *= 1.0f/area;
center.y *= 1.0f/area;
// Translate vertices to centroid (make the centroid (0, 0) for the polygon in model space)
// Note: this is not really necessary
for (int i = 0; i < newBody->shape.vertexData.vertexCount; i++)
{
newBody->shape.vertexData.positions[i].x -= center.x;
newBody->shape.vertexData.positions[i].y -= center.y;
}
newBody->mass = density*area;
newBody->inverseMass = ((newBody->mass != 0.0f) ? 1.0f/newBody->mass : 0.0f);
newBody->inertia = density*inertia;
newBody->inverseInertia = ((newBody->inertia != 0.0f) ? 1.0f/newBody->inertia : 0.0f);
newBody->staticFriction = 0.4f;
newBody->dynamicFriction = 0.2f;
newBody->restitution = 0.0f;
newBody->useGravity = true;
newBody->isGrounded = false;
newBody->freezeOrient = false;
// Add new body to bodies pointers array and update bodies count
bodies[physicsBodiesCount] = newBody;
physicsBodiesCount++;
#if defined(PHYSAC_DEBUG)
printf("[PHYSAC] created polygon physics body id %i\n", newBody->id);
#endif
}
#if defined(PHYSAC_DEBUG)
else printf("[PHYSAC] new physics body creation failed because there is any available id to use\n");
#endif
return newBody;
}
// Adds a force to a physics body
PHYSACDEF void PhysicsAddForce(PhysicsBody body, Vector2 force)
{
if (body != NULL) body->force = Vector2Add(body->force, force);
}
// Adds an angular force to a physics body
PHYSACDEF void PhysicsAddTorque(PhysicsBody body, float amount)
{
if (body != NULL) body->torque += amount;
}
// Shatters a polygon shape physics body to little physics bodies with explosion force
PHYSACDEF void PhysicsShatter(PhysicsBody body, Vector2 position, float force)
{
if (body != NULL)
{
if (body->shape.type == PHYSICS_POLYGON)
{
PolygonData vertexData = body->shape.vertexData;
bool collision = false;
for (int i = 0; i < vertexData.vertexCount; i++)
{
Vector2 positionA = body->position;
Vector2 positionB = Mat2MultiplyVector2(body->shape.transform, Vector2Add(body->position, vertexData.positions[i]));
int nextIndex = (((i + 1) < vertexData.vertexCount) ? (i + 1) : 0);
Vector2 positionC = Mat2MultiplyVector2(body->shape.transform, Vector2Add(body->position, vertexData.positions[nextIndex]));
// Check collision between each triangle
float alpha = ((positionB.y - positionC.y)*(position.x - positionC.x) + (positionC.x - positionB.x)*(position.y - positionC.y))/
((positionB.y - positionC.y)*(positionA.x - positionC.x) + (positionC.x - positionB.x)*(positionA.y - positionC.y));
float beta = ((positionC.y - positionA.y)*(position.x - positionC.x) + (positionA.x - positionC.x)*(position.y - positionC.y))/
((positionB.y - positionC.y)*(positionA.x - positionC.x) + (positionC.x - positionB.x)*(positionA.y - positionC.y));
float gamma = 1.0f - alpha - beta;
if ((alpha > 0.0f) && (beta > 0.0f) & (gamma > 0.0f))
{
collision = true;
break;
}
}
if (collision)
{
int count = vertexData.vertexCount;
Vector2 bodyPos = body->position;
Vector2 vertices[count];
Mat2 trans = body->shape.transform;
for (int i = 0; i < count; i++) vertices[i] = vertexData.positions[i];
// Destroy shattered physics body
DestroyPhysicsBody(body);
for (int i = 0; i < count; i++)
{
int nextIndex = (((i + 1) < count) ? (i + 1) : 0);
Vector2 center = TriangleBarycenter(vertices[i], vertices[nextIndex], PHYSAC_VECTOR_ZERO);
center = Vector2Add(bodyPos, center);
Vector2 offset = Vector2Subtract(center, bodyPos);
PhysicsBody newBody = CreatePhysicsBodyPolygon(center, 10, 3, 10); // Create polygon physics body with relevant values
PolygonData newData = { 0 };
newData.vertexCount = 3;
newData.positions[0] = Vector2Subtract(vertices[i], offset);
newData.positions[1] = Vector2Subtract(vertices[nextIndex], offset);
newData.positions[2] = Vector2Subtract(position, center);
// Separate vertices to avoid unnecessary physics collisions
newData.positions[0].x *= 0.95f;
newData.positions[0].y *= 0.95f;
newData.positions[1].x *= 0.95f;
newData.positions[1].y *= 0.95f;
newData.positions[2].x *= 0.95f;
newData.positions[2].y *= 0.95f;
// Calculate polygon faces normals
for (int j = 0; j < newData.vertexCount; j++)
{
int nextVertex = (((j + 1) < newData.vertexCount) ? (j + 1) : 0);
Vector2 face = Vector2Subtract(newData.positions[nextVertex], newData.positions[j]);
newData.normals[j] = (Vector2){ face.y, -face.x };
MathNormalize(&newData.normals[j]);
}
// Apply computed vertex data to new physics body shape
newBody->shape.vertexData = newData;
newBody->shape.transform = trans;
// Calculate centroid and moment of inertia
center = PHYSAC_VECTOR_ZERO;
float area = 0.0f;
float inertia = 0.0f;
for (int j = 0; j < newBody->shape.vertexData.vertexCount; j++)
{
// Triangle vertices, third vertex implied as (0, 0)
Vector2 p1 = newBody->shape.vertexData.positions[j];
int nextVertex = (((j + 1) < newBody->shape.vertexData.vertexCount) ? (j + 1) : 0);
Vector2 p2 = newBody->shape.vertexData.positions[nextVertex];
float D = MathCrossVector2(p1, p2);
float triangleArea = D/2;
area += triangleArea;
// Use area to weight the centroid average, not just vertex position
center.x += triangleArea*PHYSAC_K*(p1.x + p2.x);
center.y += triangleArea*PHYSAC_K*(p1.y + p2.y);
float intx2 = p1.x*p1.x + p2.x*p1.x + p2.x*p2.x;
float inty2 = p1.y*p1.y + p2.y*p1.y + p2.y*p2.y;
inertia += (0.25f*PHYSAC_K*D)*(intx2 + inty2);
}
center.x *= 1.0f/area;
center.y *= 1.0f/area;
newBody->mass = area;
newBody->inverseMass = ((newBody->mass != 0.0f) ? 1.0f/newBody->mass : 0.0f);
newBody->inertia = inertia;
newBody->inverseInertia = ((newBody->inertia != 0.0f) ? 1.0f/newBody->inertia : 0.0f);
// Calculate explosion force direction
Vector2 pointA = newBody->position;
Vector2 pointB = Vector2Subtract(newData.positions[1], newData.positions[0]);
pointB.x /= 2.0f;
pointB.y /= 2.0f;
Vector2 forceDirection = Vector2Subtract(Vector2Add(pointA, Vector2Add(newData.positions[0], pointB)), newBody->position);
MathNormalize(&forceDirection);
forceDirection.x *= force;
forceDirection.y *= force;
// Apply force to new physics body
PhysicsAddForce(newBody, forceDirection);
}
}
}
}
#if defined(PHYSAC_DEBUG)
else printf("[PHYSAC] error when trying to shatter a null reference physics body");
#endif
}
// Returns the current amount of created physics bodies
PHYSACDEF int GetPhysicsBodiesCount(void)
{
return physicsBodiesCount;
}
// Returns a physics body of the bodies pool at a specific index
PHYSACDEF PhysicsBody GetPhysicsBody(int index)
{
PhysicsBody body = NULL;
if (index < physicsBodiesCount)
{
body = bodies[index];
if (body == NULL)
{
#if defined(PHYSAC_DEBUG)
printf("[PHYSAC] error when trying to get a null reference physics body");
#endif
}
}
#if defined(PHYSAC_DEBUG)
else printf("[PHYSAC] physics body index is out of bounds");
#endif
return body;
}
// Returns the physics body shape type (PHYSICS_CIRCLE or PHYSICS_POLYGON)
PHYSACDEF int GetPhysicsShapeType(int index)
{
int result = -1;
if (index < physicsBodiesCount)
{
PhysicsBody body = bodies[index];
if (body != NULL) result = body->shape.type;
#if defined(PHYSAC_DEBUG)
else printf("[PHYSAC] error when trying to get a null reference physics body");
#endif
}
#if defined(PHYSAC_DEBUG)
else printf("[PHYSAC] physics body index is out of bounds");
#endif
return result;
}
// Returns the amount of vertices of a physics body shape
PHYSACDEF int GetPhysicsShapeVerticesCount(int index)
{
int result = 0;
if (index < physicsBodiesCount)
{
PhysicsBody body = bodies[index];
if (body != NULL)
{
switch (body->shape.type)
{
case PHYSICS_CIRCLE: result = PHYSAC_CIRCLE_VERTICES; break;
case PHYSICS_POLYGON: result = body->shape.vertexData.vertexCount; break;
default: break;
}
}
#if defined(PHYSAC_DEBUG)
else printf("[PHYSAC] error when trying to get a null reference physics body");
#endif
}
#if defined(PHYSAC_DEBUG)
else printf("[PHYSAC] physics body index is out of bounds");
#endif
return result;
}
// Returns transformed position of a body shape (body position + vertex transformed position)
PHYSACDEF Vector2 GetPhysicsShapeVertex(PhysicsBody body, int vertex)
{
Vector2 position = { 0.0f, 0.0f };
if (body != NULL)
{
switch (body->shape.type)
{
case PHYSICS_CIRCLE:
{
position.x = body->position.x + cosf(360.0f/PHYSAC_CIRCLE_VERTICES*vertex*PHYSAC_DEG2RAD)*body->shape.radius;
position.y = body->position.y + sinf(360.0f/PHYSAC_CIRCLE_VERTICES*vertex*PHYSAC_DEG2RAD)*body->shape.radius;
} break;
case PHYSICS_POLYGON:
{
PolygonData vertexData = body->shape.vertexData;
position = Vector2Add(body->position, Mat2MultiplyVector2(body->shape.transform, vertexData.positions[vertex]));
} break;
default: break;
}
}
#if defined(PHYSAC_DEBUG)
else printf("[PHYSAC] error when trying to get a null reference physics body");
#endif
return position;
}
// Sets physics body shape transform based on radians parameter
PHYSACDEF void SetPhysicsBodyRotation(PhysicsBody body, float radians)
{
if (body != NULL)
{
body->orient = radians;
if (body->shape.type == PHYSICS_POLYGON) body->shape.transform = Mat2Radians(radians);
}
}
// Unitializes and destroys a physics body
PHYSACDEF void DestroyPhysicsBody(PhysicsBody body)
{
if (body != NULL)
{
int id = body->id;
int index = -1;
for (int i = 0; i < physicsBodiesCount; i++)
{
if (bodies[i]->id == id)
{
index = i;
break;
}
}
#if defined(PHYSAC_DEBUG)
if (index == -1) printf("[PHYSAC] cannot find body id %i in pointers array\n", id);
#endif
// Free body allocated memory
PHYSAC_FREE(body);
usedMemory -= sizeof(PhysicsBodyData);
bodies[index] = NULL;
// Reorder physics bodies pointers array and its catched index
for (int i = index; i < physicsBodiesCount; i++)
{
if ((i + 1) < physicsBodiesCount) bodies[i] = bodies[i + 1];
}
// Update physics bodies count
physicsBodiesCount--;
#if defined(PHYSAC_DEBUG)
printf("[PHYSAC] destroyed physics body id %i\n", id);
#endif
}
#if defined(PHYSAC_DEBUG)
else printf("[PHYSAC] error trying to destroy a null referenced body\n");
#endif
}
// Destroys created physics bodies and manifolds and resets global values
PHYSACDEF void ResetPhysics(void)
{
// Unitialize physics bodies dynamic memory allocations
for (int i = physicsBodiesCount - 1; i >= 0; i--)
{
PhysicsBody body = bodies[i];
if (body != NULL)
{
PHYSAC_FREE(body);
bodies[i] = NULL;
usedMemory -= sizeof(PhysicsBodyData);
}
}
physicsBodiesCount = 0;
// Unitialize physics manifolds dynamic memory allocations
for (int i = physicsManifoldsCount - 1; i >= 0; i--)
{
PhysicsManifold manifold = contacts[i];
if (manifold != NULL)
{
PHYSAC_FREE(manifold);
contacts[i] = NULL;
usedMemory -= sizeof(PhysicsManifoldData);
}
}
physicsManifoldsCount = 0;
#if defined(PHYSAC_DEBUG)
printf("[PHYSAC] physics module reset successfully\n");
#endif
}
// Unitializes physics pointers and exits physics loop thread
PHYSACDEF void ClosePhysics(void)
{
// Exit physics loop thread
physicsThreadEnabled = false;
#if !defined(PHYSAC_NO_THREADS)
pthread_join(physicsThreadId, NULL);
#endif
}
//----------------------------------------------------------------------------------
// Module Internal Functions Definition
//----------------------------------------------------------------------------------
// Finds a valid index for a new physics body initialization
static int FindAvailableBodyIndex()
{
int index = -1;
for (int i = 0; i < PHYSAC_MAX_BODIES; i++)
{
int currentId = i;
// Check if current id already exist in other physics body
for (int k = 0; k < physicsBodiesCount; k++)
{
if (bodies[k]->id == currentId)
{
currentId++;
break;
}
}
// If it is not used, use it as new physics body id
if (currentId == i)
{
index = i;
break;
}
}
return index;
}
// Creates a random polygon shape with max vertex distance from polygon pivot
static PolygonData CreateRandomPolygon(float radius, int sides)
{
PolygonData data = { 0 };
data.vertexCount = sides;
// Calculate polygon vertices positions
for (int i = 0; i < data.vertexCount; i++)
{
data.positions[i].x = cosf(360.0f/sides*i*PHYSAC_DEG2RAD)*radius;
data.positions[i].y = sinf(360.0f/sides*i*PHYSAC_DEG2RAD)*radius;
}
// Calculate polygon faces normals
for (int i = 0; i < data.vertexCount; i++)
{
int nextIndex = (((i + 1) < sides) ? (i + 1) : 0);
Vector2 face = Vector2Subtract(data.positions[nextIndex], data.positions[i]);
data.normals[i] = (Vector2){ face.y, -face.x };
MathNormalize(&data.normals[i]);
}
return data;
}
// Creates a rectangle polygon shape based on a min and max positions
static PolygonData CreateRectanglePolygon(Vector2 pos, Vector2 size)
{
PolygonData data = { 0 };
data.vertexCount = 4;
// Calculate polygon vertices positions
data.positions[0] = (Vector2){ pos.x + size.x/2, pos.y - size.y/2 };
data.positions[1] = (Vector2){ pos.x + size.x/2, pos.y + size.y/2 };
data.positions[2] = (Vector2){ pos.x - size.x/2, pos.y + size.y/2 };
data.positions[3] = (Vector2){ pos.x - size.x/2, pos.y - size.y/2 };
// Calculate polygon faces normals
for (int i = 0; i < data.vertexCount; i++)
{
int nextIndex = (((i + 1) < data.vertexCount) ? (i + 1) : 0);
Vector2 face = Vector2Subtract(data.positions[nextIndex], data.positions[i]);
data.normals[i] = (Vector2){ face.y, -face.x };
MathNormalize(&data.normals[i]);
}
return data;
}