tinyphysicsengine.h 52 KB

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