tinyphysicsengine.h 62 KB

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