tinyphysicsengine.h 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852
  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_Unit TPE_vec3DotProductPlain(TPE_Vec4 v1, TPE_Vec4 v2);
  97. TPE_Vec4 TPE_vec4(TPE_Unit x, TPE_Unit y, TPE_Unit z, TPE_Unit w);
  98. TPE_Vec4 TPE_vec3Plus(TPE_Vec4 a, TPE_Vec4 b);
  99. TPE_Vec4 TPE_vec3Minus(TPE_Vec4 a, TPE_Vec4 b);
  100. TPE_Vec4 TPE_vec3Times(TPE_Vec4 a, TPE_Unit f);
  101. TPE_Vec4 TPE_vec3TimesAntiZero(TPE_Vec4 a, TPE_Unit f);
  102. TPE_Vec4 TPE_vec3Cross(TPE_Vec4 a, TPE_Vec4 b);
  103. static inline TPE_Vec4 TPE_vec3Normalized(TPE_Vec4 v);
  104. static inline TPE_Vec4 TPE_vec3Projected(TPE_Vec4 v, TPE_Vec4 base);
  105. /** Returns the closest point on given line segment (a,b) to given point (p). */
  106. TPE_Vec4 TPE_lineSegmentClosestPoint(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 p);
  107. /** Converts a linear velocity of an orbiting point to the angular velocity
  108. (angle units per time units). This depends on the distance of the point from
  109. the center of rotation. */
  110. TPE_Unit TPE_linearVelocityToAngular(TPE_Unit velocity, TPE_Unit distance);
  111. /** Performs the opposite conversion of TPE_linearVelocityToAngular. */
  112. TPE_Unit TPE_angularVelocityToLinear(TPE_Unit velocity, TPE_Unit distance);
  113. /** Holds a rotation state around a single axis, in a way that prevents rounding
  114. errors from distorting the rotation over time. In theory rotation of a body
  115. could be represented as
  116. [current orientation, axis of rotation, angular velocity]
  117. However applying the rotation and normalizing the orientation quaternion each
  118. simulation step leads to error cumulation and the rotation gets aligned with
  119. one principal axis after some time. Because of this we rather represent the
  120. rotation state as
  121. [original orientation, axis of rotation, angular velocity, current angle]
  122. From this we can at each simulation step compute the current orientation by
  123. applying rotation by current angle to the original rotation without error
  124. cumulation. */
  125. typedef struct
  126. {
  127. TPE_Vec4 originalOrientation; /**< quaternion holding the original
  128. orientation of the body at the time when it
  129. has taken on this rotational state */
  130. TPE_Vec4 axisVelocity; /**< axis of rotation (x,y,z) and a
  131. non-negative angular velocity around this
  132. axis (w), determined ny the right hand
  133. rule */
  134. TPE_Unit currentAngle; /**< angle the body has already rotated along
  135. the rotation axis (from the original
  136. orientation) */
  137. } TPE_RotationState;
  138. typedef struct
  139. {
  140. uint8_t shape;
  141. TPE_Unit shapeParams[TPE_MAX_SHAPE_PARAMS]; ///< parameters of the body type
  142. void *shapeParamPointers[TPE_MAX_SHAPE_PARAMPOINTERS]; ///< pointer parameters
  143. uint8_t flags;
  144. TPE_Unit mass; /**< body mass, setting this to TPE_INFINITY will
  145. make the object static (not moving at all)
  146. which may help performance */
  147. TPE_Vec4 position; ///< position of the body's center of mass
  148. TPE_Vec4 velocity; ///< linear velocity vector
  149. TPE_RotationState rotation; /**< holds the state related to rotation, i.e.
  150. the rotation axis, angular momentum and data
  151. from which current orientation can be
  152. inferred */
  153. TPE_Unit boundingSphereRadius;
  154. } TPE_Body;
  155. /** Initializes a physical body, this should be called on all TPE_Body objects
  156. that are created.*/
  157. void TPE_bodyInit(TPE_Body *body);
  158. /** Recomputes the body bounding sphere, must be called every time the body's
  159. shape parameters change. */
  160. void TPE_bodyRecomputeBounds(TPE_Body *body);
  161. /** Computes a 4x4 transform matrix of given body. The matrix has the same
  162. format as S3L_Mat4 from small3dlib. */
  163. void TPE_bodyGetTransformMatrix(const TPE_Body *body, TPE_Unit matrix[4][4]);
  164. /** Gets the current orientation of a body as a quaternion. */
  165. TPE_Vec4 TPE_bodyGetOrientation(const TPE_Body *body);
  166. void TPE_bodySetOrientation(TPE_Body *body, TPE_Vec4 orientation);
  167. /** Updates the body position and rotation according to its current velocity
  168. and rotation state. */
  169. void TPE_bodyStep(TPE_Body *body);
  170. /** Sets the rotation state of a body as an axis of rotation and angular
  171. velocity around this axis. */
  172. void TPE_bodySetRotation(TPE_Body *body, TPE_Vec4 axis, TPE_Unit velocity);
  173. /** Adds a rotation to the current rotation of a body. This addition is perfomed
  174. as a vector addition of the current and new rotation represented as vectors
  175. whose direction is the rotation axis and magnitude is the angular velocity
  176. around that axis. */
  177. void TPE_bodyAddRotation(TPE_Body *body, TPE_Vec4 axis, TPE_Unit velocity);
  178. /** Applies a velocity change to a body at a specific point (relative to the
  179. body center), which will change its linear and/or angular velocity. This is
  180. similar to an impulse but doesn't take mass into account, only velocity. */
  181. void TPE_bodyApplyVelocity(TPE_Body *body, TPE_Vec4 point, TPE_Vec4 velocity);
  182. /** Computes and returns a body's bounding sphere radius, i.e. the maximum
  183. extent from its center point. */
  184. TPE_Unit TPE_bodyGetMaxExtent(const TPE_Body *body);
  185. /** Computes and returns a body's total kinetic energy (sum of linear and
  186. rotational kin. energy). In rotating bodies this may not be physically
  187. accurate as, for simplicity, we operate with the moment of inertia of sphere
  188. for all bodies (when in reality moment of inertia depends on shape). */
  189. TPE_Unit TPE_bodyGetKineticEnergy(const TPE_Body *body);
  190. /** Collision detection: checks if two bodies are colliding. The return value is
  191. the collision depth along the collision normal (0 if the bodies are not
  192. colliding). World-space collision point is returned via a pointer. Collision
  193. normal (normalized) is also returned via a pointer and its direction is
  194. "away from body1", i.e. if you move body1 in the opposite direction of this
  195. normal by the collision depth (return value), the bodies should no longer
  196. exhibit this particular collision. This function checks the bounding spheres
  197. to quickly opt out of impossible collisions. */
  198. TPE_Unit TPE_bodyCollides(const TPE_Body *body1, const TPE_Body *body2,
  199. TPE_Vec4 *collisionPoint, TPE_Vec4 *collisionNormal);
  200. /** Gets a velocity of a single point on a rigid body, taking into account its
  201. linear velocity and rotation. The point coordinates are relative to the body
  202. center. The point does NOT have to be on the surface, it can be inside and
  203. even outside the body too. */
  204. TPE_Vec4 TPE_bodyGetPointVelocity(const TPE_Body *body, TPE_Vec4 point);
  205. void TPE_resolveCollision(TPE_Body *body1 ,TPE_Body *body2,
  206. TPE_Vec4 collisionPoint, TPE_Vec4 collisionNormal, TPE_Unit collisionDepth);
  207. /** Gets a uint16_t integer type of collision depending on two shapes, the order
  208. of shapes doesn't matter. */
  209. #define TPE_COLLISION_TYPE(shape1,shape2) \
  210. ((shape1) <= (shape2) ? \
  211. (((uint16_t) (shape1)) << 8) | (shape2) : \
  212. (((uint16_t) (shape2)) << 8) | (shape1))
  213. typedef struct
  214. {
  215. uint16_t bodyCount;
  216. TPE_Body *bodies;
  217. } TPE_PhysicsWorld;
  218. /** Multiplies two quaternions which can be seen as chaining two rotations
  219. represented by them. This is not commutative (a*b != b*a)! Rotations a is
  220. performed firth, then rotation b is performed. */
  221. void TPE_quaternionMultiply(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  222. /** Initializes quaternion to the rotation identity (i.e. NOT zero
  223. quaternion). */
  224. void TPE_quaternionInit(TPE_Vec4 *quaternion);
  225. /** Converts a rotation given as an axis and angle around this axis (by right
  226. hand rule) to a rotation quaternion. */
  227. void TPE_rotationToQuaternion(TPE_Vec4 axis, TPE_Unit angle,
  228. TPE_Vec4 *quaternion);
  229. void TPE_quaternionToRotation(TPE_Vec4 quaternion, TPE_Vec4 *axis,
  230. TPE_Unit *angle);
  231. /** Computes the conjugate of a quaternion (analogous to matrix inversion, the
  232. quaternion will represent the opposite rotation). */
  233. TPE_Vec4 TPE_quaternionConjugate(TPE_Vec4 quaternion);
  234. /** Converts a rotation quaternion to a 4x4 rotation matrix. The matrix is
  235. indexed as [column][row] and is in the same format as S3L_Mat4 from
  236. small3dlib. */
  237. void TPE_quaternionToRotationMatrix(TPE_Vec4 quaternion, TPE_Unit matrix[4][4]);
  238. void TPE_rotatePoint(TPE_Vec4 *point, TPE_Vec4 quaternion);
  239. void TPE_getVelocitiesAfterCollision(
  240. TPE_Unit *v1,
  241. TPE_Unit *v2,
  242. TPE_Unit m1,
  243. TPE_Unit m2,
  244. TPE_Unit elasticity
  245. );
  246. //------------------------------------------------------------------------------
  247. void TPE_initVec4(TPE_Vec4 *v)
  248. {
  249. v->x = 0;
  250. v->y = 0;
  251. v->z = 0;
  252. v->w = 0;
  253. }
  254. TPE_Vec4 TPE_vec4(TPE_Unit x, TPE_Unit y, TPE_Unit z, TPE_Unit w)
  255. {
  256. TPE_Vec4 r;
  257. r.x = x;
  258. r.y = y;
  259. r.z = z;
  260. r.w = w;
  261. return r;
  262. }
  263. void TPE_vec4Set(TPE_Vec4 *v, TPE_Unit x, TPE_Unit y, TPE_Unit z, TPE_Unit w)
  264. {
  265. v->x = x;
  266. v->y = y;
  267. v->z = z;
  268. v->w = w;
  269. }
  270. TPE_Unit TPE_wrap(TPE_Unit value, TPE_Unit mod)
  271. {
  272. return value >= 0 ? (value % mod) : (mod + (value % mod) - 1);
  273. }
  274. TPE_Unit TPE_clamp(TPE_Unit v, TPE_Unit v1, TPE_Unit v2)
  275. {
  276. return v >= v1 ? (v <= v2 ? v : v2) : v1;
  277. }
  278. TPE_Unit TPE_nonZero(TPE_Unit x)
  279. {
  280. return x + (x == 0);
  281. }
  282. #define TPE_SIN_TABLE_LENGTH 128
  283. static const TPE_Unit TPE_sinTable[TPE_SIN_TABLE_LENGTH] =
  284. {
  285. /* 511 was chosen here as a highest number that doesn't overflow during
  286. compilation for TPE_FRACTIONS_PER_UNIT == 1024 */
  287. (0*TPE_FRACTIONS_PER_UNIT)/511, (6*TPE_FRACTIONS_PER_UNIT)/511,
  288. (12*TPE_FRACTIONS_PER_UNIT)/511, (18*TPE_FRACTIONS_PER_UNIT)/511,
  289. (25*TPE_FRACTIONS_PER_UNIT)/511, (31*TPE_FRACTIONS_PER_UNIT)/511,
  290. (37*TPE_FRACTIONS_PER_UNIT)/511, (43*TPE_FRACTIONS_PER_UNIT)/511,
  291. (50*TPE_FRACTIONS_PER_UNIT)/511, (56*TPE_FRACTIONS_PER_UNIT)/511,
  292. (62*TPE_FRACTIONS_PER_UNIT)/511, (68*TPE_FRACTIONS_PER_UNIT)/511,
  293. (74*TPE_FRACTIONS_PER_UNIT)/511, (81*TPE_FRACTIONS_PER_UNIT)/511,
  294. (87*TPE_FRACTIONS_PER_UNIT)/511, (93*TPE_FRACTIONS_PER_UNIT)/511,
  295. (99*TPE_FRACTIONS_PER_UNIT)/511, (105*TPE_FRACTIONS_PER_UNIT)/511,
  296. (111*TPE_FRACTIONS_PER_UNIT)/511, (118*TPE_FRACTIONS_PER_UNIT)/511,
  297. (124*TPE_FRACTIONS_PER_UNIT)/511, (130*TPE_FRACTIONS_PER_UNIT)/511,
  298. (136*TPE_FRACTIONS_PER_UNIT)/511, (142*TPE_FRACTIONS_PER_UNIT)/511,
  299. (148*TPE_FRACTIONS_PER_UNIT)/511, (154*TPE_FRACTIONS_PER_UNIT)/511,
  300. (160*TPE_FRACTIONS_PER_UNIT)/511, (166*TPE_FRACTIONS_PER_UNIT)/511,
  301. (172*TPE_FRACTIONS_PER_UNIT)/511, (178*TPE_FRACTIONS_PER_UNIT)/511,
  302. (183*TPE_FRACTIONS_PER_UNIT)/511, (189*TPE_FRACTIONS_PER_UNIT)/511,
  303. (195*TPE_FRACTIONS_PER_UNIT)/511, (201*TPE_FRACTIONS_PER_UNIT)/511,
  304. (207*TPE_FRACTIONS_PER_UNIT)/511, (212*TPE_FRACTIONS_PER_UNIT)/511,
  305. (218*TPE_FRACTIONS_PER_UNIT)/511, (224*TPE_FRACTIONS_PER_UNIT)/511,
  306. (229*TPE_FRACTIONS_PER_UNIT)/511, (235*TPE_FRACTIONS_PER_UNIT)/511,
  307. (240*TPE_FRACTIONS_PER_UNIT)/511, (246*TPE_FRACTIONS_PER_UNIT)/511,
  308. (251*TPE_FRACTIONS_PER_UNIT)/511, (257*TPE_FRACTIONS_PER_UNIT)/511,
  309. (262*TPE_FRACTIONS_PER_UNIT)/511, (268*TPE_FRACTIONS_PER_UNIT)/511,
  310. (273*TPE_FRACTIONS_PER_UNIT)/511, (278*TPE_FRACTIONS_PER_UNIT)/511,
  311. (283*TPE_FRACTIONS_PER_UNIT)/511, (289*TPE_FRACTIONS_PER_UNIT)/511,
  312. (294*TPE_FRACTIONS_PER_UNIT)/511, (299*TPE_FRACTIONS_PER_UNIT)/511,
  313. (304*TPE_FRACTIONS_PER_UNIT)/511, (309*TPE_FRACTIONS_PER_UNIT)/511,
  314. (314*TPE_FRACTIONS_PER_UNIT)/511, (319*TPE_FRACTIONS_PER_UNIT)/511,
  315. (324*TPE_FRACTIONS_PER_UNIT)/511, (328*TPE_FRACTIONS_PER_UNIT)/511,
  316. (333*TPE_FRACTIONS_PER_UNIT)/511, (338*TPE_FRACTIONS_PER_UNIT)/511,
  317. (343*TPE_FRACTIONS_PER_UNIT)/511, (347*TPE_FRACTIONS_PER_UNIT)/511,
  318. (352*TPE_FRACTIONS_PER_UNIT)/511, (356*TPE_FRACTIONS_PER_UNIT)/511,
  319. (361*TPE_FRACTIONS_PER_UNIT)/511, (365*TPE_FRACTIONS_PER_UNIT)/511,
  320. (370*TPE_FRACTIONS_PER_UNIT)/511, (374*TPE_FRACTIONS_PER_UNIT)/511,
  321. (378*TPE_FRACTIONS_PER_UNIT)/511, (382*TPE_FRACTIONS_PER_UNIT)/511,
  322. (386*TPE_FRACTIONS_PER_UNIT)/511, (391*TPE_FRACTIONS_PER_UNIT)/511,
  323. (395*TPE_FRACTIONS_PER_UNIT)/511, (398*TPE_FRACTIONS_PER_UNIT)/511,
  324. (402*TPE_FRACTIONS_PER_UNIT)/511, (406*TPE_FRACTIONS_PER_UNIT)/511,
  325. (410*TPE_FRACTIONS_PER_UNIT)/511, (414*TPE_FRACTIONS_PER_UNIT)/511,
  326. (417*TPE_FRACTIONS_PER_UNIT)/511, (421*TPE_FRACTIONS_PER_UNIT)/511,
  327. (424*TPE_FRACTIONS_PER_UNIT)/511, (428*TPE_FRACTIONS_PER_UNIT)/511,
  328. (431*TPE_FRACTIONS_PER_UNIT)/511, (435*TPE_FRACTIONS_PER_UNIT)/511,
  329. (438*TPE_FRACTIONS_PER_UNIT)/511, (441*TPE_FRACTIONS_PER_UNIT)/511,
  330. (444*TPE_FRACTIONS_PER_UNIT)/511, (447*TPE_FRACTIONS_PER_UNIT)/511,
  331. (450*TPE_FRACTIONS_PER_UNIT)/511, (453*TPE_FRACTIONS_PER_UNIT)/511,
  332. (456*TPE_FRACTIONS_PER_UNIT)/511, (459*TPE_FRACTIONS_PER_UNIT)/511,
  333. (461*TPE_FRACTIONS_PER_UNIT)/511, (464*TPE_FRACTIONS_PER_UNIT)/511,
  334. (467*TPE_FRACTIONS_PER_UNIT)/511, (469*TPE_FRACTIONS_PER_UNIT)/511,
  335. (472*TPE_FRACTIONS_PER_UNIT)/511, (474*TPE_FRACTIONS_PER_UNIT)/511,
  336. (476*TPE_FRACTIONS_PER_UNIT)/511, (478*TPE_FRACTIONS_PER_UNIT)/511,
  337. (481*TPE_FRACTIONS_PER_UNIT)/511, (483*TPE_FRACTIONS_PER_UNIT)/511,
  338. (485*TPE_FRACTIONS_PER_UNIT)/511, (487*TPE_FRACTIONS_PER_UNIT)/511,
  339. (488*TPE_FRACTIONS_PER_UNIT)/511, (490*TPE_FRACTIONS_PER_UNIT)/511,
  340. (492*TPE_FRACTIONS_PER_UNIT)/511, (494*TPE_FRACTIONS_PER_UNIT)/511,
  341. (495*TPE_FRACTIONS_PER_UNIT)/511, (497*TPE_FRACTIONS_PER_UNIT)/511,
  342. (498*TPE_FRACTIONS_PER_UNIT)/511, (499*TPE_FRACTIONS_PER_UNIT)/511,
  343. (501*TPE_FRACTIONS_PER_UNIT)/511, (502*TPE_FRACTIONS_PER_UNIT)/511,
  344. (503*TPE_FRACTIONS_PER_UNIT)/511, (504*TPE_FRACTIONS_PER_UNIT)/511,
  345. (505*TPE_FRACTIONS_PER_UNIT)/511, (506*TPE_FRACTIONS_PER_UNIT)/511,
  346. (507*TPE_FRACTIONS_PER_UNIT)/511, (507*TPE_FRACTIONS_PER_UNIT)/511,
  347. (508*TPE_FRACTIONS_PER_UNIT)/511, (509*TPE_FRACTIONS_PER_UNIT)/511,
  348. (509*TPE_FRACTIONS_PER_UNIT)/511, (510*TPE_FRACTIONS_PER_UNIT)/511,
  349. (510*TPE_FRACTIONS_PER_UNIT)/511, (510*TPE_FRACTIONS_PER_UNIT)/511,
  350. (510*TPE_FRACTIONS_PER_UNIT)/511, (510*TPE_FRACTIONS_PER_UNIT)/511
  351. };
  352. #define TPE_SIN_TABLE_UNIT_STEP\
  353. (TPE_FRACTIONS_PER_UNIT / (TPE_SIN_TABLE_LENGTH * 4))
  354. TPE_Unit TPE_sqrt(TPE_Unit value)
  355. {
  356. int8_t sign = 1;
  357. if (value < 0)
  358. {
  359. sign = -1;
  360. value *= -1;
  361. }
  362. uint32_t result = 0;
  363. uint32_t a = value;
  364. uint32_t b = 1u << 30;
  365. while (b > a)
  366. b >>= 2;
  367. while (b != 0)
  368. {
  369. if (a >= result + b)
  370. {
  371. a -= result + b;
  372. result = result + 2 * b;
  373. }
  374. b >>= 2;
  375. result >>= 1;
  376. }
  377. return result * sign;
  378. }
  379. TPE_Unit TPE_sin(TPE_Unit x)
  380. {
  381. x = TPE_wrap(x / TPE_SIN_TABLE_UNIT_STEP,TPE_SIN_TABLE_LENGTH * 4);
  382. int8_t positive = 1;
  383. if (x < TPE_SIN_TABLE_LENGTH)
  384. {
  385. }
  386. else if (x < TPE_SIN_TABLE_LENGTH * 2)
  387. {
  388. x = TPE_SIN_TABLE_LENGTH * 2 - x - 1;
  389. }
  390. else if (x < TPE_SIN_TABLE_LENGTH * 3)
  391. {
  392. x = x - TPE_SIN_TABLE_LENGTH * 2;
  393. positive = 0;
  394. }
  395. else
  396. {
  397. x = TPE_SIN_TABLE_LENGTH - (x - TPE_SIN_TABLE_LENGTH * 3) - 1;
  398. positive = 0;
  399. }
  400. return positive ? TPE_sinTable[x] : -1 * TPE_sinTable[x];
  401. }
  402. TPE_Unit TPE_cos(TPE_Unit x)
  403. {
  404. return TPE_sin(x + TPE_FRACTIONS_PER_UNIT / 4);
  405. }
  406. void TPE_bodyInit(TPE_Body *body)
  407. {
  408. // TODO
  409. TPE_initVec4(&(body->position));
  410. TPE_initVec4(&(body->velocity));
  411. // init orientation to identity unit quaternion (1,0,0,0):
  412. TPE_quaternionInit(&(body->rotation.originalOrientation));
  413. TPE_vec4Set(&(body->rotation.axisVelocity),TPE_FRACTIONS_PER_UNIT,0,0,0);
  414. body->rotation.currentAngle = 0;
  415. body->mass = TPE_FRACTIONS_PER_UNIT;
  416. body->boundingSphereRadius = 0;
  417. }
  418. void TPE_bodySetOrientation(TPE_Body *body, TPE_Vec4 orientation)
  419. {
  420. body->rotation.originalOrientation = orientation;
  421. body->rotation.currentAngle = 0;
  422. }
  423. TPE_Vec4 TPE_bodyGetOrientation(const TPE_Body *body)
  424. {
  425. TPE_Vec4 axisRotation, result;
  426. TPE_rotationToQuaternion(
  427. body->rotation.axisVelocity,
  428. body->rotation.currentAngle,
  429. &axisRotation);
  430. TPE_quaternionMultiply(
  431. body->rotation.originalOrientation,
  432. axisRotation,
  433. &result);
  434. TPE_vec4Normalize(&result);
  435. return result;
  436. }
  437. void TPE_vec3CrossProduct(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result)
  438. {
  439. TPE_Vec4 r;
  440. r.x = (a.y * b.z - a.z * b.y) / TPE_FRACTIONS_PER_UNIT;
  441. r.y = (a.z * b.x - a.x * b.z) / TPE_FRACTIONS_PER_UNIT;
  442. r.z = (a.x * b.y - a.y * b.x) / TPE_FRACTIONS_PER_UNIT;
  443. *result = r;
  444. }
  445. TPE_Vec4 TPE_vec3Cross(TPE_Vec4 a, TPE_Vec4 b)
  446. {
  447. TPE_vec3CrossProduct(a,b,&a);
  448. return a;
  449. }
  450. void TPE_bodyApplyVelocity(TPE_Body *body, TPE_Vec4 point, TPE_Vec4 velocity)
  451. {
  452. TPE_Unit pointDistance = TPE_vec3Len(point);
  453. if (pointDistance != 0)
  454. {
  455. TPE_Vec4 angularVelocity, rotationAxis;
  456. TPE_vec3Add(body->velocity,velocity,&(body->velocity));
  457. /* normalize the point, we don't use the function as we don't want to
  458. recompute the vector length */
  459. point.x = (point.x * TPE_FRACTIONS_PER_UNIT) / pointDistance;
  460. point.y = (point.y * TPE_FRACTIONS_PER_UNIT) / pointDistance;
  461. point.z = (point.z * TPE_FRACTIONS_PER_UNIT) / pointDistance;
  462. /* Now we take only a part of the applied velocity, the part projected
  463. to a plane perpendicular to the point vector, and this part will
  464. contribute to the body rotation. */
  465. TPE_Vec4 tmp;
  466. TPE_vec3Project(velocity,point,&tmp);
  467. TPE_vec3Substract(velocity,tmp,&angularVelocity);
  468. TPE_vec3CrossProduct(point,angularVelocity,&rotationAxis);
  469. // TPE_bodyAddRotation(body,rotationAxis,
  470. // TPE_linearVelocityToAngular(
  471. // TPE_vec3Len(angularVelocity),-1 * pointDistance));
  472. }
  473. }
  474. void _TPE_getShapes(const TPE_Body *b1, const TPE_Body *b2, uint8_t shape1,
  475. const TPE_Body **first, const TPE_Body **second)
  476. {
  477. if (b1->shape == shape1)
  478. {
  479. *first = b1;
  480. *second = b2;
  481. }
  482. else
  483. {
  484. *first = b2;
  485. *second = b1;
  486. }
  487. }
  488. void _TPE_getCapsuleCyllinderEndpoints(const TPE_Body *body,
  489. TPE_Vec4 *a, TPE_Vec4 *b)
  490. {
  491. TPE_Vec4 quat = TPE_bodyGetOrientation(body);
  492. *a = TPE_vec4(0,body->shapeParams[1] / 2,0,0);
  493. *b = TPE_vec4(0,-1 * a->y,0,0);
  494. TPE_rotatePoint(a,quat);
  495. TPE_rotatePoint(b,quat);
  496. TPE_vec3Add(*a,body->position,a);
  497. TPE_vec3Add(*b,body->position,b);
  498. }
  499. /** Helpter function for cuboid collision detection. Given a line segment
  500. as a line equation limited by parameter bounds t1 and t2, center point C and
  501. side offset from the center point O, the function further limits the parameter
  502. bounds (t1, t2) to restrict the line only to the region between two planes:
  503. both with normal O, one passing throung point C + O and the other through
  504. C - O. If t2 > t1 after this function finishes, the line segment is completely
  505. outside the region. */
  506. void _TPE_cutLineSegmentByPlanes(TPE_Vec4 center, TPE_Vec4 sideOffset,
  507. TPE_Vec4 lineStart, TPE_Vec4 lineDir, TPE_Unit *t1, TPE_Unit *t2)
  508. {
  509. TPE_Unit da = TPE_vec3DotProductPlain(sideOffset,lineStart);
  510. TPE_Vec4 dc;
  511. dc.z = 0;
  512. // TODO: dor(d,dc) could be cached for all sides between calls to save recomputing
  513. dc = TPE_vec3Plus(center,sideOffset);
  514. TPE_Unit denom = TPE_nonZero(TPE_vec3DotProductPlain(sideOffset,lineDir));
  515. TPE_Unit tA =
  516. ((TPE_vec3DotProductPlain(sideOffset,dc) - da) * TPE_FRACTIONS_PER_UNIT)
  517. / denom;
  518. dc = TPE_vec3Minus(center,sideOffset);
  519. TPE_Unit tB =
  520. ((TPE_vec3DotProductPlain(sideOffset,dc) - da) * TPE_FRACTIONS_PER_UNIT)
  521. / denom;
  522. if (tB < tA)
  523. {
  524. TPE_Unit tmp = tA;
  525. tA = tB;
  526. tB = tmp;
  527. }
  528. if (tA > *t1)
  529. *t1 = tA;
  530. if (tB < *t2)
  531. *t2 = tB;
  532. }
  533. TPE_Unit TPE_bodyCollides(const TPE_Body *body1, const TPE_Body *body2,
  534. TPE_Vec4 *collisionPoint, TPE_Vec4 *collisionNormal)
  535. {
  536. // handle collision of different shapes each in a specific case:
  537. uint16_t collType = TPE_COLLISION_TYPE(body1->shape,body2->shape);
  538. if (collType != TPE_COLLISION_TYPE(TPE_SHAPE_SPHERE,TPE_SHAPE_SPHERE))
  539. {
  540. // initial bounding sphere check to quickly discard impossible collisions
  541. // TODO: taxicab could be also considered here
  542. if (TPE_vec3Len(TPE_vec3Minus(body1->position,body2->position)) >
  543. body1->boundingSphereRadius + body2->boundingSphereRadius)
  544. return 0;
  545. }
  546. switch (TPE_COLLISION_TYPE(body1->shape,body2->shape))
  547. {
  548. case TPE_COLLISION_TYPE(TPE_SHAPE_SPHERE,TPE_SHAPE_SPHERE):
  549. {
  550. TPE_Vec4 distanceVec;
  551. TPE_vec3Substract(body2->position,body1->position,&distanceVec);
  552. TPE_Unit distance = TPE_vec3Len(distanceVec);
  553. distance -= body1->shapeParams[0] + body2->shapeParams[0];
  554. if (distance < 0)
  555. {
  556. TPE_vec3Average(body1->position,body2->position,collisionPoint);
  557. *collisionNormal = distanceVec;
  558. TPE_vec3Normalize(collisionNormal);
  559. return -1 * distance;
  560. }
  561. break;
  562. }
  563. case TPE_COLLISION_TYPE(TPE_SHAPE_SPHERE,TPE_SHAPE_CAPSULE):
  564. {
  565. const TPE_Body *sphere;
  566. const TPE_Body *capsule;
  567. _TPE_getShapes(body1,body2,TPE_SHAPE_SPHERE,&sphere,&capsule);
  568. TPE_Vec4 cA, cB;
  569. _TPE_getCapsuleCyllinderEndpoints(capsule,&cA,&cB);
  570. TPE_Body sphere2; // sphere at the capsule's closest point
  571. TPE_bodyInit(&sphere2);
  572. sphere2.shape = TPE_SHAPE_SPHERE;
  573. sphere2.shapeParams[0] = capsule->shapeParams[0];
  574. sphere2.position = TPE_lineSegmentClosestPoint(cA,cB,sphere->position);
  575. uint8_t swap = sphere == body2;
  576. return TPE_bodyCollides(swap ? &sphere2 : sphere,swap ? sphere : &sphere2,
  577. collisionPoint,collisionNormal);
  578. break;
  579. }
  580. case TPE_COLLISION_TYPE(TPE_SHAPE_CAPSULE,TPE_SHAPE_CAPSULE):
  581. {
  582. TPE_Vec4 a1, b1, a2, b2;
  583. _TPE_getCapsuleCyllinderEndpoints(body1,&a1,&b1);
  584. _TPE_getCapsuleCyllinderEndpoints(body2,&a2,&b2);
  585. TPE_Unit aa, ab, ba, bb; // squared distances between points
  586. TPE_Vec4 tmp;
  587. tmp = TPE_vec3Minus(a1,a2);
  588. aa = tmp.x * tmp.x + tmp.y * tmp.y + tmp.z * tmp.z;
  589. tmp = TPE_vec3Minus(a1,b2);
  590. ab = tmp.x * tmp.x + tmp.y * tmp.y + tmp.z * tmp.z;
  591. tmp = TPE_vec3Minus(b1,a2);
  592. ba = tmp.x * tmp.x + tmp.y * tmp.y + tmp.z * tmp.z;
  593. tmp = TPE_vec3Minus(b1,b2);
  594. bb = tmp.x * tmp.x + tmp.y * tmp.y + tmp.z * tmp.z;
  595. // let a1 hold the point figuring in the shortest distance:
  596. if (ab < aa)
  597. aa = ab; // means: aa = min(aa,ab)
  598. if (bb < ba)
  599. ba = bb; // means: ba = min(ba,bb)
  600. if (ba < aa) // means: min(ba,bb) < min(aa,ab)
  601. a1 = b1;
  602. a2 = TPE_lineSegmentClosestPoint(a2,b2,a1);
  603. a1 = TPE_lineSegmentClosestPoint(a1,b1,a2);
  604. // now a1 and a2 are the closest two points on capsule axes
  605. TPE_Body sphere1, sphere2;
  606. TPE_bodyInit(&sphere1);
  607. sphere1.shape = TPE_SHAPE_SPHERE;
  608. sphere1.shapeParams[0] = body1->shapeParams[0];
  609. sphere1.position = a1;
  610. TPE_bodyInit(&sphere2);
  611. sphere2.shape = TPE_SHAPE_SPHERE;
  612. sphere2.shapeParams[0] = body2->shapeParams[0];
  613. sphere2.position = a2;
  614. return TPE_bodyCollides(&sphere1,&sphere2,collisionPoint,collisionNormal);
  615. break;
  616. }
  617. case TPE_COLLISION_TYPE(TPE_SHAPE_SPHERE,TPE_SHAPE_CYLINDER):
  618. {
  619. // TODO: would this be better to do via sphere-capsule collision?
  620. const TPE_Body *sphere;
  621. const TPE_Body *cylinder;
  622. _TPE_getShapes(body1,body2,TPE_SHAPE_SPHERE,&sphere,&cylinder);
  623. TPE_Vec4 sphereRelativePos = // by this we shift the cylinder to [0,0,0]
  624. TPE_vec3Minus(sphere->position,cylinder->position);
  625. // vector along the cylinder height:
  626. TPE_Vec4 cylinderAxis = TPE_vec4(0,TPE_FRACTIONS_PER_UNIT,0,0);
  627. TPE_rotatePoint(&cylinderAxis,TPE_bodyGetOrientation(cylinder));
  628. TPE_Vec4 sphereAxisPos = // sphere pos projected to the cylinder axis
  629. TPE_vec3Projected(sphereRelativePos,cylinderAxis);
  630. TPE_Unit sphereAxisDistance = TPE_vec3Len(sphereAxisPos);
  631. TPE_Unit tmp = cylinder->shapeParams[1] / 2; // half of cylinder height
  632. /* now we have three possible regions the sphere can occupy:
  633. C :B: A :B: C
  634. : :_____: :
  635. : |_____| : cylinder
  636. : : : :
  637. : : : : */
  638. if (sphereAxisDistance >= tmp + sphere->shapeParams[0]) // case C: no col.
  639. break;
  640. TPE_Vec4 sphereAxisToRelative =
  641. TPE_vec3Minus(sphereRelativePos,sphereAxisPos);
  642. TPE_Unit sphereCylinderDistance = TPE_vec3Len(sphereAxisToRelative);
  643. tmp = sphereAxisDistance - tmp;
  644. if (tmp < 0) // case A: potential collision with cylinder body
  645. {
  646. TPE_Unit penetration = cylinder->shapeParams[0]
  647. - (sphereCylinderDistance - sphere->shapeParams[0]);
  648. if (penetration > 0)
  649. {
  650. TPE_vec3Normalize(&sphereAxisToRelative);
  651. *collisionPoint = TPE_vec3Plus(cylinder->position,
  652. TPE_vec3Plus(sphereAxisPos,TPE_vec3Times(
  653. sphereAxisToRelative,cylinder->shapeParams[0])));
  654. *collisionNormal = sphereAxisToRelative;
  655. if (sphere == body1)
  656. TPE_vec3MultiplyPlain(*collisionNormal,-1,collisionNormal);
  657. return penetration;
  658. }
  659. else
  660. break;
  661. }
  662. /* case B: here we have two subcases, one with the sphere center being
  663. within the cylinder radius (collision with the cylinder top/bottom),
  664. and the other case (collision with the cylinder top/bottom edge). */
  665. TPE_Vec4 cylinderPlaneMiddle = TPE_vec3Times(
  666. TPE_vec3Normalized(sphereAxisPos),
  667. cylinder->shapeParams[1] / 2);
  668. if (sphereCylinderDistance < cylinder->shapeParams[0]) // top/bottom cap
  669. {
  670. TPE_Unit penetration = cylinder->shapeParams[1] / 2 -
  671. (sphereAxisDistance - sphere->shapeParams[0]);
  672. if (penetration <= 0) // shouldn't normally happen, but rounding errors
  673. penetration = 1;
  674. *collisionNormal = TPE_vec3Normalized(sphereAxisPos);
  675. *collisionPoint =
  676. TPE_vec3Plus(
  677. cylinder->position,
  678. TPE_vec3Plus(sphereAxisToRelative,cylinderPlaneMiddle));
  679. if (body1 == sphere)
  680. TPE_vec3MultiplyPlain(*collisionNormal,-1,collisionNormal);
  681. return penetration;
  682. }
  683. else // potential edge collision
  684. {
  685. TPE_Vec4 edgePoint = TPE_vec3Plus(cylinderPlaneMiddle,
  686. TPE_vec3Times(TPE_vec3Normalized(sphereAxisToRelative),
  687. cylinder->shapeParams[0]));
  688. TPE_Unit penetration = sphere->shapeParams[0] -
  689. TPE_vec3Dist(edgePoint,sphereRelativePos);
  690. if (penetration > 0)
  691. {
  692. *collisionPoint = TPE_vec3Plus(cylinder->position,edgePoint);
  693. *collisionNormal =
  694. TPE_vec3Normalized(TPE_vec3Minus(sphereRelativePos,edgePoint));
  695. if (body1 == sphere)
  696. TPE_vec3MultiplyPlain(*collisionNormal,-1,collisionNormal);
  697. return penetration;
  698. }
  699. }
  700. break;
  701. }
  702. case TPE_COLLISION_TYPE(TPE_SHAPE_CUBOID,TPE_SHAPE_CUBOID):
  703. {
  704. TPE_Vec4 // min/max extent of the colliding area:
  705. collisionExtentMax =
  706. TPE_vec4(-TPE_INFINITY,-TPE_INFINITY,-TPE_INFINITY,0),
  707. collisionExtentMin =
  708. TPE_vec4(TPE_INFINITY,TPE_INFINITY,TPE_INFINITY,0);
  709. uint8_t collisionHappened = 0;
  710. TPE_Vec4 aX1, aY1, aZ1, // first cuboid axes
  711. aX2, aY2, aZ2; // second cuboid axes
  712. for (uint8_t i = 0; i < 2; ++i) // for each body
  713. {
  714. TPE_Vec4 q = TPE_bodyGetOrientation(body1);
  715. // construct the cuboid axes:
  716. aX1 = TPE_vec4(body1->shapeParams[0] / 2,0,0,0);
  717. TPE_rotatePoint(&aX1,q);
  718. aY1 = TPE_vec4(0,body1->shapeParams[1] / 2,0,0);
  719. TPE_rotatePoint(&aY1,q);
  720. aZ1 = TPE_vec4(0,0,body1->shapeParams[2] / 2,0);
  721. TPE_rotatePoint(&aZ1,q);
  722. q = TPE_bodyGetOrientation(body2);
  723. aX2 = TPE_vec4(body2->shapeParams[0] / 2,0,0,0);
  724. TPE_rotatePoint(&aX2,q);
  725. aY2 = TPE_vec4(0,body2->shapeParams[1] / 2,0,0);
  726. TPE_rotatePoint(&aY2,q);
  727. aZ2 = TPE_vec4(0,0,body2->shapeParams[2] / 2,0);
  728. TPE_rotatePoint(&aZ2,q);
  729. uint8_t edges[12] = // list of all cuboid edges as combinations of axes
  730. { // xyz xyz
  731. 0x3b, // +++ -++ |
  732. 0x3e, // +++ ++- | top
  733. 0x13, // -+- -++ |
  734. 0x16, // -+- ++- |
  735. 0x29, // +-+ --+ |
  736. 0x2c, // +-+ +-- | bottom
  737. 0x01, // --- --+ |
  738. 0x04, // --- +-- |
  739. 0x3d, // +++ +-+ |
  740. 0x19, // -++ --+ | sides
  741. 0x10, // -+- --- |
  742. 0x34 // ++- +-- |
  743. };
  744. for (uint8_t j = 0; j < 12; ++j) // for each edge
  745. {
  746. // we check the edge against all sides of the other cuboid
  747. TPE_Vec4 lineStart = body1->position;
  748. TPE_Vec4 lineEnd = body1->position;
  749. uint8_t edge = edges[j];
  750. #define offsetCenter(c,v,a) \
  751. v = (edge & c) ? TPE_vec3Plus(v,a) : TPE_vec3Minus(v,a);
  752. offsetCenter(0x04,lineStart,aX1)
  753. offsetCenter(0x02,lineStart,aY1)
  754. offsetCenter(0x01,lineStart,aZ1)
  755. offsetCenter(0x20,lineEnd,aX1)
  756. offsetCenter(0x10,lineEnd,aY1)
  757. offsetCenter(0x08,lineEnd,aZ1)
  758. #undef offsetCenter
  759. TPE_Unit t1 = 0, t2 = TPE_FRACTIONS_PER_UNIT;
  760. TPE_Vec4 edgeDir = TPE_vec3Minus(lineEnd,lineStart);
  761. for (uint8_t k = 0; k < 3; ++k) // for each axis (pair of sides)
  762. {
  763. TPE_Vec4 *sideOffset;
  764. if (k == 0)
  765. sideOffset = &aX2;
  766. else if (k == 1)
  767. sideOffset = &aY2;
  768. else
  769. sideOffset = &aZ2;
  770. _TPE_cutLineSegmentByPlanes(body2->position,*sideOffset,lineStart,
  771. edgeDir,&t1,&t2);
  772. if (t1 > t2)
  773. break; // no solution already, no point checking on
  774. }
  775. if (t2 > t1) // if part of edge exists between all side planes
  776. {
  777. // edge collided with the cuboid
  778. collisionHappened = 1;
  779. *collisionPoint = edgeDir;
  780. collisionPoint->x = (collisionPoint->x * t1) / TPE_FRACTIONS_PER_UNIT;
  781. collisionPoint->y = (collisionPoint->y * t1) / TPE_FRACTIONS_PER_UNIT;
  782. collisionPoint->z = (collisionPoint->z * t1) / TPE_FRACTIONS_PER_UNIT;
  783. *collisionPoint = TPE_vec3Plus(lineStart,*collisionPoint);
  784. if (collisionPoint->x > collisionExtentMax.x)
  785. collisionExtentMax.x = collisionPoint->x;
  786. if (collisionPoint->x < collisionExtentMin.x)
  787. collisionExtentMin.x = collisionPoint->x;
  788. if (collisionPoint->y > collisionExtentMax.y)
  789. collisionExtentMax.y = collisionPoint->y;
  790. if (collisionPoint->y < collisionExtentMin.y)
  791. collisionExtentMin.y = collisionPoint->y;
  792. if (collisionPoint->z > collisionExtentMax.z)
  793. collisionExtentMax.z = collisionPoint->z;
  794. if (collisionPoint->z < collisionExtentMin.z)
  795. collisionExtentMin.z = collisionPoint->z;
  796. *collisionPoint = edgeDir;
  797. collisionPoint->x = (collisionPoint->x * t2) / TPE_FRACTIONS_PER_UNIT;
  798. collisionPoint->y = (collisionPoint->y * t2) / TPE_FRACTIONS_PER_UNIT;
  799. collisionPoint->z = (collisionPoint->z * t2) / TPE_FRACTIONS_PER_UNIT;
  800. *collisionPoint = TPE_vec3Plus(lineStart,*collisionPoint);
  801. if (collisionPoint->x > collisionExtentMax.x)
  802. collisionExtentMax.x = collisionPoint->x;
  803. if (collisionPoint->x < collisionExtentMin.x)
  804. collisionExtentMin.x = collisionPoint->x;
  805. if (collisionPoint->y > collisionExtentMax.y)
  806. collisionExtentMax.y = collisionPoint->y;
  807. if (collisionPoint->y < collisionExtentMin.y)
  808. collisionExtentMin.y = collisionPoint->y;
  809. if (collisionPoint->z > collisionExtentMax.z)
  810. collisionExtentMax.z = collisionPoint->z;
  811. if (collisionPoint->z < collisionExtentMin.z)
  812. collisionExtentMin.z = collisionPoint->z;
  813. }
  814. } // for each edge
  815. if (i == 0)
  816. {
  817. // now swap the bodies and do it again:
  818. const TPE_Body *tmp = body1;
  819. body1 = body2;
  820. body2 = tmp;
  821. }
  822. } // for each body
  823. if (collisionHappened)
  824. {
  825. // average all collision points to get the center point
  826. *collisionPoint = TPE_vec3Plus(collisionExtentMin,collisionExtentMax);
  827. collisionPoint->x /= 2;
  828. collisionPoint->y /= 2;
  829. collisionPoint->z /= 2;
  830. collisionPoint->w = 0;
  831. // compute the coll. normal as the axis closest to the coll. point
  832. TPE_Vec4 bestAxis = TPE_vec4(1,0,0,0);
  833. TPE_Unit bestDot = -1;
  834. TPE_Unit currentDot;
  835. uint8_t currentBody = 0;
  836. uint8_t bestBody = 0;
  837. // TODO: optimize this shit? create array instead of aX1, aX2 etc.?
  838. collisionExtentMin = TPE_vec3Minus(*collisionPoint,body1->position); // reuse
  839. #define checkAxis(a) \
  840. currentDot = (TPE_vec3DotProduct(a,collisionExtentMin) * TPE_FRACTIONS_PER_UNIT) / \
  841. TPE_nonZero(TPE_vec3DotProduct(a,a)); \
  842. if (currentDot > bestDot) \
  843. { bestDot = currentDot; bestAxis = a; bestBody = currentBody; } \
  844. else { \
  845. currentDot *= -1; \
  846. if (currentDot > bestDot) { \
  847. bestDot = currentDot; bestAxis = a; bestBody = currentBody; \
  848. TPE_vec3MultiplyPlain(bestAxis,-1,&bestAxis); } \
  849. }
  850. checkAxis(aX1)
  851. checkAxis(aY1)
  852. checkAxis(aZ1)
  853. collisionExtentMin = TPE_vec3Minus(*collisionPoint,body2->position);
  854. currentBody = 1;
  855. checkAxis(aX2)
  856. checkAxis(aY2)
  857. checkAxis(aZ2)
  858. #undef checkAxis
  859. // TODO: optimize/refactor this mess
  860. *collisionNormal = bestAxis;
  861. if (bestBody == 0)
  862. TPE_vec3MultiplyPlain(*collisionNormal,-1,collisionNormal);
  863. TPE_vec3Normalize(collisionNormal);
  864. TPE_Unit len = TPE_nonZero(TPE_vec3Len(bestAxis));
  865. return len -
  866. TPE_vec3DotProductPlain(bestAxis,
  867. TPE_vec3Minus(*collisionPoint,
  868. bestBody == 0 ? body1->position : body2->position)) / len;
  869. }
  870. break;
  871. }
  872. default:
  873. break;
  874. }
  875. return 0;
  876. }
  877. TPE_Vec4 TPE_bodyGetPointVelocity(const TPE_Body *body, TPE_Vec4 point)
  878. {
  879. TPE_Vec4 result = body->velocity;
  880. TPE_Vec4 normal = TPE_vec3Cross(
  881. point,TPE_vec3Minus(point,body->rotation.axisVelocity));
  882. TPE_vec3MultiplyPlain(normal,-1,&normal); // TODO: think about WHY
  883. TPE_Unit dist = TPE_vec3Len(normal); // point-line distance
  884. TPE_Unit velocity =
  885. TPE_angularVelocityToLinear(body->rotation.axisVelocity.w,dist);
  886. TPE_vec3Normalize(&normal);
  887. return TPE_vec3Plus(result,TPE_vec3Times(normal,velocity));
  888. }
  889. void TPE_resolveCollision(TPE_Body *body1 ,TPE_Body *body2,
  890. TPE_Vec4 collisionPoint, TPE_Vec4 collisionNormal, TPE_Unit collisionDepth)
  891. {
  892. printf("---\n");
  893. TPE_Vec4 v1, v2, p1, p2;
  894. p1 = TPE_vec3Minus(collisionPoint,body1->position);
  895. p2 = TPE_vec3Minus(collisionPoint,body2->position);
  896. /*
  897. TODO:
  898. We don't have to compute second body's final velocity! From momentum
  899. preservation it can be computer from the initial total momentum and first
  900. body's new momentum.
  901. ALSO: compute the rotation velocity from preservaion of rotational kinetic
  902. energy!
  903. */
  904. // separate the bodies:
  905. collisionPoint = collisionNormal; // reuse collisionPoint
  906. TPE_vec3Multiply(collisionPoint,collisionDepth,&collisionPoint);
  907. TPE_vec3Add(body2->position,collisionPoint,&body2->position);
  908. TPE_vec3Substract(body1->position,collisionPoint,&body1->position);
  909. v1 = TPE_bodyGetPointVelocity(body1,p1);
  910. v2 = TPE_bodyGetPointVelocity(body2,p2);
  911. TPE_Unit tmp = TPE_vec3DotProduct(v1,collisionNormal);
  912. int8_t v1Sign = tmp > 0 ? 1 : (tmp < 0 ? -1 : 0);
  913. tmp = TPE_vec3DotProduct(v2,collisionNormal);
  914. int8_t v2Sign = tmp > 0 ? 1 : (tmp < 0 ? -1 : 0);
  915. if (v1Sign == -1 && v2Sign != -1)
  916. return; // opposite going velocities => not a real collision
  917. /* if the velocities are too small, weird behavior occurs, so we define a min
  918. velocity for collisions and potentially modify the velocities: */
  919. // TODO: something more elegant?
  920. #define MIN_V 5
  921. if (v1.x != 0 || v1.y != 0 || v1.z != 0)
  922. while (TPE_vec3LenTaxicab(v1) < MIN_V)
  923. {
  924. v1.x *= 2;
  925. v1.y *= 2;
  926. v1.z *= 2;
  927. }
  928. if (v2.x != 0 || v2.y != 0 || v2.z != 0)
  929. while (TPE_vec3LenTaxicab(v2) < MIN_V)
  930. {
  931. v2.x *= 2;
  932. v2.y *= 2;
  933. v2.z *= 2;
  934. }
  935. #undef MIN_V
  936. TPE_vec3Project(v1,collisionNormal,&v1);
  937. TPE_vec3Project(v2,collisionNormal,&v2);
  938. TPE_Unit
  939. v1Scalar = TPE_vec3Len(v1) * v1Sign,
  940. v2Scalar = TPE_vec3Len(v2) * v2Sign;
  941. if ((v1Sign == 1 && v2Sign == 1 && (v2Scalar > v1Scalar)) ||
  942. (v1Sign == -1 && v2Sign == -1 && (v1Scalar > v2Scalar)))
  943. return; // not a valid collision
  944. TPE_Unit
  945. v1ScalarNew = v1Scalar,
  946. v2ScalarNew = v2Scalar;
  947. TPE_getVelocitiesAfterCollision(
  948. &v1ScalarNew,
  949. &v2ScalarNew,
  950. body1->mass,
  951. body2->mass,
  952. 512); // TODO: elasticity
  953. // TODO: ACTUALLY MAKE SURE MOMENTUM IS CONSERVED (rounding errors may add energy!)
  954. //TPE_vec3MultiplyPlain(collisionNormal,-1,&collisionNormal);
  955. TPE_bodyApplyVelocity(body1,p1,
  956. // TPE_vec3TimesAntiZero(collisionNormal,v1ScalarNew - v1Scalar));
  957. TPE_vec3Times(collisionNormal,v1ScalarNew - v1Scalar));
  958. TPE_bodyApplyVelocity(body2,p2,
  959. // TPE_vec3TimesAntiZero(collisionNormal,v2ScalarNew - v2Scalar));
  960. TPE_vec3Times(collisionNormal,v2ScalarNew - v2Scalar));
  961. }
  962. TPE_Unit TPE_linearVelocityToAngular(TPE_Unit velocity, TPE_Unit distance)
  963. {
  964. TPE_Unit circumfence = (2 * TPE_PI * distance) / TPE_FRACTIONS_PER_UNIT;
  965. return (velocity * TPE_FRACTIONS_PER_UNIT) / circumfence;
  966. }
  967. TPE_Unit TPE_angularVelocityToLinear(TPE_Unit velocity, TPE_Unit distance)
  968. {
  969. TPE_Unit circumfence = (2 * TPE_PI * distance) / TPE_FRACTIONS_PER_UNIT;
  970. return (velocity * circumfence) / TPE_FRACTIONS_PER_UNIT;
  971. }
  972. void TPE_bodyStep(TPE_Body *body)
  973. {
  974. TPE_vec3Add(body->position,body->velocity,&(body->position));
  975. body->rotation.currentAngle += body->rotation.axisVelocity.w;
  976. }
  977. void TPE_bodySetRotation(TPE_Body *body, TPE_Vec4 axis, TPE_Unit velocity)
  978. {
  979. body->rotation.originalOrientation = TPE_bodyGetOrientation(body);
  980. if (velocity < 0)
  981. {
  982. axis.x *= -1;
  983. axis.y *= -1;
  984. axis.z *= -1;
  985. velocity *= -1;
  986. }
  987. TPE_vec3Normalize(&axis);
  988. body->rotation.axisVelocity = axis;
  989. body->rotation.axisVelocity.w = velocity;
  990. body->rotation.currentAngle = 0;
  991. }
  992. void TPE_bodyAddRotation(TPE_Body *body, TPE_Vec4 axis, TPE_Unit velocity)
  993. {
  994. /* Rotation is added like this: we convert both the original and added
  995. rotation to vectors whose direction is along the rotations axis and
  996. magnitude is the rotation speed, then we add these vectors and convert
  997. the final vector back to normalized rotation axis + scalar rotation
  998. speed.*/
  999. body->rotation.axisVelocity.x =
  1000. (body->rotation.axisVelocity.x * body->rotation.axisVelocity.w)
  1001. / TPE_FRACTIONS_PER_UNIT;
  1002. body->rotation.axisVelocity.y =
  1003. (body->rotation.axisVelocity.y * body->rotation.axisVelocity.w)
  1004. / TPE_FRACTIONS_PER_UNIT;
  1005. body->rotation.axisVelocity.z =
  1006. (body->rotation.axisVelocity.z * body->rotation.axisVelocity.w)
  1007. / TPE_FRACTIONS_PER_UNIT;
  1008. TPE_vec3Normalize(&axis);
  1009. axis.x = (axis.x * velocity) / TPE_FRACTIONS_PER_UNIT;
  1010. axis.y = (axis.y * velocity) / TPE_FRACTIONS_PER_UNIT;
  1011. axis.z = (axis.z * velocity) / TPE_FRACTIONS_PER_UNIT;
  1012. TPE_vec3Add(body->rotation.axisVelocity,axis,&axis);
  1013. axis.w = TPE_vec3Len(axis);
  1014. TPE_bodySetRotation(body,axis,axis.w);
  1015. }
  1016. void TPE_quaternionMultiply(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result)
  1017. {
  1018. TPE_Vec4 r; // in case result is identical to a or b
  1019. r.x =
  1020. (a.w * b.x +
  1021. a.x * b.w +
  1022. a.y * b.z -
  1023. a.z * b.y) / TPE_FRACTIONS_PER_UNIT;
  1024. r.y =
  1025. (a.w * b.y -
  1026. a.x * b.z +
  1027. a.y * b.w +
  1028. a.z * b.x) / TPE_FRACTIONS_PER_UNIT;
  1029. r.z =
  1030. (a.w * b.z +
  1031. a.x * b.y -
  1032. a.y * b.x +
  1033. a.z * b.w) / TPE_FRACTIONS_PER_UNIT;
  1034. r.w =
  1035. (a.w * b.w -
  1036. a.x * b.x -
  1037. a.y * b.y -
  1038. a.z * b.z) / TPE_FRACTIONS_PER_UNIT;
  1039. result->x = r.x;
  1040. result->y = r.y;
  1041. result->z = r.z;
  1042. result->w = r.w;
  1043. }
  1044. void TPE_rotationToQuaternion(TPE_Vec4 axis, TPE_Unit angle, TPE_Vec4 *quaternion)
  1045. {
  1046. TPE_vec3Normalize(&axis);
  1047. angle /= 2;
  1048. TPE_Unit s = TPE_sin(angle);
  1049. quaternion->x = (s * axis.x) / TPE_FRACTIONS_PER_UNIT;
  1050. quaternion->y = (s * axis.y) / TPE_FRACTIONS_PER_UNIT;
  1051. quaternion->z = (s * axis.z) / TPE_FRACTIONS_PER_UNIT;
  1052. quaternion->w = TPE_cos(angle);
  1053. }
  1054. TPE_Unit TPE_asin(TPE_Unit x)
  1055. {
  1056. x = TPE_clamp(x,-TPE_FRACTIONS_PER_UNIT,TPE_FRACTIONS_PER_UNIT);
  1057. int8_t sign = 1;
  1058. if (x < 0)
  1059. {
  1060. sign = -1;
  1061. x *= -1;
  1062. }
  1063. int16_t low = 0;
  1064. int16_t high = TPE_SIN_TABLE_LENGTH -1;
  1065. int16_t middle;
  1066. while (low <= high) // binary search
  1067. {
  1068. middle = (low + high) / 2;
  1069. TPE_Unit v = TPE_sinTable[middle];
  1070. if (v > x)
  1071. high = middle - 1;
  1072. else if (v < x)
  1073. low = middle + 1;
  1074. else
  1075. break;
  1076. }
  1077. middle *= TPE_SIN_TABLE_UNIT_STEP;
  1078. return sign * middle;
  1079. }
  1080. TPE_Unit TPE_acos(TPE_Unit x)
  1081. {
  1082. return TPE_asin(-1 * x) + TPE_FRACTIONS_PER_UNIT / 4;
  1083. }
  1084. void TPE_quaternionToRotation(TPE_Vec4 quaternion, TPE_Vec4 *axis, TPE_Unit *angle)
  1085. {
  1086. *angle = 2 * TPE_acos(quaternion.x);
  1087. TPE_Unit tmp =
  1088. TPE_nonZero(TPE_sqrt(
  1089. (TPE_FRACTIONS_PER_UNIT -
  1090. (quaternion.x * quaternion.x) / TPE_FRACTIONS_PER_UNIT
  1091. ) * TPE_FRACTIONS_PER_UNIT));
  1092. axis->x = (quaternion.x * TPE_FRACTIONS_PER_UNIT) / tmp;
  1093. axis->y = (quaternion.y * TPE_FRACTIONS_PER_UNIT) / tmp;
  1094. axis->z = (quaternion.z * TPE_FRACTIONS_PER_UNIT) / tmp;
  1095. }
  1096. void TPE_quaternionToRotationMatrix(TPE_Vec4 quaternion, TPE_Unit matrix[4][4])
  1097. {
  1098. TPE_Unit
  1099. _2x2 = (2 * quaternion.x * quaternion.x) / TPE_FRACTIONS_PER_UNIT,
  1100. _2y2 = (2 * quaternion.y * quaternion.y) / TPE_FRACTIONS_PER_UNIT,
  1101. _2z2 = (2 * quaternion.z * quaternion.z) / TPE_FRACTIONS_PER_UNIT,
  1102. _2xy = (2 * quaternion.x * quaternion.y) / TPE_FRACTIONS_PER_UNIT,
  1103. _2xw = (2 * quaternion.x * quaternion.w) / TPE_FRACTIONS_PER_UNIT,
  1104. _2zw = (2 * quaternion.z * quaternion.w) / TPE_FRACTIONS_PER_UNIT,
  1105. _2xz = (2 * quaternion.x * quaternion.z) / TPE_FRACTIONS_PER_UNIT,
  1106. _2yw = (2 * quaternion.y * quaternion.w) / TPE_FRACTIONS_PER_UNIT,
  1107. _2yz = (2 * quaternion.y * quaternion.z) / TPE_FRACTIONS_PER_UNIT;
  1108. #define ONE TPE_FRACTIONS_PER_UNIT
  1109. matrix[0][0] = ONE - _2y2 - _2z2;
  1110. matrix[1][0] = _2xy - _2zw;
  1111. matrix[2][0] = _2xz + _2yw;
  1112. matrix[3][0] = 0;
  1113. matrix[0][1] = _2xy + _2zw;
  1114. matrix[1][1] = ONE - _2x2 - _2z2;
  1115. matrix[2][1] = _2yz - _2xw;
  1116. matrix[3][1] = 0;
  1117. matrix[0][2] = _2xz - _2yw;
  1118. matrix[1][2] = _2yz + _2xw;
  1119. matrix[2][2] = ONE - _2x2 - _2y2;
  1120. matrix[3][2] = 0;
  1121. matrix[0][3] = 0;
  1122. matrix[1][3] = 0;
  1123. matrix[2][3] = 0;
  1124. matrix[3][3] = ONE;
  1125. #undef ONE
  1126. }
  1127. void TPE_vec3Add(const TPE_Vec4 a, const TPE_Vec4 b, TPE_Vec4 *result)
  1128. {
  1129. result->x = a.x + b.x;
  1130. result->y = a.y + b.y;
  1131. result->z = a.z + b.z;
  1132. }
  1133. void TPE_vec4Add(const TPE_Vec4 a, const TPE_Vec4 b, TPE_Vec4 *result)
  1134. {
  1135. result->x = a.x + b.x;
  1136. result->y = a.y + b.y;
  1137. result->z = a.z + b.z;
  1138. result->w = a.w + b.w;
  1139. }
  1140. void TPE_vec3Substract(const TPE_Vec4 a, const TPE_Vec4 b, TPE_Vec4 *result)
  1141. {
  1142. result->x = a.x - b.x;
  1143. result->y = a.y - b.y;
  1144. result->z = a.z - b.z;
  1145. }
  1146. TPE_Vec4 TPE_vec3Plus(TPE_Vec4 a, TPE_Vec4 b)
  1147. {
  1148. a.x += b.x;
  1149. a.y += b.y;
  1150. a.z += b.z;
  1151. return a;
  1152. }
  1153. TPE_Vec4 TPE_vec3Minus(TPE_Vec4 a, TPE_Vec4 b)
  1154. {
  1155. a.x -= b.x;
  1156. a.y -= b.y;
  1157. a.z -= b.z;
  1158. return a;
  1159. }
  1160. TPE_Vec4 TPE_vec3Times(TPE_Vec4 a, TPE_Unit f)
  1161. {
  1162. a.x = (a.x * f) / TPE_FRACTIONS_PER_UNIT;
  1163. a.y = (a.y * f) / TPE_FRACTIONS_PER_UNIT;
  1164. a.z = (a.z * f) / TPE_FRACTIONS_PER_UNIT;
  1165. return a;
  1166. }
  1167. TPE_Vec4 TPE_vec3TimesAntiZero(TPE_Vec4 a, TPE_Unit f)
  1168. {
  1169. a.x *= f;
  1170. if (a.x != 0)
  1171. a.x = a.x >= TPE_FRACTIONS_PER_UNIT ? a.x / TPE_FRACTIONS_PER_UNIT :
  1172. (a.x > 0 ? 1 : -1);
  1173. a.y *= f;
  1174. if (a.y != 0)
  1175. a.y = a.y >= TPE_FRACTIONS_PER_UNIT ? a.y / TPE_FRACTIONS_PER_UNIT :
  1176. (a.y > 0 ? 1 : -1);
  1177. a.z *= f;
  1178. if (a.z != 0)
  1179. a.z = a.z >= TPE_FRACTIONS_PER_UNIT ? a.z / TPE_FRACTIONS_PER_UNIT :
  1180. (a.z > 0 ? 1 : -1);
  1181. /*
  1182. if (a.x != 0)
  1183. a.x = a.x >= TPE_FRACTIONS_PER_UNIT ? a.x / TPE_FRACTIONS_PER_UNIT :
  1184. (a.x > 0 ? 1 : -1);
  1185. if (a.y != 0)
  1186. a.y = a.y >= TPE_FRACTIONS_PER_UNIT ? a.y / TPE_FRACTIONS_PER_UNIT :
  1187. (a.y > 0 ? 1 : -1);
  1188. if (a.z != 0)
  1189. a.z = a.z >= TPE_FRACTIONS_PER_UNIT ? a.z / TPE_FRACTIONS_PER_UNIT :
  1190. (a.z > 0 ? 1 : -1);
  1191. */
  1192. return a;
  1193. }
  1194. void TPE_vec3Average(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result)
  1195. {
  1196. result->x = (a.x + b.x) / 2;
  1197. result->y = (a.y + b.y) / 2;
  1198. result->z = (a.z + b.z) / 2;
  1199. }
  1200. void TPE_vec4Substract(const TPE_Vec4 a, const TPE_Vec4 b, TPE_Vec4 *result)
  1201. {
  1202. result->x = a.x - b.x;
  1203. result->y = a.y - b.y;
  1204. result->z = a.z - b.z;
  1205. result->w = a.w - b.w;
  1206. }
  1207. void TPE_vec3Multiply(const TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result)
  1208. {
  1209. result->x = (v.x * f) / TPE_FRACTIONS_PER_UNIT;
  1210. result->y = (v.y * f) / TPE_FRACTIONS_PER_UNIT;
  1211. result->z = (v.z * f) / TPE_FRACTIONS_PER_UNIT;
  1212. }
  1213. void TPE_vec3MultiplyPlain(TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result)
  1214. {
  1215. result->x = v.x * f;
  1216. result->y = v.y * f;
  1217. result->z = v.z * f;
  1218. }
  1219. void TPE_vec4Multiply(const TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result)
  1220. {
  1221. result->x = (v.x * f) / TPE_FRACTIONS_PER_UNIT;
  1222. result->y = (v.y * f) / TPE_FRACTIONS_PER_UNIT;
  1223. result->z = (v.z * f) / TPE_FRACTIONS_PER_UNIT;
  1224. result->w = (v.w * f) / TPE_FRACTIONS_PER_UNIT;
  1225. }
  1226. TPE_Unit TPE_abs(TPE_Unit x)
  1227. {
  1228. return (x >= 0) ? x : (-1 * x);
  1229. }
  1230. TPE_Unit TPE_vec3Len(TPE_Vec4 v)
  1231. {
  1232. return TPE_sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
  1233. }
  1234. TPE_Unit TPE_vec3Dist(TPE_Vec4 a, TPE_Vec4 b)
  1235. {
  1236. return TPE_vec3Len(TPE_vec3Minus(a,b));
  1237. }
  1238. TPE_Unit TPE_vec4Len(TPE_Vec4 v)
  1239. {
  1240. return TPE_sqrt(v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w);
  1241. }
  1242. TPE_Unit TPE_vec3LenTaxicab(TPE_Vec4 v)
  1243. {
  1244. return TPE_abs(v.x) + TPE_abs(v.y) + TPE_abs(v.z);
  1245. }
  1246. TPE_Unit TPE_vec3DotProduct(const TPE_Vec4 v1, const TPE_Vec4 v2)
  1247. {
  1248. return
  1249. (v1.x * v2.x + v1.y * v2.y + v1.z * v2.z) / TPE_FRACTIONS_PER_UNIT;
  1250. }
  1251. TPE_Unit TPE_vec3DotProductPlain(const TPE_Vec4 v1, const TPE_Vec4 v2)
  1252. {
  1253. return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
  1254. }
  1255. void TPE_vec3Normalize(TPE_Vec4 *v)
  1256. {
  1257. TPE_Unit l = TPE_vec3Len(*v);
  1258. if (l == 0)
  1259. {
  1260. v->x = TPE_FRACTIONS_PER_UNIT;
  1261. return;
  1262. }
  1263. v->x = (v->x * TPE_FRACTIONS_PER_UNIT) / l;
  1264. v->y = (v->y * TPE_FRACTIONS_PER_UNIT) / l;
  1265. v->z = (v->z * TPE_FRACTIONS_PER_UNIT) / l;
  1266. }
  1267. void TPE_vec4Normalize(TPE_Vec4 *v)
  1268. {
  1269. TPE_Unit l = TPE_vec4Len(*v);
  1270. if (l == 0)
  1271. {
  1272. v->x = TPE_FRACTIONS_PER_UNIT;
  1273. return;
  1274. }
  1275. v->x = (v->x * TPE_FRACTIONS_PER_UNIT) / l;
  1276. v->y = (v->y * TPE_FRACTIONS_PER_UNIT) / l;
  1277. v->z = (v->z * TPE_FRACTIONS_PER_UNIT) / l;
  1278. v->w = (v->w * TPE_FRACTIONS_PER_UNIT) / l;
  1279. }
  1280. void TPE_vec3Project(TPE_Vec4 v, TPE_Vec4 base, TPE_Vec4 *result)
  1281. {
  1282. TPE_Unit p = TPE_vec3DotProduct(v,base);
  1283. result->x = (p * base.x) / TPE_FRACTIONS_PER_UNIT;
  1284. result->y = (p * base.y) / TPE_FRACTIONS_PER_UNIT;
  1285. result->z = (p * base.z) / TPE_FRACTIONS_PER_UNIT;
  1286. }
  1287. TPE_Vec4 TPE_vec3Projected(TPE_Vec4 v, TPE_Vec4 base)
  1288. {
  1289. TPE_Vec4 r;
  1290. TPE_vec3Project(v,base,&r);
  1291. return r;
  1292. }
  1293. void TPE_getVelocitiesAfterCollision(
  1294. TPE_Unit *v1,
  1295. TPE_Unit *v2,
  1296. TPE_Unit m1,
  1297. TPE_Unit m2,
  1298. TPE_Unit elasticity
  1299. )
  1300. {
  1301. /* in the following a lot of TPE_FRACTIONS_PER_UNIT cancel out, feel free to
  1302. check if confused */
  1303. #define ANTI_OVERFLOW 30000
  1304. #define ANTI_OVERFLOW_SCALE 128
  1305. uint8_t overflowDanger = m1 > ANTI_OVERFLOW || *v1 > ANTI_OVERFLOW ||
  1306. m2 > ANTI_OVERFLOW || *v2 > ANTI_OVERFLOW;
  1307. if (overflowDanger)
  1308. {
  1309. m1 = (m1 != 0) ? TPE_nonZero(m1 / ANTI_OVERFLOW_SCALE) : 0;
  1310. m2 = (m2 != 0) ? TPE_nonZero(m2 / ANTI_OVERFLOW_SCALE) : 0;
  1311. *v1 = (*v1 != 0) ? TPE_nonZero(*v1 / ANTI_OVERFLOW_SCALE) : 0;
  1312. *v2 = (*v2 != 0) ? TPE_nonZero(*v2 / ANTI_OVERFLOW_SCALE) : 0;
  1313. }
  1314. TPE_Unit m1Pm2 = TPE_nonZero(m1 + m2);
  1315. TPE_Unit v2Mv1 = TPE_nonZero(*v2 - *v1);
  1316. TPE_Unit m1v1Pm2v2 = ((m1 * *v1) + (m2 * *v2));
  1317. *v1 = (((elasticity * m2 / TPE_FRACTIONS_PER_UNIT) * v2Mv1)
  1318. + m1v1Pm2v2) / m1Pm2;
  1319. *v2 = (((elasticity * m1 / TPE_FRACTIONS_PER_UNIT) * -1 * v2Mv1)
  1320. + m1v1Pm2v2) / m1Pm2;
  1321. if (overflowDanger)
  1322. {
  1323. *v1 *= ANTI_OVERFLOW_SCALE;
  1324. *v2 *= ANTI_OVERFLOW_SCALE;
  1325. }
  1326. #undef ANTI_OVERFLOW
  1327. #undef ANTI_OVERFLOW_SCALE
  1328. }
  1329. void TPE_bodyGetTransformMatrix(const TPE_Body *body, TPE_Unit matrix[4][4])
  1330. {
  1331. TPE_Vec4 orientation;
  1332. orientation = TPE_bodyGetOrientation(body);
  1333. TPE_quaternionToRotationMatrix(orientation,matrix);
  1334. matrix[0][3] = body->position.x;
  1335. matrix[1][3] = body->position.y;
  1336. matrix[2][3] = body->position.z;
  1337. }
  1338. void TPE_quaternionInit(TPE_Vec4 *quaternion)
  1339. {
  1340. quaternion->x = 0;
  1341. quaternion->y = 0;
  1342. quaternion->z = 0;
  1343. quaternion->w = TPE_FRACTIONS_PER_UNIT;
  1344. }
  1345. void TPE_rotatePoint(TPE_Vec4 *point, TPE_Vec4 quaternion)
  1346. {
  1347. // TODO: the first method is bugged, but maybe would be faster?
  1348. #if 0
  1349. TPE_Vec4 quaternionConjugate = TPE_quaternionConjugate(quaternion);
  1350. point->w = 0;
  1351. TPE_quaternionMultiply(quaternion,*point,point);
  1352. TPE_quaternionMultiply(*point,quaternionConjugate,point);
  1353. #else
  1354. TPE_Unit m[4][4];
  1355. TPE_quaternionToRotationMatrix(quaternion,m);
  1356. TPE_Vec4 p = *point;
  1357. point->x = (p.x * m[0][0] + p.y * m[0][1] + p.z * m[0][2]) / TPE_FRACTIONS_PER_UNIT;
  1358. point->y = (p.x * m[1][0] + p.y * m[1][1] + p.z * m[1][2]) / TPE_FRACTIONS_PER_UNIT;
  1359. point->z = (p.x * m[2][0] + p.y * m[2][1] + p.z * m[2][2]) / TPE_FRACTIONS_PER_UNIT;
  1360. #endif
  1361. }
  1362. TPE_Vec4 TPE_quaternionConjugate(TPE_Vec4 quaternion)
  1363. {
  1364. quaternion.x *= -1;
  1365. quaternion.y *= -1;
  1366. quaternion.z *= -1;
  1367. return quaternion;
  1368. }
  1369. TPE_Vec4 TPE_vec3Normalized(TPE_Vec4 v)
  1370. {
  1371. TPE_vec3Normalize(&v);
  1372. return v;
  1373. }
  1374. TPE_Vec4 TPE_lineSegmentClosestPoint(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 p)
  1375. {
  1376. TPE_Vec4 ab = TPE_vec3Minus(b,a);
  1377. TPE_Unit t = ((TPE_vec3DotProduct(ab,TPE_vec3Minus(p,a)) *
  1378. TPE_FRACTIONS_PER_UNIT) / TPE_nonZero(TPE_vec3DotProduct(ab,ab)));
  1379. if (t < 0)
  1380. t = 0;
  1381. else if (t > TPE_FRACTIONS_PER_UNIT)
  1382. t = TPE_FRACTIONS_PER_UNIT;
  1383. TPE_vec3Multiply(ab,t,&ab);
  1384. return TPE_vec3Plus(a,ab);
  1385. }
  1386. TPE_Unit TPE_bodyGetKineticEnergy(const TPE_Body *body)
  1387. {
  1388. TPE_Unit v = TPE_vec3Len(body->velocity);
  1389. v *= v;
  1390. v = (v == 0 || v >= TPE_FRACTIONS_PER_UNIT) ?
  1391. v / TPE_FRACTIONS_PER_UNIT : 1;
  1392. // TODO: handle small values
  1393. return (body->mass * v) /
  1394. (2 * TPE_FRACTIONS_PER_UNIT);
  1395. // TODO: rot
  1396. }
  1397. TPE_Unit TPE_bodyGetMaxExtent(const TPE_Body *body)
  1398. {
  1399. switch (body->shape)
  1400. {
  1401. case TPE_SHAPE_SPHERE:
  1402. return body->shapeParams[0];
  1403. break;
  1404. case TPE_SHAPE_CUBOID:
  1405. return TPE_vec3Len(TPE_vec4(
  1406. body->shapeParams[0] / 2,
  1407. body->shapeParams[1] / 2,
  1408. body->shapeParams[2] / 2,0));
  1409. break;
  1410. // TODO: other shapes
  1411. default: return 0; break;
  1412. }
  1413. }
  1414. void TPE_bodyRecomputeBounds(TPE_Body *body)
  1415. {
  1416. body->boundingSphereRadius = TPE_bodyGetMaxExtent(body);
  1417. }
  1418. #endif // guard