tinyphysicsengine.h 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  1. #ifndef TINYPHYSICSENGINE_H
  2. #define TINYPHYSICSENGINE_H
  3. /**
  4. author: Miloslav Ciz
  5. license: CC0 1.0 (public domain)
  6. found at https://creativecommons.org/publicdomain/zero/1.0/
  7. + additional waiver of all IP
  8. version: 0.1d
  9. This is a suckless library for simple 3D (and 2D) physics simulation. The
  10. physics is based on the Newtonian model but is further simplified,
  11. particularly in the area of rotation: there is no moment of inertia for
  12. objects, i.e. every object rotates as if it was a ball, and the object can be
  13. rotating around at most one axis at a time, i.e. it is not possible to
  14. simulate e.g. the Dzhanibekov effect. Therefore the library is mostly intended
  15. for entertainment software.
  16. CONVENTIONS:
  17. - Compatibility and simple usage with small3dlib is intended, so most
  18. convention and data types copy those of small3dlib (which takes a lot of
  19. conventions of OpenGL).
  20. - No floating point is used, we instead use integers (effectively a fixed
  21. point). TPE_FRACTIONS_PER_UNIT is an equivalent to 1.0 in floating point and
  22. all numbers are normalized by this constant.
  23. - Units: for any measure only an abstract mathematical unit is used. This unit
  24. always has TPE_FRACTIONS_PER_UNIT parts. You can assign any correcpondence
  25. with real life units to these units. E.g. 1 spatial unit (which you can see
  26. as e.g. 1 meter) is equal to TPE_FRACTIONS_PER_UNIT. Same with temporatl
  27. (e.g. 1 second) and mass (e.g. 1 kilogram) units, and also any derived
  28. units, e.g. a unit of velocity (e.g. 1 m/s) is also equal to 1
  29. TPE_FRACTIONS_PER_UNIT. A full angle is also split into
  30. TPE_FRACTIONS_PER_UNIT parts (instead of 2 * PI or degrees).
  31. - Quaternions are represented as vec4 where x ~ i, y ~ j, z ~ k, w ~ real.
  32. - There is no vec3 type, vec4 is usead for all vectors, for simplicity.
  33. */
  34. #include <stdint.h>
  35. typedef int32_t TPE_Unit;
  36. /** How many fractions a unit is split into. This is NOT SUPPOSED TO BE
  37. REDEFINED, so rather don't do it (otherwise things may overflow etc.). */
  38. #define TPE_FRACTIONS_PER_UNIT 512
  39. #define TPE_INFINITY 2147483647
  40. #define TPE_PI 1608 ///< pi in TPE_Units
  41. #define TPE_SHAPE_POINT 0 ///< single point in space
  42. #define TPE_SHAPE_SPHERE 1 ///< sphere, params.: radius
  43. #define TPE_SHAPE_CAPSULE 2 ///< capsule: radius, height
  44. #define TPE_SHAPE_CUBOID 3 ///< cuboid, params.: width, height, depth
  45. #define TPE_SHAPE_PLANE 4 ///< plane, params.: width, depth
  46. #define TPE_SHAPE_CYLINDER 5 ///< cylinder, params.: radius, height
  47. #define TPE_SHAPE_TRIMESH 6 /**< triangle mesh, params.:
  48. vertex count,
  49. triangle count
  50. vertices (int32_t pointer),
  51. indices (uint16_t pointer) */
  52. #define TPE_MAX_SHAPE_PARAMS 3
  53. #define TPE_MAX_SHAPE_PARAMPOINTERS 2
  54. #define TPE_BODY_FLAG_DISABLED 0x00 ///< won't take part in simul. at all
  55. #define TPE_BODY_FLAG_NONCOLLIDING 0x01 ///< simulated but won't collide
  56. TPE_Unit TPE_wrap(TPE_Unit value, TPE_Unit mod);
  57. TPE_Unit TPE_clamp(TPE_Unit v, TPE_Unit v1, TPE_Unit v2);
  58. static inline TPE_Unit TPE_abs(TPE_Unit x);
  59. static inline TPE_Unit TPE_nonZero(TPE_Unit x);
  60. /** Returns an integer square root of given value. */
  61. TPE_Unit TPE_sqrt(TPE_Unit value);
  62. /** Returns a sine of given arguments, both in TPE_Units (see the library
  63. conventions). */
  64. TPE_Unit TPE_sin(TPE_Unit x);
  65. TPE_Unit TPE_cos(TPE_Unit x);
  66. TPE_Unit TPE_asin(TPE_Unit x);
  67. TPE_Unit TPE_acos(TPE_Unit x);
  68. typedef struct
  69. {
  70. TPE_Unit x;
  71. TPE_Unit y;
  72. TPE_Unit z;
  73. TPE_Unit w;
  74. } TPE_Vec4;
  75. #define TPE_PRINTF_VEC4(v) printf("[%d %d %d %d] ",(v).x,(v).y,(v).z,(v).w);
  76. /** Initializes vec4 to a zero vector. */
  77. void TPE_initVec4(TPE_Vec4 *v);
  78. void TPE_vec4Set(TPE_Vec4 *v, TPE_Unit x, TPE_Unit y, TPE_Unit z, TPE_Unit w);
  79. void TPE_vec3Add(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  80. void TPE_vec4Add(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  81. void TPE_vec3Substract(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  82. void TPE_vec3Average(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  83. void TPE_vec4Substract(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  84. void TPE_vec3Multiply(TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result);
  85. void TPE_vec3MultiplyPlain(TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result);
  86. void TPE_vec4Multiply(TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result);
  87. void TPE_vec3CrossProduct(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  88. void TPE_vec3Normalize(TPE_Vec4 *v);
  89. void TPE_vec4Normalize(TPE_Vec4 *v);
  90. void TPE_vec3Project(TPE_Vec4 v, TPE_Vec4 base, TPE_Vec4 *result);
  91. TPE_Unit TPE_vec3Len(TPE_Vec4 v);
  92. TPE_Unit TPE_vec3LenTaxicab(TPE_Vec4 v);
  93. TPE_Unit TPE_vec3Dist(TPE_Vec4 a, TPE_Vec4 b);
  94. TPE_Unit TPE_vec4Len(TPE_Vec4 v);
  95. TPE_Unit TPE_vec3DotProduct(TPE_Vec4 v1, TPE_Vec4 v2);
  96. TPE_Vec4 TPE_vec4(TPE_Unit x, TPE_Unit y, TPE_Unit z, TPE_Unit w);
  97. TPE_Vec4 TPE_vec3Plus(TPE_Vec4 a, TPE_Vec4 b);
  98. TPE_Vec4 TPE_vec3Minus(TPE_Vec4 a, TPE_Vec4 b);
  99. TPE_Vec4 TPE_vec3Times(TPE_Vec4 a, TPE_Unit f);
  100. TPE_Vec4 TPE_vec3Cross(TPE_Vec4 a, TPE_Vec4 b);
  101. static inline TPE_Vec4 TPE_vec3Normalized(TPE_Vec4 v);
  102. static inline TPE_Vec4 TPE_vec3Projected(TPE_Vec4 v, TPE_Vec4 base);
  103. /** Returns the closest point on given line segment (a,b) to given point (p). */
  104. TPE_Vec4 TPE_lineSegmentClosestPoint(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 p);
  105. /** Converts a linear velocity of an orbiting point to the angular velocity
  106. (angle units per time units). This depends on the distance of the point from
  107. the center of rotation. */
  108. TPE_Unit TPE_linearVelocityToAngular(TPE_Unit velocity, TPE_Unit distance);
  109. /** Performs the opposite conversion of TPE_linearVelocityToAngular. */
  110. TPE_Unit TPE_angularVelocityToLinear(TPE_Unit velocity, TPE_Unit distance);
  111. /** Holds a rotation state around a single axis, in a way that prevents rounding
  112. errors from distorting the rotation over time. In theory rotation of a body
  113. could be represented as
  114. [current orientation, axis of rotation, angular velocity]
  115. However applying the rotation and normalizing the orientation quaternion each
  116. simulation step leads to error cumulation and the rotation gets aligned with
  117. one principal axis after some time. Because of this we rather represent the
  118. rotation state as
  119. [original orientation, axis of rotation, angular velocity, current angle]
  120. From this we can at each simulation step compute the current orientation by
  121. applying rotation by current angle to the original rotation without error
  122. cumulation. */
  123. typedef struct
  124. {
  125. TPE_Vec4 originalOrientation; /**< quaternion holding the original
  126. orientation of the body at the time when it
  127. has taken on this rotational state */
  128. TPE_Vec4 axisVelocity; /**< axis of rotation (x,y,z) and a
  129. non-negative angular velocity around this
  130. axis (w), determined ny the right hand
  131. rule */
  132. TPE_Unit currentAngle; /**< angle the body has already rotated along
  133. the rotation axis (from the original
  134. orientation) */
  135. } TPE_RotationState;
  136. typedef struct
  137. {
  138. uint8_t shape;
  139. TPE_Unit shapeParams[TPE_MAX_SHAPE_PARAMS]; ///< parameters of the body type
  140. void *shapeParamPointers[TPE_MAX_SHAPE_PARAMPOINTERS]; ///< pointer parameters
  141. uint8_t flags;
  142. TPE_Unit mass; /**< body mass, setting this to TPE_INFINITY will
  143. make the object static (not moving at all)
  144. which may help performance */
  145. TPE_Vec4 position; ///< position of the body's center of mass
  146. TPE_Vec4 velocity; ///< linear velocity vector
  147. TPE_RotationState rotation; /**< holds the state related to rotation, i.e.
  148. the rotation axis, angular momentum and data
  149. from which current orientation can be
  150. inferred */
  151. } TPE_Body;
  152. /** Initializes a physical body, this should be called on all TPE_Body objects
  153. that are created.*/
  154. void TPE_bodyInit(TPE_Body *body);
  155. /** Computes a 4x4 transform matrix of given body. The matrix has the same
  156. format as S3L_Mat4 from small3dlib. */
  157. void TPE_bodyGetTransformMatrix(const TPE_Body *body, TPE_Unit matrix[4][4]);
  158. /** Gets the current orientation of a body as a quaternion. */
  159. TPE_Vec4 TPE_bodyGetOrientation(const TPE_Body *body);
  160. TPE_Vec4 TPE_bodySetOrientation(TPE_Body *body, TPE_Vec4 orientation);
  161. /** Updates the body position and rotation according to its current velocity
  162. and rotation state. */
  163. void TPE_bodyStep(TPE_Body *body);
  164. /** Sets the rotation state of a body as an axis of rotation and angular
  165. velocity around this axis. */
  166. void TPE_bodySetRotation(TPE_Body *body, TPE_Vec4 axis, TPE_Unit velocity);
  167. /** Adds a rotation to the current rotation of a body. This addition is perfomed
  168. as a vector addition of the current and new rotation represented as vectors
  169. whose direction is the rotation axis and magnitude is the angular velocity
  170. around that axis. */
  171. void TPE_bodyAddRotation(TPE_Body *body, TPE_Vec4 axis, TPE_Unit velocity);
  172. /** Applies a velocity change to a body at a specific point (relative to the
  173. body center), which will change its linear and/or angular velocity. This is
  174. similar to an impulse but doesn't take mass into account, only velocity. */
  175. void TPE_bodyApplyVelocity(TPE_Body *body, TPE_Vec4 point, TPE_Vec4 velocity);
  176. /** Collision detection: checks if two bodies are colliding. The return value is
  177. the collision depth along the collision normal (0 if the bodies are not
  178. colliding). World-space collision point is returned via a pointer. Collision
  179. normal is also returned via a pointer and its direction is "away from body1",
  180. i.e. if you move body1 in the opposite direction of this normal by the
  181. collision depth (return value), the bodies should no longer be colliding
  182. (in some cases another collision may still occur). */
  183. TPE_Unit TPE_bodyCollides(const TPE_Body *body1, const TPE_Body *body2,
  184. TPE_Vec4 *collisionPoint, TPE_Vec4 *collisionNormal);
  185. /** Gets a velocity of a single point on a rigid body, taking into account its
  186. linear velocity and rotation. The point coordinates are relative to the body
  187. center. The point does NOT have to be on the surface, it can be inside and
  188. even outside the body too. */
  189. TPE_Vec4 TPE_bodyGetPointVelocity(const TPE_Body *body, TPE_Vec4 point);
  190. void TPE_resolveCollision(TPE_Body *body1 ,TPE_Body *body2,
  191. TPE_Vec4 collisionPoint, TPE_Vec4 collisionNormal);
  192. /** Gets a uint16_t integer type of collision depending on two shapes, the order
  193. of shapes doesn't matter. */
  194. #define TPE_COLLISION_TYPE(shape1,shape2) \
  195. ((shape1) <= (shape2) ? \
  196. (((uint16_t) (shape1)) << 8) | (shape2) : \
  197. (((uint16_t) (shape2)) << 8) | (shape1))
  198. typedef struct
  199. {
  200. uint16_t bodyCount;
  201. TPE_Body *bodies;
  202. } TPE_PhysicsWorld;
  203. /** Multiplies two quaternions which can be seen as chaining two rotations
  204. represented by them. This is not commutative (a*b != b*a)! Rotations a is
  205. performed firth, then rotation b is performed. */
  206. void TPE_quaternionMultiply(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  207. /** Initializes quaternion to the rotation identity (i.e. NOT zero
  208. quaternion). */
  209. void TPE_quaternionInit(TPE_Vec4 *quaternion);
  210. /** Converts a rotation given as an axis and angle around this axis (by right
  211. hand rule) to a rotation quaternion. */
  212. void TPE_rotationToQuaternion(TPE_Vec4 axis, TPE_Unit angle,
  213. TPE_Vec4 *quaternion);
  214. void TPE_quaternionToRotation(TPE_Vec4 quaternion, TPE_Vec4 *axis,
  215. TPE_Unit *angle);
  216. /** Computes the conjugate of a quaternion (analogous to matrix inversion, the
  217. quaternion will represent the opposite rotation). */
  218. TPE_Vec4 TPE_quaternionConjugate(TPE_Vec4 quaternion);
  219. /** Converts a rotation quaternion to a 4x4 rotation matrix. The matrix is
  220. indexed as [column][row] and is in the same format as S3L_Mat4 from
  221. small3dlib. */
  222. void TPE_quaternionToRotationMatrix(TPE_Vec4 quaternion, TPE_Unit matrix[4][4]);
  223. void TPE_rotatePoint(TPE_Vec4 *point, TPE_Vec4 quaternion);
  224. void TPE_getVelocitiesAfterCollision(
  225. TPE_Unit *v1,
  226. TPE_Unit *v2,
  227. TPE_Unit m1,
  228. TPE_Unit m2,
  229. TPE_Unit elasticity
  230. );
  231. //------------------------------------------------------------------------------
  232. void TPE_initVec4(TPE_Vec4 *v)
  233. {
  234. v->x = 0;
  235. v->y = 0;
  236. v->z = 0;
  237. v->w = 0;
  238. }
  239. TPE_Vec4 TPE_vec4(TPE_Unit x, TPE_Unit y, TPE_Unit z, TPE_Unit w)
  240. {
  241. TPE_Vec4 r;
  242. r.x = x;
  243. r.y = y;
  244. r.z = z;
  245. r.w = w;
  246. return r;
  247. }
  248. void TPE_vec4Set(TPE_Vec4 *v, TPE_Unit x, TPE_Unit y, TPE_Unit z, TPE_Unit w)
  249. {
  250. v->x = x;
  251. v->y = y;
  252. v->z = z;
  253. v->w = w;
  254. }
  255. TPE_Unit TPE_wrap(TPE_Unit value, TPE_Unit mod)
  256. {
  257. return value >= 0 ? (value % mod) : (mod + (value % mod) - 1);
  258. }
  259. TPE_Unit TPE_clamp(TPE_Unit v, TPE_Unit v1, TPE_Unit v2)
  260. {
  261. return v >= v1 ? (v <= v2 ? v : v2) : v1;
  262. }
  263. TPE_Unit TPE_nonZero(TPE_Unit x)
  264. {
  265. return x + (x == 0);
  266. }
  267. #define TPE_SIN_TABLE_LENGTH 128
  268. static const TPE_Unit TPE_sinTable[TPE_SIN_TABLE_LENGTH] =
  269. {
  270. /* 511 was chosen here as a highest number that doesn't overflow during
  271. compilation for TPE_FRACTIONS_PER_UNIT == 1024 */
  272. (0*TPE_FRACTIONS_PER_UNIT)/511, (6*TPE_FRACTIONS_PER_UNIT)/511,
  273. (12*TPE_FRACTIONS_PER_UNIT)/511, (18*TPE_FRACTIONS_PER_UNIT)/511,
  274. (25*TPE_FRACTIONS_PER_UNIT)/511, (31*TPE_FRACTIONS_PER_UNIT)/511,
  275. (37*TPE_FRACTIONS_PER_UNIT)/511, (43*TPE_FRACTIONS_PER_UNIT)/511,
  276. (50*TPE_FRACTIONS_PER_UNIT)/511, (56*TPE_FRACTIONS_PER_UNIT)/511,
  277. (62*TPE_FRACTIONS_PER_UNIT)/511, (68*TPE_FRACTIONS_PER_UNIT)/511,
  278. (74*TPE_FRACTIONS_PER_UNIT)/511, (81*TPE_FRACTIONS_PER_UNIT)/511,
  279. (87*TPE_FRACTIONS_PER_UNIT)/511, (93*TPE_FRACTIONS_PER_UNIT)/511,
  280. (99*TPE_FRACTIONS_PER_UNIT)/511, (105*TPE_FRACTIONS_PER_UNIT)/511,
  281. (111*TPE_FRACTIONS_PER_UNIT)/511, (118*TPE_FRACTIONS_PER_UNIT)/511,
  282. (124*TPE_FRACTIONS_PER_UNIT)/511, (130*TPE_FRACTIONS_PER_UNIT)/511,
  283. (136*TPE_FRACTIONS_PER_UNIT)/511, (142*TPE_FRACTIONS_PER_UNIT)/511,
  284. (148*TPE_FRACTIONS_PER_UNIT)/511, (154*TPE_FRACTIONS_PER_UNIT)/511,
  285. (160*TPE_FRACTIONS_PER_UNIT)/511, (166*TPE_FRACTIONS_PER_UNIT)/511,
  286. (172*TPE_FRACTIONS_PER_UNIT)/511, (178*TPE_FRACTIONS_PER_UNIT)/511,
  287. (183*TPE_FRACTIONS_PER_UNIT)/511, (189*TPE_FRACTIONS_PER_UNIT)/511,
  288. (195*TPE_FRACTIONS_PER_UNIT)/511, (201*TPE_FRACTIONS_PER_UNIT)/511,
  289. (207*TPE_FRACTIONS_PER_UNIT)/511, (212*TPE_FRACTIONS_PER_UNIT)/511,
  290. (218*TPE_FRACTIONS_PER_UNIT)/511, (224*TPE_FRACTIONS_PER_UNIT)/511,
  291. (229*TPE_FRACTIONS_PER_UNIT)/511, (235*TPE_FRACTIONS_PER_UNIT)/511,
  292. (240*TPE_FRACTIONS_PER_UNIT)/511, (246*TPE_FRACTIONS_PER_UNIT)/511,
  293. (251*TPE_FRACTIONS_PER_UNIT)/511, (257*TPE_FRACTIONS_PER_UNIT)/511,
  294. (262*TPE_FRACTIONS_PER_UNIT)/511, (268*TPE_FRACTIONS_PER_UNIT)/511,
  295. (273*TPE_FRACTIONS_PER_UNIT)/511, (278*TPE_FRACTIONS_PER_UNIT)/511,
  296. (283*TPE_FRACTIONS_PER_UNIT)/511, (289*TPE_FRACTIONS_PER_UNIT)/511,
  297. (294*TPE_FRACTIONS_PER_UNIT)/511, (299*TPE_FRACTIONS_PER_UNIT)/511,
  298. (304*TPE_FRACTIONS_PER_UNIT)/511, (309*TPE_FRACTIONS_PER_UNIT)/511,
  299. (314*TPE_FRACTIONS_PER_UNIT)/511, (319*TPE_FRACTIONS_PER_UNIT)/511,
  300. (324*TPE_FRACTIONS_PER_UNIT)/511, (328*TPE_FRACTIONS_PER_UNIT)/511,
  301. (333*TPE_FRACTIONS_PER_UNIT)/511, (338*TPE_FRACTIONS_PER_UNIT)/511,
  302. (343*TPE_FRACTIONS_PER_UNIT)/511, (347*TPE_FRACTIONS_PER_UNIT)/511,
  303. (352*TPE_FRACTIONS_PER_UNIT)/511, (356*TPE_FRACTIONS_PER_UNIT)/511,
  304. (361*TPE_FRACTIONS_PER_UNIT)/511, (365*TPE_FRACTIONS_PER_UNIT)/511,
  305. (370*TPE_FRACTIONS_PER_UNIT)/511, (374*TPE_FRACTIONS_PER_UNIT)/511,
  306. (378*TPE_FRACTIONS_PER_UNIT)/511, (382*TPE_FRACTIONS_PER_UNIT)/511,
  307. (386*TPE_FRACTIONS_PER_UNIT)/511, (391*TPE_FRACTIONS_PER_UNIT)/511,
  308. (395*TPE_FRACTIONS_PER_UNIT)/511, (398*TPE_FRACTIONS_PER_UNIT)/511,
  309. (402*TPE_FRACTIONS_PER_UNIT)/511, (406*TPE_FRACTIONS_PER_UNIT)/511,
  310. (410*TPE_FRACTIONS_PER_UNIT)/511, (414*TPE_FRACTIONS_PER_UNIT)/511,
  311. (417*TPE_FRACTIONS_PER_UNIT)/511, (421*TPE_FRACTIONS_PER_UNIT)/511,
  312. (424*TPE_FRACTIONS_PER_UNIT)/511, (428*TPE_FRACTIONS_PER_UNIT)/511,
  313. (431*TPE_FRACTIONS_PER_UNIT)/511, (435*TPE_FRACTIONS_PER_UNIT)/511,
  314. (438*TPE_FRACTIONS_PER_UNIT)/511, (441*TPE_FRACTIONS_PER_UNIT)/511,
  315. (444*TPE_FRACTIONS_PER_UNIT)/511, (447*TPE_FRACTIONS_PER_UNIT)/511,
  316. (450*TPE_FRACTIONS_PER_UNIT)/511, (453*TPE_FRACTIONS_PER_UNIT)/511,
  317. (456*TPE_FRACTIONS_PER_UNIT)/511, (459*TPE_FRACTIONS_PER_UNIT)/511,
  318. (461*TPE_FRACTIONS_PER_UNIT)/511, (464*TPE_FRACTIONS_PER_UNIT)/511,
  319. (467*TPE_FRACTIONS_PER_UNIT)/511, (469*TPE_FRACTIONS_PER_UNIT)/511,
  320. (472*TPE_FRACTIONS_PER_UNIT)/511, (474*TPE_FRACTIONS_PER_UNIT)/511,
  321. (476*TPE_FRACTIONS_PER_UNIT)/511, (478*TPE_FRACTIONS_PER_UNIT)/511,
  322. (481*TPE_FRACTIONS_PER_UNIT)/511, (483*TPE_FRACTIONS_PER_UNIT)/511,
  323. (485*TPE_FRACTIONS_PER_UNIT)/511, (487*TPE_FRACTIONS_PER_UNIT)/511,
  324. (488*TPE_FRACTIONS_PER_UNIT)/511, (490*TPE_FRACTIONS_PER_UNIT)/511,
  325. (492*TPE_FRACTIONS_PER_UNIT)/511, (494*TPE_FRACTIONS_PER_UNIT)/511,
  326. (495*TPE_FRACTIONS_PER_UNIT)/511, (497*TPE_FRACTIONS_PER_UNIT)/511,
  327. (498*TPE_FRACTIONS_PER_UNIT)/511, (499*TPE_FRACTIONS_PER_UNIT)/511,
  328. (501*TPE_FRACTIONS_PER_UNIT)/511, (502*TPE_FRACTIONS_PER_UNIT)/511,
  329. (503*TPE_FRACTIONS_PER_UNIT)/511, (504*TPE_FRACTIONS_PER_UNIT)/511,
  330. (505*TPE_FRACTIONS_PER_UNIT)/511, (506*TPE_FRACTIONS_PER_UNIT)/511,
  331. (507*TPE_FRACTIONS_PER_UNIT)/511, (507*TPE_FRACTIONS_PER_UNIT)/511,
  332. (508*TPE_FRACTIONS_PER_UNIT)/511, (509*TPE_FRACTIONS_PER_UNIT)/511,
  333. (509*TPE_FRACTIONS_PER_UNIT)/511, (510*TPE_FRACTIONS_PER_UNIT)/511,
  334. (510*TPE_FRACTIONS_PER_UNIT)/511, (510*TPE_FRACTIONS_PER_UNIT)/511,
  335. (510*TPE_FRACTIONS_PER_UNIT)/511, (510*TPE_FRACTIONS_PER_UNIT)/511
  336. };
  337. #define TPE_SIN_TABLE_UNIT_STEP\
  338. (TPE_FRACTIONS_PER_UNIT / (TPE_SIN_TABLE_LENGTH * 4))
  339. TPE_Unit TPE_sqrt(TPE_Unit value)
  340. {
  341. int8_t sign = 1;
  342. if (value < 0)
  343. {
  344. sign = -1;
  345. value *= -1;
  346. }
  347. uint32_t result = 0;
  348. uint32_t a = value;
  349. uint32_t b = 1u << 30;
  350. while (b > a)
  351. b >>= 2;
  352. while (b != 0)
  353. {
  354. if (a >= result + b)
  355. {
  356. a -= result + b;
  357. result = result + 2 * b;
  358. }
  359. b >>= 2;
  360. result >>= 1;
  361. }
  362. return result * sign;
  363. }
  364. TPE_Unit TPE_sin(TPE_Unit x)
  365. {
  366. x = TPE_wrap(x / TPE_SIN_TABLE_UNIT_STEP,TPE_SIN_TABLE_LENGTH * 4);
  367. int8_t positive = 1;
  368. if (x < TPE_SIN_TABLE_LENGTH)
  369. {
  370. }
  371. else if (x < TPE_SIN_TABLE_LENGTH * 2)
  372. {
  373. x = TPE_SIN_TABLE_LENGTH * 2 - x - 1;
  374. }
  375. else if (x < TPE_SIN_TABLE_LENGTH * 3)
  376. {
  377. x = x - TPE_SIN_TABLE_LENGTH * 2;
  378. positive = 0;
  379. }
  380. else
  381. {
  382. x = TPE_SIN_TABLE_LENGTH - (x - TPE_SIN_TABLE_LENGTH * 3) - 1;
  383. positive = 0;
  384. }
  385. return positive ? TPE_sinTable[x] : -1 * TPE_sinTable[x];
  386. }
  387. TPE_Unit TPE_cos(TPE_Unit x)
  388. {
  389. return TPE_sin(x + TPE_FRACTIONS_PER_UNIT / 4);
  390. }
  391. void TPE_bodyInit(TPE_Body *body)
  392. {
  393. // TODO
  394. TPE_initVec4(&(body->position));
  395. TPE_initVec4(&(body->velocity));
  396. // init orientation to identity unit quaternion (1,0,0,0):
  397. TPE_quaternionInit(&(body->rotation.originalOrientation));
  398. TPE_vec4Set(&(body->rotation.axisVelocity),TPE_FRACTIONS_PER_UNIT,0,0,0);
  399. body->rotation.currentAngle = 0;
  400. body->mass = TPE_FRACTIONS_PER_UNIT;
  401. }
  402. TPE_Vec4 TPE_bodySetOrientation(TPE_Body *body, TPE_Vec4 orientation)
  403. {
  404. body->rotation.originalOrientation = orientation;
  405. body->rotation.currentAngle = 0;
  406. }
  407. TPE_Vec4 TPE_bodyGetOrientation(const TPE_Body *body)
  408. {
  409. TPE_Vec4 axisRotation, result;
  410. TPE_rotationToQuaternion(
  411. body->rotation.axisVelocity,
  412. body->rotation.currentAngle,
  413. &axisRotation);
  414. TPE_quaternionMultiply(
  415. body->rotation.originalOrientation,
  416. axisRotation,
  417. &result);
  418. TPE_vec4Normalize(&result);
  419. return result;
  420. }
  421. void TPE_vec3CrossProduct(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result)
  422. {
  423. TPE_Vec4 r;
  424. r.x = (a.y * b.z - a.z * b.y) / TPE_FRACTIONS_PER_UNIT;
  425. r.y = (a.z * b.x - a.x * b.z) / TPE_FRACTIONS_PER_UNIT;
  426. r.z = (a.x * b.y - a.y * b.x) / TPE_FRACTIONS_PER_UNIT;
  427. *result = r;
  428. }
  429. TPE_Vec4 TPE_vec3Cross(TPE_Vec4 a, TPE_Vec4 b)
  430. {
  431. TPE_vec3CrossProduct(a,b,&a);
  432. return a;
  433. }
  434. void TPE_bodyApplyVelocity(TPE_Body *body, TPE_Vec4 point, TPE_Vec4 velocity)
  435. {
  436. TPE_Vec4 angularVelocity, rotationAxis;
  437. TPE_vec3Add(body->velocity,velocity,&(body->velocity));
  438. TPE_Unit pointDistance = TPE_vec3Len(point);
  439. if (pointDistance != 0)
  440. {
  441. /* normalize the point, we don't use the function as we don't want to
  442. recompute the vector length */
  443. point.x = (point.x * TPE_FRACTIONS_PER_UNIT) / pointDistance;
  444. point.y = (point.y * TPE_FRACTIONS_PER_UNIT) / pointDistance;
  445. point.z = (point.z * TPE_FRACTIONS_PER_UNIT) / pointDistance;
  446. /* Now we take only a part of the applied velocity, the part projected
  447. to a plane perpendicular to the point vector, and this part will
  448. contribute to the body rotation. */
  449. TPE_Vec4 tmp;
  450. TPE_vec3Project(velocity,point,&tmp);
  451. TPE_vec3Substract(velocity,tmp,&angularVelocity);
  452. TPE_vec3CrossProduct(point,angularVelocity,&rotationAxis);
  453. TPE_bodyAddRotation(body,rotationAxis,
  454. TPE_linearVelocityToAngular(
  455. TPE_vec3Len(angularVelocity),-1 * pointDistance));
  456. }
  457. }
  458. void _TPE_getShapes(const TPE_Body *b1, const TPE_Body *b2, uint8_t shape1,
  459. const TPE_Body **first, const TPE_Body **second)
  460. {
  461. if (b1->shape == shape1)
  462. {
  463. *first = b1;
  464. *second = b2;
  465. }
  466. else
  467. {
  468. *first = b2;
  469. *second = b1;
  470. }
  471. }
  472. TPE_Unit TPE_bodyCollides(const TPE_Body *body1, const TPE_Body *body2,
  473. TPE_Vec4 *collisionPoint, TPE_Vec4 *collisionNormal)
  474. {
  475. // handle collision of different shapes each in a specific case:
  476. switch (TPE_COLLISION_TYPE(body1->shape,body2->shape))
  477. {
  478. case TPE_COLLISION_TYPE(TPE_SHAPE_SPHERE,TPE_SHAPE_SPHERE):
  479. {
  480. TPE_Vec4 distanceVec;
  481. TPE_vec3Substract(body2->position,body1->position,&distanceVec);
  482. TPE_Unit distance = TPE_vec3Len(distanceVec);
  483. distance -= body1->shapeParams[0] + body2->shapeParams[0];
  484. if (distance < 0)
  485. {
  486. TPE_vec3Average(body1->position,body2->position,collisionPoint);
  487. *collisionNormal = distanceVec;
  488. TPE_vec3Normalize(collisionNormal);
  489. return -1 * distance;
  490. }
  491. break;
  492. }
  493. case TPE_COLLISION_TYPE(TPE_SHAPE_SPHERE,TPE_SHAPE_CYLINDER):
  494. {
  495. const TPE_Body *sphere;
  496. const TPE_Body *cylinder;
  497. _TPE_getShapes(body1,body2,TPE_SHAPE_SPHERE,&sphere,&cylinder);
  498. TPE_Vec4 sphereRelativePos = // by this we shift the cylinder to [0,0,0]
  499. TPE_vec3Minus(sphere->position,cylinder->position);
  500. // vector along the cylinder height:
  501. TPE_Vec4 cylinderAxis = TPE_vec4(0,TPE_FRACTIONS_PER_UNIT,0,0);
  502. TPE_rotatePoint(&cylinderAxis,TPE_bodyGetOrientation(cylinder));
  503. TPE_Vec4 sphereAxisPos = // sphere pos projected to the cylinder axis
  504. TPE_vec3Projected(sphereRelativePos,cylinderAxis);
  505. TPE_Unit sphereAxisDistance = TPE_vec3Len(sphereAxisPos);
  506. TPE_Unit tmp = cylinder->shapeParams[1] / 2; // half of cylinder height
  507. /* now we have three possible regions the sphere can occupy:
  508. C :B: A :B: C
  509. : :_____: :
  510. : |_____| : cylinder
  511. : : : :
  512. : : : : */
  513. if (sphereAxisDistance >= tmp + sphere->shapeParams[0]) // case C: no col.
  514. break;
  515. TPE_Vec4 sphereAxisToRelative =
  516. TPE_vec3Minus(sphereRelativePos,sphereAxisPos);
  517. TPE_Unit sphereCylinderDistance = TPE_vec3Len(sphereAxisToRelative);
  518. tmp = sphereAxisDistance - tmp;
  519. if (tmp < 0) // case A: potential collision with cylinder body
  520. {
  521. TPE_Unit penetration = cylinder->shapeParams[0]
  522. - (sphereCylinderDistance - sphere->shapeParams[0]);
  523. if (penetration > 0)
  524. {
  525. TPE_vec3Normalize(&sphereAxisToRelative);
  526. *collisionPoint = TPE_vec3Plus(cylinder->position,
  527. TPE_vec3Plus(sphereAxisPos,TPE_vec3Times(
  528. sphereAxisToRelative,cylinder->shapeParams[0])));
  529. *collisionNormal = sphereAxisToRelative;
  530. if (sphere == body1)
  531. TPE_vec3MultiplyPlain(*collisionNormal,-1,collisionNormal);
  532. return penetration;
  533. }
  534. else
  535. break;
  536. }
  537. /* case B: here we have two subcases, one with the sphere center being
  538. within the cylinder radius (collision with the cylinder top/bottom),
  539. and the other case (collision with the cylinder top/bottom edge). */
  540. TPE_Vec4 cylinderPlaneMiddle = TPE_vec3Times(
  541. TPE_vec3Normalized(sphereAxisPos),
  542. cylinder->shapeParams[1] / 2);
  543. if (sphereCylinderDistance < cylinder->shapeParams[0]) // top/bottom cap
  544. {
  545. TPE_Unit penetration = cylinder->shapeParams[1] / 2 -
  546. (sphereAxisDistance - sphere->shapeParams[0]);
  547. if (penetration <= 0) // shouldn't normally happen, but rounding errors
  548. penetration = 1;
  549. *collisionNormal = TPE_vec3Normalized(sphereAxisPos);
  550. *collisionPoint =
  551. TPE_vec3Plus(
  552. cylinder->position,
  553. TPE_vec3Plus(sphereAxisToRelative,cylinderPlaneMiddle));
  554. if (body1 == sphere)
  555. TPE_vec3MultiplyPlain(*collisionNormal,-1,collisionNormal);
  556. return penetration;
  557. }
  558. else // potential edge collision
  559. {
  560. TPE_Vec4 edgePoint = TPE_vec3Plus(cylinderPlaneMiddle,
  561. TPE_vec3Times(TPE_vec3Normalized(sphereAxisToRelative),
  562. cylinder->shapeParams[0]));
  563. TPE_Unit penetration = sphere->shapeParams[0] -
  564. TPE_vec3Dist(edgePoint,sphereRelativePos);
  565. if (penetration > 0)
  566. {
  567. *collisionPoint = TPE_vec3Plus(cylinder->position,edgePoint);
  568. *collisionNormal =
  569. TPE_vec3Normalized(TPE_vec3Minus(sphereRelativePos,edgePoint));
  570. if (body1 == sphere)
  571. TPE_vec3MultiplyPlain(*collisionNormal,-1,collisionNormal);
  572. return penetration;
  573. }
  574. }
  575. break;
  576. }
  577. case TPE_COLLISION_TYPE(TPE_SHAPE_SPHERE,TPE_SHAPE_CUBOID):
  578. {
  579. const TPE_Body *sphere;
  580. const TPE_Body *cuboid;
  581. _TPE_getShapes(body1,body2,TPE_SHAPE_SPHERE,&sphere,&cuboid);
  582. break;
  583. }
  584. default:
  585. break;
  586. }
  587. return 0;
  588. }
  589. TPE_Vec4 TPE_bodyGetPointVelocity(const TPE_Body *body, TPE_Vec4 point)
  590. {
  591. TPE_Vec4 result = body->velocity;
  592. TPE_Vec4 normal = TPE_vec3Cross(
  593. point,TPE_vec3Minus(point,body->rotation.axisVelocity));
  594. TPE_Unit dist = TPE_vec3Len(normal); // point-line distance
  595. TPE_Unit velocity =
  596. TPE_angularVelocityToLinear(body->rotation.axisVelocity.w,dist);
  597. TPE_vec3Normalize(&normal);
  598. return TPE_vec3Plus(result,TPE_vec3Times(normal,velocity));
  599. }
  600. void TPE_resolveCollision(TPE_Body *body1 ,TPE_Body *body2,
  601. TPE_Vec4 collisionPoint, TPE_Vec4 collisionNormal)
  602. {
  603. TPE_Vec4 v1, v2, p1, p2;
  604. p1 = TPE_vec3Minus(collisionPoint,body1->position);
  605. p2 = TPE_vec3Minus(collisionPoint,body2->position);
  606. v1 = TPE_bodyGetPointVelocity(body1,p1);
  607. v2 = TPE_bodyGetPointVelocity(body2,p2);
  608. int8_t
  609. v1Sign = TPE_vec3DotProduct(v1,collisionNormal) >= 0,
  610. v2Sign = TPE_vec3DotProduct(v2,collisionNormal) >= 0;
  611. if (!v1Sign && v2Sign)
  612. return; // opposite going velocities => not a real collision
  613. /* if the velocities are too small, weird behavior occurs, so we define a min
  614. velocity for collisions and potentially modify the velocities: */
  615. // TODO: something more elegant?
  616. #define MIN_V 5
  617. if (v1.x != 0 || v1.y != 0 || v1.z != 0)
  618. while (TPE_vec3LenTaxicab(v1) < MIN_V)
  619. {
  620. v1.x *= 2;
  621. v1.y *= 2;
  622. v1.z *= 2;
  623. }
  624. if (v2.x != 0 || v2.y != 0 || v2.z != 0)
  625. while (TPE_vec3LenTaxicab(v1) < MIN_V)
  626. {
  627. v2.x *= 2;
  628. v2.y *= 2;
  629. v2.z *= 2;
  630. }
  631. #undef MIN_V
  632. TPE_vec3Project(v1,collisionNormal,&v1);
  633. TPE_vec3Project(v2,collisionNormal,&v2);
  634. TPE_Unit
  635. v1Scalar = TPE_vec3Len(v1) * (v1Sign ? 1 : -1),
  636. v2Scalar = TPE_vec3Len(v2) * (v2Sign ? 1 : -1);
  637. if ((v1Sign && v2Sign && (v2Scalar > v1Scalar)) ||
  638. (!v1Sign && !v2Sign && (v1Scalar > v2Scalar)))
  639. return; // not a valid collision
  640. TPE_Unit
  641. v1ScalarNew = v1Scalar,
  642. v2ScalarNew = v2Scalar;
  643. TPE_getVelocitiesAfterCollision(
  644. &v1ScalarNew,
  645. &v2ScalarNew,
  646. body1->mass,
  647. body2->mass,
  648. 512); // TODO: elasticity
  649. TPE_bodyApplyVelocity(body1,p1,
  650. TPE_vec3Times(collisionNormal,v1ScalarNew - v1Scalar));
  651. TPE_bodyApplyVelocity(body2,p2,
  652. TPE_vec3Times(collisionNormal,v2ScalarNew - v2Scalar));
  653. }
  654. TPE_Unit TPE_linearVelocityToAngular(TPE_Unit velocity, TPE_Unit distance)
  655. {
  656. TPE_Unit circumfence = (2 * TPE_PI * distance) / TPE_FRACTIONS_PER_UNIT;
  657. return (velocity * TPE_FRACTIONS_PER_UNIT) / circumfence;
  658. }
  659. TPE_Unit TPE_angularVelocityToLinear(TPE_Unit velocity, TPE_Unit distance)
  660. {
  661. TPE_Unit circumfence = (2 * TPE_PI * distance) / TPE_FRACTIONS_PER_UNIT;
  662. return (velocity * circumfence) / TPE_FRACTIONS_PER_UNIT;
  663. }
  664. void TPE_bodyStep(TPE_Body *body)
  665. {
  666. TPE_vec3Add(body->position,body->velocity,&(body->position));
  667. body->rotation.currentAngle += body->rotation.axisVelocity.w;
  668. }
  669. void TPE_bodySetRotation(TPE_Body *body, TPE_Vec4 axis, TPE_Unit velocity)
  670. {
  671. body->rotation.originalOrientation = TPE_bodyGetOrientation(body);
  672. if (velocity < 0)
  673. {
  674. axis.x *= -1;
  675. axis.y *= -1;
  676. axis.z *= -1;
  677. velocity *= -1;
  678. }
  679. TPE_vec3Normalize(&axis);
  680. body->rotation.axisVelocity = axis;
  681. body->rotation.axisVelocity.w = velocity;
  682. body->rotation.currentAngle = 0;
  683. }
  684. void TPE_bodyAddRotation(TPE_Body *body, TPE_Vec4 axis, TPE_Unit velocity)
  685. {
  686. /* Rotation is added like this: we convert both the original and added
  687. rotation to vectors whose direction is along the rotations axis and
  688. magnitude is the rotation speed, then we add these vectors and convert
  689. the final vector back to normalized rotation axis + scalar rotation
  690. speed.*/
  691. body->rotation.axisVelocity.x =
  692. (body->rotation.axisVelocity.x * body->rotation.axisVelocity.w)
  693. / TPE_FRACTIONS_PER_UNIT;
  694. body->rotation.axisVelocity.y =
  695. (body->rotation.axisVelocity.y * body->rotation.axisVelocity.w)
  696. / TPE_FRACTIONS_PER_UNIT;
  697. body->rotation.axisVelocity.z =
  698. (body->rotation.axisVelocity.z * body->rotation.axisVelocity.w)
  699. / TPE_FRACTIONS_PER_UNIT;
  700. TPE_vec3Normalize(&axis);
  701. axis.x = (axis.x * velocity) / TPE_FRACTIONS_PER_UNIT;
  702. axis.y = (axis.y * velocity) / TPE_FRACTIONS_PER_UNIT;
  703. axis.z = (axis.z * velocity) / TPE_FRACTIONS_PER_UNIT;
  704. TPE_vec3Add(body->rotation.axisVelocity,axis,&axis);
  705. axis.w = TPE_vec3Len(axis);
  706. TPE_bodySetRotation(body,axis,axis.w);
  707. }
  708. void TPE_quaternionMultiply(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result)
  709. {
  710. TPE_Vec4 r; // in case result is identical to a or b
  711. r.x =
  712. (a.w * b.x +
  713. a.x * b.w +
  714. a.y * b.z -
  715. a.z * b.y) / TPE_FRACTIONS_PER_UNIT;
  716. r.y =
  717. (a.w * b.y -
  718. a.x * b.z +
  719. a.y * b.w +
  720. a.z * b.x) / TPE_FRACTIONS_PER_UNIT;
  721. r.z =
  722. (a.w * b.z +
  723. a.x * b.y -
  724. a.y * b.x +
  725. a.z * b.w) / TPE_FRACTIONS_PER_UNIT;
  726. r.w =
  727. (a.w * b.w -
  728. a.x * b.x -
  729. a.y * b.y -
  730. a.z * b.z) / TPE_FRACTIONS_PER_UNIT;
  731. result->x = r.x;
  732. result->y = r.y;
  733. result->z = r.z;
  734. result->w = r.w;
  735. }
  736. void TPE_rotationToQuaternion(TPE_Vec4 axis, TPE_Unit angle, TPE_Vec4 *quaternion)
  737. {
  738. TPE_vec3Normalize(&axis);
  739. angle /= 2;
  740. TPE_Unit s = TPE_sin(angle);
  741. quaternion->x = (s * axis.x) / TPE_FRACTIONS_PER_UNIT;
  742. quaternion->y = (s * axis.y) / TPE_FRACTIONS_PER_UNIT;
  743. quaternion->z = (s * axis.z) / TPE_FRACTIONS_PER_UNIT;
  744. quaternion->w = TPE_cos(angle);
  745. }
  746. TPE_Unit TPE_asin(TPE_Unit x)
  747. {
  748. x = TPE_clamp(x,-TPE_FRACTIONS_PER_UNIT,TPE_FRACTIONS_PER_UNIT);
  749. int8_t sign = 1;
  750. if (x < 0)
  751. {
  752. sign = -1;
  753. x *= -1;
  754. }
  755. int16_t low = 0;
  756. int16_t high = TPE_SIN_TABLE_LENGTH -1;
  757. int16_t middle;
  758. while (low <= high) // binary search
  759. {
  760. middle = (low + high) / 2;
  761. TPE_Unit v = TPE_sinTable[middle];
  762. if (v > x)
  763. high = middle - 1;
  764. else if (v < x)
  765. low = middle + 1;
  766. else
  767. break;
  768. }
  769. middle *= TPE_SIN_TABLE_UNIT_STEP;
  770. return sign * middle;
  771. }
  772. TPE_Unit TPE_acos(TPE_Unit x)
  773. {
  774. return TPE_asin(-1 * x) + TPE_FRACTIONS_PER_UNIT / 4;
  775. }
  776. void TPE_quaternionToRotation(TPE_Vec4 quaternion, TPE_Vec4 *axis, TPE_Unit *angle)
  777. {
  778. *angle = 2 * TPE_acos(quaternion.x);
  779. TPE_Unit tmp =
  780. TPE_nonZero(TPE_sqrt(
  781. (TPE_FRACTIONS_PER_UNIT -
  782. (quaternion.x * quaternion.x) / TPE_FRACTIONS_PER_UNIT
  783. ) * TPE_FRACTIONS_PER_UNIT));
  784. axis->x = (quaternion.x * TPE_FRACTIONS_PER_UNIT) / tmp;
  785. axis->y = (quaternion.y * TPE_FRACTIONS_PER_UNIT) / tmp;
  786. axis->z = (quaternion.z * TPE_FRACTIONS_PER_UNIT) / tmp;
  787. }
  788. void TPE_quaternionToRotationMatrix(TPE_Vec4 quaternion, TPE_Unit matrix[4][4])
  789. {
  790. TPE_Unit
  791. _2x2 = (2 * quaternion.x * quaternion.x) / TPE_FRACTIONS_PER_UNIT,
  792. _2y2 = (2 * quaternion.y * quaternion.y) / TPE_FRACTIONS_PER_UNIT,
  793. _2z2 = (2 * quaternion.z * quaternion.z) / TPE_FRACTIONS_PER_UNIT,
  794. _2xy = (2 * quaternion.x * quaternion.y) / TPE_FRACTIONS_PER_UNIT,
  795. _2xw = (2 * quaternion.x * quaternion.w) / TPE_FRACTIONS_PER_UNIT,
  796. _2zw = (2 * quaternion.z * quaternion.w) / TPE_FRACTIONS_PER_UNIT,
  797. _2xz = (2 * quaternion.x * quaternion.z) / TPE_FRACTIONS_PER_UNIT,
  798. _2yw = (2 * quaternion.y * quaternion.w) / TPE_FRACTIONS_PER_UNIT,
  799. _2yz = (2 * quaternion.y * quaternion.z) / TPE_FRACTIONS_PER_UNIT;
  800. #define ONE TPE_FRACTIONS_PER_UNIT
  801. matrix[0][0] = ONE - _2y2 - _2z2;
  802. matrix[1][0] = _2xy - _2zw;
  803. matrix[2][0] = _2xz + _2yw;
  804. matrix[3][0] = 0;
  805. matrix[0][1] = _2xy + _2zw;
  806. matrix[1][1] = ONE - _2x2 - _2z2;
  807. matrix[2][1] = _2yz - _2xw;
  808. matrix[3][1] = 0;
  809. matrix[0][2] = _2xz - _2yw;
  810. matrix[1][2] = _2yz + _2xw;
  811. matrix[2][2] = ONE - _2x2 - _2y2;
  812. matrix[3][2] = 0;
  813. matrix[0][3] = 0;
  814. matrix[1][3] = 0;
  815. matrix[2][3] = 0;
  816. matrix[3][3] = ONE;
  817. #undef ONE
  818. }
  819. void TPE_vec3Add(const TPE_Vec4 a, const TPE_Vec4 b, TPE_Vec4 *result)
  820. {
  821. result->x = a.x + b.x;
  822. result->y = a.y + b.y;
  823. result->z = a.z + b.z;
  824. }
  825. void TPE_vec4Add(const TPE_Vec4 a, const TPE_Vec4 b, TPE_Vec4 *result)
  826. {
  827. result->x = a.x + b.x;
  828. result->y = a.y + b.y;
  829. result->z = a.z + b.z;
  830. result->w = a.w + b.w;
  831. }
  832. void TPE_vec3Substract(const TPE_Vec4 a, const TPE_Vec4 b, TPE_Vec4 *result)
  833. {
  834. result->x = a.x - b.x;
  835. result->y = a.y - b.y;
  836. result->z = a.z - b.z;
  837. }
  838. TPE_Vec4 TPE_vec3Plus(TPE_Vec4 a, TPE_Vec4 b)
  839. {
  840. a.x += b.x;
  841. a.y += b.y;
  842. a.z += b.z;
  843. return a;
  844. }
  845. TPE_Vec4 TPE_vec3Minus(TPE_Vec4 a, TPE_Vec4 b)
  846. {
  847. a.x -= b.x;
  848. a.y -= b.y;
  849. a.z -= b.z;
  850. return a;
  851. }
  852. TPE_Vec4 TPE_vec3Times(TPE_Vec4 a, TPE_Unit f)
  853. {
  854. a.x = (a.x * f) / TPE_FRACTIONS_PER_UNIT;
  855. a.y = (a.y * f) / TPE_FRACTIONS_PER_UNIT;
  856. a.z = (a.z * f) / TPE_FRACTIONS_PER_UNIT;
  857. return a;
  858. }
  859. void TPE_vec3Average(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result)
  860. {
  861. result->x = (a.x + b.x) / 2;
  862. result->y = (a.y + b.y) / 2;
  863. result->z = (a.z + b.z) / 2;
  864. }
  865. void TPE_vec4Substract(const TPE_Vec4 a, const TPE_Vec4 b, TPE_Vec4 *result)
  866. {
  867. result->x = a.x - b.x;
  868. result->y = a.y - b.y;
  869. result->z = a.z - b.z;
  870. result->w = a.w - b.w;
  871. }
  872. void TPE_vec3Multiply(const TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result)
  873. {
  874. result->x = (v.x * f) / TPE_FRACTIONS_PER_UNIT;
  875. result->y = (v.y * f) / TPE_FRACTIONS_PER_UNIT;
  876. result->z = (v.z * f) / TPE_FRACTIONS_PER_UNIT;
  877. }
  878. void TPE_vec3MultiplyPlain(TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result)
  879. {
  880. result->x = v.x * f;
  881. result->y = v.y * f;
  882. result->z = v.z * f;
  883. }
  884. void TPE_vec4Multiply(const TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result)
  885. {
  886. result->x = (v.x * f) / TPE_FRACTIONS_PER_UNIT;
  887. result->y = (v.y * f) / TPE_FRACTIONS_PER_UNIT;
  888. result->z = (v.z * f) / TPE_FRACTIONS_PER_UNIT;
  889. result->w = (v.w * f) / TPE_FRACTIONS_PER_UNIT;
  890. }
  891. TPE_Unit TPE_abs(TPE_Unit x)
  892. {
  893. return (x >= 0) ? x : (-1 * x);
  894. }
  895. TPE_Unit TPE_vec3Len(TPE_Vec4 v)
  896. {
  897. return TPE_sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
  898. }
  899. TPE_Unit TPE_vec3Dist(TPE_Vec4 a, TPE_Vec4 b)
  900. {
  901. return TPE_vec3Len(TPE_vec3Minus(a,b));
  902. }
  903. TPE_Unit TPE_vec4Len(TPE_Vec4 v)
  904. {
  905. return TPE_sqrt(v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w);
  906. }
  907. TPE_Unit TPE_vec3LenTaxicab(TPE_Vec4 v)
  908. {
  909. return TPE_abs(v.x) + TPE_abs(v.y) + TPE_abs(v.z);
  910. }
  911. TPE_Unit TPE_vec3DotProduct(const TPE_Vec4 v1, const TPE_Vec4 v2)
  912. {
  913. return
  914. (v1.x * v2.x + v1.y * v2.y + v1.z * v2.z) / TPE_FRACTIONS_PER_UNIT;
  915. }
  916. void TPE_vec3Normalize(TPE_Vec4 *v)
  917. {
  918. TPE_Unit l = TPE_vec3Len(*v);
  919. if (l == 0)
  920. {
  921. v->x = TPE_FRACTIONS_PER_UNIT;
  922. return;
  923. }
  924. v->x = (v->x * TPE_FRACTIONS_PER_UNIT) / l;
  925. v->y = (v->y * TPE_FRACTIONS_PER_UNIT) / l;
  926. v->z = (v->z * TPE_FRACTIONS_PER_UNIT) / l;
  927. }
  928. void TPE_vec4Normalize(TPE_Vec4 *v)
  929. {
  930. TPE_Unit l = TPE_vec4Len(*v);
  931. if (l == 0)
  932. {
  933. v->x = TPE_FRACTIONS_PER_UNIT;
  934. return;
  935. }
  936. v->x = (v->x * TPE_FRACTIONS_PER_UNIT) / l;
  937. v->y = (v->y * TPE_FRACTIONS_PER_UNIT) / l;
  938. v->z = (v->z * TPE_FRACTIONS_PER_UNIT) / l;
  939. v->w = (v->w * TPE_FRACTIONS_PER_UNIT) / l;
  940. }
  941. void TPE_vec3Project(TPE_Vec4 v, TPE_Vec4 base, TPE_Vec4 *result)
  942. {
  943. TPE_Unit p = TPE_vec3DotProduct(v,base);
  944. result->x = (p * base.x) / TPE_FRACTIONS_PER_UNIT;
  945. result->y = (p * base.y) / TPE_FRACTIONS_PER_UNIT;
  946. result->z = (p * base.z) / TPE_FRACTIONS_PER_UNIT;
  947. }
  948. TPE_Vec4 TPE_vec3Projected(TPE_Vec4 v, TPE_Vec4 base)
  949. {
  950. TPE_Vec4 r;
  951. TPE_vec3Project(v,base,&r);
  952. return r;
  953. }
  954. void TPE_getVelocitiesAfterCollision(
  955. TPE_Unit *v1,
  956. TPE_Unit *v2,
  957. TPE_Unit m1,
  958. TPE_Unit m2,
  959. TPE_Unit elasticity
  960. )
  961. {
  962. /* in the following a lot of TPE_FRACTIONS_PER_UNIT cancel out, feel free to
  963. check if confused */
  964. #define ANTI_OVERFLOW 30000
  965. #define ANTI_OVERFLOW_SCALE 128
  966. uint8_t overflowDanger = m1 > ANTI_OVERFLOW || *v1 > ANTI_OVERFLOW ||
  967. m2 > ANTI_OVERFLOW || *v2 > ANTI_OVERFLOW;
  968. if (overflowDanger)
  969. {
  970. m1 = (m1 != 0) ? TPE_nonZero(m1 / ANTI_OVERFLOW_SCALE) : 0;
  971. m2 = (m2 != 0) ? TPE_nonZero(m2 / ANTI_OVERFLOW_SCALE) : 0;
  972. *v1 = (*v1 != 0) ? TPE_nonZero(*v1 / ANTI_OVERFLOW_SCALE) : 0;
  973. *v2 = (*v2 != 0) ? TPE_nonZero(*v2 / ANTI_OVERFLOW_SCALE) : 0;
  974. }
  975. TPE_Unit m1Pm2 = TPE_nonZero(m1 + m2);
  976. TPE_Unit v2Mv1 = TPE_nonZero(*v2 - *v1);
  977. TPE_Unit m1v1Pm2v2 = ((m1 * *v1) + (m2 * *v2));
  978. *v1 = (((elasticity * m2 / TPE_FRACTIONS_PER_UNIT) * v2Mv1)
  979. + m1v1Pm2v2) / m1Pm2;
  980. *v2 = (((elasticity * m1 / TPE_FRACTIONS_PER_UNIT) * -1 * v2Mv1)
  981. + m1v1Pm2v2) / m1Pm2;
  982. if (overflowDanger)
  983. {
  984. *v1 *= ANTI_OVERFLOW_SCALE;
  985. *v2 *= ANTI_OVERFLOW_SCALE;
  986. }
  987. #undef ANTI_OVERFLOW
  988. #undef ANTI_OVERFLOW_SCALE
  989. }
  990. void TPE_bodyGetTransformMatrix(const TPE_Body *body, TPE_Unit matrix[4][4])
  991. {
  992. TPE_Vec4 orientation;
  993. orientation = TPE_bodyGetOrientation(body);
  994. TPE_quaternionToRotationMatrix(orientation,matrix);
  995. matrix[0][3] = body->position.x;
  996. matrix[1][3] = body->position.y;
  997. matrix[2][3] = body->position.z;
  998. }
  999. void TPE_quaternionInit(TPE_Vec4 *quaternion)
  1000. {
  1001. quaternion->x = 0;
  1002. quaternion->y = 0;
  1003. quaternion->z = 0;
  1004. quaternion->w = TPE_FRACTIONS_PER_UNIT;
  1005. }
  1006. void TPE_rotatePoint(TPE_Vec4 *point, TPE_Vec4 quaternion)
  1007. {
  1008. // TODO: the first method is bugged, but maybe would be faster?
  1009. #if 0
  1010. TPE_Vec4 quaternionConjugate = TPE_quaternionConjugate(quaternion);
  1011. point->w = 0;
  1012. TPE_quaternionMultiply(quaternion,*point,point);
  1013. TPE_quaternionMultiply(*point,quaternionConjugate,point);
  1014. #else
  1015. TPE_Unit m[4][4];
  1016. TPE_quaternionToRotationMatrix(quaternion,m);
  1017. TPE_Vec4 p = *point;
  1018. point->x = (p.x * m[0][0] + p.y * m[0][1] + p.z * m[0][2]) / TPE_FRACTIONS_PER_UNIT;
  1019. point->y = (p.x * m[1][0] + p.y * m[1][1] + p.z * m[1][2]) / TPE_FRACTIONS_PER_UNIT;
  1020. point->z = (p.x * m[2][0] + p.y * m[2][1] + p.z * m[2][2]) / TPE_FRACTIONS_PER_UNIT;
  1021. #endif
  1022. }
  1023. TPE_Vec4 TPE_quaternionConjugate(TPE_Vec4 quaternion)
  1024. {
  1025. quaternion.x *= -1;
  1026. quaternion.y *= -1;
  1027. quaternion.z *= -1;
  1028. return quaternion;
  1029. }
  1030. TPE_Vec4 TPE_vec3Normalized(TPE_Vec4 v)
  1031. {
  1032. TPE_vec3Normalize(&v);
  1033. return v;
  1034. }
  1035. TPE_Vec4 TPE_lineSegmentClosestPoint(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 p)
  1036. {
  1037. TPE_Vec4 ab = TPE_vec3Minus(b,a);
  1038. TPE_Unit t = ((TPE_vec3DotProduct(ab,TPE_vec3Minus(p,a)) *
  1039. TPE_FRACTIONS_PER_UNIT) / TPE_vec3DotProduct(ab,ab));
  1040. if (t < 0)
  1041. t = 0;
  1042. else if (t > TPE_FRACTIONS_PER_UNIT)
  1043. t = TPE_FRACTIONS_PER_UNIT;
  1044. TPE_vec3Multiply(ab,t,&ab);
  1045. return TPE_vec3Plus(a,ab);
  1046. }
  1047. #endif // guard