tinyphysicsengine.h 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028
  1. #ifndef _TINYPHYSICSENGINE_H
  2. #define _TINYPHYSICSENGINE_H
  3. /**
  4. WORK IN PROGRESS, UNUSABLE YET
  5. Simple/suckless header-only hybrid 3D physics engine with no floating point,
  6. only 32 bit int arithmetic, similar to e.g. small3dlib.
  7. Conventions and formats are the same or similar to those of small3dlib so as
  8. to make them easily integrate with each other.
  9. Orientations/rotations are in extrinsic Euler angles in the ZXY order (by Z,
  10. then by X, then by Y).
  11. Where it matters (e.g. rotations about axes) we consider a left-handed coord.
  12. system (x right, y up, z forward).
  13. --------------------
  14. by drummyfish, 2022
  15. This work's goal is to never be encumbered by any exclusive intellectual
  16. property rights. The work is therefore provided under CC0 1.0 + additional
  17. WAIVER OF ALL INTELLECTUAL PROPERTY RIGHTS that waives the rest of
  18. intellectual property rights not already waived by CC0 1.0. The WAIVER OF ALL
  19. INTELLECTUAL PROPERTY RGHTS is as follows:
  20. Each contributor to this work agrees that they waive any exclusive rights,
  21. including but not limited to copyright, patents, trademark, trade dress,
  22. industrial design, plant varieties and trade secrets, to any and all ideas,
  23. concepts, processes, discoveries, improvements and inventions conceived,
  24. discovered, made, designed, researched or developed by the contributor either
  25. solely or jointly with others, which relate to this work or result from this
  26. work. Should any waiver of such right be judged legally invalid or
  27. ineffective under applicable law, the contributor hereby grants to each
  28. affected person a royalty-free, non transferable, non sublicensable, non
  29. exclusive, irrevocable and unconditional license to this right.
  30. */
  31. #include <stdint.h>
  32. typedef int32_t TPE_Unit;
  33. typedef int16_t TPE_UnitReduced; ///< Like TPE_Unit but saving space
  34. #define TPE_FRACTIONS_PER_UNIT 512
  35. #define TPE_JOINT_SIZE_MULTIPLIER 32
  36. #define TPE_INFINITY 2147483647
  37. #define TPE_JOINT_SIZE(joint) ((joint).sizeDivided * TPE_JOINT_SIZE_MULTIPLIER)
  38. #ifndef TPE_APPROXIMATE_LENGTH
  39. #define TPE_APPROXIMATE_LENGTH 0 /**< whether or not use length/distance
  40. approximation rather than exact
  41. calculation (1 is faster but less
  42. accurate) */
  43. #endif
  44. #if !TPE_APPROXIMATE_LENGTH
  45. #define TPE_DISTANCE TPE_dist
  46. #define TPE_LENGTH TPE_vec3Len
  47. #else
  48. #define TPE_DISTANCE TPE_distApprox
  49. #define TPE_LENGTH TPE_vec3LenApprox
  50. #endif
  51. // TODO: faster and more accurate distance approx function based on regions/LUT
  52. #ifndef TPE_LOG
  53. #define TPE_LOG(s) ;
  54. #endif
  55. #ifndef TPE_LOW_SPEED
  56. /** Speed, in TPE_Units per ticks, that is considered low (used e.g. for auto
  57. disabling bodies). */
  58. #define TPE_LOW_SPEED 30
  59. #endif
  60. #ifndef TPE_RESHAPE_TENSION_LIMIT
  61. /** Tension limit, in TPE_Units, after which a non-soft body will be reshaped.
  62. Smaller number will keep more stable shapes but will cost more performance. */
  63. #define TPE_RESHAPE_TENSION_LIMIT 20
  64. #endif
  65. #ifndef TPE_RESHAPE_ITERATIONS
  66. /** How many iterations of reshaping will be performed by the step function if
  67. the body's shape needs to be reshaped. Greater number will keep shapes more
  68. stable but will cost some performance. */
  69. #define TPE_RESHAPE_ITERATIONS 3
  70. #endif
  71. #ifndef TPE_DEACTIVATE_AFTER
  72. /** After how many ticks of low speed should a body be disabled. This mustn't
  73. be greater than 255. */
  74. #define TPE_DEACTIVATE_AFTER 128
  75. #endif
  76. #ifndef TPE_LIGHT_DEACTIVATION
  77. /** When a body is activated by a collision, its deactivation counter will be
  78. set to this value, i.e. after a collision the body will be prone to deactivate
  79. sooner than normally. This is to handle situations with many bodies touching
  80. each other that would normally keep activating each other, never coming to
  81. rest. */
  82. #define TPE_LIGHT_DEACTIVATION \
  83. (TPE_DEACTIVATE_AFTER - TPE_DEACTIVATE_AFTER / 10)
  84. #endif
  85. #ifndef TPE_TENSION_ACCELERATION_DIVIDER
  86. /** Number by which the base acceleration (TPE_FRACTIONS_PER_UNIT per tick
  87. squared) caused by the connection tension will be divided. This should be power
  88. of 2. */
  89. #define TPE_TENSION_ACCELERATION_DIVIDER 32
  90. #endif
  91. #ifndef TPE_TENSION_ACCELERATION_THRESHOLD
  92. /** Limit within which acceleration caused by connection tension won't be
  93. applied. */
  94. #define TPE_TENSION_ACCELERATION_THRESHOLD 5
  95. #endif
  96. #ifndef TPE_COLLISION_RESOLUTION_ITERATIONS
  97. /** Maximum number of iterations to try to uncollide two colliding bodies. */
  98. #define TPE_COLLISION_RESOLUTION_ITERATIONS 3
  99. #endif
  100. #ifndef TPE_COLLISION_RESOLUTION_MARGIN
  101. /** Margin, in TPE_Units, by which a body will be shifted back to get out of
  102. collision. */
  103. #define TPE_COLLISION_RESOLUTION_MARGIN (TPE_FRACTIONS_PER_UNIT / 64)
  104. #endif
  105. #ifndef TPE_NONROTATING_COLLISION_RESOLVE_ATTEMPTS
  106. /** Number of times a collision of nonrotating bodies with environment will be
  107. attempted to resolve. This probably won't have great performance implications
  108. as complex collisions of this kind should be relatively rare. */
  109. #define TPE_NONROTATING_COLLISION_RESOLVE_ATTEMPTS 3
  110. #endif
  111. #define TPE_PRINTF_VEC3(v) printf("[%d %d %d]",(v).x,(v).y,(v).z);
  112. typedef struct
  113. {
  114. TPE_Unit x;
  115. TPE_Unit y;
  116. TPE_Unit z;
  117. } TPE_Vec3;
  118. typedef struct
  119. {
  120. TPE_Vec3 position;
  121. TPE_UnitReduced velocity[3];
  122. uint8_t sizeDivided; /**< size (radius, ...), for saving space divided by
  123. TPE_JOINT_SIZE_MULTIPLIER */
  124. } TPE_Joint;
  125. typedef struct
  126. {
  127. uint8_t joint1;
  128. uint16_t joint2;
  129. uint16_t length; ///< connection's preferred length, uint16_t saves space
  130. } TPE_Connection;
  131. #define TPE_BODY_FLAG_DEACTIVATED 1 /**< Not being updated due to low energy,
  132. "sleeping", will be woken by
  133. collisions etc. */
  134. #define TPE_BODY_FLAG_NONROTATING 2 /**< When set, the body won't rotate, will
  135. only move linearly. */
  136. #define TPE_BODY_FLAG_DISABLED 4 /**< Disabled, not taking part in
  137. simulation. */
  138. #define TPE_BODY_FLAG_SOFT 8 /**< Soft connections, effort won't be made
  139. to keep the body's shape. */
  140. /** Function used for defining static environment, working similarly to an SDF
  141. (signed distance function). The parameters are: 3D point P, max distance D.
  142. The function should behave like this: if P is inside the solid environment
  143. volume, P will be returned; otherwise closest point (by Euclidean distance) to
  144. the solid environment volume from P will be returned, except for a case when
  145. this closest point would be further away than D, in which case any arbitrary
  146. point further away than D may be returned (this allows for potentially
  147. potentially faster implementation). */
  148. typedef TPE_Vec3 (*TPE_ClosestPointFunction)(TPE_Vec3, TPE_Unit);
  149. /** Function that can be used as a joint-joint or joint-environment collision
  150. callback, parameters are following: body1 index, joint1 index, body2 index,
  151. joint2 index, collision world position. If body1 index is the same as body1
  152. index, then collision type is body-environment, otherwise it is body-body type.
  153. The function has to return either 1 if the collision is to be allowed or 0 if
  154. it is to be discarded. */
  155. typedef uint8_t (*TPE_CollisionCallback)(uint16_t, uint16_t, uint16_t, uint16_t,
  156. TPE_Vec3);
  157. /** Function used by the debug drawing functions to draw individual pixels to
  158. the screen. The parameters are following: pixel x, pixel y, pixel color. */
  159. typedef void (*TPE_DebugDrawFunction)(uint16_t, uint16_t, uint8_t);
  160. typedef struct
  161. {
  162. TPE_Joint *joints;
  163. uint8_t jointCount;
  164. TPE_Connection *connections;
  165. uint8_t connectionCount;
  166. TPE_UnitReduced jointMass;
  167. TPE_UnitReduced friction;
  168. TPE_UnitReduced elasticity;
  169. uint8_t flags;
  170. uint8_t deactivateCount;
  171. } TPE_Body;
  172. typedef struct
  173. {
  174. TPE_Body *bodies;
  175. uint16_t bodyCount;
  176. TPE_ClosestPointFunction environmentFunction;
  177. TPE_CollisionCallback collisionCallback;
  178. } TPE_World;
  179. void TPE_bodyInit(TPE_Body *body,
  180. TPE_Joint *joints, uint8_t jointCount,
  181. TPE_Connection *connections, uint8_t connectionCount,
  182. TPE_Unit mass);
  183. void TPE_worldInit(TPE_World *world,
  184. TPE_Body *bodies, uint16_t bodyCount,
  185. TPE_ClosestPointFunction environmentFunction);
  186. /** Gets orientation (rotation) of a body from a position of three of its
  187. joints. The vector from joint1 to joint2 is considered the body's forward
  188. direction, the vector from joint1 to joint3 its right direction. */
  189. TPE_Vec3 TPE_bodyGetOrientation(const TPE_Body *body, uint16_t joint1,
  190. uint16_t joint2, uint16_t joint3);
  191. void TPE_vec3Normalize(TPE_Vec3 *v);
  192. TPE_Vec3 TPE_pointRotate(TPE_Vec3 point, TPE_Vec3 rotation);
  193. TPE_Vec3 TPE_rotationInverse(TPE_Vec3 rotation);
  194. void TPE_getVelocitiesAfterCollision(
  195. TPE_Unit *v1,
  196. TPE_Unit *v2,
  197. TPE_Unit m1,
  198. TPE_Unit m2,
  199. TPE_Unit elasticity);
  200. TPE_Unit TPE_keepInRange(TPE_Unit x, TPE_Unit xMin, TPE_Unit xMax);
  201. TPE_Vec3 TPE_vec3(TPE_Unit x, TPE_Unit y, TPE_Unit z);
  202. TPE_Vec3 TPE_vec3Minus(TPE_Vec3 v1, TPE_Vec3 v2);
  203. TPE_Vec3 TPE_vec3Plus(TPE_Vec3 v1, TPE_Vec3 v2);
  204. TPE_Vec3 TPE_vec3Cross(TPE_Vec3 v1, TPE_Vec3 v2);
  205. TPE_Vec3 TPE_vec3Project(TPE_Vec3 v, TPE_Vec3 base);
  206. TPE_Vec3 TPE_vec3Times(TPE_Vec3 v, TPE_Unit units);
  207. TPE_Vec3 TPE_vec3TimesNonNormalized(TPE_Vec3 v, TPE_Unit q);
  208. TPE_Vec3 TPE_vec3Normalized(TPE_Vec3 v);
  209. /** Keeps given point inside specified axis-aligned box. This can be used e.g.
  210. to smooth rendered movement of jittering physics bodies. */
  211. TPE_Vec3 TPE_vec3KeepWithinBox(TPE_Vec3 point, TPE_Vec3 boxCenter,
  212. TPE_Vec3 boxMaxVect);
  213. /** Computes orientation/rotation (see docs for orientation format) from two
  214. vectors (which should be at least a close to being perpensicular and do NOT
  215. need to be normalized). */
  216. TPE_Vec3 TPE_orientationFromVecs(TPE_Vec3 forward, TPE_Vec3 right);
  217. TPE_Unit TPE_vec3Dot(TPE_Vec3 v1, TPE_Vec3 v2);
  218. TPE_Unit TPE_sqrt(TPE_Unit value);
  219. TPE_Unit TPE_vec3Len(TPE_Vec3 v);
  220. TPE_Unit TPE_vec3LenApprox(TPE_Vec3 v);
  221. static inline TPE_Unit TPE_nonZero(TPE_Unit x);
  222. static inline TPE_Unit TPE_dist(TPE_Vec3 p1, TPE_Vec3 p2);
  223. static inline TPE_Unit TPE_distApprox(TPE_Vec3 p1, TPE_Vec3 p2);
  224. TPE_Joint TPE_joint(TPE_Vec3 position, TPE_Unit size);
  225. uint8_t TPE_jointsResolveCollision(TPE_Joint *j1, TPE_Joint *j2,
  226. TPE_Unit mass1, TPE_Unit mass2, TPE_Unit elasticity, TPE_Unit friction);
  227. /** Tests and potentially resolves a collision between a joint and environment,
  228. returns 0 if no collision happened, 1 if it happened and was resolved normally
  229. and 2 if it couldn't be resolved normally. */
  230. uint8_t TPE_jointEnvironmentResolveCollision(TPE_Joint *joint, TPE_Unit
  231. elasticity, TPE_Unit friction, TPE_ClosestPointFunction env);
  232. uint8_t TPE_bodyEnvironmentCollide(const TPE_Body *body,
  233. TPE_ClosestPointFunction env);
  234. uint8_t TPE_bodyEnvironmentResolveCollision(TPE_Body *body,
  235. TPE_ClosestPointFunction env);
  236. void TPE_bodyGetAABB(const TPE_Body *body, TPE_Vec3 *vMin, TPE_Vec3 *vMax);
  237. uint8_t TPE_checkOverlapAABB(TPE_Vec3 v1Min, TPE_Vec3 v1Max, TPE_Vec3 v2Min,
  238. TPE_Vec3 v2Max);
  239. uint8_t TPE_bodiesResolveCollision(TPE_Body *b1, TPE_Body *b2);
  240. void TPE_jointPin(TPE_Joint *joint, TPE_Vec3 position);
  241. // -----------------------------------------------------------------------------
  242. // body generation functions:
  243. void TPE_makeBox(TPE_Joint joints[8], TPE_Connection connections[16],
  244. TPE_Unit width, TPE_Unit depth, TPE_Unit height, TPE_Unit jointSize);
  245. void TPE_makeCenterBox(TPE_Joint joints[9], TPE_Connection connections[18],
  246. TPE_Unit width, TPE_Unit depth, TPE_Unit height, TPE_Unit jointSize);
  247. void TPE_makeRect(TPE_Joint joints[4], TPE_Connection connections[6],
  248. TPE_Unit width, TPE_Unit depth, TPE_Unit jointSize);
  249. void TPE_makeTriangle(TPE_Joint joints[3], TPE_Connection connections[3],
  250. TPE_Unit sideLength, TPE_Unit jointSize);
  251. void TPE_makeCenterRect(TPE_Joint joints[5], TPE_Connection connections[8],
  252. TPE_Unit width, TPE_Unit depth, TPE_Unit jointSize);
  253. void TPE_make2Line(TPE_Joint joints[2], TPE_Connection connections[1],
  254. TPE_Unit length, TPE_Unit jointSize);
  255. //------------------------------------------------------------------------------
  256. // environment functions:
  257. TPE_Vec3 TPE_envAABoxInside(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 size);
  258. TPE_Vec3 TPE_envAABox(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 maxCornerVec);
  259. TPE_Vec3 TPE_envBox(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 maxCornerVec,
  260. TPE_Vec3 rotation);
  261. TPE_Vec3 TPE_envSphere(TPE_Vec3 point, TPE_Vec3 center, TPE_Unit radius);
  262. TPE_Vec3 TPE_envHalfPlane(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 normal);
  263. #define TPE_ENV_START(test,point) TPE_Vec3 _pBest = test, _pTest; \
  264. TPE_Unit _dBest = TPE_DISTANCE(_pBest,point), _dTest;
  265. #define TPE_ENV_NEXT(test,point) \
  266. { if (_pBest.x == point.x && _pBest.y == point.y && _pBest.z == point.z) \
  267. return _pBest; \
  268. _pTest = test; _dTest = TPE_DISTANCE(_pTest,point); \
  269. if (_dTest < _dBest) { _pBest = _pTest; _dBest = _dTest; } }
  270. #define TPE_ENV_END return _pBest;
  271. //---------------------------
  272. void TPE_worldStep(TPE_World *world);
  273. TPE_Unit TPE_bodyNetSpeed(const TPE_Body *body);
  274. TPE_Unit TPE_bodyAverageSpeed(const TPE_Body *body);
  275. void TPE_bodyDeactivate(TPE_Body *body);
  276. void TPE_bodyLimitAverageSpeed(TPE_Body *body, TPE_Unit speedMin,
  277. TPE_Unit speedMax);
  278. void TPE_bodyMultiplyNetSpeed(TPE_Body *body, TPE_Unit factor);
  279. /** Attempts to shift the joints of a soft body so that the tension of all
  280. strings becomes zero while keeping the joints near their current position. This
  281. function performs one iteration of the equalizing algorithm and doesn't
  282. guarantee a perfect solution, it may help to run multiple iterations (call this
  283. function multiple times). */
  284. void TPE_bodyReshape(TPE_Body *body, TPE_ClosestPointFunction
  285. environmentFunction);
  286. /** Move a soft body by certain offset. */
  287. void TPE_bodyMove(TPE_Body *body, TPE_Vec3 offset);
  288. /** Zero velocities of all soft body joints. */
  289. void TPE_bodyStop(TPE_Body *body);
  290. void TPE_bodyActivate(TPE_Body *body);
  291. /** Add velocity to a soft body. */
  292. void TPE_bodyAccelerate(TPE_Body *body, TPE_Vec3 velocity);
  293. void TPE_bodyApplyGravity(TPE_Body *body, TPE_Unit downwardsAccel);
  294. /** Add angular velocity to a soft body. The rotation vector specifies the axis
  295. of rotation by its direction and angular velocity by its magnitude (magnitude
  296. of TPE_FRACTIONS_PER_UNIT will add linear velocity of TPE_FRACTIONS_PER_UNIT per
  297. tick to a point in the distance of TPE_FRACTIONS_PER_UNIT from the rotation
  298. axis). */
  299. void TPE_bodySpin(TPE_Body *body, TPE_Vec3 rotation);
  300. /** Instantly rotate soft body, the rotation vector specifies the rotation axis
  301. by its direction and the rotation angle by its magnitude (TPE_FRACTIONS_PER_UNIT
  302. stands for full angle, i.e. 2 * PI x). */
  303. void TPE_bodyRotateByAxis(TPE_Body *body, TPE_Vec3 rotation);
  304. /** Compute the center of mass of a soft body. */
  305. TPE_Vec3 TPE_bodyGetCenter(const TPE_Body *body);
  306. /** Compute sine, TPE_FRACTIONS_PER_UNIT as argument corresponds to 2 * PI
  307. radians. Returns a number from -TPE_FRACTIONS_PER_UNIT to
  308. TPE_FRACTIONS_PER_UNIT. */
  309. TPE_Unit TPE_sin(TPE_Unit x);
  310. TPE_Unit TPE_cos(TPE_Unit x);
  311. TPE_Unit TPE_atan(TPE_Unit x);
  312. /** Draws a debug view of a 3D physics world using a provided pixel drawing
  313. function. This can be used to overlay a simple visualization of the physics
  314. objects to your main render, to spot exact borders of objects etc. The
  315. function draws simple dotted lines and circles with different "colors" for
  316. different types of objects (joints, connections, environemnt). camPos, camRot
  317. and camView should match the camera settings of your main renderer. CamView.x
  318. is horizontal resolution in pixels, camView.y is the vertical resolution,
  319. CamView.z says the camera focal length (~FOV) in TPE_Units. envGridRes is the
  320. resolution of an environment probe grid (the function will probe points in
  321. space and draw borders of the physics environemnt), envGridSize is the size
  322. (int TPE_Units) of the grid cell. Note the function may be slow (reducing
  323. envGridRes can help, workable value can be e.g. 16). */
  324. void TPE_worldDebugDraw(TPE_World *world, TPE_DebugDrawFunction drawFunc,
  325. TPE_Vec3 camPos, TPE_Vec3 camRot, TPE_Vec3 camView, uint16_t envGridRes,
  326. TPE_Unit envGridSize);
  327. //------------------------------------------------------------------------------
  328. // privates:
  329. uint16_t _TPE_body1Index, _TPE_body2Index, _TPE_joint1Index, _TPE_joint2Index;
  330. TPE_CollisionCallback _TPE_collisionCallback;
  331. static inline TPE_Unit TPE_nonZero(TPE_Unit x)
  332. {
  333. return x != 0 ? x : 1;
  334. }
  335. TPE_Joint TPE_joint(TPE_Vec3 position, TPE_Unit size)
  336. {
  337. TPE_Joint result;
  338. result.velocity[0] = 0;
  339. result.velocity[1] = 0;
  340. result.velocity[2] = 0;
  341. result.position = position;
  342. size /= TPE_JOINT_SIZE_MULTIPLIER;
  343. if (size > 0xff)
  344. TPE_LOG("WARNING: joint size too big in TPE_joint");
  345. result.sizeDivided = size;
  346. return result;
  347. }
  348. TPE_Vec3 TPE_vec3(TPE_Unit x, TPE_Unit y, TPE_Unit z)
  349. {
  350. TPE_Vec3 r;
  351. r.x = x;
  352. r.y = y;
  353. r.z = z;
  354. return r;
  355. }
  356. TPE_Unit TPE_sqrt(TPE_Unit value)
  357. {
  358. int8_t sign = 1;
  359. if (value < 0)
  360. {
  361. sign = -1;
  362. value *= -1;
  363. }
  364. uint32_t result = 0;
  365. uint32_t a = value;
  366. uint32_t b = 1u << 30;
  367. while (b > a)
  368. b >>= 2;
  369. while (b != 0)
  370. {
  371. if (a >= result + b)
  372. {
  373. a -= result + b;
  374. result = result + 2 * b;
  375. }
  376. b >>= 2;
  377. result >>= 1;
  378. }
  379. return result * sign;
  380. }
  381. TPE_Unit TPE_vec3Len(TPE_Vec3 v)
  382. {
  383. return TPE_sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
  384. }
  385. TPE_Unit TPE_vec3LenApprox(TPE_Vec3 v)
  386. {
  387. if (v.x < 0)
  388. v.x *= -1;
  389. if (v.y < 0)
  390. v.y *= -1;
  391. if (v.z < 0)
  392. v.z *= -1;
  393. TPE_Unit sum = v.x + v.y + v.z;
  394. v.x = (v.x > v.y) ?
  395. (v.x > v.z ? v.x : v.z) :
  396. (v.y > v.z ? v.y : v.z);
  397. return (v.x + sum) / 2;
  398. }
  399. TPE_Unit TPE_dist(TPE_Vec3 p1, TPE_Vec3 p2)
  400. {
  401. p1 = TPE_vec3Minus(p1,p2);
  402. return TPE_vec3Len(p1);
  403. }
  404. TPE_Unit TPE_distApprox(TPE_Vec3 p1, TPE_Vec3 p2)
  405. {
  406. p1 = TPE_vec3Minus(p1,p2);
  407. return TPE_vec3LenApprox(p1);
  408. }
  409. void TPE_bodyInit(TPE_Body *body,
  410. TPE_Joint *joints, uint8_t jointCount,
  411. TPE_Connection *connections, uint8_t connectionCount,
  412. TPE_Unit mass)
  413. {
  414. body->joints = joints;
  415. body->jointCount = jointCount;
  416. body->connections = connections;
  417. body->connectionCount = connectionCount;
  418. body->deactivateCount = 0;
  419. body->friction = TPE_FRACTIONS_PER_UNIT / 2;
  420. body->elasticity = TPE_FRACTIONS_PER_UNIT / 2;
  421. body->flags = 0;
  422. body->jointMass = mass / jointCount;
  423. if (body->jointMass == 0)
  424. body->jointMass = 1;
  425. for (uint32_t i = 0; i < connectionCount; ++i)
  426. {
  427. TPE_Unit d = TPE_DISTANCE(
  428. joints[connections[i].joint1].position,
  429. joints[connections[i].joint2].position);
  430. if (d > 0xffff)
  431. TPE_LOG("WARNING: joint distance too long in TPE_bodyInit");
  432. connections[i].length = d != 0 ? d : 1; // prevent later division by zero
  433. }
  434. }
  435. void TPE_worldInit(TPE_World *world,
  436. TPE_Body *bodies, uint16_t bodyCount,
  437. TPE_ClosestPointFunction environmentFunction)
  438. {
  439. world->bodies = bodies;
  440. world->bodyCount = bodyCount;
  441. world->environmentFunction = environmentFunction;
  442. world->collisionCallback = 0;
  443. }
  444. #define C(n,a,b) connections[n].joint1 = a; connections[n].joint2 = b;
  445. void TPE_make2Line(TPE_Joint joints[2], TPE_Connection connections[1],
  446. TPE_Unit length, TPE_Unit jointSize)
  447. {
  448. joints[0] = TPE_joint(TPE_vec3(length / 2,0,0),jointSize);
  449. joints[1] = TPE_joint(TPE_vec3(length / -2,0,0),jointSize);
  450. C(0, 0,1)
  451. }
  452. void TPE_makeRect(TPE_Joint joints[4], TPE_Connection connections[6],
  453. TPE_Unit width, TPE_Unit depth, TPE_Unit jointSize)
  454. {
  455. width /= 2;
  456. depth /= 2;
  457. for (uint8_t i = 0; i < 4; ++i)
  458. joints[i] = TPE_joint(
  459. TPE_vec3((i % 2) ? -1 * width : width,
  460. 0,(i / 2) ? - 1 * depth : depth),
  461. jointSize);
  462. C(0, 0,1) C(1, 0,2) C (2, 3,1) C(3, 3,2)
  463. C(4, 0,3) C(5, 1,2)
  464. }
  465. void TPE_makeCenterRect(TPE_Joint joints[5], TPE_Connection connections[8],
  466. TPE_Unit width, TPE_Unit depth, TPE_Unit jointSize)
  467. {
  468. TPE_makeRect(joints,connections,width,depth,jointSize);
  469. joints[4] = TPE_joint(TPE_vec3(0,0,0),jointSize);
  470. C(6, 0,4) C(7, 3,4)
  471. }
  472. void TPE_makeTriangle(TPE_Joint joints[3], TPE_Connection connections[3],
  473. TPE_Unit sideLength, TPE_Unit jointSize)
  474. {
  475. joints[0] = TPE_joint(TPE_vec3(sideLength / 2,0,
  476. TPE_sqrt((sideLength * sideLength) / 2) / 2),
  477. jointSize);
  478. joints[1] = joints[0];
  479. joints[1].position.x *= -1;
  480. joints[2] = TPE_joint(TPE_vec3(0,0,-1 * joints[0].position.z),jointSize);
  481. C(0, 0,1) C(1, 1,2) C(2, 2,0)
  482. }
  483. void TPE_makeBox(TPE_Joint joints[8], TPE_Connection connections[16],
  484. TPE_Unit width, TPE_Unit depth, TPE_Unit height, TPE_Unit jointSize)
  485. {
  486. width /= 2;
  487. depth /= 2;
  488. height /= 2;
  489. for (uint8_t i = 0; i < 8; ++i)
  490. joints[i] = TPE_joint(
  491. TPE_vec3(
  492. (i % 2) ? width : (-1 * width),
  493. ((i >> 2) % 2) ? height : (-1 * height),
  494. ((i >> 1) % 2) ? depth : (-1 * depth)),
  495. jointSize);
  496. C(0, 0,1) C(1, 1,3) C(2, 3,2) C(3, 2,0) // top
  497. C(4, 4,5) C(5, 5,7) C(6, 7,6) C(7, 6,4) // bottom
  498. C(8, 0,4) C(9, 1,5) C(10,3,7) C(11,2,6) // middle
  499. C(12,0,7) C(13,1,6) C(14,2,5) C(15,3,4) // diagonal
  500. }
  501. void TPE_makeCenterBox(TPE_Joint joints[9], TPE_Connection connections[18],
  502. TPE_Unit width, TPE_Unit depth, TPE_Unit height, TPE_Unit jointSize)
  503. {
  504. TPE_makeBox(joints,connections,width,depth,height,jointSize);
  505. joints[8] = TPE_joint(TPE_vec3(0,0,0),jointSize);
  506. C(16, 0,8) C(17, 7,8)
  507. }
  508. #undef C
  509. void TPE_bodyDeactivate(TPE_Body *body)
  510. {
  511. body->flags |= TPE_BODY_FLAG_DEACTIVATED;
  512. }
  513. void TPE_worldStep(TPE_World *world)
  514. {
  515. _TPE_collisionCallback = world->collisionCallback;
  516. for (uint16_t i = 0; i < world->bodyCount; ++i)
  517. {
  518. TPE_Body *body = world->bodies + i;
  519. if (body->flags & (TPE_BODY_FLAG_DEACTIVATED | TPE_BODY_FLAG_DISABLED))
  520. continue;
  521. TPE_Joint *joint = body->joints, *joint2;
  522. TPE_Vec3 origPos = body->joints[0].position;
  523. for (uint16_t j = 0; j < body->jointCount; ++j) // apply velocities
  524. {
  525. // non-rotating bodies will copy the 1st joint's velocity
  526. if (body->flags & TPE_BODY_FLAG_NONROTATING)
  527. for (uint8_t k = 0; k < 3; ++k)
  528. joint->velocity[k] = body->joints[0].velocity[k];
  529. joint->position.x += joint->velocity[0];
  530. joint->position.y += joint->velocity[1];
  531. joint->position.z += joint->velocity[2];
  532. joint++;
  533. }
  534. TPE_Connection *connection = body->connections;
  535. TPE_Vec3 aabbMin, aabbMax;
  536. TPE_bodyGetAABB(body,&aabbMin,&aabbMax);
  537. _TPE_body1Index = i;
  538. for (uint16_t j = 0; j < world->bodyCount; ++j)
  539. {
  540. if (j > i || (world->bodies[j].flags & TPE_BODY_FLAG_DEACTIVATED))
  541. {
  542. // firstly quick-check collision of body AA bounding boxes
  543. TPE_Vec3 aabbMin2, aabbMax2;
  544. TPE_bodyGetAABB(&world->bodies[j],&aabbMin2,&aabbMax2);
  545. _TPE_body2Index = j;
  546. if (TPE_checkOverlapAABB(aabbMin,aabbMax,aabbMin2,aabbMax2) &&
  547. TPE_bodiesResolveCollision(body,world->bodies + j))
  548. {
  549. TPE_bodyActivate(body);
  550. body->deactivateCount = TPE_LIGHT_DEACTIVATION;
  551. TPE_bodyActivate(world->bodies + j);
  552. world->bodies[j].deactivateCount = TPE_LIGHT_DEACTIVATION;
  553. }
  554. }
  555. }
  556. _TPE_body2Index = _TPE_body1Index;
  557. uint8_t collided =
  558. TPE_bodyEnvironmentResolveCollision(body,world->environmentFunction);
  559. if (body->flags & TPE_BODY_FLAG_NONROTATING)
  560. {
  561. /* Non-rotating bodies may end up still colliding after environment coll
  562. resolvement (unlike rotating bodies where each joint is ensured separately
  563. to not collide). So if still in collision, we try a few more times. If not
  564. successful, we simply undo any shifts we've done. This should absolutely
  565. prevent any body escaping out of environment bounds. */
  566. for (uint8_t i = 0; i < TPE_NONROTATING_COLLISION_RESOLVE_ATTEMPTS; ++i)
  567. {
  568. if (!collided)
  569. break;
  570. collided =
  571. TPE_bodyEnvironmentResolveCollision(body,world->environmentFunction);
  572. }
  573. if (collided &&
  574. TPE_bodyEnvironmentCollide(body,world->environmentFunction))
  575. TPE_bodyMove(body,TPE_vec3Minus(origPos,body->joints[0].position));
  576. }
  577. else
  578. {
  579. TPE_Unit bodyTension = 0;
  580. for (uint16_t j = 0; j < body->connectionCount; ++j) // joint tension
  581. {
  582. joint = &(body->joints[connection->joint1]);
  583. joint2 = &(body->joints[connection->joint2]);
  584. TPE_Vec3 dir = TPE_vec3Minus(joint2->position,joint->position);
  585. TPE_Unit len = TPE_LENGTH(dir);
  586. len = (len * TPE_FRACTIONS_PER_UNIT) /
  587. connection->length - TPE_FRACTIONS_PER_UNIT;
  588. bodyTension += len > 0 ? len : -len;
  589. if (len > TPE_TENSION_ACCELERATION_THRESHOLD ||
  590. len < -1 * TPE_TENSION_ACCELERATION_THRESHOLD)
  591. {
  592. TPE_vec3Normalize(&dir);
  593. dir.x /= TPE_TENSION_ACCELERATION_DIVIDER;
  594. dir.y /= TPE_TENSION_ACCELERATION_DIVIDER;
  595. dir.z /= TPE_TENSION_ACCELERATION_DIVIDER;
  596. if (len < 0)
  597. {
  598. dir.x *= -1;
  599. dir.y *= -1;
  600. dir.z *= -1;
  601. }
  602. joint->velocity[0] += dir.x;
  603. joint->velocity[1] += dir.y;
  604. joint->velocity[2] += dir.z;
  605. joint2->velocity[0] -= dir.x;
  606. joint2->velocity[1] -= dir.y;
  607. joint2->velocity[2] -= dir.z;
  608. }
  609. connection++;
  610. }
  611. if (body->connectionCount > 0 && !(body->flags & TPE_BODY_FLAG_SOFT))
  612. {
  613. TPE_bodyReshape(body,world->environmentFunction);
  614. bodyTension /= body->connectionCount;
  615. if (bodyTension > TPE_RESHAPE_TENSION_LIMIT)
  616. for (uint8_t k = 0; k < TPE_RESHAPE_ITERATIONS; ++k)
  617. TPE_bodyReshape(body,world->environmentFunction);
  618. }
  619. }
  620. if (body->deactivateCount >= TPE_DEACTIVATE_AFTER)
  621. {
  622. TPE_bodyStop(body);
  623. body->deactivateCount = 0;
  624. body->flags |= TPE_BODY_FLAG_DEACTIVATED;
  625. }
  626. else if (TPE_bodyAverageSpeed(body) <= TPE_LOW_SPEED) // TODO: optimize
  627. body->deactivateCount++;
  628. else
  629. body->deactivateCount = 0;
  630. }
  631. }
  632. void TPE_bodyActivate(TPE_Body *body)
  633. {
  634. // the if check has to be here, don't remove it
  635. if (body->flags & TPE_BODY_FLAG_DEACTIVATED)
  636. {
  637. TPE_bodyStop(body);
  638. body->flags &= ~TPE_BODY_FLAG_DEACTIVATED;
  639. body->deactivateCount = 0;
  640. }
  641. }
  642. TPE_Unit TPE_bodyNetSpeed(const TPE_Body *body)
  643. {
  644. TPE_Unit velocity = 0;
  645. const TPE_Joint *joint = body->joints;
  646. for (uint16_t i = 0; i < body->jointCount; ++i)
  647. {
  648. velocity += TPE_LENGTH(
  649. TPE_vec3(joint->velocity[0],joint->velocity[1],joint->velocity[2]));
  650. joint++;
  651. }
  652. return velocity;
  653. }
  654. TPE_Unit TPE_bodyAverageSpeed(const TPE_Body *body)
  655. {
  656. return TPE_bodyNetSpeed(body) / body->jointCount;
  657. }
  658. void TPE_bodyMultiplyNetSpeed(TPE_Body *body, TPE_Unit factor)
  659. {
  660. TPE_Joint *joint = body->joints;
  661. for (uint16_t j = 0; j < body->jointCount; ++j)
  662. {
  663. for (uint8_t k = 0; k < 3; ++k)
  664. joint->velocity[k] =
  665. (((TPE_Unit) joint->velocity[k]) * factor) /
  666. TPE_FRACTIONS_PER_UNIT;
  667. joint++;
  668. }
  669. }
  670. void TPE_bodyLimitAverageSpeed(TPE_Body *body, TPE_Unit speedMin,
  671. TPE_Unit speedMax)
  672. {
  673. for (uint8_t i = 0; i < 16; ++i)
  674. {
  675. TPE_Unit speed = TPE_bodyAverageSpeed(body);
  676. if (speed >= speedMin && speed <= speedMax)
  677. return;
  678. TPE_Unit fraction =
  679. (((speedMax + speedMin) / 2) * TPE_FRACTIONS_PER_UNIT) /
  680. TPE_nonZero(speed);
  681. TPE_bodyMultiplyNetSpeed(body,fraction);
  682. }
  683. }
  684. void TPE_bodyReshape(TPE_Body *body,
  685. TPE_ClosestPointFunction environmentFunction)
  686. {
  687. for (uint16_t i = 0; i < body->connectionCount; ++i)
  688. {
  689. TPE_Connection *c = &body->connections[i];
  690. TPE_Joint *j1 = &(body->joints[c->joint1]);
  691. TPE_Joint *j2 = &(body->joints[c->joint2]);
  692. TPE_Vec3 dir = TPE_vec3Minus(j2->position,j1->position);
  693. TPE_Vec3 middle = TPE_vec3Plus(j1->position,j2->position);
  694. middle.x /= 2;
  695. middle.y /= 2;
  696. middle.z /= 2;
  697. TPE_vec3Normalize(&dir);
  698. dir.x = (dir.x * c->length) / TPE_FRACTIONS_PER_UNIT;
  699. dir.y = (dir.y * c->length) / TPE_FRACTIONS_PER_UNIT;
  700. dir.z = (dir.z * c->length) / TPE_FRACTIONS_PER_UNIT;
  701. TPE_Vec3 positionBackup = j1->position;
  702. j1->position.x = middle.x - dir.x / 2;
  703. j1->position.y = middle.y - dir.y / 2;
  704. j1->position.z = middle.z - dir.z / 2;
  705. if (environmentFunction != 0 && TPE_LENGTH(TPE_vec3Minus(j1->position,
  706. environmentFunction(j1->position,TPE_JOINT_SIZE(*j1))))
  707. < TPE_JOINT_SIZE(*j1))
  708. j1->position = positionBackup;
  709. positionBackup = j2->position;
  710. j2->position.x = j1->position.x + dir.x;
  711. j2->position.y = j1->position.y + dir.y;
  712. j2->position.z = j1->position.z + dir.z;
  713. if (environmentFunction != 0 && TPE_LENGTH(TPE_vec3Minus(j2->position,
  714. environmentFunction(j2->position,TPE_JOINT_SIZE(*j2))))
  715. < TPE_JOINT_SIZE(*j2))
  716. j2->position = positionBackup;
  717. }
  718. }
  719. TPE_Vec3 TPE_vec3Plus(TPE_Vec3 v1, TPE_Vec3 v2)
  720. {
  721. v1.x += v2.x;
  722. v1.y += v2.y;
  723. v1.z += v2.z;
  724. return v1;
  725. }
  726. TPE_Vec3 TPE_vec3Minus(TPE_Vec3 v1, TPE_Vec3 v2)
  727. {
  728. v1.x -= v2.x;
  729. v1.y -= v2.y;
  730. v1.z -= v2.z;
  731. return v1;
  732. }
  733. void TPE_vec3Normalize(TPE_Vec3 *v)
  734. {
  735. TPE_Unit l = TPE_LENGTH(*v);
  736. if (l != 0)
  737. {
  738. v->x = (v->x * TPE_FRACTIONS_PER_UNIT) / l;
  739. v->y = (v->y * TPE_FRACTIONS_PER_UNIT) / l;
  740. v->z = (v->z * TPE_FRACTIONS_PER_UNIT) / l;
  741. }
  742. }
  743. TPE_Vec3 TPE_bodyGetOrientation(const TPE_Body *body, uint16_t joint1,
  744. uint16_t joint2, uint16_t joint3)
  745. {
  746. return TPE_orientationFromVecs(
  747. TPE_vec3Minus(
  748. body->joints[joint2].position,
  749. body->joints[joint1].position),
  750. TPE_vec3Minus(
  751. body->joints[joint3].position,
  752. body->joints[joint1].position));
  753. }
  754. TPE_Vec3 TPE_bodyGetCenter(const TPE_Body *body)
  755. {
  756. // TODO: take into account possibly different joint sizes? does it even matter?
  757. TPE_Vec3 result = TPE_vec3(0,0,0);
  758. const TPE_Joint *j = body->joints;
  759. for (uint16_t i = 0; i < body->jointCount; ++i)
  760. {
  761. result = TPE_vec3Plus(result,j->position);
  762. j++;
  763. }
  764. result.x /= body->jointCount;
  765. result.y /= body->jointCount;
  766. result.z /= body->jointCount;
  767. return result;
  768. }
  769. void TPE_bodySpin(TPE_Body *body, TPE_Vec3 rotation)
  770. {
  771. TPE_Vec3 center = TPE_bodyGetCenter(body);
  772. for (uint16_t i = 0; i < body->jointCount; ++i)
  773. {
  774. TPE_Joint *j = body->joints + i;
  775. TPE_Vec3 toPoint = TPE_vec3Minus(j->position,center);
  776. toPoint = TPE_vec3Project(toPoint,rotation);
  777. toPoint = TPE_vec3Plus(center,toPoint);
  778. toPoint = TPE_vec3Minus(j->position,toPoint);
  779. toPoint = TPE_vec3Cross(toPoint,rotation);
  780. j->velocity[0] += toPoint.x;
  781. j->velocity[1] += toPoint.y;
  782. j->velocity[2] += toPoint.z;
  783. }
  784. }
  785. void TPE_bodyRotateByAxis(TPE_Body *body, TPE_Vec3 rotation)
  786. {
  787. TPE_Vec3 bodyCenter = TPE_bodyGetCenter(body);
  788. TPE_Unit angle = TPE_LENGTH(rotation);
  789. TPE_vec3Normalize(&rotation);
  790. for (uint16_t i = 0; i < body->jointCount; ++i)
  791. {
  792. TPE_Joint *j = body->joints + i;
  793. TPE_Vec3 toPoint = TPE_vec3Minus(j->position,bodyCenter);
  794. toPoint = TPE_vec3Project(toPoint,rotation);
  795. TPE_Vec3 rotationCenter = TPE_vec3Plus(bodyCenter,toPoint);
  796. toPoint = TPE_vec3Minus(j->position,rotationCenter);
  797. TPE_Vec3 toPoint2 = TPE_vec3Cross(toPoint,rotation);
  798. j->position = TPE_vec3Plus(rotationCenter,
  799. TPE_vec3Plus(
  800. TPE_vec3Times(toPoint,TPE_cos(angle)),
  801. TPE_vec3Times(toPoint2,TPE_sin(angle))));
  802. }
  803. }
  804. TPE_Vec3 TPE_vec3Cross(TPE_Vec3 v1, TPE_Vec3 v2)
  805. {
  806. TPE_Vec3 r;
  807. r.x = (v1.y * v2.z - v1.z * v2.y) / TPE_FRACTIONS_PER_UNIT;
  808. r.y = (v1.z * v2.x - v1.x * v2.z) / TPE_FRACTIONS_PER_UNIT;
  809. r.z = (v1.x * v2.y - v1.y * v2.x) / TPE_FRACTIONS_PER_UNIT;
  810. return r;
  811. }
  812. TPE_Vec3 TPE_vec3Project(TPE_Vec3 v, TPE_Vec3 base)
  813. {
  814. TPE_Vec3 r;
  815. TPE_vec3Normalize(&base);
  816. TPE_Unit p = TPE_vec3Dot(v,base);
  817. r.x = (p * base.x) / TPE_FRACTIONS_PER_UNIT;
  818. r.y = (p * base.y) / TPE_FRACTIONS_PER_UNIT;
  819. r.z = (p * base.z) / TPE_FRACTIONS_PER_UNIT;
  820. return r;
  821. }
  822. void TPE_bodyMove(TPE_Body *body, TPE_Vec3 offset)
  823. {
  824. for (uint16_t i = 0; i < body->jointCount; ++i)
  825. body->joints[i].position = TPE_vec3Plus(body->joints[i].position,
  826. offset);
  827. }
  828. void TPE_bodyApplyGravity(TPE_Body *body, TPE_Unit downwardsAccel)
  829. {
  830. if ((body->flags & TPE_BODY_FLAG_DEACTIVATED) ||
  831. (body->flags & TPE_BODY_FLAG_DISABLED))
  832. return;
  833. for (uint16_t i = 0; i < body->jointCount; ++i)
  834. body->joints[i].velocity[1] -= downwardsAccel;
  835. }
  836. void TPE_bodyAccelerate(TPE_Body *body, TPE_Vec3 velocity)
  837. {
  838. TPE_bodyActivate(body);
  839. for (uint16_t i = 0; i < body->jointCount; ++i)
  840. {
  841. body->joints[i].velocity[0] += velocity.x;
  842. body->joints[i].velocity[1] += velocity.y;
  843. body->joints[i].velocity[2] += velocity.z;
  844. }
  845. }
  846. void TPE_bodyStop(TPE_Body *body)
  847. {
  848. for (uint16_t i = 0; i < body->jointCount; ++i)
  849. {
  850. body->joints[i].velocity[0] = 0;
  851. body->joints[i].velocity[1] = 0;
  852. body->joints[i].velocity[2] = 0;
  853. }
  854. }
  855. void _TPE_bodyNonrotatingJointCollided(TPE_Body *b, int16_t jointIndex,
  856. TPE_Vec3 origPos, uint8_t success)
  857. {
  858. origPos = TPE_vec3Minus(b->joints[jointIndex].position,origPos);
  859. for (uint16_t i = 0; i < b->jointCount; ++i)
  860. if (i != jointIndex)
  861. {
  862. b->joints[i].position = TPE_vec3Plus(b->joints[i].position,origPos);
  863. if (success)
  864. for (uint8_t j = 0; j < 3; ++j)
  865. b->joints[i].velocity[j] = b->joints[jointIndex].velocity[j];
  866. }
  867. }
  868. TPE_Unit TPE_vec3Dot(TPE_Vec3 v1, TPE_Vec3 v2)
  869. {
  870. return (v1.x * v2.x + v1.y * v2.y + v1.z * v2.z) / TPE_FRACTIONS_PER_UNIT;
  871. }
  872. TPE_Unit TPE_cos(TPE_Unit x)
  873. {
  874. return TPE_sin(x + TPE_FRACTIONS_PER_UNIT / 4);
  875. }
  876. TPE_Unit TPE_sin(TPE_Unit x)
  877. {
  878. int8_t sign = 1;
  879. if (x < 0) // odd function
  880. {
  881. x *= -1;
  882. sign = -1;
  883. }
  884. x %= TPE_FRACTIONS_PER_UNIT;
  885. if (x > TPE_FRACTIONS_PER_UNIT / 2)
  886. {
  887. x -= TPE_FRACTIONS_PER_UNIT / 2;
  888. sign *= -1;
  889. }
  890. TPE_Unit tmp = TPE_FRACTIONS_PER_UNIT - 2 * x;
  891. #define _PI2 ((TPE_Unit) (9.8696044 * TPE_FRACTIONS_PER_UNIT))
  892. return sign * // Bhaskara's approximation
  893. (((32 * x * _PI2) / TPE_FRACTIONS_PER_UNIT) * tmp) /
  894. ((_PI2 * (5 * TPE_FRACTIONS_PER_UNIT - (8 * x * tmp) /
  895. TPE_FRACTIONS_PER_UNIT)) / TPE_FRACTIONS_PER_UNIT);
  896. #undef _PI2
  897. }
  898. uint8_t TPE_bodiesResolveCollision(TPE_Body *b1, TPE_Body *b2)
  899. {
  900. uint8_t r = 0;
  901. for (uint16_t i = 0; i < b1->jointCount; ++i)
  902. for (uint16_t j = 0; j < b2->jointCount; ++j)
  903. {
  904. TPE_Vec3 origPos2 = b2->joints[j].position;
  905. TPE_Vec3 origPos1 = b1->joints[i].position;
  906. _TPE_joint1Index = i;
  907. _TPE_joint2Index = j;
  908. if (TPE_jointsResolveCollision(&(b1->joints[i]),&(b2->joints[j]),
  909. b1->jointMass,b2->jointMass,(b1->elasticity + b2->elasticity) / 2,
  910. (b1->friction + b2->friction) / 2))
  911. {
  912. r = 1;
  913. if (b1->flags & TPE_BODY_FLAG_NONROTATING)
  914. _TPE_bodyNonrotatingJointCollided(b1,i,origPos1,1);
  915. if (b2->flags & TPE_BODY_FLAG_NONROTATING)
  916. _TPE_bodyNonrotatingJointCollided(b2,j,origPos2,1);
  917. }
  918. }
  919. return r;
  920. }
  921. uint8_t TPE_jointsResolveCollision(TPE_Joint *j1, TPE_Joint *j2,
  922. TPE_Unit mass1, TPE_Unit mass2, TPE_Unit elasticity, TPE_Unit friction)
  923. {
  924. TPE_Vec3 dir = TPE_vec3Minus(j2->position,j1->position);
  925. TPE_Unit d = TPE_LENGTH(dir) - TPE_JOINT_SIZE(*j1) - TPE_JOINT_SIZE(*j2);
  926. if (d < 0) // collision?
  927. {
  928. if (_TPE_collisionCallback != 0)
  929. if (!_TPE_collisionCallback(_TPE_body1Index,_TPE_joint1Index,
  930. _TPE_body2Index,_TPE_joint2Index,TPE_vec3Plus(j1->position,dir)))
  931. return 0;
  932. // separate bodies, the shift distance will depend on the weight ratio:
  933. d = -1 * d + TPE_COLLISION_RESOLUTION_MARGIN;
  934. TPE_vec3Normalize(&dir);
  935. TPE_Unit ratio = (mass2 * TPE_FRACTIONS_PER_UNIT) /
  936. TPE_nonZero(mass1 + mass2);
  937. TPE_Unit shiftDistance = (ratio * d) / TPE_FRACTIONS_PER_UNIT;
  938. TPE_Vec3 shift = TPE_vec3Times(dir,shiftDistance);
  939. j1->position = TPE_vec3Minus(j1->position,shift);
  940. shiftDistance = d - shiftDistance;
  941. shift = TPE_vec3Times(dir,shiftDistance);
  942. j2->position = TPE_vec3Plus(j2->position,shift);
  943. // compute new velocities:
  944. TPE_Unit v1, v2;
  945. TPE_Vec3 vel = TPE_vec3(j1->velocity[0],j1->velocity[1],j1->velocity[2]);
  946. vel = TPE_vec3Project(vel,dir);
  947. j1->velocity[0] = j1->velocity[0] - vel.x;
  948. j1->velocity[1] = j1->velocity[1] - vel.y;
  949. j1->velocity[2] = j1->velocity[2] - vel.z;
  950. /* friction explanation: Not physically correct (doesn't depend on load),
  951. friction basically means we weighted average the velocities of the bodies
  952. in the direction perpendicular to the hit normal, in the ratio of their
  953. masses, friction coefficient just says how much of this effect we apply
  954. (it multiplies the friction vectors we are subtracting) */
  955. TPE_Vec3 frictionVec =
  956. TPE_vec3(j1->velocity[0],j1->velocity[1],j1->velocity[2]);
  957. v1 = TPE_vec3Dot(vel,dir);
  958. vel = TPE_vec3(j2->velocity[0],j2->velocity[1],j2->velocity[2]);
  959. vel = TPE_vec3Project(vel,dir);
  960. j2->velocity[0] = j2->velocity[0] - vel.x;
  961. j2->velocity[1] = j2->velocity[1] - vel.y;
  962. j2->velocity[2] = j2->velocity[2] - vel.z;
  963. frictionVec = TPE_vec3Minus(
  964. TPE_vec3(j2->velocity[0],j2->velocity[1],j2->velocity[2]),
  965. frictionVec);
  966. v2 = TPE_vec3Dot(vel,dir);
  967. TPE_getVelocitiesAfterCollision(&v1,&v2,mass1,mass2,elasticity);
  968. vel = TPE_vec3Times(dir,v1);
  969. #define assignVec(j,i,d,o) \
  970. j->velocity[i] = j->velocity[i] + vel.d o (((frictionVec.d * ratio) / \
  971. TPE_FRACTIONS_PER_UNIT) * friction) / TPE_FRACTIONS_PER_UNIT;
  972. assignVec(j1,0,x,+)
  973. assignVec(j1,1,y,+)
  974. assignVec(j1,2,z,+)
  975. vel = TPE_vec3Times(dir,v2);
  976. ratio = TPE_FRACTIONS_PER_UNIT - ratio;
  977. assignVec(j2,0,x,-)
  978. assignVec(j2,1,y,-)
  979. assignVec(j2,2,z,-)
  980. #undef assignVec
  981. return 1;
  982. }
  983. return 0;
  984. }
  985. TPE_Vec3 TPE_vec3Times(TPE_Vec3 v, TPE_Unit units)
  986. {
  987. v.x = (v.x * units) / TPE_FRACTIONS_PER_UNIT;
  988. v.y = (v.y * units) / TPE_FRACTIONS_PER_UNIT;
  989. v.z = (v.z * units) / TPE_FRACTIONS_PER_UNIT;
  990. return v;
  991. }
  992. TPE_Vec3 TPE_vec3TimesNonNormalized(TPE_Vec3 v, TPE_Unit q)
  993. {
  994. v.x *= q;
  995. v.y *= q;
  996. v.z *= q;
  997. return v;
  998. }
  999. void TPE_getVelocitiesAfterCollision(
  1000. TPE_Unit *v1,
  1001. TPE_Unit *v2,
  1002. TPE_Unit m1,
  1003. TPE_Unit m2,
  1004. TPE_Unit elasticity
  1005. )
  1006. {
  1007. /* In the following a lot of TPE_FRACTIONS_PER_UNIT cancel out, feel free to
  1008. check if confused. */
  1009. TPE_Unit m1Pm2 = TPE_nonZero(m1 + m2);
  1010. TPE_Unit v2Mv1 = TPE_nonZero(*v2 - *v1);
  1011. TPE_Unit m1v1Pm2v2 = ((m1 * *v1) + (m2 * *v2));
  1012. *v1 = (((elasticity * m2 / TPE_FRACTIONS_PER_UNIT) * v2Mv1)
  1013. + m1v1Pm2v2) / m1Pm2;
  1014. *v2 = (((elasticity * m1 / TPE_FRACTIONS_PER_UNIT) * -1 * v2Mv1)
  1015. + m1v1Pm2v2) / m1Pm2;
  1016. }
  1017. uint8_t TPE_jointEnvironmentResolveCollision(TPE_Joint *joint, TPE_Unit elasticity,
  1018. TPE_Unit friction, TPE_ClosestPointFunction env)
  1019. {
  1020. TPE_Vec3 toJoint = TPE_vec3Minus(joint->position,env(joint->position,TPE_JOINT_SIZE(*joint)));
  1021. TPE_Unit len = TPE_LENGTH(toJoint);
  1022. if (len <= TPE_JOINT_SIZE(*joint))
  1023. {
  1024. if (_TPE_collisionCallback != 0)
  1025. if (!_TPE_collisionCallback(_TPE_body1Index,
  1026. _TPE_joint1Index,_TPE_body2Index,_TPE_joint2Index,
  1027. TPE_vec3Minus(joint->position,toJoint)))
  1028. return 0;
  1029. // colliding
  1030. TPE_Vec3 positionBackup = joint->position, shift;
  1031. uint8_t success = 0;
  1032. if (len > 0)
  1033. {
  1034. /* Joint center is still outside the geometry so we can determine the
  1035. normal and use it to shift it outside. This can still leave the joint
  1036. colliding though, so try to repeat it a few times. */
  1037. for (int i = 0; i < TPE_COLLISION_RESOLUTION_ITERATIONS; ++i)
  1038. {
  1039. shift = toJoint;
  1040. TPE_vec3Normalize(&shift);
  1041. shift = TPE_vec3Times(shift,TPE_JOINT_SIZE(*joint) - len +
  1042. TPE_COLLISION_RESOLUTION_MARGIN);
  1043. joint->position = TPE_vec3Plus(joint->position,shift);
  1044. toJoint = TPE_vec3Minus(joint->position,env(joint->position,
  1045. TPE_JOINT_SIZE(*joint)));
  1046. len = TPE_LENGTH(toJoint); // still colliding?
  1047. if (len >= TPE_JOINT_SIZE(*joint))
  1048. {
  1049. success = 1;
  1050. break;
  1051. }
  1052. }
  1053. }
  1054. if (!success)
  1055. {
  1056. /* Shifting along normal was unsuccessfull, now try different approach:
  1057. shift back by joint velocity. */
  1058. shift = TPE_vec3(-1 * joint->velocity[0],-1 * joint->velocity[1],
  1059. -1 * joint->velocity[2]);
  1060. for (int i = 0; i < TPE_COLLISION_RESOLUTION_ITERATIONS; ++i)
  1061. {
  1062. joint->position = TPE_vec3Plus(joint->position,shift);
  1063. toJoint = TPE_vec3Minus(joint->position,env(joint->position,TPE_JOINT_SIZE(*joint)));
  1064. len = TPE_LENGTH(toJoint); // still colliding?
  1065. if (len >= TPE_JOINT_SIZE(*joint))
  1066. {
  1067. success = 1;
  1068. break;
  1069. }
  1070. shift.x /= 2; // decrease the step a bit
  1071. shift.y /= 2;
  1072. shift.z /= 2;
  1073. }
  1074. }
  1075. if (success)
  1076. {
  1077. TPE_Vec3 vel = TPE_vec3(joint->velocity[0],joint->velocity[1],
  1078. joint->velocity[2]);
  1079. vel = TPE_vec3Project(vel,shift); // parallel part of velocity
  1080. TPE_Vec3 vel2 = TPE_vec3Minus( // perpendicular part of velocity
  1081. TPE_vec3(joint->velocity[0],joint->velocity[1],joint->velocity[2]),vel);
  1082. vel2 = TPE_vec3Times(vel2,friction);
  1083. vel = TPE_vec3Times(vel,TPE_FRACTIONS_PER_UNIT + elasticity);
  1084. joint->velocity[0] -= vel.x + vel2.x;
  1085. joint->velocity[1] -= vel.y + vel2.y;
  1086. joint->velocity[2] -= vel.z + vel2.z;
  1087. }
  1088. else
  1089. {
  1090. TPE_LOG("WARNING: joint-environment collision couldn't be resolved");
  1091. joint->position = positionBackup;
  1092. joint->velocity[0] = 0;
  1093. joint->velocity[1] = 0;
  1094. joint->velocity[2] = 0;
  1095. return 2;
  1096. }
  1097. return 1;
  1098. }
  1099. return 0;
  1100. }
  1101. uint8_t TPE_bodyEnvironmentCollide(const TPE_Body *body,
  1102. TPE_ClosestPointFunction env)
  1103. {
  1104. // TODO: should bounding vol check be here? maybe in param?
  1105. for (uint16_t i = 0; i < body->jointCount; ++i)
  1106. {
  1107. const TPE_Joint *joint = body->joints + i;
  1108. TPE_Unit size = TPE_JOINT_SIZE(*joint);
  1109. if (TPE_DISTANCE(joint->position,env(joint->position,size)) <= size)
  1110. return 1;
  1111. }
  1112. return 0;
  1113. }
  1114. uint8_t TPE_bodyEnvironmentResolveCollision(TPE_Body *body,
  1115. TPE_ClosestPointFunction env)
  1116. {
  1117. /* Bounding sphere test first. NOTE: This is not a minimal bounding sphere
  1118. but one created from the bounding box. Hopes are that this can be faster.
  1119. TODO: actually test if the minimal B sphere is faster */
  1120. TPE_Vec3 v1, v2;
  1121. TPE_bodyGetAABB(body,&v1,&v2);
  1122. v1.x = (v1.x + v2.x) / 2;
  1123. v1.y = (v1.y + v2.y) / 2;
  1124. v1.z = (v1.z + v2.z) / 2;
  1125. TPE_Unit d = TPE_DISTANCE(v1,v2);
  1126. if (TPE_DISTANCE(v1,env(v1,d)) > d)
  1127. return 0;
  1128. // now test the full body collision:
  1129. uint8_t collision = 0;
  1130. for (uint16_t i = 0; i < body->jointCount; ++i)
  1131. {
  1132. TPE_Vec3 previousPos = body->joints[i].position;
  1133. _TPE_joint1Index = i;
  1134. uint8_t r = TPE_jointEnvironmentResolveCollision(
  1135. body->joints + i,body->elasticity,body->friction,env);
  1136. if (r)
  1137. {
  1138. collision = 1;
  1139. if (body->flags & TPE_BODY_FLAG_NONROTATING)
  1140. _TPE_bodyNonrotatingJointCollided(body,i,previousPos,r == 1);
  1141. }
  1142. }
  1143. return collision;
  1144. }
  1145. TPE_Vec3 TPE_vec3Normalized(TPE_Vec3 v)
  1146. {
  1147. TPE_vec3Normalize(&v);
  1148. return v;
  1149. }
  1150. TPE_Unit TPE_atan(TPE_Unit x)
  1151. {
  1152. /* atan approximation by polynomial
  1153. WARNING: this will break with different value of TPE_FRACTIONS_PER_UNIT */
  1154. TPE_Unit sign = 1, x2 = x * x;
  1155. if (x < 0)
  1156. {
  1157. x *= -1;
  1158. sign = -1;
  1159. }
  1160. if (x > 30000) // anti overflow
  1161. return sign * (TPE_FRACTIONS_PER_UNIT / 4);
  1162. return sign *
  1163. (307 * x + x2) / ((267026 + 633 * x + x2) / 128);
  1164. }
  1165. void _TPE_vec2Rotate(TPE_Unit *x, TPE_Unit *y, TPE_Unit angle)
  1166. {
  1167. TPE_Unit tmp = *x;
  1168. TPE_Unit s = TPE_sin(angle);
  1169. TPE_Unit c = TPE_cos(angle);
  1170. *x = (c * *x - s * *y) / TPE_FRACTIONS_PER_UNIT;
  1171. *y = (s * tmp + c * *y) / TPE_FRACTIONS_PER_UNIT;
  1172. }
  1173. TPE_Unit _TPE_vec2Angle(TPE_Unit x, TPE_Unit y)
  1174. {
  1175. TPE_Unit r = 0;
  1176. if (x != 0)
  1177. {
  1178. r = TPE_atan((y * TPE_FRACTIONS_PER_UNIT) / x);
  1179. if (x < 0)
  1180. r += TPE_FRACTIONS_PER_UNIT / 2;
  1181. else if (r < 0)
  1182. r += TPE_FRACTIONS_PER_UNIT;
  1183. }
  1184. else
  1185. {
  1186. if (y < 0)
  1187. r = (3 * TPE_FRACTIONS_PER_UNIT) / 4;
  1188. else if (y > 0)
  1189. r = TPE_FRACTIONS_PER_UNIT / 4;
  1190. // else (y == 0) r stays 0
  1191. }
  1192. return r;
  1193. }
  1194. TPE_Vec3 TPE_orientationFromVecs(TPE_Vec3 forward, TPE_Vec3 right)
  1195. {
  1196. TPE_Vec3 result;
  1197. // get rotation around Y:
  1198. result.y = _TPE_vec2Angle(forward.z,-1 * forward.x);
  1199. // now rotate back by this angle to align with x = 0 plane:
  1200. _TPE_vec2Rotate(&forward.z,&forward.x,result.y);
  1201. _TPE_vec2Rotate(&right.z,&right.x,result.y);
  1202. // now do the same for the second axis:
  1203. result.x =
  1204. _TPE_vec2Angle(forward.z,forward.y);
  1205. _TPE_vec2Rotate(&right.z,&right.y,-1 * result.x);
  1206. result.z = _TPE_vec2Angle(right.x,-1 * right.y);
  1207. return result;
  1208. }
  1209. TPE_Vec3 _TPE_project3DPoint(TPE_Vec3 p, TPE_Vec3 camPos, TPE_Vec3 camRot,
  1210. TPE_Vec3 camView)
  1211. {
  1212. // transform to camera space:
  1213. p = TPE_vec3Minus(p,camPos);
  1214. _TPE_vec2Rotate(&p.z,&p.x,camRot.y);
  1215. _TPE_vec2Rotate(&p.z,&p.y,-1 * camRot.x);
  1216. _TPE_vec2Rotate(&p.y,&p.x,-1 * camRot.z);
  1217. if (p.z <= 0)
  1218. return p;
  1219. p.x = (p.x * camView.z) / p.z;
  1220. p.y = (p.y * camView.z) / p.z;
  1221. p.x = camView.x / 2 + (p.x * camView.x) / (2 * TPE_FRACTIONS_PER_UNIT);
  1222. p.y = camView.y / 2 - (p.y * camView.x) / (2 * TPE_FRACTIONS_PER_UNIT);
  1223. // ^ x here intentional
  1224. return p;
  1225. }
  1226. void _TPE_drawDebugPixel(
  1227. TPE_Unit x, TPE_Unit y, TPE_Unit w, TPE_Unit h, uint8_t c,
  1228. TPE_DebugDrawFunction f)
  1229. {
  1230. if (x >= 0 && x < w && y >= 0 && y < h)
  1231. f(x,y,c);
  1232. }
  1233. void TPE_worldDebugDraw(TPE_World *world, TPE_DebugDrawFunction drawFunc,
  1234. TPE_Vec3 camPos, TPE_Vec3 camRot, TPE_Vec3 camView, uint16_t envGridRes,
  1235. TPE_Unit envGridSize)
  1236. {
  1237. #define Z_LIMIT 250
  1238. if (world->environmentFunction != 0)
  1239. {
  1240. // environment:
  1241. TPE_Vec3 testPoint;
  1242. TPE_Vec3 center = TPE_vec3(0,TPE_sin(camRot.x),TPE_cos(camRot.x));
  1243. _TPE_vec2Rotate(&center.x,&center.z,camRot.y);
  1244. TPE_Unit gridHalfSize = (envGridSize * envGridRes) / 2;
  1245. center = TPE_vec3Times(center,gridHalfSize);
  1246. center = TPE_vec3Plus(camPos,center);
  1247. center.x = (center.x / envGridSize) * envGridSize;
  1248. center.y = (center.y / envGridSize) * envGridSize;
  1249. center.z = (center.z / envGridSize) * envGridSize;
  1250. testPoint.y = center.y - gridHalfSize;
  1251. for (uint8_t j = 0; j < envGridRes; ++j)
  1252. {
  1253. testPoint.x = center.x - gridHalfSize;
  1254. for (uint8_t k = 0; k < envGridRes; ++k)
  1255. {
  1256. testPoint.z = center.z - gridHalfSize;
  1257. for (uint8_t l = 0; l < envGridRes; ++l)
  1258. {
  1259. TPE_Vec3 r = world->environmentFunction(testPoint,envGridSize);
  1260. if ((r.x != testPoint.x || r.y != testPoint.y || r.z != testPoint.z))
  1261. {
  1262. // TODO: accel. by testing cheb dist first?
  1263. r = _TPE_project3DPoint(r,camPos,camRot,camView);
  1264. if (r.z > Z_LIMIT)
  1265. _TPE_drawDebugPixel(r.x,r.y,camView.x,camView.y,2,drawFunc);
  1266. }
  1267. testPoint.z += envGridSize;
  1268. }
  1269. testPoint.x += envGridSize;
  1270. }
  1271. testPoint.y += envGridSize;
  1272. }
  1273. }
  1274. for (uint16_t i = 0; i < world->bodyCount; ++i)
  1275. {
  1276. // connections:
  1277. for (uint16_t j = 0; j < world->bodies[i].connectionCount; ++j)
  1278. {
  1279. TPE_Vec3
  1280. p1 = world->bodies[i].joints[world->bodies[i].connections[j].joint1].position,
  1281. p2 = world->bodies[i].joints[world->bodies[i].connections[j].joint2].position;
  1282. p1 = _TPE_project3DPoint(p1,camPos,camRot,camView);
  1283. p2 = _TPE_project3DPoint(p2,camPos,camRot,camView);
  1284. if (p1.z <= Z_LIMIT || p2.z <= Z_LIMIT)
  1285. continue;
  1286. TPE_Vec3 diff = TPE_vec3Minus(p2,p1);
  1287. #define SEGS 16
  1288. for (uint16_t k = 0; k < SEGS; ++k)
  1289. {
  1290. p2.x = p1.x + (diff.x * k) / SEGS;
  1291. p2.y = p1.y + (diff.y * k) / SEGS;
  1292. _TPE_drawDebugPixel(p2.x,p2.y,camView.x,camView.y,0,drawFunc);
  1293. }
  1294. #undef SEGS
  1295. }
  1296. // joints:
  1297. for (uint16_t j = 0; j < world->bodies[i].jointCount; ++j)
  1298. {
  1299. TPE_Vec3 p = _TPE_project3DPoint(world->bodies[i].joints[j].position,
  1300. camPos,camRot,camView);
  1301. if (p.z > Z_LIMIT)
  1302. {
  1303. _TPE_drawDebugPixel(p.x,p.y,camView.x,camView.y,1,drawFunc);
  1304. TPE_Unit size = TPE_JOINT_SIZE(world->bodies[i].joints[j]) / 2;
  1305. size = (size * camView.x) / TPE_FRACTIONS_PER_UNIT;
  1306. size = (size * camView.z) / p.z;
  1307. #define SEGS 4
  1308. for (uint8_t k = 0; k < SEGS + 1; ++k)
  1309. {
  1310. TPE_Unit
  1311. dx = (TPE_sin(TPE_FRACTIONS_PER_UNIT * k / (8 * SEGS)) * size)
  1312. / TPE_FRACTIONS_PER_UNIT,
  1313. dy = (TPE_cos(TPE_FRACTIONS_PER_UNIT * k / (8 * SEGS)) * size)
  1314. / TPE_FRACTIONS_PER_UNIT;
  1315. #define dp(a,b,c,d) \
  1316. _TPE_drawDebugPixel(p.x a b,p.y c d,camView.x,camView.y,1,drawFunc);
  1317. dp(+,dx,+,dy) dp(+,dx,-,dy) dp(-,dx,+,dy) dp(-,dx,-,dy)
  1318. dp(+,dy,+,dx) dp(+,dy,-,dx) dp(-,dy,+,dx) dp(-,dy,-,dx)
  1319. #undef dp
  1320. #undef SEGS
  1321. }
  1322. }
  1323. }
  1324. }
  1325. #undef Z_LIMIT
  1326. }
  1327. TPE_Vec3 TPE_envBox(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 maxCornerVec,
  1328. TPE_Vec3 rotation)
  1329. {
  1330. point = TPE_pointRotate(TPE_vec3Minus(point,center),
  1331. TPE_rotationInverse(rotation));
  1332. return TPE_vec3Plus(center,TPE_pointRotate(TPE_envAABox(point,TPE_vec3(0,0,0),
  1333. maxCornerVec),rotation));
  1334. }
  1335. TPE_Vec3 TPE_envAABox(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 maxCornerVec)
  1336. {
  1337. TPE_Vec3 shifted = TPE_vec3Minus(point,center);
  1338. int8_t sign[3] = {1, 1, 1};
  1339. if (shifted.x < 0)
  1340. {
  1341. shifted.x *= -1;
  1342. sign[0] = -1;
  1343. }
  1344. if (shifted.y < 0)
  1345. {
  1346. shifted.y *= -1;
  1347. sign[1] = -1;
  1348. }
  1349. if (shifted.z < 0)
  1350. {
  1351. shifted.z *= -1;
  1352. sign[2] = -1;
  1353. }
  1354. uint8_t region =
  1355. (shifted.x > maxCornerVec.x) |
  1356. ((shifted.y > maxCornerVec.y) << 1) |
  1357. ((shifted.z > maxCornerVec.z) << 2);
  1358. switch (region)
  1359. {
  1360. #define align(c,i) point.c = center.c + sign[i] * maxCornerVec.c
  1361. case 0x01: align(x,0); break;
  1362. case 0x02: align(y,1); break;
  1363. case 0x04: align(z,2); break;
  1364. case 0x03: align(x,0); align(y,1); break;
  1365. case 0x05: align(x,0); align(z,2); break;
  1366. case 0x06: align(y,1); align(z,2); break;
  1367. case 0x07: align(x,0); align(y,1); align(z,2); break;
  1368. default: break;
  1369. #undef align
  1370. }
  1371. return point;
  1372. }
  1373. TPE_Vec3 TPE_envAABoxInside(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 size)
  1374. {
  1375. size.x /= 2;
  1376. size.y /= 2;
  1377. size.z /= 2;
  1378. TPE_Vec3 shifted = TPE_vec3Minus(point,center);
  1379. TPE_Vec3 a = TPE_vec3Minus(size,shifted),
  1380. b = TPE_vec3Plus(shifted,size);
  1381. int8_t sx = 1, sy = 1, sz = 1;
  1382. if (b.x < a.x)
  1383. {
  1384. a.x = b.x;
  1385. sx = -1;
  1386. }
  1387. if (b.y < a.y)
  1388. {
  1389. a.y = b.y;
  1390. sy = -1;
  1391. }
  1392. if (b.z < a.z)
  1393. {
  1394. a.z = b.z;
  1395. sz = -1;
  1396. }
  1397. if (a.x < 0 || a.y < 0 || a.z < 0)
  1398. return point;
  1399. if (a.x < a.y)
  1400. {
  1401. if (a.x < a.z)
  1402. point.x = center.x + sx * size.x;
  1403. else
  1404. point.z = center.z + sz * size.z;
  1405. }
  1406. else
  1407. {
  1408. if (a.y < a.z)
  1409. point.y = center.y + sy * size.y;
  1410. else
  1411. point.z = center.z + sz * size.z;
  1412. }
  1413. return point;
  1414. }
  1415. TPE_Vec3 TPE_envSphere(TPE_Vec3 point, TPE_Vec3 center, TPE_Unit radius)
  1416. {
  1417. // TODO: optim?
  1418. TPE_Vec3 dir = TPE_vec3Minus(point,center);
  1419. TPE_Unit l = TPE_LENGTH(dir);
  1420. if (l <= radius)
  1421. return point;
  1422. dir.x = (dir.x * radius) / l;
  1423. dir.y = (dir.y * radius) / l;
  1424. dir.z = (dir.z * radius) / l;
  1425. return TPE_vec3Plus(center,dir);
  1426. }
  1427. TPE_Vec3 TPE_envHalfPlane(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 normal)
  1428. {
  1429. TPE_Vec3 point2 = TPE_vec3Minus(point,center);
  1430. TPE_Unit tmp = point2.x * normal.x + point2.y * normal.y + point2.z * normal.z;
  1431. if (tmp < 0)
  1432. return point;
  1433. TPE_Unit l = TPE_LENGTH(normal);
  1434. tmp /= l;
  1435. normal.x = (normal.x * TPE_FRACTIONS_PER_UNIT) / l;
  1436. normal.y = (normal.y * TPE_FRACTIONS_PER_UNIT) / l;
  1437. normal.z = (normal.z * TPE_FRACTIONS_PER_UNIT) / l;
  1438. return TPE_vec3Minus(point,
  1439. TPE_vec3Times(normal,tmp));
  1440. }
  1441. uint8_t TPE_checkOverlapAABB(TPE_Vec3 v1Min, TPE_Vec3 v1Max, TPE_Vec3 v2Min,
  1442. TPE_Vec3 v2Max)
  1443. {
  1444. TPE_Unit dist;
  1445. #define test(c) \
  1446. dist = v1Min.c + v1Max.c - v2Max.c - v2Min.c; \
  1447. if (dist < 0) dist *= -1; \
  1448. if (dist > v1Max.c - v1Min.c + v2Max.c - v2Min.c) return 0;
  1449. test(x)
  1450. test(y)
  1451. test(z)
  1452. #undef test
  1453. return 1;
  1454. }
  1455. void TPE_bodyGetAABB(const TPE_Body *body, TPE_Vec3 *vMin, TPE_Vec3 *vMax)
  1456. {
  1457. *vMin = body->joints[0].position;
  1458. *vMax = *vMin;
  1459. TPE_Unit js = TPE_JOINT_SIZE(body->joints[0]);
  1460. vMin->x -= js;
  1461. vMin->y -= js;
  1462. vMin->z -= js;
  1463. vMax->x += js;
  1464. vMax->y += js;
  1465. vMax->z += js;
  1466. for (uint16_t i = 1; i < body->jointCount; ++i)
  1467. {
  1468. TPE_Unit v;
  1469. js = TPE_JOINT_SIZE(body->joints[i]);
  1470. #define test(c) \
  1471. v = body->joints[i].position.c - js; \
  1472. if (v < vMin->c) \
  1473. vMin->c = v; \
  1474. v += 2 * js; \
  1475. if (v > vMax->c) \
  1476. vMax->c = v;
  1477. test(x)
  1478. test(y)
  1479. test(z)
  1480. #undef test
  1481. }
  1482. }
  1483. void TPE_jointPin(TPE_Joint *joint, TPE_Vec3 position)
  1484. {
  1485. joint->position = position;
  1486. joint->velocity[0] = 0;
  1487. joint->velocity[1] = 0;
  1488. joint->velocity[2] = 0;
  1489. }
  1490. TPE_Vec3 TPE_pointRotate(TPE_Vec3 point, TPE_Vec3 rotation)
  1491. {
  1492. _TPE_vec2Rotate(&point.y,&point.x,rotation.z);
  1493. _TPE_vec2Rotate(&point.z,&point.y,rotation.x);
  1494. _TPE_vec2Rotate(&point.x,&point.z,rotation.y);
  1495. return point;
  1496. }
  1497. TPE_Vec3 TPE_rotationInverse(TPE_Vec3 rotation)
  1498. {
  1499. /* If r1 = (X,Y,Z) is rotation in convention ABC then r1^-1 = (-X,-Y,-Z) in
  1500. convention CBA is its inverse rotation. We exploit this, i.e. we rotate
  1501. forward/right vectors in opposite axis order and then turn the result
  1502. into normal rotation/orientation. */
  1503. TPE_Vec3 f = TPE_vec3(0,0,TPE_FRACTIONS_PER_UNIT);
  1504. TPE_Vec3 r = TPE_vec3(TPE_FRACTIONS_PER_UNIT,0,0);
  1505. rotation.x *= -1;
  1506. rotation.y *= -1;
  1507. rotation.z *= -1;
  1508. _TPE_vec2Rotate(&f.x,&f.z,rotation.y);
  1509. _TPE_vec2Rotate(&f.z,&f.y,rotation.x);
  1510. _TPE_vec2Rotate(&f.y,&f.x,rotation.z);
  1511. _TPE_vec2Rotate(&r.x,&r.z,rotation.y);
  1512. _TPE_vec2Rotate(&r.z,&r.y,rotation.x);
  1513. _TPE_vec2Rotate(&r.y,&r.x,rotation.z);
  1514. return TPE_orientationFromVecs(f,r);
  1515. }
  1516. TPE_Unit TPE_keepInRange(TPE_Unit x, TPE_Unit xMin, TPE_Unit xMax)
  1517. {
  1518. return x > xMin ? (x < xMax ? x : xMax) : xMin;
  1519. }
  1520. TPE_Vec3 TPE_vec3KeepWithinBox(TPE_Vec3 point, TPE_Vec3 boxCenter,
  1521. TPE_Vec3 boxMaxVect)
  1522. {
  1523. point.x = TPE_keepInRange(point.x,
  1524. boxCenter.x - boxMaxVect.x,boxCenter.x + boxMaxVect.x);
  1525. point.y = TPE_keepInRange(point.y,
  1526. boxCenter.y - boxMaxVect.y,boxCenter.y + boxMaxVect.y);
  1527. point.z = TPE_keepInRange(point.z,
  1528. boxCenter.z - boxMaxVect.z,boxCenter.z + boxMaxVect.z);
  1529. return point;
  1530. }
  1531. #endif // guard