tinyphysicsengine.h 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222
  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. // anti-vibration constants:
  57. #define TPE_ANTI_VIBRATION_MAX_FRAMES 100
  58. #define TPE_ANTI_VIBRATION_INCREMENT 20
  59. #define TPE_ANTI_VIBRATION_VELOCITY_BREAK 60
  60. TPE_Unit TPE_wrap(TPE_Unit value, TPE_Unit mod);
  61. TPE_Unit TPE_clamp(TPE_Unit v, TPE_Unit v1, TPE_Unit v2);
  62. static inline TPE_Unit TPE_abs(TPE_Unit x);
  63. static inline TPE_Unit TPE_nonZero(TPE_Unit x);
  64. /** Returns an integer square root of given value. */
  65. TPE_Unit TPE_sqrt(TPE_Unit value);
  66. /** Multiplies two values (with normalization) so that the result is 0 only if
  67. one or both values are zero. */
  68. TPE_Unit TPE_timesAntiZero(TPE_Unit a, TPE_Unit b);
  69. /** Returns a sine of given arguments, both in TPE_Units (see the library
  70. conventions). */
  71. TPE_Unit TPE_sin(TPE_Unit x);
  72. TPE_Unit TPE_cos(TPE_Unit x);
  73. TPE_Unit TPE_asin(TPE_Unit x);
  74. TPE_Unit TPE_acos(TPE_Unit x);
  75. int8_t TPE_sign(TPE_Unit x);
  76. typedef struct
  77. {
  78. TPE_Unit x;
  79. TPE_Unit y;
  80. TPE_Unit z;
  81. TPE_Unit w;
  82. } TPE_Vec4;
  83. #define TPE_PRINTF_VEC4(v) printf("[%d %d %d %d] ",(v).x,(v).y,(v).z,(v).w);
  84. /** Initializes vec4 to a zero vector. */
  85. void TPE_initVec4(TPE_Vec4 *v);
  86. void TPE_vec4Set(TPE_Vec4 *v, TPE_Unit x, TPE_Unit y, TPE_Unit z, TPE_Unit w);
  87. void TPE_vec3Add(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  88. void TPE_vec4Add(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  89. void TPE_vec3Substract(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  90. void TPE_vec3Average(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  91. void TPE_vec4Substract(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  92. void TPE_vec3Multiply(TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result);
  93. void TPE_vec3MultiplyPlain(TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result);
  94. void TPE_vec4Multiply(TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result);
  95. void TPE_vec3CrossProduct(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  96. void TPE_vec3Normalize(TPE_Vec4 *v);
  97. void TPE_vec4Normalize(TPE_Vec4 *v);
  98. void TPE_vec3Project(TPE_Vec4 v, TPE_Vec4 base, TPE_Vec4 *result);
  99. TPE_Unit TPE_vec3Len(TPE_Vec4 v);
  100. TPE_Unit TPE_vec3LenTaxicab(TPE_Vec4 v);
  101. TPE_Unit TPE_vec3Dist(TPE_Vec4 a, TPE_Vec4 b);
  102. TPE_Unit TPE_vec4Len(TPE_Vec4 v);
  103. TPE_Unit TPE_vec3DotProduct(TPE_Vec4 v1, TPE_Vec4 v2);
  104. TPE_Unit TPE_vec3DotProductPlain(TPE_Vec4 v1, TPE_Vec4 v2);
  105. TPE_Vec4 TPE_vec4(TPE_Unit x, TPE_Unit y, TPE_Unit z, TPE_Unit w);
  106. TPE_Vec4 TPE_vec3Plus(TPE_Vec4 a, TPE_Vec4 b);
  107. TPE_Vec4 TPE_vec3Minus(TPE_Vec4 a, TPE_Vec4 b);
  108. TPE_Vec4 TPE_vec3Times(TPE_Vec4 a, TPE_Unit f);
  109. TPE_Vec4 TPE_vec3TimesAntiZero(TPE_Vec4 a, TPE_Unit f);
  110. TPE_Vec4 TPE_vec3Cross(TPE_Vec4 a, TPE_Vec4 b);
  111. static inline TPE_Vec4 TPE_vec3Normalized(TPE_Vec4 v);
  112. static inline TPE_Vec4 TPE_vec3Projected(TPE_Vec4 v, TPE_Vec4 base);
  113. /** Returns the closest point on given line segment (a,b) to given point (p). */
  114. TPE_Vec4 TPE_lineSegmentClosestPoint(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 p);
  115. /** Converts a linear velocity of an orbiting point to the angular velocity
  116. (angle units per time units). This depends on the distance of the point from
  117. the center of rotation. */
  118. TPE_Unit TPE_linearVelocityToAngular(TPE_Unit velocity, TPE_Unit distance);
  119. /** Performs the opposite conversion of TPE_linearVelocityToAngular. */
  120. TPE_Unit TPE_angularVelocityToLinear(TPE_Unit velocity, TPE_Unit distance);
  121. /** Holds a rotation state around a single axis, in a way that prevents rounding
  122. errors from distorting the rotation over time. In theory rotation of a body
  123. could be represented as
  124. [current orientation, axis of rotation, angular velocity]
  125. However applying the rotation and normalizing the orientation quaternion each
  126. simulation step leads to error cumulation and the rotation gets aligned with
  127. one principal axis after some time. Because of this we rather represent the
  128. rotation state as
  129. [original orientation, axis of rotation, angular velocity, current angle]
  130. From this we can at each simulation step compute the current orientation by
  131. applying rotation by current angle to the original rotation without error
  132. cumulation. */
  133. typedef struct
  134. {
  135. TPE_Vec4 originalOrientation; /**< quaternion holding the original
  136. orientation of the body at the time when it
  137. has taken on this rotational state */
  138. TPE_Vec4 axisVelocity; /**< axis of rotation (x,y,z) and a
  139. non-negative angular velocity around this
  140. axis (w), determined ny the right hand
  141. rule */
  142. TPE_Unit currentAngle; /**< angle the body has already rotated along
  143. the rotation axis (from the original
  144. orientation) */
  145. } TPE_RotationState;
  146. /** Represents a physical rigid body that has certain attributes such as a
  147. specific shape or mass. */
  148. typedef struct
  149. {
  150. uint8_t shape;
  151. TPE_Unit shapeParams[TPE_MAX_SHAPE_PARAMS]; ///< parameters of the body type
  152. void *shapeParamPointers[TPE_MAX_SHAPE_PARAMPOINTERS]; ///< pointer parameters
  153. uint8_t flags;
  154. TPE_Unit mass; /**< body mass, setting this to TPE_INFINITY will
  155. make the object static (not moving at all)
  156. which may help performance */
  157. TPE_Vec4 position; ///< position of the body's center of mass
  158. TPE_Vec4 velocity; ///< linear velocity vector
  159. TPE_RotationState rotation; /**< holds the state related to rotation, i.e.
  160. the rotation axis, angular momentum and data
  161. from which current orientation can be
  162. inferred */
  163. TPE_Unit boundingSphereRadius;
  164. uint8_t antiVibration;
  165. } TPE_Body;
  166. /** Initializes a physical body, this should be called on all TPE_Body objects
  167. that are created.*/
  168. void TPE_bodyInit(TPE_Body *body);
  169. /** Recomputes the body bounding sphere, must be called every time the body's
  170. shape parameters change. */
  171. void TPE_bodyRecomputeBounds(TPE_Body *body);
  172. /** Computes a 4x4 transform matrix of given body. The matrix has the same
  173. format as S3L_Mat4 from small3dlib. */
  174. void TPE_bodyGetTransformMatrix(const TPE_Body *body, TPE_Unit matrix[4][4]);
  175. /** Gets the current orientation of a body as a quaternion. */
  176. TPE_Vec4 TPE_bodyGetOrientation(const TPE_Body *body);
  177. /** Multiplies the body's kinetic energy, i.e. changes its linear and angular
  178. velocity. */
  179. void TPE_bodyMultiplyKineticEnergy(TPE_Body *body, TPE_Unit f);
  180. void TPE_bodySetOrientation(TPE_Body *body, TPE_Vec4 orientation);
  181. /** Updates the body position and rotation according to its current velocity
  182. and rotation state. */
  183. void TPE_bodyStep(TPE_Body *body);
  184. /** Sets the rotation state of a body as an axis of rotation and angular
  185. velocity around this axis. */
  186. void TPE_bodySetRotation(TPE_Body *body, TPE_Vec4 axis, TPE_Unit velocity);
  187. /** Adds a rotation to the current rotation of a body. This addition is perfomed
  188. as a vector addition of the current and new rotation represented as vectors
  189. whose direction is the rotation axis and magnitude is the angular velocity
  190. around that axis. */
  191. void TPE_bodyAddRotation(TPE_Body *body, TPE_Vec4 axis, TPE_Unit velocity);
  192. /** Applies impulse (force in short time) to a body at a specified point
  193. (relative to its center), which will potentially change its linear and/or
  194. angular velocity. */
  195. void TPE_bodyApplyImpulse(TPE_Body *body, TPE_Vec4 point, TPE_Vec4 impulse);
  196. void TPE_attractBodies(TPE_Body *body1, TPE_Body *body2, TPE_Unit acceleration);
  197. /** Computes and returns a body's bounding sphere radius, i.e. the maximum
  198. extent from its center point. */
  199. TPE_Unit TPE_bodyGetMaxExtent(const TPE_Body *body);
  200. /** Computes and returns a body's total kinetic energy (sum of linear and
  201. rotational kin. energy). In rotating bodies this may not be physically
  202. accurate as, for simplicity, we operate with the moment of inertia of sphere
  203. for all bodies (when in reality moment of inertia depends on shape). */
  204. TPE_Unit TPE_bodyGetKineticEnergy(const TPE_Body *body);
  205. /** Attempts to correct rounding errors in the total energy of a system of two
  206. bodies after collision, given the initial energy and desired restitution
  207. (fraction of energy that should remain after the collision). */
  208. void TPE_correctEnergies(TPE_Body *body1, TPE_Body *body2,
  209. TPE_Unit previousEnergy, TPE_Unit restitution);
  210. /** Collision detection: checks if two bodies are colliding. The return value is
  211. the collision depth along the collision normal (0 if the bodies are not
  212. colliding). World-space collision point is returned via a pointer. Collision
  213. normal (normalized) is also returned via a pointer and its direction is
  214. "away from body1", i.e. if you move body1 in the opposite direction of this
  215. normal by the collision depth (return value), the bodies should no longer
  216. exhibit this particular collision. This function checks the bounding spheres
  217. to quickly opt out of impossible collisions. */
  218. TPE_Unit TPE_bodyCollides(const TPE_Body *body1, const TPE_Body *body2,
  219. TPE_Vec4 *collisionPoint, TPE_Vec4 *collisionNormal);
  220. /** Gets a velocity of a single point on a rigid body, taking into account its
  221. linear velocity and rotation. The point coordinates are relative to the body
  222. center. The point does NOT have to be on the surface, it can be inside and
  223. even outside the body too. */
  224. TPE_Vec4 TPE_bodyGetPointVelocity(const TPE_Body *body, TPE_Vec4 point);
  225. void TPE_resolveCollision(TPE_Body *body1 ,TPE_Body *body2,
  226. TPE_Vec4 collisionPoint, TPE_Vec4 collisionNormal, TPE_Unit collisionDepth,
  227. TPE_Unit energyMultiplier);
  228. /** Gets a uint16_t integer type of collision depending on two shapes, the order
  229. of shapes doesn't matter. */
  230. #define TPE_COLLISION_TYPE(shape1,shape2) \
  231. ((shape1) <= (shape2) ? \
  232. (((uint16_t) (shape1)) << 8) | (shape2) : \
  233. (((uint16_t) (shape2)) << 8) | (shape1))
  234. /** Represents a world consisting of physics bodies. */
  235. typedef struct
  236. {
  237. TPE_Body *bodies; ///< array of bodies
  238. uint16_t bodyCount; ///< length of the body array
  239. } TPE_World;
  240. void TPE_worldInit(TPE_World *world);
  241. void TPE_worldStepBodies(TPE_World *world);
  242. void TPE_worldApplyGravityDown(TPE_World *world, TPE_Unit g);
  243. void TPE_worldApplyGravityCenter(TPE_World *world, TPE_Vec4 center, TPE_Unit g);
  244. void TPE_worldResolveCollisionNaive(TPE_World *world);
  245. /** Multiplies two quaternions which can be seen as chaining two rotations
  246. represented by them. This is not commutative (a*b != b*a)! Rotations a is
  247. performed firth, then rotation b is performed. */
  248. void TPE_quaternionMultiply(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  249. /** Initializes quaternion to the rotation identity (i.e. NOT zero
  250. quaternion). */
  251. void TPE_quaternionInit(TPE_Vec4 *quaternion);
  252. /** Converts a rotation given as an axis and angle around this axis (by right
  253. hand rule) to a rotation quaternion. */
  254. void TPE_rotationToQuaternion(TPE_Vec4 axis, TPE_Unit angle,
  255. TPE_Vec4 *quaternion);
  256. void TPE_quaternionToRotation(TPE_Vec4 quaternion, TPE_Vec4 *axis,
  257. TPE_Unit *angle);
  258. /** Computes the conjugate of a quaternion (analogous to matrix inversion, the
  259. quaternion will represent the opposite rotation). */
  260. TPE_Vec4 TPE_quaternionConjugate(TPE_Vec4 quaternion);
  261. /** Converts a rotation quaternion to a 4x4 rotation matrix. The matrix is
  262. indexed as [column][row] and is in the same format as S3L_Mat4 from
  263. small3dlib. */
  264. void TPE_quaternionToRotationMatrix(TPE_Vec4 quaternion, TPE_Unit matrix[4][4]);
  265. void TPE_rotatePoint(TPE_Vec4 *point, TPE_Vec4 quaternion);
  266. TPE_Vec4 TPE_createVecFromTo(TPE_Vec4 pointFrom, TPE_Vec4 pointTo,
  267. TPE_Unit size);
  268. void TPE_getVelocitiesAfterCollision(
  269. TPE_Unit *v1,
  270. TPE_Unit *v2,
  271. TPE_Unit m1,
  272. TPE_Unit m2,
  273. TPE_Unit elasticity
  274. );
  275. //------------------------------------------------------------------------------
  276. void TPE_initVec4(TPE_Vec4 *v)
  277. {
  278. v->x = 0;
  279. v->y = 0;
  280. v->z = 0;
  281. v->w = 0;
  282. }
  283. TPE_Vec4 TPE_vec4(TPE_Unit x, TPE_Unit y, TPE_Unit z, TPE_Unit w)
  284. {
  285. TPE_Vec4 r;
  286. r.x = x;
  287. r.y = y;
  288. r.z = z;
  289. r.w = w;
  290. return r;
  291. }
  292. void TPE_vec4Set(TPE_Vec4 *v, TPE_Unit x, TPE_Unit y, TPE_Unit z, TPE_Unit w)
  293. {
  294. v->x = x;
  295. v->y = y;
  296. v->z = z;
  297. v->w = w;
  298. }
  299. TPE_Unit TPE_wrap(TPE_Unit value, TPE_Unit mod)
  300. {
  301. return value >= 0 ? (value % mod) : (mod + (value % mod) - 1);
  302. }
  303. TPE_Unit TPE_clamp(TPE_Unit v, TPE_Unit v1, TPE_Unit v2)
  304. {
  305. return v >= v1 ? (v <= v2 ? v : v2) : v1;
  306. }
  307. TPE_Unit TPE_nonZero(TPE_Unit x)
  308. {
  309. return x + (x == 0);
  310. }
  311. #define TPE_SIN_TABLE_LENGTH 128
  312. static const TPE_Unit TPE_sinTable[TPE_SIN_TABLE_LENGTH] =
  313. {
  314. /* 511 was chosen here as a highest number that doesn't overflow during
  315. compilation for TPE_FRACTIONS_PER_UNIT == 1024 */
  316. (0*TPE_FRACTIONS_PER_UNIT)/511, (6*TPE_FRACTIONS_PER_UNIT)/511,
  317. (12*TPE_FRACTIONS_PER_UNIT)/511, (18*TPE_FRACTIONS_PER_UNIT)/511,
  318. (25*TPE_FRACTIONS_PER_UNIT)/511, (31*TPE_FRACTIONS_PER_UNIT)/511,
  319. (37*TPE_FRACTIONS_PER_UNIT)/511, (43*TPE_FRACTIONS_PER_UNIT)/511,
  320. (50*TPE_FRACTIONS_PER_UNIT)/511, (56*TPE_FRACTIONS_PER_UNIT)/511,
  321. (62*TPE_FRACTIONS_PER_UNIT)/511, (68*TPE_FRACTIONS_PER_UNIT)/511,
  322. (74*TPE_FRACTIONS_PER_UNIT)/511, (81*TPE_FRACTIONS_PER_UNIT)/511,
  323. (87*TPE_FRACTIONS_PER_UNIT)/511, (93*TPE_FRACTIONS_PER_UNIT)/511,
  324. (99*TPE_FRACTIONS_PER_UNIT)/511, (105*TPE_FRACTIONS_PER_UNIT)/511,
  325. (111*TPE_FRACTIONS_PER_UNIT)/511, (118*TPE_FRACTIONS_PER_UNIT)/511,
  326. (124*TPE_FRACTIONS_PER_UNIT)/511, (130*TPE_FRACTIONS_PER_UNIT)/511,
  327. (136*TPE_FRACTIONS_PER_UNIT)/511, (142*TPE_FRACTIONS_PER_UNIT)/511,
  328. (148*TPE_FRACTIONS_PER_UNIT)/511, (154*TPE_FRACTIONS_PER_UNIT)/511,
  329. (160*TPE_FRACTIONS_PER_UNIT)/511, (166*TPE_FRACTIONS_PER_UNIT)/511,
  330. (172*TPE_FRACTIONS_PER_UNIT)/511, (178*TPE_FRACTIONS_PER_UNIT)/511,
  331. (183*TPE_FRACTIONS_PER_UNIT)/511, (189*TPE_FRACTIONS_PER_UNIT)/511,
  332. (195*TPE_FRACTIONS_PER_UNIT)/511, (201*TPE_FRACTIONS_PER_UNIT)/511,
  333. (207*TPE_FRACTIONS_PER_UNIT)/511, (212*TPE_FRACTIONS_PER_UNIT)/511,
  334. (218*TPE_FRACTIONS_PER_UNIT)/511, (224*TPE_FRACTIONS_PER_UNIT)/511,
  335. (229*TPE_FRACTIONS_PER_UNIT)/511, (235*TPE_FRACTIONS_PER_UNIT)/511,
  336. (240*TPE_FRACTIONS_PER_UNIT)/511, (246*TPE_FRACTIONS_PER_UNIT)/511,
  337. (251*TPE_FRACTIONS_PER_UNIT)/511, (257*TPE_FRACTIONS_PER_UNIT)/511,
  338. (262*TPE_FRACTIONS_PER_UNIT)/511, (268*TPE_FRACTIONS_PER_UNIT)/511,
  339. (273*TPE_FRACTIONS_PER_UNIT)/511, (278*TPE_FRACTIONS_PER_UNIT)/511,
  340. (283*TPE_FRACTIONS_PER_UNIT)/511, (289*TPE_FRACTIONS_PER_UNIT)/511,
  341. (294*TPE_FRACTIONS_PER_UNIT)/511, (299*TPE_FRACTIONS_PER_UNIT)/511,
  342. (304*TPE_FRACTIONS_PER_UNIT)/511, (309*TPE_FRACTIONS_PER_UNIT)/511,
  343. (314*TPE_FRACTIONS_PER_UNIT)/511, (319*TPE_FRACTIONS_PER_UNIT)/511,
  344. (324*TPE_FRACTIONS_PER_UNIT)/511, (328*TPE_FRACTIONS_PER_UNIT)/511,
  345. (333*TPE_FRACTIONS_PER_UNIT)/511, (338*TPE_FRACTIONS_PER_UNIT)/511,
  346. (343*TPE_FRACTIONS_PER_UNIT)/511, (347*TPE_FRACTIONS_PER_UNIT)/511,
  347. (352*TPE_FRACTIONS_PER_UNIT)/511, (356*TPE_FRACTIONS_PER_UNIT)/511,
  348. (361*TPE_FRACTIONS_PER_UNIT)/511, (365*TPE_FRACTIONS_PER_UNIT)/511,
  349. (370*TPE_FRACTIONS_PER_UNIT)/511, (374*TPE_FRACTIONS_PER_UNIT)/511,
  350. (378*TPE_FRACTIONS_PER_UNIT)/511, (382*TPE_FRACTIONS_PER_UNIT)/511,
  351. (386*TPE_FRACTIONS_PER_UNIT)/511, (391*TPE_FRACTIONS_PER_UNIT)/511,
  352. (395*TPE_FRACTIONS_PER_UNIT)/511, (398*TPE_FRACTIONS_PER_UNIT)/511,
  353. (402*TPE_FRACTIONS_PER_UNIT)/511, (406*TPE_FRACTIONS_PER_UNIT)/511,
  354. (410*TPE_FRACTIONS_PER_UNIT)/511, (414*TPE_FRACTIONS_PER_UNIT)/511,
  355. (417*TPE_FRACTIONS_PER_UNIT)/511, (421*TPE_FRACTIONS_PER_UNIT)/511,
  356. (424*TPE_FRACTIONS_PER_UNIT)/511, (428*TPE_FRACTIONS_PER_UNIT)/511,
  357. (431*TPE_FRACTIONS_PER_UNIT)/511, (435*TPE_FRACTIONS_PER_UNIT)/511,
  358. (438*TPE_FRACTIONS_PER_UNIT)/511, (441*TPE_FRACTIONS_PER_UNIT)/511,
  359. (444*TPE_FRACTIONS_PER_UNIT)/511, (447*TPE_FRACTIONS_PER_UNIT)/511,
  360. (450*TPE_FRACTIONS_PER_UNIT)/511, (453*TPE_FRACTIONS_PER_UNIT)/511,
  361. (456*TPE_FRACTIONS_PER_UNIT)/511, (459*TPE_FRACTIONS_PER_UNIT)/511,
  362. (461*TPE_FRACTIONS_PER_UNIT)/511, (464*TPE_FRACTIONS_PER_UNIT)/511,
  363. (467*TPE_FRACTIONS_PER_UNIT)/511, (469*TPE_FRACTIONS_PER_UNIT)/511,
  364. (472*TPE_FRACTIONS_PER_UNIT)/511, (474*TPE_FRACTIONS_PER_UNIT)/511,
  365. (476*TPE_FRACTIONS_PER_UNIT)/511, (478*TPE_FRACTIONS_PER_UNIT)/511,
  366. (481*TPE_FRACTIONS_PER_UNIT)/511, (483*TPE_FRACTIONS_PER_UNIT)/511,
  367. (485*TPE_FRACTIONS_PER_UNIT)/511, (487*TPE_FRACTIONS_PER_UNIT)/511,
  368. (488*TPE_FRACTIONS_PER_UNIT)/511, (490*TPE_FRACTIONS_PER_UNIT)/511,
  369. (492*TPE_FRACTIONS_PER_UNIT)/511, (494*TPE_FRACTIONS_PER_UNIT)/511,
  370. (495*TPE_FRACTIONS_PER_UNIT)/511, (497*TPE_FRACTIONS_PER_UNIT)/511,
  371. (498*TPE_FRACTIONS_PER_UNIT)/511, (499*TPE_FRACTIONS_PER_UNIT)/511,
  372. (501*TPE_FRACTIONS_PER_UNIT)/511, (502*TPE_FRACTIONS_PER_UNIT)/511,
  373. (503*TPE_FRACTIONS_PER_UNIT)/511, (504*TPE_FRACTIONS_PER_UNIT)/511,
  374. (505*TPE_FRACTIONS_PER_UNIT)/511, (506*TPE_FRACTIONS_PER_UNIT)/511,
  375. (507*TPE_FRACTIONS_PER_UNIT)/511, (507*TPE_FRACTIONS_PER_UNIT)/511,
  376. (508*TPE_FRACTIONS_PER_UNIT)/511, (509*TPE_FRACTIONS_PER_UNIT)/511,
  377. (509*TPE_FRACTIONS_PER_UNIT)/511, (510*TPE_FRACTIONS_PER_UNIT)/511,
  378. (510*TPE_FRACTIONS_PER_UNIT)/511, (510*TPE_FRACTIONS_PER_UNIT)/511,
  379. (510*TPE_FRACTIONS_PER_UNIT)/511, (510*TPE_FRACTIONS_PER_UNIT)/511
  380. };
  381. #define TPE_SIN_TABLE_UNIT_STEP\
  382. (TPE_FRACTIONS_PER_UNIT / (TPE_SIN_TABLE_LENGTH * 4))
  383. TPE_Unit TPE_sqrt(TPE_Unit value)
  384. {
  385. int8_t sign = 1;
  386. if (value < 0)
  387. {
  388. sign = -1;
  389. value *= -1;
  390. }
  391. uint32_t result = 0;
  392. uint32_t a = value;
  393. uint32_t b = 1u << 30;
  394. while (b > a)
  395. b >>= 2;
  396. while (b != 0)
  397. {
  398. if (a >= result + b)
  399. {
  400. a -= result + b;
  401. result = result + 2 * b;
  402. }
  403. b >>= 2;
  404. result >>= 1;
  405. }
  406. return result * sign;
  407. }
  408. TPE_Unit TPE_sin(TPE_Unit x)
  409. {
  410. x = TPE_wrap(x / TPE_SIN_TABLE_UNIT_STEP,TPE_SIN_TABLE_LENGTH * 4);
  411. int8_t positive = 1;
  412. if (x < TPE_SIN_TABLE_LENGTH)
  413. {
  414. }
  415. else if (x < TPE_SIN_TABLE_LENGTH * 2)
  416. {
  417. x = TPE_SIN_TABLE_LENGTH * 2 - x - 1;
  418. }
  419. else if (x < TPE_SIN_TABLE_LENGTH * 3)
  420. {
  421. x = x - TPE_SIN_TABLE_LENGTH * 2;
  422. positive = 0;
  423. }
  424. else
  425. {
  426. x = TPE_SIN_TABLE_LENGTH - (x - TPE_SIN_TABLE_LENGTH * 3) - 1;
  427. positive = 0;
  428. }
  429. return positive ? TPE_sinTable[x] : -1 * TPE_sinTable[x];
  430. }
  431. TPE_Unit TPE_cos(TPE_Unit x)
  432. {
  433. return TPE_sin(x + TPE_FRACTIONS_PER_UNIT / 4);
  434. }
  435. void TPE_bodyInit(TPE_Body *body)
  436. {
  437. // TODO
  438. TPE_initVec4(&(body->position));
  439. TPE_initVec4(&(body->velocity));
  440. // init orientation to identity unit quaternion (1,0,0,0):
  441. TPE_quaternionInit(&(body->rotation.originalOrientation));
  442. TPE_vec4Set(&(body->rotation.axisVelocity),TPE_FRACTIONS_PER_UNIT,0,0,0);
  443. body->rotation.currentAngle = 0;
  444. body->mass = TPE_FRACTIONS_PER_UNIT;
  445. body->boundingSphereRadius = 0;
  446. body->antiVibration = 0;
  447. }
  448. void TPE_bodySetOrientation(TPE_Body *body, TPE_Vec4 orientation)
  449. {
  450. body->rotation.originalOrientation = orientation;
  451. body->rotation.currentAngle = 0;
  452. }
  453. TPE_Vec4 TPE_bodyGetOrientation(const TPE_Body *body)
  454. {
  455. TPE_Vec4 axisRotation, result;
  456. TPE_rotationToQuaternion(
  457. body->rotation.axisVelocity,
  458. body->rotation.currentAngle,
  459. &axisRotation);
  460. TPE_quaternionMultiply(
  461. body->rotation.originalOrientation,
  462. axisRotation,
  463. &result);
  464. TPE_vec4Normalize(&result);
  465. return result;
  466. }
  467. void TPE_vec3CrossProduct(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result)
  468. {
  469. TPE_Vec4 r;
  470. r.x = (a.y * b.z - a.z * b.y) / TPE_FRACTIONS_PER_UNIT;
  471. r.y = (a.z * b.x - a.x * b.z) / TPE_FRACTIONS_PER_UNIT;
  472. r.z = (a.x * b.y - a.y * b.x) / TPE_FRACTIONS_PER_UNIT;
  473. *result = r;
  474. }
  475. TPE_Vec4 TPE_vec3Cross(TPE_Vec4 a, TPE_Vec4 b)
  476. {
  477. TPE_vec3CrossProduct(a,b,&a);
  478. return a;
  479. }
  480. void TPE_bodyApplyImpulse(TPE_Body *body, TPE_Vec4 point, TPE_Vec4 impulse)
  481. {
  482. TPE_Unit pointDistance = TPE_vec3Len(point);
  483. if (pointDistance != 0)
  484. {
  485. impulse.x = (impulse.x * TPE_FRACTIONS_PER_UNIT) / body->mass;
  486. impulse.y = (impulse.y * TPE_FRACTIONS_PER_UNIT) / body->mass;
  487. impulse.z = (impulse.z * TPE_FRACTIONS_PER_UNIT) / body->mass;
  488. TPE_vec3Add(body->velocity,impulse,&(body->velocity));
  489. /* normalize the point, we don't use the function as we don't want to
  490. recompute the vector length */
  491. point.x = (point.x * TPE_FRACTIONS_PER_UNIT) / pointDistance;
  492. point.y = (point.y * TPE_FRACTIONS_PER_UNIT) / pointDistance;
  493. point.z = (point.z * TPE_FRACTIONS_PER_UNIT) / pointDistance;
  494. /* for simplicity we'll suppose angular momentum of a sphere: */
  495. impulse = TPE_vec3Cross(impulse,point);
  496. TPE_Unit r = TPE_bodyGetMaxExtent(body);
  497. r = TPE_nonZero((2 * r * r) / TPE_FRACTIONS_PER_UNIT);
  498. TPE_Vec4 tmp = impulse;
  499. impulse.x = (impulse.x * 5 * TPE_FRACTIONS_PER_UNIT) / r;
  500. impulse.y = (impulse.y * 5 * TPE_FRACTIONS_PER_UNIT) / r;
  501. impulse.z = (impulse.z * 5 * TPE_FRACTIONS_PER_UNIT) / r;
  502. if (impulse.x == 0 &&
  503. impulse.y == 0 &&
  504. impulse.z == 0 &&
  505. (
  506. tmp.x != 0 ||
  507. tmp.y != 0 ||
  508. tmp.z != 0
  509. ))
  510. {
  511. impulse.x = TPE_sign(tmp.x);
  512. impulse.y = TPE_sign(tmp.y);
  513. impulse.z = TPE_sign(tmp.z);
  514. }
  515. /*
  516. impulse.x = (impulse.x * 5 * TPE_FRACTIONS_PER_UNIT) / r;
  517. impulse.y = (impulse.y * 5 * TPE_FRACTIONS_PER_UNIT) / r;
  518. impulse.z = (impulse.z * 5 * TPE_FRACTIONS_PER_UNIT) / r;
  519. */
  520. TPE_bodyAddRotation(body,impulse,TPE_vec3Len(impulse));
  521. }
  522. }
  523. void _TPE_getShapes(const TPE_Body *b1, const TPE_Body *b2, uint8_t shape1,
  524. const TPE_Body **first, const TPE_Body **second)
  525. {
  526. if (b1->shape == shape1)
  527. {
  528. *first = b1;
  529. *second = b2;
  530. }
  531. else
  532. {
  533. *first = b2;
  534. *second = b1;
  535. }
  536. }
  537. void _TPE_getCapsuleCyllinderEndpoints(const TPE_Body *body,
  538. TPE_Vec4 *a, TPE_Vec4 *b)
  539. {
  540. TPE_Vec4 quat = TPE_bodyGetOrientation(body);
  541. *a = TPE_vec4(0,body->shapeParams[1] / 2,0,0);
  542. *b = TPE_vec4(0,-1 * a->y,0,0);
  543. TPE_rotatePoint(a,quat);
  544. TPE_rotatePoint(b,quat);
  545. TPE_vec3Add(*a,body->position,a);
  546. TPE_vec3Add(*b,body->position,b);
  547. }
  548. /** Helpter function for cuboid collision detection. Given a line segment
  549. as a line equation limited by parameter bounds t1 and t2, center point C and
  550. side offset from the center point O, the function further limits the parameter
  551. bounds (t1, t2) to restrict the line only to the region between two planes:
  552. both with normal O, one passing throung point C + O and the other through
  553. C - O. If t2 > t1 after this function finishes, the line segment is completely
  554. outside the region. */
  555. void _TPE_cutLineSegmentByPlanes(TPE_Vec4 center, TPE_Vec4 sideOffset,
  556. TPE_Vec4 lineStart, TPE_Vec4 lineDir, TPE_Unit *t1, TPE_Unit *t2)
  557. {
  558. // we shift the center to [0,0,0] to simplify and prevent overflows
  559. lineStart = TPE_vec3Minus(lineStart,center);
  560. //center = TPE_vec4(0,0,0,0);
  561. TPE_Unit da = TPE_vec3DotProductPlain(sideOffset,lineStart);
  562. TPE_Vec4 dc;
  563. dc.z = 0;
  564. // TODO: dot(d,dc) could be cached for all sides between calls to save recomputing
  565. dc = sideOffset;
  566. TPE_Unit denom = TPE_nonZero(TPE_vec3DotProductPlain(sideOffset,lineDir));
  567. #define tAntiOverflow(t) \
  568. TPE_Unit t = TPE_vec3DotProductPlain(sideOffset,dc) - da;\
  569. t = (TPE_abs(t) < 500000) ? (t * TPE_FRACTIONS_PER_UNIT) / denom :\
  570. (((t / 64) * TPE_FRACTIONS_PER_UNIT) / TPE_nonZero(denom / 64));
  571. tAntiOverflow(tA)
  572. TPE_vec3MultiplyPlain(sideOffset,-1,&dc);
  573. tAntiOverflow(tB)
  574. #undef tAntiOverflow
  575. if (tB < tA)
  576. {
  577. TPE_Unit tmp = tA;
  578. tA = tB;
  579. tB = tmp;
  580. }
  581. if (tA > *t1)
  582. *t1 = tA;
  583. if (tB < *t2)
  584. *t2 = tB;
  585. }
  586. TPE_Unit TPE_bodyCollides(const TPE_Body *body1, const TPE_Body *body2,
  587. TPE_Vec4 *collisionPoint, TPE_Vec4 *collisionNormal)
  588. {
  589. // handle collision of different shapes each in a specific case:
  590. uint16_t collType = TPE_COLLISION_TYPE(body1->shape,body2->shape);
  591. if (collType != TPE_COLLISION_TYPE(TPE_SHAPE_SPHERE,TPE_SHAPE_SPHERE))
  592. {
  593. /* initial bounding sphere check to quickly discard impossible collisions,
  594. plus this also prevents overflow errors in long-distance computations */
  595. // TODO: taxicab could be also considered here
  596. if (TPE_vec3Len(TPE_vec3Minus(body1->position,body2->position)) >
  597. body1->boundingSphereRadius + body2->boundingSphereRadius)
  598. return 0;
  599. }
  600. switch (TPE_COLLISION_TYPE(body1->shape,body2->shape))
  601. {
  602. case TPE_COLLISION_TYPE(TPE_SHAPE_SPHERE,TPE_SHAPE_SPHERE):
  603. {
  604. TPE_Vec4 distanceVec;
  605. TPE_vec3Substract(body2->position,body1->position,&distanceVec);
  606. TPE_Unit distance = TPE_vec3Len(distanceVec);
  607. distance -= body1->shapeParams[0] + body2->shapeParams[0];
  608. if (distance < 0)
  609. {
  610. TPE_vec3Average(body1->position,body2->position,collisionPoint);
  611. *collisionNormal = distanceVec;
  612. TPE_vec3Normalize(collisionNormal);
  613. return -1 * distance;
  614. }
  615. break;
  616. }
  617. case TPE_COLLISION_TYPE(TPE_SHAPE_SPHERE,TPE_SHAPE_CAPSULE):
  618. {
  619. const TPE_Body *sphere;
  620. const TPE_Body *capsule;
  621. _TPE_getShapes(body1,body2,TPE_SHAPE_SPHERE,&sphere,&capsule);
  622. TPE_Vec4 cA, cB;
  623. _TPE_getCapsuleCyllinderEndpoints(capsule,&cA,&cB);
  624. TPE_Body sphere2; // sphere at the capsule's closest point
  625. TPE_bodyInit(&sphere2);
  626. sphere2.shape = TPE_SHAPE_SPHERE;
  627. sphere2.shapeParams[0] = capsule->shapeParams[0];
  628. sphere2.position = TPE_lineSegmentClosestPoint(cA,cB,sphere->position);
  629. uint8_t swap = sphere == body2;
  630. return TPE_bodyCollides(swap ? &sphere2 : sphere,swap ? sphere : &sphere2,
  631. collisionPoint,collisionNormal);
  632. break;
  633. }
  634. case TPE_COLLISION_TYPE(TPE_SHAPE_CAPSULE,TPE_SHAPE_CAPSULE):
  635. {
  636. TPE_Vec4 a1, b1, a2, b2;
  637. _TPE_getCapsuleCyllinderEndpoints(body1,&a1,&b1);
  638. _TPE_getCapsuleCyllinderEndpoints(body2,&a2,&b2);
  639. TPE_Unit aa, ab, ba, bb; // squared distances between points
  640. TPE_Vec4 tmp;
  641. tmp = TPE_vec3Minus(a1,a2);
  642. aa = tmp.x * tmp.x + tmp.y * tmp.y + tmp.z * tmp.z;
  643. tmp = TPE_vec3Minus(a1,b2);
  644. ab = tmp.x * tmp.x + tmp.y * tmp.y + tmp.z * tmp.z;
  645. tmp = TPE_vec3Minus(b1,a2);
  646. ba = tmp.x * tmp.x + tmp.y * tmp.y + tmp.z * tmp.z;
  647. tmp = TPE_vec3Minus(b1,b2);
  648. bb = tmp.x * tmp.x + tmp.y * tmp.y + tmp.z * tmp.z;
  649. // let a1 hold the point figuring in the shortest distance:
  650. if (ab < aa)
  651. aa = ab; // means: aa = min(aa,ab)
  652. if (bb < ba)
  653. ba = bb; // means: ba = min(ba,bb)
  654. if (ba < aa) // means: min(ba,bb) < min(aa,ab)
  655. a1 = b1;
  656. a2 = TPE_lineSegmentClosestPoint(a2,b2,a1);
  657. a1 = TPE_lineSegmentClosestPoint(a1,b1,a2);
  658. // now a1 and a2 are the closest two points on capsule axes
  659. TPE_Body sphere1, sphere2;
  660. TPE_bodyInit(&sphere1);
  661. sphere1.shape = TPE_SHAPE_SPHERE;
  662. sphere1.shapeParams[0] = body1->shapeParams[0];
  663. sphere1.position = a1;
  664. TPE_bodyInit(&sphere2);
  665. sphere2.shape = TPE_SHAPE_SPHERE;
  666. sphere2.shapeParams[0] = body2->shapeParams[0];
  667. sphere2.position = a2;
  668. return TPE_bodyCollides(&sphere1,&sphere2,collisionPoint,collisionNormal);
  669. break;
  670. }
  671. case TPE_COLLISION_TYPE(TPE_SHAPE_SPHERE,TPE_SHAPE_CYLINDER):
  672. {
  673. // TODO: would this be better to do via sphere-capsule collision?
  674. const TPE_Body *sphere;
  675. const TPE_Body *cylinder;
  676. _TPE_getShapes(body1,body2,TPE_SHAPE_SPHERE,&sphere,&cylinder);
  677. TPE_Vec4 sphereRelativePos = // by this we shift the cylinder to [0,0,0]
  678. TPE_vec3Minus(sphere->position,cylinder->position);
  679. // vector along the cylinder height:
  680. TPE_Vec4 cylinderAxis = TPE_vec4(0,TPE_FRACTIONS_PER_UNIT,0,0);
  681. TPE_rotatePoint(&cylinderAxis,TPE_bodyGetOrientation(cylinder));
  682. TPE_Vec4 sphereAxisPos = // sphere pos projected to the cylinder axis
  683. TPE_vec3Projected(sphereRelativePos,cylinderAxis);
  684. TPE_Unit sphereAxisDistance = TPE_vec3Len(sphereAxisPos);
  685. TPE_Unit tmp = cylinder->shapeParams[1] / 2; // half of cylinder height
  686. /* now we have three possible regions the sphere can occupy:
  687. C :B: A :B: C
  688. : :_____: :
  689. : |_____| : cylinder
  690. : : : :
  691. : : : : */
  692. if (sphereAxisDistance >= tmp + sphere->shapeParams[0]) // case C: no col.
  693. break;
  694. TPE_Vec4 sphereAxisToRelative =
  695. TPE_vec3Minus(sphereRelativePos,sphereAxisPos);
  696. TPE_Unit sphereCylinderDistance = TPE_vec3Len(sphereAxisToRelative);
  697. tmp = sphereAxisDistance - tmp;
  698. if (tmp < 0) // case A: potential collision with cylinder body
  699. {
  700. TPE_Unit penetration = cylinder->shapeParams[0]
  701. - (sphereCylinderDistance - sphere->shapeParams[0]);
  702. if (penetration > 0)
  703. {
  704. TPE_vec3Normalize(&sphereAxisToRelative);
  705. *collisionPoint = TPE_vec3Plus(cylinder->position,
  706. TPE_vec3Plus(sphereAxisPos,TPE_vec3Times(
  707. sphereAxisToRelative,cylinder->shapeParams[0])));
  708. *collisionNormal = sphereAxisToRelative;
  709. if (sphere == body1)
  710. TPE_vec3MultiplyPlain(*collisionNormal,-1,collisionNormal);
  711. return penetration;
  712. }
  713. else
  714. break;
  715. }
  716. /* case B: here we have two subcases, one with the sphere center being
  717. within the cylinder radius (collision with the cylinder top/bottom),
  718. and the other case (collision with the cylinder top/bottom edge). */
  719. TPE_Vec4 cylinderPlaneMiddle = TPE_vec3Times(
  720. TPE_vec3Normalized(sphereAxisPos),
  721. cylinder->shapeParams[1] / 2);
  722. if (sphereCylinderDistance < cylinder->shapeParams[0]) // top/bottom cap
  723. {
  724. TPE_Unit penetration = cylinder->shapeParams[1] / 2 -
  725. (sphereAxisDistance - sphere->shapeParams[0]);
  726. if (penetration <= 0) // shouldn't normally happen, but rounding errors
  727. penetration = 1;
  728. *collisionNormal = TPE_vec3Normalized(sphereAxisPos);
  729. *collisionPoint =
  730. TPE_vec3Plus(
  731. cylinder->position,
  732. TPE_vec3Plus(sphereAxisToRelative,cylinderPlaneMiddle));
  733. if (body1 == sphere)
  734. TPE_vec3MultiplyPlain(*collisionNormal,-1,collisionNormal);
  735. return penetration;
  736. }
  737. else // potential edge collision
  738. {
  739. TPE_Vec4 edgePoint = TPE_vec3Plus(cylinderPlaneMiddle,
  740. TPE_vec3Times(TPE_vec3Normalized(sphereAxisToRelative),
  741. cylinder->shapeParams[0]));
  742. TPE_Unit penetration = sphere->shapeParams[0] -
  743. TPE_vec3Dist(edgePoint,sphereRelativePos);
  744. if (penetration > 0)
  745. {
  746. *collisionPoint = TPE_vec3Plus(cylinder->position,edgePoint);
  747. *collisionNormal =
  748. TPE_vec3Normalized(TPE_vec3Minus(sphereRelativePos,edgePoint));
  749. if (body1 == sphere)
  750. TPE_vec3MultiplyPlain(*collisionNormal,-1,collisionNormal);
  751. return penetration;
  752. }
  753. }
  754. break;
  755. }
  756. case TPE_COLLISION_TYPE(TPE_SHAPE_CUBOID,TPE_SHAPE_CUBOID):
  757. {
  758. TPE_Vec4 // min/max extent of the colliding area:
  759. collisionExtentMax =
  760. TPE_vec4(-TPE_INFINITY,-TPE_INFINITY,-TPE_INFINITY,0),
  761. collisionExtentMin =
  762. TPE_vec4(TPE_INFINITY,TPE_INFINITY,TPE_INFINITY,0);
  763. uint8_t collisionHappened = 0;
  764. TPE_Vec4 aX1, aY1, aZ1, // first cuboid axes
  765. aX2, aY2, aZ2; // second cuboid axes
  766. for (uint8_t i = 0; i < 2; ++i) // for each body
  767. {
  768. TPE_Vec4 q = TPE_bodyGetOrientation(body1);
  769. // construct the cuboid axes:
  770. aX1 = TPE_vec4(body1->shapeParams[0] / 2,0,0,0);
  771. TPE_rotatePoint(&aX1,q);
  772. aY1 = TPE_vec4(0,body1->shapeParams[1] / 2,0,0);
  773. TPE_rotatePoint(&aY1,q);
  774. aZ1 = TPE_vec4(0,0,body1->shapeParams[2] / 2,0);
  775. TPE_rotatePoint(&aZ1,q);
  776. q = TPE_bodyGetOrientation(body2);
  777. aX2 = TPE_vec4(body2->shapeParams[0] / 2,0,0,0);
  778. TPE_rotatePoint(&aX2,q);
  779. aY2 = TPE_vec4(0,body2->shapeParams[1] / 2,0,0);
  780. TPE_rotatePoint(&aY2,q);
  781. aZ2 = TPE_vec4(0,0,body2->shapeParams[2] / 2,0);
  782. TPE_rotatePoint(&aZ2,q);
  783. uint8_t edges[12] = // list of all cuboid edges as combinations of axes
  784. { // xyz xyz
  785. 0x3b, // +++ -++ |
  786. 0x3e, // +++ ++- | top
  787. 0x13, // -+- -++ |
  788. 0x16, // -+- ++- |
  789. 0x29, // +-+ --+ |
  790. 0x2c, // +-+ +-- | bottom
  791. 0x01, // --- --+ |
  792. 0x04, // --- +-- |
  793. 0x3d, // +++ +-+ |
  794. 0x19, // -++ --+ | sides
  795. 0x10, // -+- --- |
  796. 0x34 // ++- +-- |
  797. };
  798. for (uint8_t j = 0; j < 12; ++j) // for each edge
  799. {
  800. // we check the edge against all sides of the other cuboid
  801. TPE_Vec4 lineStart = body1->position;
  802. TPE_Vec4 lineEnd = body1->position;
  803. uint8_t edge = edges[j];
  804. #define offsetCenter(c,v,a) \
  805. v = (edge & c) ? TPE_vec3Plus(v,a) : TPE_vec3Minus(v,a);
  806. offsetCenter(0x04,lineStart,aX1)
  807. offsetCenter(0x02,lineStart,aY1)
  808. offsetCenter(0x01,lineStart,aZ1)
  809. offsetCenter(0x20,lineEnd,aX1)
  810. offsetCenter(0x10,lineEnd,aY1)
  811. offsetCenter(0x08,lineEnd,aZ1)
  812. #undef offsetCenter
  813. TPE_Unit t1 = 0, t2 = TPE_FRACTIONS_PER_UNIT;
  814. TPE_Vec4 edgeDir = TPE_vec3Minus(lineEnd,lineStart);
  815. for (uint8_t k = 0; k < 3; ++k) // for each axis (pair of sides)
  816. {
  817. TPE_Vec4 *sideOffset;
  818. if (k == 0)
  819. sideOffset = &aX2;
  820. else if (k == 1)
  821. sideOffset = &aY2;
  822. else
  823. sideOffset = &aZ2;
  824. _TPE_cutLineSegmentByPlanes(body2->position,*sideOffset,lineStart,
  825. edgeDir,&t1,&t2);
  826. if (t1 > t2)
  827. break; // no solution already, no point checking on
  828. }
  829. if (t2 > t1) // if part of edge exists between all side planes
  830. {
  831. // edge collided with the cuboid
  832. collisionHappened = 1;
  833. *collisionPoint = edgeDir;
  834. collisionPoint->x = (collisionPoint->x * t1) / TPE_FRACTIONS_PER_UNIT;
  835. collisionPoint->y = (collisionPoint->y * t1) / TPE_FRACTIONS_PER_UNIT;
  836. collisionPoint->z = (collisionPoint->z * t1) / TPE_FRACTIONS_PER_UNIT;
  837. *collisionPoint = TPE_vec3Plus(lineStart,*collisionPoint);
  838. if (collisionPoint->x > collisionExtentMax.x)
  839. collisionExtentMax.x = collisionPoint->x;
  840. if (collisionPoint->x < collisionExtentMin.x)
  841. collisionExtentMin.x = collisionPoint->x;
  842. if (collisionPoint->y > collisionExtentMax.y)
  843. collisionExtentMax.y = collisionPoint->y;
  844. if (collisionPoint->y < collisionExtentMin.y)
  845. collisionExtentMin.y = collisionPoint->y;
  846. if (collisionPoint->z > collisionExtentMax.z)
  847. collisionExtentMax.z = collisionPoint->z;
  848. if (collisionPoint->z < collisionExtentMin.z)
  849. collisionExtentMin.z = collisionPoint->z;
  850. *collisionPoint = edgeDir;
  851. collisionPoint->x = (collisionPoint->x * t2) / TPE_FRACTIONS_PER_UNIT;
  852. collisionPoint->y = (collisionPoint->y * t2) / TPE_FRACTIONS_PER_UNIT;
  853. collisionPoint->z = (collisionPoint->z * t2) / TPE_FRACTIONS_PER_UNIT;
  854. *collisionPoint = TPE_vec3Plus(lineStart,*collisionPoint);
  855. if (collisionPoint->x > collisionExtentMax.x)
  856. collisionExtentMax.x = collisionPoint->x;
  857. if (collisionPoint->x < collisionExtentMin.x)
  858. collisionExtentMin.x = collisionPoint->x;
  859. if (collisionPoint->y > collisionExtentMax.y)
  860. collisionExtentMax.y = collisionPoint->y;
  861. if (collisionPoint->y < collisionExtentMin.y)
  862. collisionExtentMin.y = collisionPoint->y;
  863. if (collisionPoint->z > collisionExtentMax.z)
  864. collisionExtentMax.z = collisionPoint->z;
  865. if (collisionPoint->z < collisionExtentMin.z)
  866. collisionExtentMin.z = collisionPoint->z;
  867. }
  868. } // for each edge
  869. if (i == 0)
  870. {
  871. // now swap the bodies and do it again:
  872. const TPE_Body *tmp = body1;
  873. body1 = body2;
  874. body2 = tmp;
  875. }
  876. } // for each body
  877. if (collisionHappened)
  878. {
  879. // average all collision points to get the center point
  880. *collisionPoint = TPE_vec3Plus(collisionExtentMin,collisionExtentMax);
  881. collisionPoint->x /= 2;
  882. collisionPoint->y /= 2;
  883. collisionPoint->z /= 2;
  884. collisionPoint->w = 0;
  885. /* We'll find the "closest" side to collision point, compute the
  886. penetration depth for both bodies (can't do just one) and return the
  887. bigger one. */
  888. TPE_Unit result = -TPE_INFINITY;
  889. for (int i = 0; i < 2; ++i) // for each body
  890. {
  891. TPE_Vec4 bestAxis = TPE_vec4(1,0,0,0);
  892. TPE_Unit bestDot = -1;
  893. TPE_Unit currentDot;
  894. collisionExtentMin = TPE_vec3Minus(*collisionPoint,
  895. i == 0 ? body1->position : body2->position); // reuse
  896. #define checkAxis(a) \
  897. currentDot = (TPE_vec3DotProduct(a,collisionExtentMin) * TPE_FRACTIONS_PER_UNIT) / \
  898. TPE_nonZero(TPE_vec3DotProduct(a,a)); \
  899. if (currentDot > bestDot) \
  900. { bestDot = currentDot; bestAxis = a; } \
  901. else { \
  902. currentDot *= -1; \
  903. if (currentDot > bestDot) { \
  904. bestDot = currentDot; bestAxis = a; \
  905. TPE_vec3MultiplyPlain(bestAxis,-1,&bestAxis); } \
  906. }
  907. checkAxis(aX1)
  908. checkAxis(aY1)
  909. checkAxis(aZ1)
  910. #undef checkAxis
  911. TPE_Unit len = TPE_nonZero(TPE_vec3Len(bestAxis));
  912. len = len - TPE_vec3DotProductPlain(bestAxis,
  913. TPE_vec3Minus(*collisionPoint,
  914. i == 0 ? body1->position : body2->position)) / len;
  915. if (len > result)
  916. {
  917. result = len;
  918. *collisionNormal = bestAxis;
  919. TPE_vec3Normalize(collisionNormal);
  920. if (i == 0)
  921. TPE_vec3MultiplyPlain(*collisionNormal,-1,collisionNormal);
  922. }
  923. aX1 = aX2; // check the second body's axes in next iteration
  924. aY1 = aY2;
  925. aZ1 = aZ2;
  926. }
  927. return result > 1 ? result : 1;
  928. }
  929. break;
  930. }
  931. default:
  932. break;
  933. }
  934. return 0;
  935. }
  936. TPE_Vec4 TPE_bodyGetPointVelocity(const TPE_Body *body, TPE_Vec4 point)
  937. {
  938. TPE_Vec4 result = body->velocity;
  939. TPE_Vec4 normal = TPE_vec3Cross(
  940. point,TPE_vec3Minus(point,body->rotation.axisVelocity));
  941. TPE_vec3MultiplyPlain(normal,-1,&normal); // TODO: think about WHY
  942. TPE_Unit dist = TPE_vec3Len(normal); // point-line distance
  943. TPE_Unit velocity =
  944. TPE_angularVelocityToLinear(body->rotation.axisVelocity.w,dist);
  945. TPE_vec3Normalize(&normal);
  946. return TPE_vec3Plus(result,TPE_vec3Times(normal,velocity));
  947. }
  948. void TPE_bodyMultiplyKineticEnergy(TPE_Body *body, TPE_Unit f)
  949. {
  950. if (body->mass == TPE_INFINITY)
  951. return;
  952. TPE_vec3Multiply(body->velocity,f,&(body->velocity));
  953. f = TPE_sqrt(f * TPE_FRACTIONS_PER_UNIT);
  954. TPE_vec3Multiply(body->velocity,f,&(body->velocity));
  955. int8_t sign =
  956. TPE_sign(body->rotation.axisVelocity.w);
  957. body->rotation.axisVelocity.w =
  958. (body->rotation.axisVelocity.w * f) / TPE_FRACTIONS_PER_UNIT;
  959. /* we try to prevent the angular welocity from falling to 0 as that causes
  960. issues with gravity (bodies balancing on corners) */
  961. if (f != 0 &&
  962. sign != 0 && body->rotation.axisVelocity.w == 0)
  963. body->rotation.axisVelocity.w = sign;
  964. }
  965. void TPE_correctEnergies(TPE_Body *body1, TPE_Body *body2,
  966. TPE_Unit previousEnergy, TPE_Unit restitution)
  967. {
  968. if (previousEnergy == 0)
  969. return;
  970. int8_t r = restitution > TPE_FRACTIONS_PER_UNIT ?
  971. 1 : (restitution < TPE_FRACTIONS_PER_UNIT ? -1 : 0);
  972. TPE_Unit newEnergy = TPE_bodyGetKineticEnergy(body1) +
  973. TPE_bodyGetKineticEnergy(body2);
  974. TPE_Unit f = (newEnergy * TPE_FRACTIONS_PER_UNIT) /
  975. previousEnergy;
  976. restitution = (f != 0) ?
  977. (restitution * TPE_FRACTIONS_PER_UNIT) / f :
  978. TPE_FRACTIONS_PER_UNIT;
  979. if (restitution > TPE_FRACTIONS_PER_UNIT + 10 || // TODO: magic const.
  980. restitution < TPE_FRACTIONS_PER_UNIT -10)
  981. {
  982. f = (previousEnergy * restitution) / TPE_FRACTIONS_PER_UNIT;
  983. if ((r < 0 && f < previousEnergy) ||
  984. (r == 0 && f == previousEnergy) ||
  985. (r > 0 && f > previousEnergy))
  986. {
  987. TPE_bodyMultiplyKineticEnergy(body1,restitution);
  988. TPE_bodyMultiplyKineticEnergy(body2,restitution);
  989. }
  990. }
  991. }
  992. /** Return 0 if the body is vibrating. */
  993. uint8_t _TPE_bodyUpdateAntivibration(TPE_Body *body)
  994. {
  995. uint8_t tmp = body->antiVibration & 0x7f;
  996. if (body->antiVibration & 0x80)
  997. {
  998. tmp = (tmp < 127 - TPE_ANTI_VIBRATION_INCREMENT) ?
  999. tmp + TPE_ANTI_VIBRATION_INCREMENT : 127;
  1000. body->antiVibration = (body->antiVibration & 0x80) |
  1001. tmp;
  1002. }
  1003. return tmp <= TPE_ANTI_VIBRATION_MAX_FRAMES;
  1004. }
  1005. void TPE_resolveCollision(TPE_Body *body1 ,TPE_Body *body2,
  1006. TPE_Vec4 collisionPoint, TPE_Vec4 collisionNormal, TPE_Unit collisionDepth,
  1007. TPE_Unit energyMultiplier)
  1008. {
  1009. /*
  1010. TODO:
  1011. - false coll. detection?
  1012. - coll with static
  1013. - handle small values!!!
  1014. - handle big values
  1015. */
  1016. if (body2->mass == TPE_INFINITY) // handle static bodies
  1017. {
  1018. if (body1->mass == TPE_INFINITY)
  1019. return; // static-static collision: do nothing
  1020. // switch the bodies so that the static body is always the first one:
  1021. TPE_Body *tmp = body1;
  1022. body1 = body2;
  1023. body2 = tmp;
  1024. TPE_vec3MultiplyPlain(collisionNormal,-1,&collisionNormal);
  1025. }
  1026. TPE_Vec4 p1, p2;
  1027. p1 = TPE_vec3Minus(collisionPoint,body1->position);
  1028. p2 = TPE_vec3Minus(collisionPoint,body2->position);
  1029. // separate the bodies:
  1030. collisionPoint = collisionNormal; // reuse collisionPoint
  1031. if (body1->mass != TPE_INFINITY)
  1032. {
  1033. TPE_vec3Multiply(collisionPoint,collisionDepth / 2,&collisionPoint);
  1034. TPE_vec3Add(body2->position,collisionPoint,&body2->position);
  1035. TPE_vec3Substract(body1->position,collisionPoint,&body1->position);
  1036. }
  1037. else
  1038. {
  1039. TPE_vec3Multiply(collisionPoint,collisionDepth,&collisionPoint);
  1040. TPE_vec3Add(body2->position,collisionPoint,&body2->position);
  1041. }
  1042. {
  1043. TPE_Vec4 vel1, vel2;
  1044. vel1 = TPE_bodyGetPointVelocity(body1,p1);
  1045. vel2 = TPE_bodyGetPointVelocity(body2,p2);
  1046. if (TPE_vec3Len(TPE_vec3Minus(vel1,vel2)) >=
  1047. TPE_ANTI_VIBRATION_VELOCITY_BREAK)
  1048. {
  1049. body1->antiVibration = 0;
  1050. body2->antiVibration = 0;
  1051. }
  1052. if (TPE_vec3DotProduct(collisionNormal,vel1) <
  1053. TPE_vec3DotProduct(collisionNormal,vel2))
  1054. return; // invalid collision (bodies going away from each other)
  1055. }
  1056. /* We now want to find an impulse I such that if we apply I to body2 and -I
  1057. to body1, we conserve kinetic energy (or keep as much of it as defined by
  1058. energyMultiplier). The direction of I is always the direction of
  1059. collisionNormal, we are only looking for the size of the impulse. We don't
  1060. have to worry about conserving momentum, it is automatically conserved by us
  1061. applying the same (but opposite) impulse to both bodies. The equation is
  1062. constructed as:
  1063. e_out1 + e_out2 - energyMultiplier * (e_in1 + e_in2) = 0
  1064. Where e_in1 (e_in2) is the current kin. energy of body1 (body2) and e_out1
  1065. (e_out2) is the energy of body1 (body2) AFTER applying impulse I. The
  1066. unknown (x) in the equation is the size of the impulse. Expanding all this,
  1067. considering moment of ineartia of a sphere (for simplicity), we get a
  1068. quadratic equation with coefficients:
  1069. a = 1/(2 * m1) + 1/(2 * m2) +
  1070. q1/2 * dot(cross(normal,p1),cross(normal,p1)) +
  1071. q2/2 * dot(cross(normal,p2),cross(normal,p2))
  1072. b = dot(v2,normal) - dot(v1,normal) +
  1073. dot(r2,cross(normal,p2) -
  1074. dot(r1,cross(normal,p1)
  1075. c = m1/2 * dot(v1,v1) + w1 * dot(r1,r1) +
  1076. m2/2 * dot(v2,v2) + w2 * dot(r2,r2) - energyMultiplier * (e_in1 + e_in2)
  1077. where
  1078. qn = 5 / (2 * mn * dn)
  1079. wn = (mn * dn) / 5
  1080. dn = maximum extent of body n
  1081. The following code is solving this equation: */
  1082. TPE_Unit tmp = TPE_bodyGetMaxExtent(body1);
  1083. TPE_Unit w1 = ((((body1->mass * tmp) / TPE_FRACTIONS_PER_UNIT) * tmp) /
  1084. TPE_FRACTIONS_PER_UNIT) / 5;
  1085. TPE_Unit q1 = (TPE_FRACTIONS_PER_UNIT * TPE_FRACTIONS_PER_UNIT * 2) /
  1086. TPE_nonZero(w1);
  1087. TPE_Vec4 nxp1 = TPE_vec3Cross(collisionNormal,p1);
  1088. TPE_Vec4 rot1 =
  1089. TPE_vec3Times(body1->rotation.axisVelocity,body1->rotation.axisVelocity.w);
  1090. tmp = TPE_bodyGetMaxExtent(body2);
  1091. TPE_Unit w2 = ((((body2->mass * tmp) / TPE_FRACTIONS_PER_UNIT) * tmp) /
  1092. TPE_FRACTIONS_PER_UNIT) / 5;
  1093. TPE_Unit q2 = (TPE_FRACTIONS_PER_UNIT * TPE_FRACTIONS_PER_UNIT * 2) /
  1094. TPE_nonZero(w2);
  1095. TPE_Vec4 nxp2 = TPE_vec3Cross(collisionNormal,p2);
  1096. TPE_Vec4 rot2 =
  1097. TPE_vec3Times(body2->rotation.axisVelocity,body2->rotation.axisVelocity.w);
  1098. uint8_t dynamic = body1->mass != TPE_INFINITY;
  1099. // quadratic eq. coefficients:
  1100. TPE_Unit a =
  1101. ((dynamic * TPE_FRACTIONS_PER_UNIT * TPE_FRACTIONS_PER_UNIT) / body1->mass +
  1102. (TPE_FRACTIONS_PER_UNIT * TPE_FRACTIONS_PER_UNIT) / body2->mass) / 2 +
  1103. (dynamic * q1 * TPE_vec3DotProduct(nxp1,nxp1) + q2 * TPE_vec3DotProduct(nxp2,nxp2)) /
  1104. (2 * TPE_FRACTIONS_PER_UNIT);
  1105. TPE_Unit b =
  1106. TPE_vec3DotProduct(body2->velocity,collisionNormal) +
  1107. TPE_vec3DotProduct(rot2,nxp2) -
  1108. dynamic * (
  1109. TPE_vec3DotProduct(body1->velocity,collisionNormal) +
  1110. TPE_vec3DotProduct(rot1,nxp1));
  1111. TPE_Unit
  1112. e1 = dynamic * TPE_bodyGetKineticEnergy(body1),
  1113. e2 = TPE_bodyGetKineticEnergy(body2);
  1114. TPE_Unit c =
  1115. (
  1116. dynamic * body1->mass * TPE_vec3DotProduct(body1->velocity,body1->velocity) +
  1117. body2->mass * TPE_vec3DotProduct(body2->velocity,body2->velocity)
  1118. ) / (2 * TPE_FRACTIONS_PER_UNIT) +
  1119. (
  1120. dynamic * w1 * TPE_vec3DotProduct(rot1,rot1) +
  1121. w2 * TPE_vec3DotProduct(rot2,rot2)
  1122. ) / TPE_FRACTIONS_PER_UNIT
  1123. - (((e1 + e2) * energyMultiplier) / TPE_FRACTIONS_PER_UNIT);
  1124. c = TPE_sqrt(b * b - 4 * a * c); // discriminant
  1125. b *= -1;
  1126. a *= 2;
  1127. // solutions:
  1128. TPE_Unit x1, x2;
  1129. x1 = ((b - c) * TPE_FRACTIONS_PER_UNIT) / a;
  1130. x2 = ((b + c) * TPE_FRACTIONS_PER_UNIT) / a;
  1131. // here at least one solution (x1 or x2) should be 0 (or close)
  1132. if (TPE_abs(x1) < TPE_abs(x2))
  1133. x1 = x2; // we take the non-0 solution
  1134. collisionNormal = TPE_vec3Times(collisionNormal,x1);
  1135. if (_TPE_bodyUpdateAntivibration(body2))
  1136. TPE_bodyApplyImpulse(body2,p2,collisionNormal);
  1137. else
  1138. TPE_bodyMultiplyKineticEnergy(body2,0);
  1139. if (body1->mass != TPE_INFINITY)
  1140. {
  1141. if (_TPE_bodyUpdateAntivibration(body1))
  1142. {
  1143. TPE_vec3MultiplyPlain(collisionNormal,-1,&collisionNormal);
  1144. TPE_bodyApplyImpulse(body1,p1,collisionNormal);
  1145. }
  1146. else
  1147. TPE_bodyMultiplyKineticEnergy(body1,0);
  1148. }
  1149. // we try to correct possible numerical errors:
  1150. TPE_correctEnergies(body1,body2,e1 + e2,energyMultiplier);
  1151. }
  1152. TPE_Unit TPE_linearVelocityToAngular(TPE_Unit velocity, TPE_Unit distance)
  1153. {
  1154. TPE_Unit circumfence = (2 * TPE_PI * distance) / TPE_FRACTIONS_PER_UNIT;
  1155. return (velocity * TPE_FRACTIONS_PER_UNIT) / circumfence;
  1156. }
  1157. TPE_Unit TPE_angularVelocityToLinear(TPE_Unit velocity, TPE_Unit distance)
  1158. {
  1159. TPE_Unit circumfence = (2 * TPE_PI * distance) / TPE_FRACTIONS_PER_UNIT;
  1160. return (velocity * circumfence) / TPE_FRACTIONS_PER_UNIT;
  1161. }
  1162. void TPE_bodyStep(TPE_Body *body)
  1163. {
  1164. if (body->mass != TPE_INFINITY)
  1165. {
  1166. TPE_vec3Add(body->position,body->velocity,&(body->position));
  1167. body->rotation.currentAngle += body->rotation.axisVelocity.w;
  1168. }
  1169. if ((body->antiVibration & 0x7f) > 0)
  1170. {
  1171. body->antiVibration = (body->antiVibration & 0x80) |
  1172. ((body->antiVibration & 0x7f) - 1);
  1173. if (body->antiVibration == 0x80)
  1174. body->antiVibration = 0;
  1175. }
  1176. }
  1177. void TPE_bodySetRotation(TPE_Body *body, TPE_Vec4 axis, TPE_Unit velocity)
  1178. {
  1179. if (body->rotation.currentAngle != 0)
  1180. body->rotation.originalOrientation = TPE_bodyGetOrientation(body);
  1181. if (velocity < 0)
  1182. {
  1183. axis.x *= -1;
  1184. axis.y *= -1;
  1185. axis.z *= -1;
  1186. velocity *= -1;
  1187. }
  1188. TPE_vec3Normalize(&axis);
  1189. body->antiVibration = (body->antiVibration & 0x7f) |
  1190. ((TPE_vec3DotProductPlain(axis,body->rotation.axisVelocity) <= 0) << 7);
  1191. body->rotation.axisVelocity = axis;
  1192. body->rotation.axisVelocity.w = velocity;
  1193. body->rotation.currentAngle = 0;
  1194. }
  1195. void TPE_bodyAddRotation(TPE_Body *body, TPE_Vec4 axis, TPE_Unit velocity)
  1196. {
  1197. /* Rotation is added like this: we convert both the original and added
  1198. rotation to vectors whose direction is along the rotations axis and
  1199. magnitude is the rotation speed, then we add these vectors and convert
  1200. the final vector back to normalized rotation axis + scalar rotation
  1201. speed.*/
  1202. if (velocity == 0)
  1203. return;
  1204. body->rotation.axisVelocity.x =
  1205. (body->rotation.axisVelocity.x * body->rotation.axisVelocity.w)
  1206. / TPE_FRACTIONS_PER_UNIT;
  1207. body->rotation.axisVelocity.y =
  1208. (body->rotation.axisVelocity.y * body->rotation.axisVelocity.w)
  1209. / TPE_FRACTIONS_PER_UNIT;
  1210. body->rotation.axisVelocity.z =
  1211. (body->rotation.axisVelocity.z * body->rotation.axisVelocity.w)
  1212. / TPE_FRACTIONS_PER_UNIT;
  1213. TPE_vec3Normalize(&axis);
  1214. axis.x = (axis.x * velocity) / TPE_FRACTIONS_PER_UNIT;
  1215. axis.y = (axis.y * velocity) / TPE_FRACTIONS_PER_UNIT;
  1216. axis.z = (axis.z * velocity) / TPE_FRACTIONS_PER_UNIT;
  1217. TPE_vec3Add(body->rotation.axisVelocity,axis,&axis);
  1218. axis.w = TPE_vec3Len(axis);
  1219. TPE_bodySetRotation(body,axis,axis.w);
  1220. }
  1221. void TPE_quaternionMultiply(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result)
  1222. {
  1223. TPE_Vec4 r; // in case result is identical to a or b
  1224. r.x =
  1225. (a.w * b.x +
  1226. a.x * b.w +
  1227. a.y * b.z -
  1228. a.z * b.y) / TPE_FRACTIONS_PER_UNIT;
  1229. r.y =
  1230. (a.w * b.y -
  1231. a.x * b.z +
  1232. a.y * b.w +
  1233. a.z * b.x) / TPE_FRACTIONS_PER_UNIT;
  1234. r.z =
  1235. (a.w * b.z +
  1236. a.x * b.y -
  1237. a.y * b.x +
  1238. a.z * b.w) / TPE_FRACTIONS_PER_UNIT;
  1239. r.w =
  1240. (a.w * b.w -
  1241. a.x * b.x -
  1242. a.y * b.y -
  1243. a.z * b.z) / TPE_FRACTIONS_PER_UNIT;
  1244. result->x = r.x;
  1245. result->y = r.y;
  1246. result->z = r.z;
  1247. result->w = r.w;
  1248. }
  1249. void TPE_rotationToQuaternion(TPE_Vec4 axis, TPE_Unit angle, TPE_Vec4 *quaternion)
  1250. {
  1251. TPE_vec3Normalize(&axis);
  1252. angle /= 2;
  1253. TPE_Unit s = TPE_sin(angle);
  1254. quaternion->x = (s * axis.x) / TPE_FRACTIONS_PER_UNIT;
  1255. quaternion->y = (s * axis.y) / TPE_FRACTIONS_PER_UNIT;
  1256. quaternion->z = (s * axis.z) / TPE_FRACTIONS_PER_UNIT;
  1257. quaternion->w = TPE_cos(angle);
  1258. }
  1259. TPE_Unit TPE_asin(TPE_Unit x)
  1260. {
  1261. x = TPE_clamp(x,-TPE_FRACTIONS_PER_UNIT,TPE_FRACTIONS_PER_UNIT);
  1262. int8_t sign = 1;
  1263. if (x < 0)
  1264. {
  1265. sign = -1;
  1266. x *= -1;
  1267. }
  1268. int16_t low = 0;
  1269. int16_t high = TPE_SIN_TABLE_LENGTH -1;
  1270. int16_t middle;
  1271. while (low <= high) // binary search
  1272. {
  1273. middle = (low + high) / 2;
  1274. TPE_Unit v = TPE_sinTable[middle];
  1275. if (v > x)
  1276. high = middle - 1;
  1277. else if (v < x)
  1278. low = middle + 1;
  1279. else
  1280. break;
  1281. }
  1282. middle *= TPE_SIN_TABLE_UNIT_STEP;
  1283. return sign * middle;
  1284. }
  1285. TPE_Unit TPE_acos(TPE_Unit x)
  1286. {
  1287. return TPE_asin(-1 * x) + TPE_FRACTIONS_PER_UNIT / 4;
  1288. }
  1289. void TPE_quaternionToRotation(TPE_Vec4 quaternion, TPE_Vec4 *axis, TPE_Unit *angle)
  1290. {
  1291. *angle = 2 * TPE_acos(quaternion.x);
  1292. TPE_Unit tmp =
  1293. TPE_nonZero(TPE_sqrt(
  1294. (TPE_FRACTIONS_PER_UNIT -
  1295. (quaternion.x * quaternion.x) / TPE_FRACTIONS_PER_UNIT
  1296. ) * TPE_FRACTIONS_PER_UNIT));
  1297. axis->x = (quaternion.x * TPE_FRACTIONS_PER_UNIT) / tmp;
  1298. axis->y = (quaternion.y * TPE_FRACTIONS_PER_UNIT) / tmp;
  1299. axis->z = (quaternion.z * TPE_FRACTIONS_PER_UNIT) / tmp;
  1300. }
  1301. void TPE_quaternionToRotationMatrix(TPE_Vec4 quaternion, TPE_Unit matrix[4][4])
  1302. {
  1303. TPE_Unit
  1304. _2x2 = (2 * quaternion.x * quaternion.x) / TPE_FRACTIONS_PER_UNIT,
  1305. _2y2 = (2 * quaternion.y * quaternion.y) / TPE_FRACTIONS_PER_UNIT,
  1306. _2z2 = (2 * quaternion.z * quaternion.z) / TPE_FRACTIONS_PER_UNIT,
  1307. _2xy = (2 * quaternion.x * quaternion.y) / TPE_FRACTIONS_PER_UNIT,
  1308. _2xw = (2 * quaternion.x * quaternion.w) / TPE_FRACTIONS_PER_UNIT,
  1309. _2zw = (2 * quaternion.z * quaternion.w) / TPE_FRACTIONS_PER_UNIT,
  1310. _2xz = (2 * quaternion.x * quaternion.z) / TPE_FRACTIONS_PER_UNIT,
  1311. _2yw = (2 * quaternion.y * quaternion.w) / TPE_FRACTIONS_PER_UNIT,
  1312. _2yz = (2 * quaternion.y * quaternion.z) / TPE_FRACTIONS_PER_UNIT;
  1313. #define ONE TPE_FRACTIONS_PER_UNIT
  1314. matrix[0][0] = ONE - _2y2 - _2z2;
  1315. matrix[1][0] = _2xy - _2zw;
  1316. matrix[2][0] = _2xz + _2yw;
  1317. matrix[3][0] = 0;
  1318. matrix[0][1] = _2xy + _2zw;
  1319. matrix[1][1] = ONE - _2x2 - _2z2;
  1320. matrix[2][1] = _2yz - _2xw;
  1321. matrix[3][1] = 0;
  1322. matrix[0][2] = _2xz - _2yw;
  1323. matrix[1][2] = _2yz + _2xw;
  1324. matrix[2][2] = ONE - _2x2 - _2y2;
  1325. matrix[3][2] = 0;
  1326. matrix[0][3] = 0;
  1327. matrix[1][3] = 0;
  1328. matrix[2][3] = 0;
  1329. matrix[3][3] = ONE;
  1330. #undef ONE
  1331. }
  1332. void TPE_vec3Add(const TPE_Vec4 a, const TPE_Vec4 b, TPE_Vec4 *result)
  1333. {
  1334. result->x = a.x + b.x;
  1335. result->y = a.y + b.y;
  1336. result->z = a.z + b.z;
  1337. }
  1338. void TPE_vec4Add(const TPE_Vec4 a, const TPE_Vec4 b, TPE_Vec4 *result)
  1339. {
  1340. result->x = a.x + b.x;
  1341. result->y = a.y + b.y;
  1342. result->z = a.z + b.z;
  1343. result->w = a.w + b.w;
  1344. }
  1345. void TPE_vec3Substract(const TPE_Vec4 a, const TPE_Vec4 b, TPE_Vec4 *result)
  1346. {
  1347. result->x = a.x - b.x;
  1348. result->y = a.y - b.y;
  1349. result->z = a.z - b.z;
  1350. }
  1351. TPE_Vec4 TPE_vec3Plus(TPE_Vec4 a, TPE_Vec4 b)
  1352. {
  1353. a.x += b.x;
  1354. a.y += b.y;
  1355. a.z += b.z;
  1356. return a;
  1357. }
  1358. TPE_Vec4 TPE_vec3Minus(TPE_Vec4 a, TPE_Vec4 b)
  1359. {
  1360. a.x -= b.x;
  1361. a.y -= b.y;
  1362. a.z -= b.z;
  1363. return a;
  1364. }
  1365. TPE_Vec4 TPE_vec3Times(TPE_Vec4 a, TPE_Unit f)
  1366. {
  1367. a.x = (a.x * f) / TPE_FRACTIONS_PER_UNIT;
  1368. a.y = (a.y * f) / TPE_FRACTIONS_PER_UNIT;
  1369. a.z = (a.z * f) / TPE_FRACTIONS_PER_UNIT;
  1370. return a;
  1371. }
  1372. TPE_Vec4 TPE_vec3TimesAntiZero(TPE_Vec4 a, TPE_Unit f)
  1373. {
  1374. a.x *= f;
  1375. if (a.x != 0)
  1376. a.x = a.x >= TPE_FRACTIONS_PER_UNIT ? a.x / TPE_FRACTIONS_PER_UNIT :
  1377. (a.x > 0 ? 1 : -1);
  1378. a.y *= f;
  1379. if (a.y != 0)
  1380. a.y = a.y >= TPE_FRACTIONS_PER_UNIT ? a.y / TPE_FRACTIONS_PER_UNIT :
  1381. (a.y > 0 ? 1 : -1);
  1382. a.z *= f;
  1383. if (a.z != 0)
  1384. a.z = a.z >= TPE_FRACTIONS_PER_UNIT ? a.z / TPE_FRACTIONS_PER_UNIT :
  1385. (a.z > 0 ? 1 : -1);
  1386. /*
  1387. if (a.x != 0)
  1388. a.x = a.x >= TPE_FRACTIONS_PER_UNIT ? a.x / TPE_FRACTIONS_PER_UNIT :
  1389. (a.x > 0 ? 1 : -1);
  1390. if (a.y != 0)
  1391. a.y = a.y >= TPE_FRACTIONS_PER_UNIT ? a.y / TPE_FRACTIONS_PER_UNIT :
  1392. (a.y > 0 ? 1 : -1);
  1393. if (a.z != 0)
  1394. a.z = a.z >= TPE_FRACTIONS_PER_UNIT ? a.z / TPE_FRACTIONS_PER_UNIT :
  1395. (a.z > 0 ? 1 : -1);
  1396. */
  1397. return a;
  1398. }
  1399. void TPE_vec3Average(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result)
  1400. {
  1401. result->x = (a.x + b.x) / 2;
  1402. result->y = (a.y + b.y) / 2;
  1403. result->z = (a.z + b.z) / 2;
  1404. }
  1405. void TPE_vec4Substract(const TPE_Vec4 a, const TPE_Vec4 b, TPE_Vec4 *result)
  1406. {
  1407. result->x = a.x - b.x;
  1408. result->y = a.y - b.y;
  1409. result->z = a.z - b.z;
  1410. result->w = a.w - b.w;
  1411. }
  1412. void TPE_vec3Multiply(const TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result)
  1413. {
  1414. result->x = (v.x * f) / TPE_FRACTIONS_PER_UNIT;
  1415. result->y = (v.y * f) / TPE_FRACTIONS_PER_UNIT;
  1416. result->z = (v.z * f) / TPE_FRACTIONS_PER_UNIT;
  1417. }
  1418. void TPE_vec3MultiplyPlain(TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result)
  1419. {
  1420. result->x = v.x * f;
  1421. result->y = v.y * f;
  1422. result->z = v.z * f;
  1423. }
  1424. void TPE_vec4Multiply(const TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result)
  1425. {
  1426. result->x = (v.x * f) / TPE_FRACTIONS_PER_UNIT;
  1427. result->y = (v.y * f) / TPE_FRACTIONS_PER_UNIT;
  1428. result->z = (v.z * f) / TPE_FRACTIONS_PER_UNIT;
  1429. result->w = (v.w * f) / TPE_FRACTIONS_PER_UNIT;
  1430. }
  1431. TPE_Unit TPE_abs(TPE_Unit x)
  1432. {
  1433. return (x >= 0) ? x : (-1 * x);
  1434. }
  1435. TPE_Unit TPE_vec3Len(TPE_Vec4 v)
  1436. {
  1437. return TPE_sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
  1438. }
  1439. TPE_Unit TPE_vec3Dist(TPE_Vec4 a, TPE_Vec4 b)
  1440. {
  1441. return TPE_vec3Len(TPE_vec3Minus(a,b));
  1442. }
  1443. TPE_Unit TPE_vec4Len(TPE_Vec4 v)
  1444. {
  1445. return TPE_sqrt(v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w);
  1446. }
  1447. TPE_Unit TPE_vec3LenTaxicab(TPE_Vec4 v)
  1448. {
  1449. return TPE_abs(v.x) + TPE_abs(v.y) + TPE_abs(v.z);
  1450. }
  1451. TPE_Unit TPE_vec3DotProduct(const TPE_Vec4 v1, const TPE_Vec4 v2)
  1452. {
  1453. return
  1454. (v1.x * v2.x + v1.y * v2.y + v1.z * v2.z) / TPE_FRACTIONS_PER_UNIT;
  1455. }
  1456. TPE_Unit TPE_vec3DotProductPlain(const TPE_Vec4 v1, const TPE_Vec4 v2)
  1457. {
  1458. return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
  1459. }
  1460. void TPE_vec3Normalize(TPE_Vec4 *v)
  1461. {
  1462. TPE_Unit l = TPE_vec3Len(*v);
  1463. if (l == 0)
  1464. {
  1465. v->x = TPE_FRACTIONS_PER_UNIT;
  1466. return;
  1467. }
  1468. v->x = (v->x * TPE_FRACTIONS_PER_UNIT) / l;
  1469. v->y = (v->y * TPE_FRACTIONS_PER_UNIT) / l;
  1470. v->z = (v->z * TPE_FRACTIONS_PER_UNIT) / l;
  1471. }
  1472. void TPE_vec4Normalize(TPE_Vec4 *v)
  1473. {
  1474. TPE_Unit l = TPE_vec4Len(*v);
  1475. if (l == 0)
  1476. {
  1477. v->x = TPE_FRACTIONS_PER_UNIT;
  1478. return;
  1479. }
  1480. v->x = (v->x * TPE_FRACTIONS_PER_UNIT) / l;
  1481. v->y = (v->y * TPE_FRACTIONS_PER_UNIT) / l;
  1482. v->z = (v->z * TPE_FRACTIONS_PER_UNIT) / l;
  1483. v->w = (v->w * TPE_FRACTIONS_PER_UNIT) / l;
  1484. }
  1485. void TPE_vec3Project(TPE_Vec4 v, TPE_Vec4 base, TPE_Vec4 *result)
  1486. {
  1487. TPE_Unit p = TPE_vec3DotProduct(v,base);
  1488. result->x = (p * base.x) / TPE_FRACTIONS_PER_UNIT;
  1489. result->y = (p * base.y) / TPE_FRACTIONS_PER_UNIT;
  1490. result->z = (p * base.z) / TPE_FRACTIONS_PER_UNIT;
  1491. }
  1492. TPE_Vec4 TPE_vec3Projected(TPE_Vec4 v, TPE_Vec4 base)
  1493. {
  1494. TPE_Vec4 r;
  1495. TPE_vec3Project(v,base,&r);
  1496. return r;
  1497. }
  1498. void TPE_getVelocitiesAfterCollision(
  1499. TPE_Unit *v1,
  1500. TPE_Unit *v2,
  1501. TPE_Unit m1,
  1502. TPE_Unit m2,
  1503. TPE_Unit elasticity
  1504. )
  1505. {
  1506. /* in the following a lot of TPE_FRACTIONS_PER_UNIT cancel out, feel free to
  1507. check if confused */
  1508. #define ANTI_OVERFLOW 30000
  1509. #define ANTI_OVERFLOW_SCALE 128
  1510. uint8_t overflowDanger = m1 > ANTI_OVERFLOW || *v1 > ANTI_OVERFLOW ||
  1511. m2 > ANTI_OVERFLOW || *v2 > ANTI_OVERFLOW;
  1512. if (overflowDanger)
  1513. {
  1514. m1 = (m1 != 0) ? TPE_nonZero(m1 / ANTI_OVERFLOW_SCALE) : 0;
  1515. m2 = (m2 != 0) ? TPE_nonZero(m2 / ANTI_OVERFLOW_SCALE) : 0;
  1516. *v1 = (*v1 != 0) ? TPE_nonZero(*v1 / ANTI_OVERFLOW_SCALE) : 0;
  1517. *v2 = (*v2 != 0) ? TPE_nonZero(*v2 / ANTI_OVERFLOW_SCALE) : 0;
  1518. }
  1519. TPE_Unit m1Pm2 = TPE_nonZero(m1 + m2);
  1520. TPE_Unit v2Mv1 = TPE_nonZero(*v2 - *v1);
  1521. TPE_Unit m1v1Pm2v2 = ((m1 * *v1) + (m2 * *v2));
  1522. *v1 = (((elasticity * m2 / TPE_FRACTIONS_PER_UNIT) * v2Mv1)
  1523. + m1v1Pm2v2) / m1Pm2;
  1524. *v2 = (((elasticity * m1 / TPE_FRACTIONS_PER_UNIT) * -1 * v2Mv1)
  1525. + m1v1Pm2v2) / m1Pm2;
  1526. if (overflowDanger)
  1527. {
  1528. *v1 *= ANTI_OVERFLOW_SCALE;
  1529. *v2 *= ANTI_OVERFLOW_SCALE;
  1530. }
  1531. #undef ANTI_OVERFLOW
  1532. #undef ANTI_OVERFLOW_SCALE
  1533. }
  1534. void TPE_bodyGetTransformMatrix(const TPE_Body *body, TPE_Unit matrix[4][4])
  1535. {
  1536. TPE_Vec4 orientation;
  1537. orientation = TPE_bodyGetOrientation(body);
  1538. TPE_quaternionToRotationMatrix(orientation,matrix);
  1539. matrix[0][3] = body->position.x;
  1540. matrix[1][3] = body->position.y;
  1541. matrix[2][3] = body->position.z;
  1542. }
  1543. void TPE_quaternionInit(TPE_Vec4 *quaternion)
  1544. {
  1545. quaternion->x = 0;
  1546. quaternion->y = 0;
  1547. quaternion->z = 0;
  1548. quaternion->w = TPE_FRACTIONS_PER_UNIT;
  1549. }
  1550. void TPE_rotatePoint(TPE_Vec4 *point, TPE_Vec4 quaternion)
  1551. {
  1552. // TODO: the first method is bugged, but maybe would be faster?
  1553. #if 0
  1554. TPE_Vec4 quaternionConjugate = TPE_quaternionConjugate(quaternion);
  1555. point->w = 0;
  1556. TPE_quaternionMultiply(quaternion,*point,point);
  1557. TPE_quaternionMultiply(*point,quaternionConjugate,point);
  1558. #else
  1559. TPE_Unit m[4][4];
  1560. TPE_quaternionToRotationMatrix(quaternion,m);
  1561. TPE_Vec4 p = *point;
  1562. point->x = (p.x * m[0][0] + p.y * m[0][1] + p.z * m[0][2]) / TPE_FRACTIONS_PER_UNIT;
  1563. point->y = (p.x * m[1][0] + p.y * m[1][1] + p.z * m[1][2]) / TPE_FRACTIONS_PER_UNIT;
  1564. point->z = (p.x * m[2][0] + p.y * m[2][1] + p.z * m[2][2]) / TPE_FRACTIONS_PER_UNIT;
  1565. #endif
  1566. }
  1567. TPE_Vec4 TPE_quaternionConjugate(TPE_Vec4 quaternion)
  1568. {
  1569. quaternion.x *= -1;
  1570. quaternion.y *= -1;
  1571. quaternion.z *= -1;
  1572. return quaternion;
  1573. }
  1574. TPE_Vec4 TPE_vec3Normalized(TPE_Vec4 v)
  1575. {
  1576. TPE_vec3Normalize(&v);
  1577. return v;
  1578. }
  1579. TPE_Vec4 TPE_lineSegmentClosestPoint(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 p)
  1580. {
  1581. TPE_Vec4 ab = TPE_vec3Minus(b,a);
  1582. TPE_Unit t = ((TPE_vec3DotProduct(ab,TPE_vec3Minus(p,a)) *
  1583. TPE_FRACTIONS_PER_UNIT) / TPE_nonZero(TPE_vec3DotProduct(ab,ab)));
  1584. if (t < 0)
  1585. t = 0;
  1586. else if (t > TPE_FRACTIONS_PER_UNIT)
  1587. t = TPE_FRACTIONS_PER_UNIT;
  1588. TPE_vec3Multiply(ab,t,&ab);
  1589. return TPE_vec3Plus(a,ab);
  1590. }
  1591. TPE_Unit TPE_bodyGetKineticEnergy(const TPE_Body *body)
  1592. {
  1593. TPE_Unit v = TPE_vec3Len(body->velocity);
  1594. v *= v;
  1595. v = (v == 0 || v >= TPE_FRACTIONS_PER_UNIT) ?
  1596. v / TPE_FRACTIONS_PER_UNIT : 1;
  1597. v = (body->mass * v) / (2 * TPE_FRACTIONS_PER_UNIT);
  1598. // TODO: handle small values
  1599. // TODO: clean this mess :)
  1600. TPE_Unit r = TPE_bodyGetMaxExtent(body);
  1601. r =
  1602. (
  1603. TPE_timesAntiZero(
  1604. TPE_timesAntiZero(r,r),
  1605. TPE_timesAntiZero(body->rotation.axisVelocity.w,body->rotation.axisVelocity.w)
  1606. )
  1607. *
  1608. body->mass
  1609. )
  1610. / (5 * TPE_FRACTIONS_PER_UNIT);
  1611. if (r == 0 && body->rotation.axisVelocity.w != 0)
  1612. r = 1;
  1613. return v + r;
  1614. }
  1615. TPE_Unit TPE_bodyGetMaxExtent(const TPE_Body *body)
  1616. {
  1617. switch (body->shape)
  1618. {
  1619. case TPE_SHAPE_SPHERE:
  1620. return body->shapeParams[0];
  1621. break;
  1622. case TPE_SHAPE_CUBOID:
  1623. return TPE_vec3Len(TPE_vec4(
  1624. body->shapeParams[0] / 2,
  1625. body->shapeParams[1] / 2,
  1626. body->shapeParams[2] / 2,0));
  1627. break;
  1628. // TODO: other shapes
  1629. default: return 0; break;
  1630. }
  1631. }
  1632. void TPE_bodyRecomputeBounds(TPE_Body *body)
  1633. {
  1634. body->boundingSphereRadius = TPE_bodyGetMaxExtent(body);
  1635. }
  1636. TPE_Unit TPE_timesAntiZero(TPE_Unit a, TPE_Unit b)
  1637. {
  1638. TPE_Unit result = a * b;
  1639. return result >= TPE_FRACTIONS_PER_UNIT ?
  1640. result / TPE_FRACTIONS_PER_UNIT : (result != 0 ? 1 : 0);
  1641. }
  1642. int8_t TPE_sign(TPE_Unit x)
  1643. {
  1644. return x > 0 ? 1 : (x < 0 ? -1 : 0);
  1645. }
  1646. void TPE_worldInit(TPE_World *world)
  1647. {
  1648. world->bodyCount = 0;
  1649. }
  1650. void TPE_worldStepBodies(TPE_World *world)
  1651. {
  1652. for (uint16_t i = 0; i < world->bodyCount; ++i)
  1653. TPE_bodyStep(&(world->bodies[i]));
  1654. }
  1655. TPE_Vec4 TPE_createVecFromTo(TPE_Vec4 pointFrom, TPE_Vec4 pointTo,
  1656. TPE_Unit size)
  1657. {
  1658. return TPE_vec3Times(TPE_vec3Normalized(
  1659. TPE_vec3Minus(pointTo,pointFrom)),size);
  1660. }
  1661. void TPE_worldApplyGravityDown(TPE_World *world, TPE_Unit g)
  1662. {
  1663. TPE_Body *b = world->bodies;
  1664. for (uint16_t i = 0; i < world->bodyCount; ++i)
  1665. {
  1666. if (b->mass != TPE_INFINITY)
  1667. b->velocity.y -= g;
  1668. b++;
  1669. }
  1670. }
  1671. void TPE_worldApplyGravityCenter(TPE_World *world, TPE_Vec4 center, TPE_Unit g)
  1672. {
  1673. TPE_Body *b = world->bodies;
  1674. for (uint16_t i = 0; i < world->bodyCount; ++i)
  1675. {
  1676. if (b->mass != TPE_INFINITY)
  1677. b->velocity = TPE_vec3Plus(b->velocity,TPE_createVecFromTo(
  1678. b->position,center,g));
  1679. b++;
  1680. }
  1681. }
  1682. void TPE_worldResolveCollisionNaive(TPE_World *world)
  1683. {
  1684. TPE_Body *b1 = world->bodies;
  1685. for (uint16_t i = 0; i < world->bodyCount - 1; ++i)
  1686. {
  1687. TPE_Body *b2 = &(world->bodies[i + 1]);
  1688. TPE_Vec4 p, n;
  1689. for (uint16_t j = i + 1; j < world->bodyCount; ++j)
  1690. {
  1691. if (b1->mass != TPE_INFINITY || b2->mass != TPE_INFINITY)
  1692. {
  1693. TPE_Unit d = TPE_bodyCollides(b1,b2,&p,&n);
  1694. if (d)
  1695. TPE_resolveCollision(b1,b2,p,n,d,300);
  1696. }
  1697. b2++;
  1698. }
  1699. b1++;
  1700. }
  1701. }
  1702. void TPE_attractBodies(TPE_Body *body1, TPE_Body *body2, TPE_Unit acceleration)
  1703. {
  1704. TPE_Vec4 direction = TPE_createVecFromTo(body2->position,body1->position,
  1705. acceleration);
  1706. body2->velocity = TPE_vec3Plus(body2->velocity,direction);
  1707. body1->velocity = TPE_vec3Minus(body1->velocity,direction);
  1708. }
  1709. #endif // guard