tinyphysicsengine.h 39 KB

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