tinyphysicsengine.h 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533
  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. The library works with bodies made of spheres connected by elastic springs,
  10. i.e. soft bodies which however behave as "stiff" bodies by default and can
  11. be used to fake rigid body physics as well. Bodies are placed in environemnts
  12. specified by a distance function that allows to implement any mathematical
  13. shape.
  14. Orientations/rotations are in extrinsic Euler angles in the ZXY order (by Z,
  15. then by X, then by Y), if not mentioned otherwise. Angles are in TPE_Units,
  16. TPE_FRACTIONS_PER_UNIT is full angle (2 PI). Sometimes rotations can also be
  17. specified in the "about axis" format: here the object is rotated CW by given
  18. axis by an angle that's specified by the magnitude of the vector.
  19. Where it matters (e.g. rotations about axes) we consider a left-handed coord.
  20. system (x right, y up, z forward).
  21. --------------------
  22. by drummyfish, 2022
  23. This work's goal is to never be encumbered by any exclusive intellectual
  24. property rights. The work is therefore provided under CC0 1.0 + additional
  25. WAIVER OF ALL INTELLECTUAL PROPERTY RIGHTS that waives the rest of
  26. intellectual property rights not already waived by CC0 1.0. The WAIVER OF ALL
  27. INTELLECTUAL PROPERTY RGHTS is as follows:
  28. Each contributor to this work agrees that they waive any exclusive rights,
  29. including but not limited to copyright, patents, trademark, trade dress,
  30. industrial design, plant varieties and trade secrets, to any and all ideas,
  31. concepts, processes, discoveries, improvements and inventions conceived,
  32. discovered, made, designed, researched or developed by the contributor either
  33. solely or jointly with others, which relate to this work or result from this
  34. work. Should any waiver of such right be judged legally invalid or
  35. ineffective under applicable law, the contributor hereby grants to each
  36. affected person a royalty-free, non transferable, non sublicensable, non
  37. exclusive, irrevocable and unconditional license to this right.
  38. */
  39. #include <stdint.h>
  40. typedef int32_t TPE_Unit;
  41. typedef int16_t TPE_UnitReduced; ///< Like TPE_Unit but saving space
  42. #define TPE_FRACTIONS_PER_UNIT 512 ///< one fixed point unit, don't change
  43. #define TPE_JOINT_SIZE_MULTIPLIER 32 ///< joint size is scaled (size saving)
  44. #define TPE_INFINITY 2147483647
  45. #define TPE_JOINT_SIZE(joint) ((joint).sizeDivided * TPE_JOINT_SIZE_MULTIPLIER)
  46. #ifndef TPE_APPROXIMATE_LENGTH
  47. #define TPE_APPROXIMATE_LENGTH 0 /**< whether or not use length/distance
  48. approximation rather than exact
  49. calculation (1 is faster but less
  50. accurate) */
  51. #endif
  52. #if !TPE_APPROXIMATE_LENGTH
  53. #define TPE_DISTANCE TPE_dist
  54. #define TPE_LENGTH TPE_vec3Len
  55. #else
  56. #define TPE_DISTANCE TPE_distApprox
  57. #define TPE_LENGTH TPE_vec3LenApprox
  58. #endif
  59. // TODO: faster and more accurate distance approx function based on regions/LUT
  60. #ifndef TPE_LOG
  61. #define TPE_LOG(s) ;
  62. #endif
  63. #ifndef TPE_LOW_SPEED
  64. /** Speed, in TPE_Units per ticks, that is considered low (used e.g. for auto
  65. disabling bodies). */
  66. #define TPE_LOW_SPEED 30
  67. #endif
  68. #ifndef TPE_RESHAPE_TENSION_LIMIT
  69. /** Tension limit, in TPE_Units, after which a non-soft body will be reshaped.
  70. Smaller number will keep more stable shapes but will cost more performance. */
  71. #define TPE_RESHAPE_TENSION_LIMIT 20
  72. #endif
  73. #ifndef TPE_RESHAPE_ITERATIONS
  74. /** How many iterations of reshaping will be performed by the step function if
  75. the body's shape needs to be reshaped. Greater number will keep shapes more
  76. stable but will cost some performance. */
  77. #define TPE_RESHAPE_ITERATIONS 3
  78. #endif
  79. #ifndef TPE_DEACTIVATE_AFTER
  80. /** After how many ticks of low speed should a body be disabled. This mustn't
  81. be greater than 255. */
  82. #define TPE_DEACTIVATE_AFTER 128
  83. #endif
  84. #ifndef TPE_LIGHT_DEACTIVATION
  85. /** When a body is activated by a collision, its deactivation counter will be
  86. set to this value, i.e. after a collision the body will be prone to deactivate
  87. sooner than normally. This is to handle situations with many bodies touching
  88. each other that would normally keep activating each other, never coming to
  89. rest. */
  90. #define TPE_LIGHT_DEACTIVATION \
  91. (TPE_DEACTIVATE_AFTER - TPE_DEACTIVATE_AFTER / 10)
  92. #endif
  93. #ifndef TPE_TENSION_ACCELERATION_DIVIDER
  94. /** Number by which the base acceleration (TPE_FRACTIONS_PER_UNIT per tick
  95. squared) caused by the connection tension will be divided. This should be
  96. power of 2. */
  97. #define TPE_TENSION_ACCELERATION_DIVIDER 32
  98. #endif
  99. #ifndef TPE_TENSION_ACCELERATION_THRESHOLD
  100. /** Limit within which acceleration caused by connection tension won't be
  101. applied. */
  102. #define TPE_TENSION_ACCELERATION_THRESHOLD 5
  103. #endif
  104. #ifndef TPE_COLLISION_RESOLUTION_ITERATIONS
  105. /** Maximum number of iterations to try to uncollide two colliding bodies. */
  106. #define TPE_COLLISION_RESOLUTION_ITERATIONS 3
  107. #endif
  108. #ifndef TPE_COLLISION_RESOLUTION_MARGIN
  109. /** Margin, in TPE_Units, by which a body will be shifted back to get out of
  110. collision. */
  111. #define TPE_COLLISION_RESOLUTION_MARGIN (TPE_FRACTIONS_PER_UNIT / 64)
  112. #endif
  113. #ifndef TPE_NONROTATING_COLLISION_RESOLVE_ATTEMPTS
  114. /** Number of times a collision of nonrotating bodies with environment will be
  115. attempted to resolve. This probably won't have great performance implications
  116. as complex collisions of this kind should be relatively rare. */
  117. #define TPE_NONROTATING_COLLISION_RESOLVE_ATTEMPTS 3
  118. #endif
  119. #define TPE_PRINTF_VEC3(v) printf("[%d %d %d]",(v).x,(v).y,(v).z);
  120. typedef struct
  121. {
  122. TPE_Unit x;
  123. TPE_Unit y;
  124. TPE_Unit z;
  125. } TPE_Vec3;
  126. typedef struct
  127. {
  128. TPE_Vec3 position;
  129. TPE_UnitReduced velocity[3];
  130. uint8_t sizeDivided; /**< size (radius, ...), for saving space divided by
  131. TPE_JOINT_SIZE_MULTIPLIER */
  132. } TPE_Joint;
  133. typedef struct
  134. {
  135. uint8_t joint1;
  136. uint16_t joint2;
  137. uint16_t length; ///< connection's preferred length, uint16_t saves space
  138. } TPE_Connection;
  139. #define TPE_BODY_FLAG_DEACTIVATED 1 /**< Not being updated due to low energy,
  140. "sleeping", will be woken by
  141. collisions etc. */
  142. #define TPE_BODY_FLAG_NONROTATING 2 /**< When set, the body won't rotate, will
  143. only move linearly. */
  144. #define TPE_BODY_FLAG_DISABLED 4 /**< Disabled, not taking part in
  145. simulation. */
  146. #define TPE_BODY_FLAG_SOFT 8 /**< Soft connections, effort won't be made
  147. to keep the body's shape. */
  148. /** Function used for defining static environment, working similarly to an SDF
  149. (signed distance function). The parameters are: 3D point P, max distance D.
  150. The function should behave like this: if P is inside the solid environment
  151. volume, P will be returned; otherwise closest point (by Euclidean distance) to
  152. the solid environment volume from P will be returned, except for a case when
  153. this closest point would be further away than D, in which case any arbitrary
  154. point further away than D may be returned (this allows for potentially
  155. potentially faster implementation). */
  156. typedef TPE_Vec3 (*TPE_ClosestPointFunction)(TPE_Vec3, TPE_Unit);
  157. /** Function that can be used as a joint-joint or joint-environment collision
  158. callback, parameters are following: body1 index, joint1 index, body2 index,
  159. joint2 index, collision world position. If body1 index is the same as body1
  160. index, then collision type is body-environment, otherwise it is body-body
  161. type. The function has to return either 1 if the collision is to be allowed
  162. or 0 if it is to be discarded. */
  163. typedef uint8_t (*TPE_CollisionCallback)(uint16_t, uint16_t, uint16_t, uint16_t,
  164. TPE_Vec3);
  165. /** Function used by the debug drawing functions to draw individual pixels to
  166. the screen. The parameters are following: pixel x, pixel y, pixel color. */
  167. typedef void (*TPE_DebugDrawFunction)(uint16_t, uint16_t, uint8_t);
  168. /** Physics body made of spheres (each of same weight but possibly different
  169. radia) connected by elastic springs. */
  170. typedef struct
  171. {
  172. TPE_Joint *joints;
  173. uint8_t jointCount;
  174. TPE_Connection *connections;
  175. uint8_t connectionCount;
  176. TPE_UnitReduced jointMass;
  177. TPE_UnitReduced friction;
  178. TPE_UnitReduced elasticity;
  179. uint8_t flags;
  180. uint8_t deactivateCount;
  181. } TPE_Body;
  182. typedef struct
  183. {
  184. TPE_Body *bodies;
  185. uint16_t bodyCount;
  186. TPE_ClosestPointFunction environmentFunction;
  187. TPE_CollisionCallback collisionCallback;
  188. } TPE_World;
  189. void TPE_bodyInit(TPE_Body *body,
  190. TPE_Joint *joints, uint8_t jointCount,
  191. TPE_Connection *connections, uint8_t connectionCount,
  192. TPE_Unit mass);
  193. void TPE_worldInit(TPE_World *world,
  194. TPE_Body *bodies, uint16_t bodyCount,
  195. TPE_ClosestPointFunction environmentFunction);
  196. /** Gets orientation (rotation) of a body from a position of three of its
  197. joints. The vector from joint1 to joint2 is considered the body's forward
  198. direction, the vector from joint1 to joint3 its right direction. The returned
  199. rotation is in Euler angles (see rotation conventions). */
  200. TPE_Vec3 TPE_bodyGetRotation(const TPE_Body *body, uint16_t joint1,
  201. uint16_t joint2, uint16_t joint3);
  202. void TPE_vec3Normalize(TPE_Vec3 *v);
  203. TPE_Vec3 TPE_pointRotate(TPE_Vec3 point, TPE_Vec3 rotation);
  204. TPE_Vec3 TPE_rotationInverse(TPE_Vec3 rotation);
  205. /** Rotates a rotation specified in Euler angles by given axis + angle (see
  206. rotation conventions). Returns a rotation in Eurler angles. */
  207. TPE_Vec3 TPE_rotationRotateByAxis(TPE_Vec3 rotation, TPE_Vec3 rotationByAxis);
  208. /** Computes the formula of a 1 dimensional collision of rigid bodies. */
  209. void TPE_getVelocitiesAfterCollision(TPE_Unit *v1, TPE_Unit *v2, TPE_Unit m1,
  210. TPE_Unit m2, TPE_Unit elasticity);
  211. TPE_Unit TPE_sqrt(TPE_Unit value);
  212. TPE_Unit TPE_vec2Angle(TPE_Unit x, TPE_Unit y);
  213. TPE_Vec3 TPE_vec3(TPE_Unit x, TPE_Unit y, TPE_Unit z);
  214. TPE_Vec3 TPE_vec3Minus(TPE_Vec3 v1, TPE_Vec3 v2);
  215. TPE_Vec3 TPE_vec3Plus(TPE_Vec3 v1, TPE_Vec3 v2);
  216. TPE_Vec3 TPE_vec3Cross(TPE_Vec3 v1, TPE_Vec3 v2);
  217. TPE_Vec3 TPE_vec3Project(TPE_Vec3 v, TPE_Vec3 base);
  218. TPE_Vec3 TPE_vec3ProjectNormalized(TPE_Vec3 v, TPE_Vec3 baseNormalized);
  219. TPE_Vec3 TPE_vec3Times(TPE_Vec3 v, TPE_Unit units);
  220. TPE_Vec3 TPE_vec3TimesNonNormalized(TPE_Vec3 v, TPE_Unit q);
  221. TPE_Vec3 TPE_vec3Normalized(TPE_Vec3 v);
  222. TPE_Unit TPE_vec3Dot(TPE_Vec3 v1, TPE_Vec3 v2);
  223. TPE_Unit TPE_vec3Len(TPE_Vec3 v);
  224. TPE_Unit TPE_vec3LenApprox(TPE_Vec3 v);
  225. /** Keeps given value within specified range. This can be used e.g. for movement
  226. smoothing. */
  227. TPE_Unit TPE_keepInRange(TPE_Unit x, TPE_Unit xMin, TPE_Unit xMax);
  228. /** Keeps given point within specified axis-aligned box. This can be used e.g.
  229. to smooth rendered movement of jittering physics bodies. */
  230. TPE_Vec3 TPE_vec3KeepWithinBox(TPE_Vec3 point, TPE_Vec3 boxCenter,
  231. TPE_Vec3 boxMaxVect);
  232. TPE_Vec3 TPE_vec3KeepWithinDistanceBand(TPE_Vec3 point, TPE_Vec3 center,
  233. TPE_Unit minDistance, TPE_Unit maxDistance);
  234. /** Computes orientation/rotation (see docs for orientation format) from two
  235. vectors (which should be at least a close to being perpensicular and do NOT
  236. need to be normalized). */
  237. TPE_Vec3 TPE_rotationFromVecs(TPE_Vec3 forward, TPE_Vec3 right);
  238. static inline TPE_Unit TPE_nonZero(TPE_Unit x);
  239. static inline TPE_Unit TPE_dist(TPE_Vec3 p1, TPE_Vec3 p2);
  240. static inline TPE_Unit TPE_distApprox(TPE_Vec3 p1, TPE_Vec3 p2);
  241. TPE_Joint TPE_joint(TPE_Vec3 position, TPE_Unit size);
  242. uint8_t TPE_jointsResolveCollision(TPE_Joint *j1, TPE_Joint *j2,
  243. TPE_Unit mass1, TPE_Unit mass2, TPE_Unit elasticity, TPE_Unit friction,
  244. TPE_ClosestPointFunction env);
  245. /** Tests and potentially resolves a collision between a joint and environment,
  246. returns 0 if no collision happened, 1 if it happened and was resolved normally
  247. and 2 if it couldn't be resolved normally. */
  248. uint8_t TPE_jointEnvironmentResolveCollision(TPE_Joint *joint, TPE_Unit
  249. elasticity, TPE_Unit friction, TPE_ClosestPointFunction env);
  250. /** Tests whether a body is currently colliding with the environment. */
  251. uint8_t TPE_bodyEnvironmentCollide(const TPE_Body *body,
  252. TPE_ClosestPointFunction env);
  253. uint8_t TPE_bodyEnvironmentResolveCollision(TPE_Body *body,
  254. TPE_ClosestPointFunction env);
  255. TPE_Vec3 TPE_bodyGetLinearVelocity(const TPE_Body *body);
  256. void TPE_bodyGetAABB(const TPE_Body *body, TPE_Vec3 *vMin, TPE_Vec3 *vMax);
  257. /** Gets a bounding sphere of a body which is not minimal but faster to compute
  258. than the minimal bounding sphere. */
  259. void TPE_bodyGetFastBSphere(const TPE_Body *body, TPE_Vec3 *center,
  260. TPE_Unit *radius);
  261. void TPE_bodyGetBSphere(const TPE_Body *body, TPE_Vec3 *center,
  262. TPE_Unit *radius);
  263. uint8_t TPE_checkOverlapAABB(TPE_Vec3 v1Min, TPE_Vec3 v1Max, TPE_Vec3 v2Min,
  264. TPE_Vec3 v2Max);
  265. uint8_t TPE_bodiesResolveCollision(TPE_Body *b1, TPE_Body *b2,
  266. TPE_ClosestPointFunction env);
  267. /** Pins a joint of a body to specified location in space. */
  268. void TPE_jointPin(TPE_Joint *joint, TPE_Vec3 position);
  269. /** "Fakes" a rotation of a moving sphere by rotating it in the direction of
  270. its movement; this can create the illusion of the sphere actually rotating
  271. due to friction even if the physics sphere object (a body with a single joint)
  272. isn't rotating at all. Returns a rotating in the "about axis" format (see
  273. library conventions). */
  274. TPE_Vec3 TPE_fakeSphereRotation(TPE_Vec3 position1, TPE_Vec3 position2,
  275. TPE_Unit radius);
  276. // generation of bodies:
  277. void TPE_makeBox(TPE_Joint joints[8], TPE_Connection connections[16],
  278. TPE_Unit width, TPE_Unit depth, TPE_Unit height, TPE_Unit jointSize);
  279. void TPE_makeCenterBox(TPE_Joint joints[9], TPE_Connection connections[18],
  280. TPE_Unit width, TPE_Unit depth, TPE_Unit height, TPE_Unit jointSize);
  281. void TPE_makeRect(TPE_Joint joints[4], TPE_Connection connections[6],
  282. TPE_Unit width, TPE_Unit depth, TPE_Unit jointSize);
  283. void TPE_makeTriangle(TPE_Joint joints[3], TPE_Connection connections[3],
  284. TPE_Unit sideLength, TPE_Unit jointSize);
  285. void TPE_makeCenterRect(TPE_Joint joints[5], TPE_Connection connections[8],
  286. TPE_Unit width, TPE_Unit depth, TPE_Unit jointSize);
  287. void TPE_makeCenterRectFull(TPE_Joint joints[5], TPE_Connection connections[10],
  288. TPE_Unit width, TPE_Unit depth, TPE_Unit jointSize);
  289. void TPE_make2Line(TPE_Joint joints[2], TPE_Connection connections[1],
  290. TPE_Unit length, TPE_Unit jointSize);
  291. /** Casts a ray against environment and returns the closest hit of a surface. If
  292. no surface was hit, a vector with all elements equal to TPE_INFINITY will be
  293. returned. The function internally works differently for outside rays (rays
  294. cast from the outside of the environment) and inside rays. Outside rays can
  295. be traced with raymarching and will be processed very quickly and precisely;
  296. in this case if any intersection is found, the function will return a point
  297. outside the environment that's just in front of the hit surface. Inside rays
  298. are difficult and slow to trace because environment function won't provide
  299. distance, so the results aren't guaranteed to be precise (the ray may miss
  300. some intersections); here rays will be traced by given step (insideStepSize)
  301. and eventually iterated a bit towards the intersection -- if any intersection
  302. is found, the function will return a point inside the environment just before
  303. the hit surface. */
  304. TPE_Vec3 TPE_castEnvironmentRay(TPE_Vec3 rayPos, TPE_Vec3 rayDir,
  305. TPE_ClosestPointFunction environment, TPE_Unit insideStepSize,
  306. TPE_Unit rayMarchMaxStep, uint32_t maxSteps);
  307. /** Casts a ray against bodies in a world (ignoring the environment), returns
  308. the position of the closest hit as well as the hit body's index in bodyIndex
  309. (unless the bodyIndex pointer is 0 in which case it is ignored). Similarly
  310. with jointIndex. If no hit is found a vector with all elements equal to
  311. TPE_INFINITY will be returned and bodyIndex will be -1. A specific body can be
  312. excluded with excludeBody (negative value will just make this parameter
  313. ignored). */
  314. TPE_Vec3 TPE_castBodyRay(TPE_Vec3 rayPos, TPE_Vec3 rayDir, int16_t excludeBody,
  315. const TPE_World *world, uint16_t *bodyIndex, uint16_t *jointIndex);
  316. // environment building functions:
  317. TPE_Vec3 TPE_envAABoxInside(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 size);
  318. TPE_Vec3 TPE_envAABox(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 maxCornerVec);
  319. TPE_Vec3 TPE_envBox(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 maxCornerVec,
  320. TPE_Vec3 rotation);
  321. TPE_Vec3 TPE_envSphere(TPE_Vec3 point, TPE_Vec3 center, TPE_Unit radius);
  322. TPE_Vec3 TPE_envSphereInside(TPE_Vec3 point, TPE_Vec3 center, TPE_Unit radius);
  323. TPE_Vec3 TPE_envHalfPlane(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 normal);
  324. TPE_Vec3 TPE_envInfiniteCylinder(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3
  325. direction, TPE_Unit radius);
  326. #define TPE_ENV_START(test,point) TPE_Vec3 _pBest = test, _pTest; \
  327. TPE_Unit _dBest = TPE_DISTANCE(_pBest,point), _dTest; \
  328. (void)(_pBest); (void)(_dBest); (void)(_dTest); (void)(_pTest); // supress war
  329. #define TPE_ENV_NEXT(test,point) \
  330. { if (_pBest.x == point.x && _pBest.y == point.y && _pBest.z == point.z) \
  331. return _pBest; \
  332. _pTest = test; _dTest = TPE_DISTANCE(_pTest,point); \
  333. if (_dTest < _dBest) { _pBest = _pTest; _dBest = _dTest; } }
  334. #define TPE_ENV_END return _pBest;
  335. //---------------------------
  336. void TPE_worldStep(TPE_World *world);
  337. void TPE_worldDeactivateAll(TPE_World *world);
  338. TPE_Unit TPE_worldGetNetSpeed(const TPE_World *world);
  339. TPE_Unit TPE_bodyGetNetSpeed(const TPE_Body *body);
  340. TPE_Unit TPE_bodyGetAverageSpeed(const TPE_Body *body);
  341. void TPE_bodyDeactivate(TPE_Body *body);
  342. void TPE_bodyLimitAverageSpeed(TPE_Body *body, TPE_Unit speedMin,
  343. TPE_Unit speedMax);
  344. void TPE_bodyMultiplyNetSpeed(TPE_Body *body, TPE_Unit factor);
  345. /** Attempts to shift the joints of a soft body so that the tension of all
  346. strings becomes zero while keeping the joints near their current position.
  347. This function performs one iteration of the equalizing algorithm and doesn't
  348. guarantee a perfect solution, it may help to run multiple iterations (call
  349. this function multiple times). */
  350. void TPE_bodyReshape(TPE_Body *body, TPE_ClosestPointFunction
  351. environmentFunction);
  352. /** Move a body by certain offset. */
  353. void TPE_bodyMove(TPE_Body *body, TPE_Vec3 offset);
  354. /** Zero velocities of all soft body joints. */
  355. void TPE_bodyStop(TPE_Body *body);
  356. void TPE_bodyActivate(TPE_Body *body);
  357. /** Add velocity to a soft body. */
  358. void TPE_bodyAccelerate(TPE_Body *body, TPE_Vec3 velocity);
  359. void TPE_bodyApplyGravity(TPE_Body *body, TPE_Unit downwardsAccel);
  360. /** Add angular velocity to a soft body. The rotation vector specifies the axis
  361. of rotation by its direction and angular velocity by its magnitude (magnitude
  362. of TPE_FRACTIONS_PER_UNIT will add linear velocity of TPE_FRACTIONS_PER_UNIT
  363. per tick to a point in the distance of TPE_FRACTIONS_PER_UNIT from the
  364. rotation axis). */
  365. void TPE_bodySpin(TPE_Body *body, TPE_Vec3 rotation);
  366. /** Instantly rotate soft body about an axis (see library conventions for
  367. the rotation format). */
  368. void TPE_bodyRotateByAxis(TPE_Body *body, TPE_Vec3 rotation);
  369. /** Compute the center of mass of a soft body. This averages the position of
  370. all joints; note that if you need, you may estimate the center of the body
  371. faster, e.g. by taking a position of a single "center joint", or averaging
  372. just 2 extreme points. */
  373. TPE_Vec3 TPE_bodyGetCenterOfMass(const TPE_Body *body);
  374. /** Compute sine, TPE_FRACTIONS_PER_UNIT as argument corresponds to 2 * PI
  375. radians. Returns a number from -TPE_FRACTIONS_PER_UNIT to
  376. TPE_FRACTIONS_PER_UNIT. */
  377. TPE_Unit TPE_sin(TPE_Unit x);
  378. TPE_Unit TPE_cos(TPE_Unit x);
  379. TPE_Unit TPE_atan(TPE_Unit x);
  380. /** Draws a debug view of a 3D physics world using a provided pixel drawing
  381. function. This can be used to overlay a simple visualization of the physics
  382. objects to your main render, to spot exact borders of objects etc. The
  383. function draws simple dotted lines and circles with different "colors" for
  384. different types of objects (joints, connections, environemnt). camPos, camRot
  385. and camView should match the camera settings of your main renderer. CamView.x
  386. is horizontal resolution in pixels, camView.y is the vertical resolution,
  387. CamView.z says the camera focal length (~FOV) in TPE_Units (0 means
  388. orthographic projection). envGridRes is the resolution of an environment probe
  389. grid (the function will probe points in space and draw borders of the physics
  390. environemnt), envGridSize is the size (int TPE_Units) of the grid cell. Note
  391. the function may be slow (reducing envGridRes can help, workable value can be
  392. e.g. 16). */
  393. void TPE_worldDebugDraw(TPE_World *world, TPE_DebugDrawFunction drawFunc,
  394. TPE_Vec3 camPos, TPE_Vec3 camRot, TPE_Vec3 camView, uint16_t envGridRes,
  395. TPE_Unit envGridSize);
  396. #define TPE_DEBUG_COLOR_CONNECTION 0
  397. #define TPE_DEBUG_COLOR_JOINT 1
  398. #define TPE_DEBUG_COLOR_ENVIRONMENT 2
  399. #define TPE_DEBUG_COLOR_INACTIVE 3
  400. //------------------------------------------------------------------------------
  401. // privates:
  402. uint16_t _TPE_body1Index, _TPE_body2Index, _TPE_joint1Index, _TPE_joint2Index;
  403. TPE_CollisionCallback _TPE_collisionCallback;
  404. static inline TPE_Unit TPE_nonZero(TPE_Unit x)
  405. {
  406. return x != 0 ? x : 1;
  407. }
  408. TPE_Joint TPE_joint(TPE_Vec3 position, TPE_Unit size)
  409. {
  410. TPE_Joint result;
  411. result.velocity[0] = 0;
  412. result.velocity[1] = 0;
  413. result.velocity[2] = 0;
  414. result.position = position;
  415. size /= TPE_JOINT_SIZE_MULTIPLIER;
  416. if (size > 0xff)
  417. TPE_LOG("WARNING: joint size too big in TPE_joint");
  418. result.sizeDivided = size;
  419. return result;
  420. }
  421. TPE_Vec3 TPE_vec3(TPE_Unit x, TPE_Unit y, TPE_Unit z)
  422. {
  423. TPE_Vec3 r;
  424. r.x = x;
  425. r.y = y;
  426. r.z = z;
  427. return r;
  428. }
  429. TPE_Unit TPE_sqrt(TPE_Unit value)
  430. {
  431. int8_t sign = 1;
  432. if (value < 0)
  433. {
  434. sign = -1;
  435. value *= -1;
  436. }
  437. uint32_t result = 0;
  438. uint32_t a = value;
  439. uint32_t b = 1u << 30;
  440. while (b > a)
  441. b >>= 2;
  442. while (b != 0)
  443. {
  444. if (a >= result + b)
  445. {
  446. a -= result + b;
  447. result = result + 2 * b;
  448. }
  449. b >>= 2;
  450. result >>= 1;
  451. }
  452. return result * sign;
  453. }
  454. TPE_Unit TPE_vec3Len(TPE_Vec3 v)
  455. {
  456. return TPE_sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
  457. }
  458. TPE_Unit TPE_vec3LenApprox(TPE_Vec3 v)
  459. {
  460. if (v.x < 0)
  461. v.x *= -1;
  462. if (v.y < 0)
  463. v.y *= -1;
  464. if (v.z < 0)
  465. v.z *= -1;
  466. TPE_Unit sum = v.x + v.y + v.z;
  467. v.x = (v.x > v.y) ?
  468. (v.x > v.z ? v.x : v.z) :
  469. (v.y > v.z ? v.y : v.z);
  470. return (v.x + sum) / 2;
  471. }
  472. TPE_Unit TPE_dist(TPE_Vec3 p1, TPE_Vec3 p2)
  473. {
  474. p1 = TPE_vec3Minus(p1,p2);
  475. return TPE_vec3Len(p1);
  476. }
  477. TPE_Unit TPE_distApprox(TPE_Vec3 p1, TPE_Vec3 p2)
  478. {
  479. p1 = TPE_vec3Minus(p1,p2);
  480. return TPE_vec3LenApprox(p1);
  481. }
  482. void TPE_bodyInit(TPE_Body *body,
  483. TPE_Joint *joints, uint8_t jointCount,
  484. TPE_Connection *connections, uint8_t connectionCount,
  485. TPE_Unit mass)
  486. {
  487. body->joints = joints;
  488. body->jointCount = jointCount;
  489. body->connections = connections;
  490. body->connectionCount = connectionCount;
  491. body->deactivateCount = 0;
  492. body->friction = TPE_FRACTIONS_PER_UNIT / 2;
  493. body->elasticity = TPE_FRACTIONS_PER_UNIT / 2;
  494. body->flags = 0;
  495. body->jointMass = mass / jointCount;
  496. if (body->jointMass == 0)
  497. body->jointMass = 1;
  498. for (uint32_t i = 0; i < connectionCount; ++i)
  499. {
  500. TPE_Unit d = TPE_DISTANCE(
  501. joints[connections[i].joint1].position,
  502. joints[connections[i].joint2].position);
  503. if (d > 0xffff)
  504. TPE_LOG("WARNING: joint distance too long in TPE_bodyInit");
  505. connections[i].length = d != 0 ? d : 1; // prevent later division by zero
  506. }
  507. }
  508. void TPE_worldInit(TPE_World *world,
  509. TPE_Body *bodies, uint16_t bodyCount,
  510. TPE_ClosestPointFunction environmentFunction)
  511. {
  512. world->bodies = bodies;
  513. world->bodyCount = bodyCount;
  514. world->environmentFunction = environmentFunction;
  515. world->collisionCallback = 0;
  516. }
  517. #define C(n,a,b) connections[n].joint1 = a; connections[n].joint2 = b;
  518. void TPE_make2Line(TPE_Joint joints[2], TPE_Connection connections[1],
  519. TPE_Unit length, TPE_Unit jointSize)
  520. {
  521. joints[0] = TPE_joint(TPE_vec3(length / 2,0,0),jointSize);
  522. joints[1] = TPE_joint(TPE_vec3(length / -2,0,0),jointSize);
  523. C(0, 0,1)
  524. }
  525. void TPE_makeRect(TPE_Joint joints[4], TPE_Connection connections[6],
  526. TPE_Unit width, TPE_Unit depth, TPE_Unit jointSize)
  527. {
  528. width /= 2;
  529. depth /= 2;
  530. for (uint8_t i = 0; i < 4; ++i)
  531. joints[i] = TPE_joint(
  532. TPE_vec3((i % 2) ? -1 * width : width,
  533. 0,(i / 2) ? - 1 * depth : depth),
  534. jointSize);
  535. C(0, 0,1) C(1, 0,2) C (2, 3,1) C(3, 3,2)
  536. C(4, 0,3) C(5, 1,2)
  537. }
  538. void TPE_makeCenterRect(TPE_Joint joints[5], TPE_Connection connections[8],
  539. TPE_Unit width, TPE_Unit depth, TPE_Unit jointSize)
  540. {
  541. TPE_makeRect(joints,connections,width,depth,jointSize);
  542. joints[4] = TPE_joint(TPE_vec3(0,0,0),jointSize);
  543. C(6, 0,4) C(7, 3,4)
  544. }
  545. void TPE_makeCenterRectFull(TPE_Joint joints[5], TPE_Connection connections[10],
  546. TPE_Unit width, TPE_Unit depth, TPE_Unit jointSize)
  547. {
  548. TPE_makeCenterRect(joints,connections,width,depth,jointSize);
  549. C(8, 1,4) C(9, 2,4)
  550. }
  551. void TPE_makeTriangle(TPE_Joint joints[3], TPE_Connection connections[3],
  552. TPE_Unit sideLength, TPE_Unit jointSize)
  553. {
  554. joints[0] = TPE_joint(TPE_vec3(sideLength / 2,0,
  555. TPE_sqrt((sideLength * sideLength) / 2) / 2),
  556. jointSize);
  557. joints[1] = joints[0];
  558. joints[1].position.x *= -1;
  559. joints[2] = TPE_joint(TPE_vec3(0,0,-1 * joints[0].position.z),jointSize);
  560. C(0, 0,1) C(1, 1,2) C(2, 2,0)
  561. }
  562. void TPE_makeBox(TPE_Joint joints[8], TPE_Connection connections[16],
  563. TPE_Unit width, TPE_Unit depth, TPE_Unit height, TPE_Unit jointSize)
  564. {
  565. width /= 2;
  566. depth /= 2;
  567. height /= 2;
  568. for (uint8_t i = 0; i < 8; ++i)
  569. joints[i] = TPE_joint(
  570. TPE_vec3(
  571. (i % 2) ? width : (-1 * width),
  572. ((i >> 2) % 2) ? height : (-1 * height),
  573. ((i >> 1) % 2) ? depth : (-1 * depth)),
  574. jointSize);
  575. C(0, 0,1) C(1, 1,3) C(2, 3,2) C(3, 2,0) // top
  576. C(4, 4,5) C(5, 5,7) C(6, 7,6) C(7, 6,4) // bottom
  577. C(8, 0,4) C(9, 1,5) C(10,3,7) C(11,2,6) // middle
  578. C(12,0,7) C(13,1,6) C(14,2,5) C(15,3,4) // diagonal
  579. }
  580. void TPE_makeCenterBox(TPE_Joint joints[9], TPE_Connection connections[18],
  581. TPE_Unit width, TPE_Unit depth, TPE_Unit height, TPE_Unit jointSize)
  582. {
  583. TPE_makeBox(joints,connections,width,depth,height,jointSize);
  584. joints[8] = TPE_joint(TPE_vec3(0,0,0),jointSize);
  585. C(16, 0,8) C(17, 7,8)
  586. }
  587. #undef C
  588. void TPE_bodyDeactivate(TPE_Body *body)
  589. {
  590. body->flags |= TPE_BODY_FLAG_DEACTIVATED;
  591. }
  592. void TPE_worldStep(TPE_World *world)
  593. {
  594. _TPE_collisionCallback = world->collisionCallback;
  595. for (uint16_t i = 0; i < world->bodyCount; ++i)
  596. {
  597. TPE_Body *body = world->bodies + i;
  598. if (body->flags & (TPE_BODY_FLAG_DEACTIVATED | TPE_BODY_FLAG_DISABLED))
  599. continue;
  600. TPE_Joint *joint = body->joints, *joint2;
  601. TPE_Vec3 origPos = body->joints[0].position;
  602. for (uint16_t j = 0; j < body->jointCount; ++j) // apply velocities
  603. {
  604. // non-rotating bodies will copy the 1st joint's velocity
  605. if (body->flags & TPE_BODY_FLAG_NONROTATING)
  606. for (uint8_t k = 0; k < 3; ++k)
  607. joint->velocity[k] = body->joints[0].velocity[k];
  608. joint->position.x += joint->velocity[0];
  609. joint->position.y += joint->velocity[1];
  610. joint->position.z += joint->velocity[2];
  611. joint++;
  612. }
  613. TPE_Connection *connection = body->connections;
  614. TPE_Vec3 aabbMin, aabbMax;
  615. TPE_bodyGetAABB(body,&aabbMin,&aabbMax);
  616. _TPE_body1Index = i;
  617. _TPE_body2Index = _TPE_body1Index;
  618. uint8_t collided =
  619. TPE_bodyEnvironmentResolveCollision(body,world->environmentFunction);
  620. if (body->flags & TPE_BODY_FLAG_NONROTATING)
  621. {
  622. /* Non-rotating bodies may end up still colliding after environment coll
  623. resolvement (unlike rotating bodies where each joint is ensured separately
  624. to not collide). So if still in collision, we try a few more times. If not
  625. successful, we simply undo any shifts we've done. This should absolutely
  626. prevent any body escaping out of environment bounds. */
  627. for (uint8_t i = 0; i < TPE_NONROTATING_COLLISION_RESOLVE_ATTEMPTS; ++i)
  628. {
  629. if (!collided)
  630. break;
  631. collided =
  632. TPE_bodyEnvironmentResolveCollision(body,world->environmentFunction);
  633. }
  634. if (collided &&
  635. TPE_bodyEnvironmentCollide(body,world->environmentFunction))
  636. TPE_bodyMove(body,TPE_vec3Minus(origPos,body->joints[0].position));
  637. }
  638. else // normal, rotating bodies
  639. {
  640. TPE_Unit bodyTension = 0;
  641. for (uint16_t j = 0; j < body->connectionCount; ++j) // joint tension
  642. {
  643. joint = &(body->joints[connection->joint1]);
  644. joint2 = &(body->joints[connection->joint2]);
  645. TPE_Vec3 dir = TPE_vec3Minus(joint2->position,joint->position);
  646. TPE_Unit len = TPE_LENGTH(dir);
  647. len = (len * TPE_FRACTIONS_PER_UNIT) /
  648. connection->length - TPE_FRACTIONS_PER_UNIT;
  649. bodyTension += len > 0 ? len : -len;
  650. if (len > TPE_TENSION_ACCELERATION_THRESHOLD ||
  651. len < -1 * TPE_TENSION_ACCELERATION_THRESHOLD)
  652. {
  653. TPE_vec3Normalize(&dir);
  654. dir.x /= TPE_TENSION_ACCELERATION_DIVIDER;
  655. dir.y /= TPE_TENSION_ACCELERATION_DIVIDER;
  656. dir.z /= TPE_TENSION_ACCELERATION_DIVIDER;
  657. if (len < 0)
  658. {
  659. dir.x *= -1;
  660. dir.y *= -1;
  661. dir.z *= -1;
  662. }
  663. joint->velocity[0] += dir.x;
  664. joint->velocity[1] += dir.y;
  665. joint->velocity[2] += dir.z;
  666. joint2->velocity[0] -= dir.x;
  667. joint2->velocity[1] -= dir.y;
  668. joint2->velocity[2] -= dir.z;
  669. }
  670. connection++;
  671. }
  672. if (body->connectionCount > 0 && !(body->flags & TPE_BODY_FLAG_SOFT))
  673. {
  674. TPE_bodyReshape(body,world->environmentFunction);
  675. bodyTension /= body->connectionCount;
  676. if (bodyTension > TPE_RESHAPE_TENSION_LIMIT)
  677. for (uint8_t k = 0; k < TPE_RESHAPE_ITERATIONS; ++k)
  678. TPE_bodyReshape(body,world->environmentFunction);
  679. }
  680. }
  681. for (uint16_t j = 0; j < world->bodyCount; ++j)
  682. {
  683. if (j > i || (world->bodies[j].flags & TPE_BODY_FLAG_DEACTIVATED))
  684. {
  685. // firstly quick-check collision of body AA bounding boxes
  686. TPE_Vec3 aabbMin2, aabbMax2;
  687. TPE_bodyGetAABB(&world->bodies[j],&aabbMin2,&aabbMax2);
  688. _TPE_body2Index = j;
  689. if (TPE_checkOverlapAABB(aabbMin,aabbMax,aabbMin2,aabbMax2) &&
  690. TPE_bodiesResolveCollision(body,world->bodies + j,world->environmentFunction))
  691. {
  692. TPE_bodyActivate(body);
  693. body->deactivateCount = TPE_LIGHT_DEACTIVATION;
  694. TPE_bodyActivate(world->bodies + j);
  695. world->bodies[j].deactivateCount = TPE_LIGHT_DEACTIVATION;
  696. }
  697. }
  698. }
  699. if (body->deactivateCount >= TPE_DEACTIVATE_AFTER)
  700. {
  701. TPE_bodyStop(body);
  702. body->deactivateCount = 0;
  703. body->flags |= TPE_BODY_FLAG_DEACTIVATED;
  704. }
  705. else if (TPE_bodyGetAverageSpeed(body) <= TPE_LOW_SPEED) // TODO: optimize
  706. body->deactivateCount++;
  707. else
  708. body->deactivateCount = 0;
  709. }
  710. }
  711. void TPE_bodyActivate(TPE_Body *body)
  712. {
  713. // the if check has to be here, don't remove it
  714. if (body->flags & TPE_BODY_FLAG_DEACTIVATED)
  715. {
  716. TPE_bodyStop(body);
  717. body->flags &= ~TPE_BODY_FLAG_DEACTIVATED;
  718. body->deactivateCount = 0;
  719. }
  720. }
  721. TPE_Unit TPE_bodyGetNetSpeed(const TPE_Body *body)
  722. {
  723. TPE_Unit velocity = 0;
  724. const TPE_Joint *joint = body->joints;
  725. for (uint16_t i = 0; i < body->jointCount; ++i)
  726. {
  727. velocity += TPE_LENGTH(
  728. TPE_vec3(joint->velocity[0],joint->velocity[1],joint->velocity[2]));
  729. joint++;
  730. }
  731. return velocity;
  732. }
  733. TPE_Unit TPE_bodyGetAverageSpeed(const TPE_Body *body)
  734. {
  735. return TPE_bodyGetNetSpeed(body) / body->jointCount;
  736. }
  737. void TPE_bodyMultiplyNetSpeed(TPE_Body *body, TPE_Unit factor)
  738. {
  739. TPE_Joint *joint = body->joints;
  740. for (uint16_t j = 0; j < body->jointCount; ++j)
  741. {
  742. for (uint8_t k = 0; k < 3; ++k)
  743. joint->velocity[k] =
  744. (((TPE_Unit) joint->velocity[k]) * factor) /
  745. TPE_FRACTIONS_PER_UNIT;
  746. joint++;
  747. }
  748. }
  749. void TPE_bodyLimitAverageSpeed(TPE_Body *body, TPE_Unit speedMin,
  750. TPE_Unit speedMax)
  751. {
  752. for (uint8_t i = 0; i < 16; ++i)
  753. {
  754. TPE_Unit speed = TPE_bodyGetAverageSpeed(body);
  755. if (speed >= speedMin && speed <= speedMax)
  756. return;
  757. TPE_Unit fraction =
  758. (((speedMax + speedMin) / 2) * TPE_FRACTIONS_PER_UNIT) /
  759. TPE_nonZero(speed);
  760. TPE_bodyMultiplyNetSpeed(body,fraction);
  761. }
  762. }
  763. void TPE_bodyReshape(TPE_Body *body,
  764. TPE_ClosestPointFunction environmentFunction)
  765. {
  766. for (uint16_t i = 0; i < body->connectionCount; ++i)
  767. {
  768. TPE_Connection *c = &body->connections[i];
  769. TPE_Joint *j1 = &(body->joints[c->joint1]);
  770. TPE_Joint *j2 = &(body->joints[c->joint2]);
  771. TPE_Vec3 dir = TPE_vec3Minus(j2->position,j1->position);
  772. TPE_Vec3 middle = TPE_vec3Plus(j1->position,j2->position);
  773. middle.x /= 2;
  774. middle.y /= 2;
  775. middle.z /= 2;
  776. TPE_vec3Normalize(&dir);
  777. dir.x = (dir.x * c->length) / TPE_FRACTIONS_PER_UNIT;
  778. dir.y = (dir.y * c->length) / TPE_FRACTIONS_PER_UNIT;
  779. dir.z = (dir.z * c->length) / TPE_FRACTIONS_PER_UNIT;
  780. TPE_Vec3 positionBackup = j1->position;
  781. j1->position.x = middle.x - dir.x / 2;
  782. j1->position.y = middle.y - dir.y / 2;
  783. j1->position.z = middle.z - dir.z / 2;
  784. if (environmentFunction != 0 && TPE_LENGTH(TPE_vec3Minus(j1->position,
  785. environmentFunction(j1->position,TPE_JOINT_SIZE(*j1))))
  786. < TPE_JOINT_SIZE(*j1))
  787. j1->position = positionBackup;
  788. positionBackup = j2->position;
  789. j2->position.x = j1->position.x + dir.x;
  790. j2->position.y = j1->position.y + dir.y;
  791. j2->position.z = j1->position.z + dir.z;
  792. if (environmentFunction != 0 && TPE_LENGTH(TPE_vec3Minus(j2->position,
  793. environmentFunction(j2->position,TPE_JOINT_SIZE(*j2))))
  794. < TPE_JOINT_SIZE(*j2))
  795. j2->position = positionBackup;
  796. }
  797. }
  798. TPE_Vec3 TPE_vec3Plus(TPE_Vec3 v1, TPE_Vec3 v2)
  799. {
  800. v1.x += v2.x;
  801. v1.y += v2.y;
  802. v1.z += v2.z;
  803. return v1;
  804. }
  805. TPE_Vec3 TPE_vec3Minus(TPE_Vec3 v1, TPE_Vec3 v2)
  806. {
  807. v1.x -= v2.x;
  808. v1.y -= v2.y;
  809. v1.z -= v2.z;
  810. return v1;
  811. }
  812. void TPE_vec3Normalize(TPE_Vec3 *v)
  813. {
  814. TPE_Unit l = TPE_LENGTH(*v);
  815. if (l == 0)
  816. *v = TPE_vec3(TPE_FRACTIONS_PER_UNIT,0,0);
  817. else
  818. {
  819. if (l < 16) // TODO: const, for too short
  820. {
  821. v->x *= 8;
  822. v->y *= 8;
  823. v->z *= 8;
  824. l = TPE_LENGTH(*v);
  825. }
  826. v->x = (v->x * TPE_FRACTIONS_PER_UNIT) / l;
  827. v->y = (v->y * TPE_FRACTIONS_PER_UNIT) / l;
  828. v->z = (v->z * TPE_FRACTIONS_PER_UNIT) / l;
  829. }
  830. }
  831. TPE_Vec3 TPE_bodyGetRotation(const TPE_Body *body, uint16_t joint1,
  832. uint16_t joint2, uint16_t joint3)
  833. {
  834. return TPE_rotationFromVecs(
  835. TPE_vec3Minus(
  836. body->joints[joint2].position,
  837. body->joints[joint1].position),
  838. TPE_vec3Minus(
  839. body->joints[joint3].position,
  840. body->joints[joint1].position));
  841. }
  842. TPE_Vec3 TPE_bodyGetCenterOfMass(const TPE_Body *body)
  843. {
  844. // note that joint sizes don't play a role as all weight the same
  845. TPE_Vec3 result = TPE_vec3(0,0,0);
  846. const TPE_Joint *j = body->joints;
  847. for (uint16_t i = 0; i < body->jointCount; ++i)
  848. {
  849. result = TPE_vec3Plus(result,j->position);
  850. j++;
  851. }
  852. result.x /= body->jointCount;
  853. result.y /= body->jointCount;
  854. result.z /= body->jointCount;
  855. return result;
  856. }
  857. void TPE_bodySpin(TPE_Body *body, TPE_Vec3 rotation)
  858. {
  859. TPE_Vec3 center = TPE_bodyGetCenterOfMass(body);
  860. for (uint16_t i = 0; i < body->jointCount; ++i)
  861. {
  862. TPE_Joint *j = body->joints + i;
  863. TPE_Vec3 toPoint = TPE_vec3Minus(j->position,center);
  864. toPoint = TPE_vec3Project(toPoint,rotation);
  865. toPoint = TPE_vec3Plus(center,toPoint);
  866. toPoint = TPE_vec3Minus(j->position,toPoint);
  867. toPoint = TPE_vec3Cross(toPoint,rotation);
  868. j->velocity[0] += toPoint.x;
  869. j->velocity[1] += toPoint.y;
  870. j->velocity[2] += toPoint.z;
  871. }
  872. }
  873. TPE_Vec3 _TPE_rotateByAxis(TPE_Vec3 p, TPE_Vec3 axisNormalized, TPE_Unit angle)
  874. {
  875. TPE_Vec3 projected = TPE_vec3ProjectNormalized(p,axisNormalized);
  876. TPE_Vec3 a = TPE_vec3Minus(p,projected);
  877. if (a.x == 0 && a.y == 0 && a.z == 0)
  878. return p;
  879. TPE_Vec3 b = TPE_vec3Cross(a,axisNormalized);
  880. return TPE_vec3Plus(projected,TPE_vec3Plus(
  881. TPE_vec3Times(a,TPE_cos(angle)),
  882. TPE_vec3Times(b,TPE_sin(angle))));
  883. }
  884. void TPE_bodyRotateByAxis(TPE_Body *body, TPE_Vec3 rotation)
  885. {
  886. TPE_Vec3 bodyCenter = TPE_bodyGetCenterOfMass(body);
  887. TPE_Unit angle = TPE_LENGTH(rotation);
  888. TPE_vec3Normalize(&rotation);
  889. for (uint16_t i = 0; i < body->jointCount; ++i)
  890. {
  891. TPE_Vec3 toPoint = TPE_vec3Minus(body->joints[i].position,bodyCenter);
  892. body->joints[i].position = TPE_vec3Plus(bodyCenter,
  893. _TPE_rotateByAxis(toPoint,rotation,angle));
  894. }
  895. }
  896. TPE_Vec3 TPE_vec3Cross(TPE_Vec3 v1, TPE_Vec3 v2)
  897. {
  898. TPE_Vec3 r;
  899. r.x = (v1.y * v2.z - v1.z * v2.y) / TPE_FRACTIONS_PER_UNIT;
  900. r.y = (v1.z * v2.x - v1.x * v2.z) / TPE_FRACTIONS_PER_UNIT;
  901. r.z = (v1.x * v2.y - v1.y * v2.x) / TPE_FRACTIONS_PER_UNIT;
  902. return r;
  903. }
  904. TPE_Vec3 TPE_vec3ProjectNormalized(TPE_Vec3 v, TPE_Vec3 baseNormalized)
  905. {
  906. TPE_Vec3 r;
  907. TPE_Unit p = TPE_vec3Dot(v,baseNormalized);
  908. r.x = (p * baseNormalized.x) / TPE_FRACTIONS_PER_UNIT;
  909. r.y = (p * baseNormalized.y) / TPE_FRACTIONS_PER_UNIT;
  910. r.z = (p * baseNormalized.z) / TPE_FRACTIONS_PER_UNIT;
  911. return r;
  912. }
  913. TPE_Vec3 TPE_vec3Project(TPE_Vec3 v, TPE_Vec3 base)
  914. {
  915. TPE_vec3Normalize(&base);
  916. return TPE_vec3ProjectNormalized(v,base);
  917. }
  918. void TPE_bodyMove(TPE_Body *body, TPE_Vec3 offset)
  919. {
  920. for (uint16_t i = 0; i < body->jointCount; ++i)
  921. body->joints[i].position = TPE_vec3Plus(body->joints[i].position,
  922. offset);
  923. }
  924. void TPE_bodyApplyGravity(TPE_Body *body, TPE_Unit downwardsAccel)
  925. {
  926. if ((body->flags & TPE_BODY_FLAG_DEACTIVATED) ||
  927. (body->flags & TPE_BODY_FLAG_DISABLED))
  928. return;
  929. for (uint16_t i = 0; i < body->jointCount; ++i)
  930. body->joints[i].velocity[1] -= downwardsAccel;
  931. }
  932. void TPE_bodyAccelerate(TPE_Body *body, TPE_Vec3 velocity)
  933. {
  934. TPE_bodyActivate(body);
  935. for (uint16_t i = 0; i < body->jointCount; ++i)
  936. {
  937. body->joints[i].velocity[0] += velocity.x;
  938. body->joints[i].velocity[1] += velocity.y;
  939. body->joints[i].velocity[2] += velocity.z;
  940. }
  941. }
  942. void TPE_bodyStop(TPE_Body *body)
  943. {
  944. for (uint16_t i = 0; i < body->jointCount; ++i)
  945. {
  946. body->joints[i].velocity[0] = 0;
  947. body->joints[i].velocity[1] = 0;
  948. body->joints[i].velocity[2] = 0;
  949. }
  950. }
  951. void _TPE_bodyNonrotatingJointCollided(TPE_Body *b, int16_t jointIndex,
  952. TPE_Vec3 origPos, uint8_t success)
  953. {
  954. origPos = TPE_vec3Minus(b->joints[jointIndex].position,origPos);
  955. for (uint16_t i = 0; i < b->jointCount; ++i)
  956. if (i != jointIndex)
  957. {
  958. b->joints[i].position = TPE_vec3Plus(b->joints[i].position,origPos);
  959. if (success)
  960. for (uint8_t j = 0; j < 3; ++j)
  961. b->joints[i].velocity[j] = b->joints[jointIndex].velocity[j];
  962. }
  963. }
  964. TPE_Unit TPE_vec3Dot(TPE_Vec3 v1, TPE_Vec3 v2)
  965. {
  966. return (v1.x * v2.x + v1.y * v2.y + v1.z * v2.z) / TPE_FRACTIONS_PER_UNIT;
  967. }
  968. TPE_Unit TPE_cos(TPE_Unit x)
  969. {
  970. return TPE_sin(x + TPE_FRACTIONS_PER_UNIT / 4);
  971. }
  972. TPE_Unit TPE_sin(TPE_Unit x)
  973. {
  974. int8_t sign = 1;
  975. if (x < 0) // odd function
  976. {
  977. x *= -1;
  978. sign = -1;
  979. }
  980. x %= TPE_FRACTIONS_PER_UNIT;
  981. if (x > TPE_FRACTIONS_PER_UNIT / 2)
  982. {
  983. x -= TPE_FRACTIONS_PER_UNIT / 2;
  984. sign *= -1;
  985. }
  986. TPE_Unit tmp = TPE_FRACTIONS_PER_UNIT - 2 * x;
  987. #define _PI2 ((TPE_Unit) (9.8696044 * TPE_FRACTIONS_PER_UNIT))
  988. return sign * // Bhaskara's approximation
  989. (((32 * x * _PI2) / TPE_FRACTIONS_PER_UNIT) * tmp) /
  990. ((_PI2 * (5 * TPE_FRACTIONS_PER_UNIT - (8 * x * tmp) /
  991. TPE_FRACTIONS_PER_UNIT)) / TPE_FRACTIONS_PER_UNIT);
  992. #undef _PI2
  993. }
  994. uint8_t TPE_bodiesResolveCollision(TPE_Body *b1, TPE_Body *b2,
  995. TPE_ClosestPointFunction env)
  996. {
  997. uint8_t r = 0;
  998. for (uint16_t i = 0; i < b1->jointCount; ++i)
  999. for (uint16_t j = 0; j < b2->jointCount; ++j)
  1000. {
  1001. TPE_Vec3 origPos2 = b2->joints[j].position;
  1002. TPE_Vec3 origPos1 = b1->joints[i].position;
  1003. _TPE_joint1Index = i;
  1004. _TPE_joint2Index = j;
  1005. if (TPE_jointsResolveCollision(&(b1->joints[i]),&(b2->joints[j]),
  1006. b1->jointMass,b2->jointMass,(b1->elasticity + b2->elasticity) / 2,
  1007. (b1->friction + b2->friction) / 2,env))
  1008. {
  1009. r = 1;
  1010. if (b1->flags & TPE_BODY_FLAG_NONROTATING)
  1011. _TPE_bodyNonrotatingJointCollided(b1,i,origPos1,1);
  1012. if (b2->flags & TPE_BODY_FLAG_NONROTATING)
  1013. _TPE_bodyNonrotatingJointCollided(b2,j,origPos2,1);
  1014. }
  1015. }
  1016. return r;
  1017. }
  1018. uint8_t TPE_jointsResolveCollision(TPE_Joint *j1, TPE_Joint *j2,
  1019. TPE_Unit mass1, TPE_Unit mass2, TPE_Unit elasticity, TPE_Unit friction,
  1020. TPE_ClosestPointFunction env)
  1021. {
  1022. TPE_Vec3 dir = TPE_vec3Minus(j2->position,j1->position);
  1023. TPE_Unit d = TPE_LENGTH(dir) - TPE_JOINT_SIZE(*j1) - TPE_JOINT_SIZE(*j2);
  1024. if (d < 0) // collision?
  1025. {
  1026. if (_TPE_collisionCallback != 0) // TODO: unnest if
  1027. if (!_TPE_collisionCallback(_TPE_body1Index,_TPE_joint1Index,
  1028. _TPE_body2Index,_TPE_joint2Index,TPE_vec3Plus(j1->position,dir)))
  1029. return 0;
  1030. TPE_Vec3
  1031. pos1Backup = j1->position,
  1032. pos2Backup = j2->position;
  1033. // separate joints, the shift distance will depend on the weight ratio:
  1034. d = -1 * d + TPE_COLLISION_RESOLUTION_MARGIN;
  1035. TPE_vec3Normalize(&dir);
  1036. TPE_Unit ratio = (mass2 * TPE_FRACTIONS_PER_UNIT) /
  1037. TPE_nonZero(mass1 + mass2);
  1038. TPE_Unit shiftDistance = (ratio * d) / TPE_FRACTIONS_PER_UNIT;
  1039. TPE_Vec3 shift = TPE_vec3Times(dir,shiftDistance);
  1040. j1->position = TPE_vec3Minus(j1->position,shift);
  1041. shiftDistance = d - shiftDistance;
  1042. shift = TPE_vec3Times(dir,shiftDistance);
  1043. j2->position = TPE_vec3Plus(j2->position,shift);
  1044. // compute new velocities:
  1045. TPE_Unit v1, v2;
  1046. TPE_Vec3 vel = TPE_vec3(j1->velocity[0],j1->velocity[1],j1->velocity[2]);
  1047. vel = TPE_vec3Project(vel,dir);
  1048. j1->velocity[0] = j1->velocity[0] - vel.x;
  1049. j1->velocity[1] = j1->velocity[1] - vel.y;
  1050. j1->velocity[2] = j1->velocity[2] - vel.z;
  1051. /* friction explanation: Not physically correct (doesn't depend on load),
  1052. friction basically means we weighted average the velocities of the bodies
  1053. in the direction perpendicular to the hit normal, in the ratio of their
  1054. masses, friction coefficient just says how much of this effect we apply
  1055. (it multiplies the friction vectors we are subtracting) */
  1056. TPE_Vec3 frictionVec =
  1057. TPE_vec3(j1->velocity[0],j1->velocity[1],j1->velocity[2]);
  1058. v1 = TPE_vec3Dot(vel,dir);
  1059. vel = TPE_vec3(j2->velocity[0],j2->velocity[1],j2->velocity[2]);
  1060. vel = TPE_vec3Project(vel,dir);
  1061. j2->velocity[0] = j2->velocity[0] - vel.x;
  1062. j2->velocity[1] = j2->velocity[1] - vel.y;
  1063. j2->velocity[2] = j2->velocity[2] - vel.z;
  1064. frictionVec = TPE_vec3Minus(
  1065. TPE_vec3(j2->velocity[0],j2->velocity[1],j2->velocity[2]),
  1066. frictionVec);
  1067. v2 = TPE_vec3Dot(vel,dir);
  1068. TPE_getVelocitiesAfterCollision(&v1,&v2,mass1,mass2,elasticity);
  1069. vel = TPE_vec3Times(dir,v1);
  1070. #define assignVec(j,i,d,o) \
  1071. j->velocity[i] = j->velocity[i] + vel.d o (((frictionVec.d * ratio) / \
  1072. TPE_FRACTIONS_PER_UNIT) * friction) / TPE_FRACTIONS_PER_UNIT;
  1073. assignVec(j1,0,x,+)
  1074. assignVec(j1,1,y,+)
  1075. assignVec(j1,2,z,+)
  1076. vel = TPE_vec3Times(dir,v2);
  1077. ratio = TPE_FRACTIONS_PER_UNIT - ratio;
  1078. assignVec(j2,0,x,-)
  1079. assignVec(j2,1,y,-)
  1080. assignVec(j2,2,z,-)
  1081. #undef assignVec
  1082. if (env != 0)
  1083. {
  1084. // ensure the joints aren't colliding with environment
  1085. if (TPE_jointEnvironmentResolveCollision(j1,elasticity,friction,env) == 2)
  1086. j1->position = pos1Backup;
  1087. if (TPE_jointEnvironmentResolveCollision(j2,elasticity,friction,env) == 2)
  1088. j2->position = pos2Backup;
  1089. }
  1090. return 1;
  1091. }
  1092. return 0;
  1093. }
  1094. TPE_Vec3 TPE_vec3Times(TPE_Vec3 v, TPE_Unit units)
  1095. {
  1096. v.x = (v.x * units) / TPE_FRACTIONS_PER_UNIT;
  1097. v.y = (v.y * units) / TPE_FRACTIONS_PER_UNIT;
  1098. v.z = (v.z * units) / TPE_FRACTIONS_PER_UNIT;
  1099. return v;
  1100. }
  1101. TPE_Vec3 TPE_vec3TimesNonNormalized(TPE_Vec3 v, TPE_Unit q)
  1102. {
  1103. v.x *= q;
  1104. v.y *= q;
  1105. v.z *= q;
  1106. return v;
  1107. }
  1108. void TPE_getVelocitiesAfterCollision(
  1109. TPE_Unit *v1,
  1110. TPE_Unit *v2,
  1111. TPE_Unit m1,
  1112. TPE_Unit m2,
  1113. TPE_Unit elasticity
  1114. )
  1115. {
  1116. /* In the following a lot of TPE_FRACTIONS_PER_UNIT cancel out, feel free to
  1117. check if confused. */
  1118. TPE_Unit m1Pm2 = TPE_nonZero(m1 + m2);
  1119. TPE_Unit v2Mv1 = TPE_nonZero(*v2 - *v1);
  1120. TPE_Unit m1v1Pm2v2 = ((m1 * *v1) + (m2 * *v2));
  1121. *v1 = (((elasticity * m2 / TPE_FRACTIONS_PER_UNIT) * v2Mv1)
  1122. + m1v1Pm2v2) / m1Pm2;
  1123. *v2 = (((elasticity * m1 / TPE_FRACTIONS_PER_UNIT) * -1 * v2Mv1)
  1124. + m1v1Pm2v2) / m1Pm2;
  1125. }
  1126. uint8_t TPE_jointEnvironmentResolveCollision(TPE_Joint *joint,
  1127. TPE_Unit elasticity, TPE_Unit friction, TPE_ClosestPointFunction env)
  1128. {
  1129. TPE_Vec3 toJoint =
  1130. TPE_vec3Minus(joint->position,env(joint->position,TPE_JOINT_SIZE(*joint)));
  1131. TPE_Unit len = TPE_LENGTH(toJoint);
  1132. if (len <= TPE_JOINT_SIZE(*joint))
  1133. {
  1134. if (_TPE_collisionCallback != 0)
  1135. if (!_TPE_collisionCallback(_TPE_body1Index,
  1136. _TPE_joint1Index,_TPE_body2Index,_TPE_joint2Index,
  1137. TPE_vec3Minus(joint->position,toJoint)))
  1138. return 0;
  1139. // colliding
  1140. TPE_Vec3 positionBackup = joint->position, shift;
  1141. uint8_t success = 0;
  1142. if (len > 0)
  1143. {
  1144. /* Joint center is still outside the geometry so we can determine the
  1145. normal and use it to shift it outside. This can still leave the joint
  1146. colliding though, so try to repeat it a few times. */
  1147. for (int i = 0; i < TPE_COLLISION_RESOLUTION_ITERATIONS; ++i)
  1148. {
  1149. shift = toJoint;
  1150. TPE_vec3Normalize(&shift);
  1151. shift = TPE_vec3Times(shift,TPE_JOINT_SIZE(*joint) - len +
  1152. TPE_COLLISION_RESOLUTION_MARGIN);
  1153. joint->position = TPE_vec3Plus(joint->position,shift);
  1154. toJoint = TPE_vec3Minus(joint->position,env(joint->position,
  1155. TPE_JOINT_SIZE(*joint)));
  1156. len = TPE_LENGTH(toJoint); // still colliding?
  1157. if (len >= TPE_JOINT_SIZE(*joint))
  1158. {
  1159. success = 1;
  1160. break;
  1161. }
  1162. }
  1163. }
  1164. if (!success)
  1165. {
  1166. /* Shifting along normal was unsuccessfull, now try different approach:
  1167. shift back by joint velocity. */
  1168. shift = TPE_vec3(-1 * joint->velocity[0],-1 * joint->velocity[1],
  1169. -1 * joint->velocity[2]);
  1170. for (int i = 0; i < TPE_COLLISION_RESOLUTION_ITERATIONS; ++i)
  1171. {
  1172. joint->position = TPE_vec3Plus(joint->position,shift);
  1173. toJoint = TPE_vec3Minus(joint->position,env(joint->position,TPE_JOINT_SIZE(*joint)));
  1174. len = TPE_LENGTH(toJoint); // still colliding?
  1175. if (len >= TPE_JOINT_SIZE(*joint))
  1176. {
  1177. success = 1;
  1178. break;
  1179. }
  1180. shift.x /= 2; // decrease the step a bit
  1181. shift.y /= 2;
  1182. shift.z /= 2;
  1183. }
  1184. }
  1185. if (success)
  1186. {
  1187. TPE_Vec3 vel = TPE_vec3(joint->velocity[0],joint->velocity[1],
  1188. joint->velocity[2]);
  1189. vel = TPE_vec3Project(vel,shift); // parallel part of velocity
  1190. TPE_Vec3 vel2 = TPE_vec3Minus( // perpendicular part of velocity
  1191. TPE_vec3(joint->velocity[0],joint->velocity[1],joint->velocity[2]),vel);
  1192. vel2 = TPE_vec3Times(vel2,friction);
  1193. vel = TPE_vec3Times(vel,TPE_FRACTIONS_PER_UNIT + elasticity);
  1194. joint->velocity[0] -= vel.x + vel2.x;
  1195. joint->velocity[1] -= vel.y + vel2.y;
  1196. joint->velocity[2] -= vel.z + vel2.z;
  1197. }
  1198. else
  1199. {
  1200. TPE_LOG("WARNING: joint-environment collision couldn't be resolved");
  1201. joint->position = positionBackup;
  1202. joint->velocity[0] = 0;
  1203. joint->velocity[1] = 0;
  1204. joint->velocity[2] = 0;
  1205. return 2;
  1206. }
  1207. return 1;
  1208. }
  1209. return 0;
  1210. }
  1211. uint8_t TPE_bodyEnvironmentCollide(const TPE_Body *body,
  1212. TPE_ClosestPointFunction env)
  1213. {
  1214. // TODO: should bounding vol check be here? maybe in param?
  1215. for (uint16_t i = 0; i < body->jointCount; ++i)
  1216. {
  1217. const TPE_Joint *joint = body->joints + i;
  1218. TPE_Unit size = TPE_JOINT_SIZE(*joint);
  1219. if (TPE_DISTANCE(joint->position,env(joint->position,size)) <= size)
  1220. return 1;
  1221. }
  1222. return 0;
  1223. }
  1224. void TPE_bodyGetFastBSphere(const TPE_Body *body, TPE_Vec3 *center,
  1225. TPE_Unit *radius)
  1226. {
  1227. TPE_Vec3 b;
  1228. TPE_bodyGetAABB(body,center,&b);
  1229. center->x = (center->x + b.x) / 2;
  1230. center->y = (center->y + b.y) / 2;
  1231. center->z = (center->z + b.z) / 2;
  1232. *radius = TPE_DISTANCE(*center,b);
  1233. }
  1234. void TPE_bodyGetBSphere(const TPE_Body *body, TPE_Vec3 *center,
  1235. TPE_Unit *radius)
  1236. {
  1237. *radius = TPE_INFINITY;
  1238. *center = TPE_bodyGetCenterOfMass(body);
  1239. const TPE_Joint *j = body->joints;
  1240. for (uint16_t i = 0; i < body->jointCount; ++i)
  1241. {
  1242. TPE_Vec3 diff;
  1243. TPE_Unit js = TPE_JOINT_SIZE(*j);
  1244. /* Sadly we have to have these conditions here which slow this down. If we
  1245. were only computing a BB sphere of a point cloud, we wouldn't have to
  1246. compute abs vals (as squaring would effectively compute them), but here
  1247. we need to add joint size which needs to know about the sign. */
  1248. diff.x = ((center->x > j->position.x) ?
  1249. (center->x - j->position.x) : (j->position.x - center->x)) + js;
  1250. diff.y = ((center->y > j->position.y) ?
  1251. (center->y - j->position.y) : (j->position.y - center->y)) + js;
  1252. diff.z = ((center->z > j->position.z) ?
  1253. (center->z - j->position.z) : (j->position.z - center->z)) + js;
  1254. TPE_Unit distSquared =
  1255. diff.x * diff.x + diff.y * diff.y + diff.z * diff.z;
  1256. if (distSquared < *radius)
  1257. *radius = distSquared;
  1258. j++;
  1259. }
  1260. *radius = TPE_sqrt(*radius);
  1261. }
  1262. uint8_t TPE_bodyEnvironmentResolveCollision(TPE_Body *body,
  1263. TPE_ClosestPointFunction env)
  1264. {
  1265. TPE_Vec3 c;
  1266. TPE_Unit d;
  1267. TPE_bodyGetFastBSphere(body,&c,&d);
  1268. if (TPE_DISTANCE(c,env(c,d)) > d)
  1269. return 0;
  1270. // now test the full body collision:
  1271. uint8_t collision = 0;
  1272. for (uint16_t i = 0; i < body->jointCount; ++i)
  1273. {
  1274. TPE_Vec3 previousPos = body->joints[i].position;
  1275. _TPE_joint1Index = i;
  1276. uint8_t r = TPE_jointEnvironmentResolveCollision(
  1277. body->joints + i,body->elasticity,body->friction,env);
  1278. if (r)
  1279. {
  1280. collision = 1;
  1281. if (body->flags & TPE_BODY_FLAG_NONROTATING)
  1282. _TPE_bodyNonrotatingJointCollided(body,i,previousPos,r == 1);
  1283. }
  1284. }
  1285. return collision;
  1286. }
  1287. TPE_Vec3 TPE_vec3Normalized(TPE_Vec3 v)
  1288. {
  1289. TPE_vec3Normalize(&v);
  1290. return v;
  1291. }
  1292. TPE_Unit TPE_atan(TPE_Unit x)
  1293. {
  1294. /* atan approximation by polynomial
  1295. WARNING: this will break with different value of TPE_FRACTIONS_PER_UNIT */
  1296. TPE_Unit sign = 1, x2 = x * x;
  1297. if (x < 0)
  1298. {
  1299. x *= -1;
  1300. sign = -1;
  1301. }
  1302. if (x > 30000) // anti overflow
  1303. return sign * (TPE_FRACTIONS_PER_UNIT / 4);
  1304. return sign *
  1305. (307 * x + x2) / ((267026 + 633 * x + x2) / 128);
  1306. }
  1307. void _TPE_vec2Rotate(TPE_Unit *x, TPE_Unit *y, TPE_Unit angle)
  1308. {
  1309. TPE_Unit tmp = *x;
  1310. TPE_Unit s = TPE_sin(angle);
  1311. TPE_Unit c = TPE_cos(angle);
  1312. *x = (c * *x - s * *y) / TPE_FRACTIONS_PER_UNIT;
  1313. *y = (s * tmp + c * *y) / TPE_FRACTIONS_PER_UNIT;
  1314. }
  1315. TPE_Unit TPE_vec2Angle(TPE_Unit x, TPE_Unit y)
  1316. {
  1317. TPE_Unit r = 0;
  1318. if (x != 0)
  1319. {
  1320. r = TPE_atan((y * TPE_FRACTIONS_PER_UNIT) / x);
  1321. if (x < 0)
  1322. r += TPE_FRACTIONS_PER_UNIT / 2;
  1323. else if (r < 0)
  1324. r += TPE_FRACTIONS_PER_UNIT;
  1325. }
  1326. else
  1327. {
  1328. if (y < 0)
  1329. r = (3 * TPE_FRACTIONS_PER_UNIT) / 4;
  1330. else if (y > 0)
  1331. r = TPE_FRACTIONS_PER_UNIT / 4;
  1332. // else (y == 0) r stays 0
  1333. }
  1334. return r;
  1335. }
  1336. TPE_Vec3 TPE_rotationFromVecs(TPE_Vec3 forward, TPE_Vec3 right)
  1337. {
  1338. TPE_Vec3 result;
  1339. // get rotation around Y:
  1340. result.y = TPE_vec2Angle(forward.z,-1 * forward.x);
  1341. // now rotate back by this angle to align with x = 0 plane:
  1342. _TPE_vec2Rotate(&forward.z,&forward.x,result.y);
  1343. _TPE_vec2Rotate(&right.z,&right.x,result.y);
  1344. // now do the same for the second axis:
  1345. result.x =
  1346. TPE_vec2Angle(forward.z,forward.y);
  1347. _TPE_vec2Rotate(&right.z,&right.y,-1 * result.x);
  1348. result.z = TPE_vec2Angle(right.x,-1 * right.y);
  1349. return result;
  1350. }
  1351. TPE_Vec3 _TPE_project3DPoint(TPE_Vec3 p, TPE_Vec3 camPos, TPE_Vec3 camRot,
  1352. TPE_Vec3 camView)
  1353. {
  1354. // transform to camera space:
  1355. p = TPE_vec3Minus(p,camPos);
  1356. _TPE_vec2Rotate(&p.z,&p.x,camRot.y);
  1357. _TPE_vec2Rotate(&p.z,&p.y,-1 * camRot.x);
  1358. _TPE_vec2Rotate(&p.y,&p.x,-1 * camRot.z);
  1359. if (p.z <= 0)
  1360. return p;
  1361. if (camView.z != 0)
  1362. {
  1363. // perspective
  1364. p.x = (p.x * camView.z) / p.z;
  1365. p.y = (p.y * camView.z) / p.z;
  1366. p.x = camView.x / 2 + (p.x * camView.x) / (2 * TPE_FRACTIONS_PER_UNIT);
  1367. p.y = camView.y / 2 - (p.y * camView.x) / (2 * TPE_FRACTIONS_PER_UNIT);
  1368. // ^ x here intentional
  1369. }
  1370. else
  1371. {
  1372. // ortho
  1373. p.x = camView.x / 2 + p.x;
  1374. p.y = camView.y / 2 - p.y;
  1375. }
  1376. return p;
  1377. }
  1378. void _TPE_drawDebugPixel(
  1379. TPE_Unit x, TPE_Unit y, TPE_Unit w, TPE_Unit h, uint8_t c,
  1380. TPE_DebugDrawFunction f)
  1381. {
  1382. if (x >= 0 && x < w && y >= 0 && y < h)
  1383. f(x,y,c);
  1384. }
  1385. void TPE_worldDebugDraw(TPE_World *world, TPE_DebugDrawFunction drawFunc,
  1386. TPE_Vec3 camPos, TPE_Vec3 camRot, TPE_Vec3 camView, uint16_t envGridRes,
  1387. TPE_Unit envGridSize)
  1388. {
  1389. #define Z_LIMIT 250
  1390. if (world->environmentFunction != 0)
  1391. {
  1392. // environment:
  1393. TPE_Vec3 testPoint;
  1394. TPE_Unit gridHalfSize = (envGridSize * envGridRes) / 2;
  1395. TPE_Vec3 center;
  1396. if (envGridRes != 0)
  1397. {
  1398. center = TPE_vec3(0,TPE_sin(camRot.x),TPE_cos(camRot.x));
  1399. _TPE_vec2Rotate(&center.x,&center.z,camRot.y);
  1400. center = TPE_vec3Times(center,gridHalfSize);
  1401. center = TPE_vec3Plus(camPos,center);
  1402. center.x = (center.x / envGridSize) * envGridSize;
  1403. center.y = (center.y / envGridSize) * envGridSize;
  1404. center.z = (center.z / envGridSize) * envGridSize;
  1405. }
  1406. testPoint.y = center.y - gridHalfSize;
  1407. for (uint8_t j = 0; j < envGridRes; ++j)
  1408. {
  1409. testPoint.x = center.x - gridHalfSize;
  1410. for (uint8_t k = 0; k < envGridRes; ++k)
  1411. {
  1412. testPoint.z = center.z - gridHalfSize;
  1413. for (uint8_t l = 0; l < envGridRes; ++l)
  1414. {
  1415. TPE_Vec3 r = world->environmentFunction(testPoint,envGridSize);
  1416. if ((r.x != testPoint.x || r.y != testPoint.y || r.z != testPoint.z))
  1417. {
  1418. // TODO: accel. by testing cheb dist first?
  1419. r = _TPE_project3DPoint(r,camPos,camRot,camView);
  1420. if (r.z > Z_LIMIT)
  1421. _TPE_drawDebugPixel(r.x,r.y,camView.x,camView.y,
  1422. TPE_DEBUG_COLOR_ENVIRONMENT,drawFunc);
  1423. }
  1424. testPoint.z += envGridSize;
  1425. }
  1426. testPoint.x += envGridSize;
  1427. }
  1428. testPoint.y += envGridSize;
  1429. }
  1430. }
  1431. for (uint16_t i = 0; i < world->bodyCount; ++i)
  1432. {
  1433. // connections:
  1434. for (uint16_t j = 0; j < world->bodies[i].connectionCount; ++j)
  1435. {
  1436. TPE_Vec3
  1437. p1 = world->bodies[i].joints[world->bodies[i].connections[j].joint1].position,
  1438. p2 = world->bodies[i].joints[world->bodies[i].connections[j].joint2].position;
  1439. p1 = _TPE_project3DPoint(p1,camPos,camRot,camView);
  1440. p2 = _TPE_project3DPoint(p2,camPos,camRot,camView);
  1441. if (p1.z <= Z_LIMIT || p2.z <= Z_LIMIT)
  1442. continue;
  1443. TPE_Vec3 diff = TPE_vec3Minus(p2,p1);
  1444. #define SEGS 16
  1445. uint8_t c = (world->bodies[i].flags & TPE_BODY_FLAG_DEACTIVATED) ?
  1446. TPE_DEBUG_COLOR_INACTIVE : TPE_DEBUG_COLOR_CONNECTION;
  1447. for (uint16_t k = 0; k < SEGS; ++k)
  1448. {
  1449. p2.x = p1.x + (diff.x * k) / SEGS;
  1450. p2.y = p1.y + (diff.y * k) / SEGS;
  1451. _TPE_drawDebugPixel(p2.x,p2.y,camView.x,camView.y,c,drawFunc);
  1452. }
  1453. #undef SEGS
  1454. }
  1455. // joints:
  1456. for (uint16_t j = 0; j < world->bodies[i].jointCount; ++j)
  1457. {
  1458. TPE_Vec3 p = _TPE_project3DPoint(world->bodies[i].joints[j].position,
  1459. camPos,camRot,camView);
  1460. if (p.z > Z_LIMIT)
  1461. {
  1462. uint8_t color = (world->bodies[i].flags & TPE_BODY_FLAG_DEACTIVATED) ?
  1463. TPE_DEBUG_COLOR_INACTIVE : TPE_DEBUG_COLOR_JOINT;
  1464. _TPE_drawDebugPixel(p.x,p.y,camView.x,camView.y,color,drawFunc);
  1465. TPE_Unit size = TPE_JOINT_SIZE(world->bodies[i].joints[j]);
  1466. if (camView.z != 0) // not ortho?
  1467. {
  1468. size /= 2;
  1469. size = (size * camView.x) / TPE_FRACTIONS_PER_UNIT;
  1470. size = (size * camView.z) / p.z;
  1471. }
  1472. #define SEGS 4
  1473. for (uint8_t k = 0; k < SEGS + 1; ++k)
  1474. {
  1475. TPE_Unit
  1476. dx = (TPE_sin(TPE_FRACTIONS_PER_UNIT * k / (8 * SEGS)) * size)
  1477. / TPE_FRACTIONS_PER_UNIT,
  1478. dy = (TPE_cos(TPE_FRACTIONS_PER_UNIT * k / (8 * SEGS)) * size)
  1479. / TPE_FRACTIONS_PER_UNIT;
  1480. #define dp(a,b,c,d) \
  1481. _TPE_drawDebugPixel(p.x a b,p.y c d,camView.x,camView.y,color,drawFunc);
  1482. dp(+,dx,+,dy) dp(+,dx,-,dy) dp(-,dx,+,dy) dp(-,dx,-,dy)
  1483. dp(+,dy,+,dx) dp(+,dy,-,dx) dp(-,dy,+,dx) dp(-,dy,-,dx)
  1484. #undef dp
  1485. #undef SEGS
  1486. }
  1487. }
  1488. }
  1489. }
  1490. #undef Z_LIMIT
  1491. }
  1492. TPE_Vec3 TPE_envBox(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 maxCornerVec,
  1493. TPE_Vec3 rotation)
  1494. {
  1495. point = TPE_pointRotate(TPE_vec3Minus(point,center),
  1496. TPE_rotationInverse(rotation));
  1497. return TPE_vec3Plus(center,TPE_pointRotate(TPE_envAABox(point,TPE_vec3(0,0,0),
  1498. maxCornerVec),rotation));
  1499. }
  1500. TPE_Vec3 TPE_envAABox(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 maxCornerVec)
  1501. {
  1502. TPE_Vec3 shifted = TPE_vec3Minus(point,center);
  1503. int8_t sign[3] = {1, 1, 1};
  1504. if (shifted.x < 0)
  1505. {
  1506. shifted.x *= -1;
  1507. sign[0] = -1;
  1508. }
  1509. if (shifted.y < 0)
  1510. {
  1511. shifted.y *= -1;
  1512. sign[1] = -1;
  1513. }
  1514. if (shifted.z < 0)
  1515. {
  1516. shifted.z *= -1;
  1517. sign[2] = -1;
  1518. }
  1519. uint8_t region =
  1520. (shifted.x > maxCornerVec.x) |
  1521. ((shifted.y > maxCornerVec.y) << 1) |
  1522. ((shifted.z > maxCornerVec.z) << 2);
  1523. switch (region)
  1524. {
  1525. #define align(c,i) point.c = center.c + sign[i] * maxCornerVec.c
  1526. case 0x01: align(x,0); break;
  1527. case 0x02: align(y,1); break;
  1528. case 0x04: align(z,2); break;
  1529. case 0x03: align(x,0); align(y,1); break;
  1530. case 0x05: align(x,0); align(z,2); break;
  1531. case 0x06: align(y,1); align(z,2); break;
  1532. case 0x07: align(x,0); align(y,1); align(z,2); break;
  1533. default: break;
  1534. #undef align
  1535. }
  1536. return point;
  1537. }
  1538. TPE_Vec3 TPE_envAABoxInside(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 size)
  1539. {
  1540. size.x /= 2;
  1541. size.y /= 2;
  1542. size.z /= 2;
  1543. TPE_Vec3 shifted = TPE_vec3Minus(point,center);
  1544. TPE_Vec3 a = TPE_vec3Minus(size,shifted),
  1545. b = TPE_vec3Plus(shifted,size);
  1546. int8_t sx = 1, sy = 1, sz = 1;
  1547. if (b.x < a.x)
  1548. {
  1549. a.x = b.x;
  1550. sx = -1;
  1551. }
  1552. if (b.y < a.y)
  1553. {
  1554. a.y = b.y;
  1555. sy = -1;
  1556. }
  1557. if (b.z < a.z)
  1558. {
  1559. a.z = b.z;
  1560. sz = -1;
  1561. }
  1562. if (a.x < 0 || a.y < 0 || a.z < 0)
  1563. return point;
  1564. if (a.x < a.y)
  1565. {
  1566. if (a.x < a.z)
  1567. point.x = center.x + sx * size.x;
  1568. else
  1569. point.z = center.z + sz * size.z;
  1570. }
  1571. else
  1572. {
  1573. if (a.y < a.z)
  1574. point.y = center.y + sy * size.y;
  1575. else
  1576. point.z = center.z + sz * size.z;
  1577. }
  1578. return point;
  1579. }
  1580. TPE_Vec3 TPE_envSphereInside(TPE_Vec3 point, TPE_Vec3 center, TPE_Unit radius)
  1581. {
  1582. TPE_Vec3 shifted = TPE_vec3Minus(point,center);
  1583. TPE_Unit l = TPE_LENGTH(shifted);
  1584. if (l >= radius)
  1585. return point;
  1586. else if (l < 0)
  1587. return TPE_vec3(center.x + radius,center.y,center.z);
  1588. TPE_vec3Normalize(&shifted);
  1589. return TPE_vec3Plus(center,TPE_vec3Times(shifted,radius));
  1590. }
  1591. TPE_Vec3 TPE_envSphere(TPE_Vec3 point, TPE_Vec3 center, TPE_Unit radius)
  1592. {
  1593. // TODO: optim?
  1594. TPE_Vec3 dir = TPE_vec3Minus(point,center);
  1595. TPE_Unit l = TPE_LENGTH(dir);
  1596. if (l <= radius)
  1597. return point;
  1598. dir.x = (dir.x * radius) / l;
  1599. dir.y = (dir.y * radius) / l;
  1600. dir.z = (dir.z * radius) / l;
  1601. return TPE_vec3Plus(center,dir);
  1602. }
  1603. TPE_Vec3 TPE_envHalfPlane(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 normal)
  1604. {
  1605. TPE_Vec3 point2 = TPE_vec3Minus(point,center);
  1606. TPE_Unit tmp = point2.x * normal.x + point2.y * normal.y + point2.z * normal.z;
  1607. if (tmp < 0)
  1608. return point;
  1609. TPE_Unit l = TPE_LENGTH(normal);
  1610. tmp /= l;
  1611. normal.x = (normal.x * TPE_FRACTIONS_PER_UNIT) / l;
  1612. normal.y = (normal.y * TPE_FRACTIONS_PER_UNIT) / l;
  1613. normal.z = (normal.z * TPE_FRACTIONS_PER_UNIT) / l;
  1614. return TPE_vec3Minus(point,
  1615. TPE_vec3Times(normal,tmp));
  1616. }
  1617. uint8_t TPE_checkOverlapAABB(TPE_Vec3 v1Min, TPE_Vec3 v1Max, TPE_Vec3 v2Min,
  1618. TPE_Vec3 v2Max)
  1619. {
  1620. TPE_Unit dist;
  1621. #define test(c) \
  1622. dist = v1Min.c + v1Max.c - v2Max.c - v2Min.c; \
  1623. if (dist < 0) dist *= -1; \
  1624. if (dist > v1Max.c - v1Min.c + v2Max.c - v2Min.c) return 0;
  1625. test(x)
  1626. test(y)
  1627. test(z)
  1628. #undef test
  1629. return 1;
  1630. }
  1631. void TPE_bodyGetAABB(const TPE_Body *body, TPE_Vec3 *vMin, TPE_Vec3 *vMax)
  1632. {
  1633. *vMin = body->joints[0].position;
  1634. *vMax = *vMin;
  1635. TPE_Unit js = TPE_JOINT_SIZE(body->joints[0]);
  1636. vMin->x -= js;
  1637. vMin->y -= js;
  1638. vMin->z -= js;
  1639. vMax->x += js;
  1640. vMax->y += js;
  1641. vMax->z += js;
  1642. for (uint16_t i = 1; i < body->jointCount; ++i)
  1643. {
  1644. TPE_Unit v;
  1645. js = TPE_JOINT_SIZE(body->joints[i]);
  1646. #define test(c) \
  1647. v = body->joints[i].position.c - js; \
  1648. if (v < vMin->c) \
  1649. vMin->c = v; \
  1650. v += 2 * js; \
  1651. if (v > vMax->c) \
  1652. vMax->c = v;
  1653. test(x)
  1654. test(y)
  1655. test(z)
  1656. #undef test
  1657. }
  1658. }
  1659. void TPE_jointPin(TPE_Joint *joint, TPE_Vec3 position)
  1660. {
  1661. joint->position = position;
  1662. joint->velocity[0] = 0;
  1663. joint->velocity[1] = 0;
  1664. joint->velocity[2] = 0;
  1665. }
  1666. TPE_Vec3 TPE_pointRotate(TPE_Vec3 point, TPE_Vec3 rotation)
  1667. {
  1668. _TPE_vec2Rotate(&point.y,&point.x,rotation.z);
  1669. _TPE_vec2Rotate(&point.z,&point.y,rotation.x);
  1670. _TPE_vec2Rotate(&point.x,&point.z,rotation.y);
  1671. return point;
  1672. }
  1673. TPE_Vec3 TPE_rotationInverse(TPE_Vec3 rotation)
  1674. {
  1675. /* If r1 = (X,Y,Z) is rotation in convention ABC then r1^-1 = (-X,-Y,-Z) in
  1676. convention CBA is its inverse rotation. We exploit this, i.e. we rotate
  1677. forward/right vectors in opposite axis order and then turn the result
  1678. into normal rotation/orientation. */
  1679. TPE_Vec3 f = TPE_vec3(0,0,TPE_FRACTIONS_PER_UNIT);
  1680. TPE_Vec3 r = TPE_vec3(TPE_FRACTIONS_PER_UNIT,0,0);
  1681. rotation.x *= -1;
  1682. rotation.y *= -1;
  1683. rotation.z *= -1;
  1684. _TPE_vec2Rotate(&f.x,&f.z,rotation.y);
  1685. _TPE_vec2Rotate(&f.z,&f.y,rotation.x);
  1686. _TPE_vec2Rotate(&f.y,&f.x,rotation.z);
  1687. _TPE_vec2Rotate(&r.x,&r.z,rotation.y);
  1688. _TPE_vec2Rotate(&r.z,&r.y,rotation.x);
  1689. _TPE_vec2Rotate(&r.y,&r.x,rotation.z);
  1690. return TPE_rotationFromVecs(f,r);
  1691. }
  1692. TPE_Vec3 TPE_rotationRotateByAxis(TPE_Vec3 rotation, TPE_Vec3 rotationByAxis)
  1693. {
  1694. TPE_Vec3 f = TPE_pointRotate(TPE_vec3(0,0,TPE_FRACTIONS_PER_UNIT),rotation);
  1695. TPE_Vec3 r = TPE_pointRotate(TPE_vec3(TPE_FRACTIONS_PER_UNIT,0,0),rotation);
  1696. TPE_Unit a = TPE_LENGTH(rotationByAxis);
  1697. TPE_vec3Normalize(&rotationByAxis);
  1698. f = _TPE_rotateByAxis(f,rotationByAxis,a);
  1699. r = _TPE_rotateByAxis(r,rotationByAxis,a);
  1700. return TPE_rotationFromVecs(f,r);
  1701. }
  1702. TPE_Unit TPE_keepInRange(TPE_Unit x, TPE_Unit xMin, TPE_Unit xMax)
  1703. {
  1704. return x > xMin ? (x < xMax ? x : xMax) : xMin;
  1705. }
  1706. TPE_Vec3 TPE_vec3KeepWithinDistanceBand(TPE_Vec3 point, TPE_Vec3 center,
  1707. TPE_Unit minDistance, TPE_Unit maxDistance)
  1708. {
  1709. TPE_Vec3 toPoint = TPE_vec3Minus(point,center);
  1710. TPE_Unit l = TPE_LENGTH(toPoint);
  1711. if (l <= maxDistance)
  1712. {
  1713. if (l >= minDistance)
  1714. return point;
  1715. l = minDistance;
  1716. }
  1717. else
  1718. l = maxDistance;
  1719. return TPE_vec3Plus(center,
  1720. TPE_vec3Times(TPE_vec3Normalized(toPoint),l));
  1721. }
  1722. TPE_Vec3 TPE_vec3KeepWithinBox(TPE_Vec3 point, TPE_Vec3 boxCenter,
  1723. TPE_Vec3 boxMaxVect)
  1724. {
  1725. point.x = TPE_keepInRange(point.x,
  1726. boxCenter.x - boxMaxVect.x,boxCenter.x + boxMaxVect.x);
  1727. point.y = TPE_keepInRange(point.y,
  1728. boxCenter.y - boxMaxVect.y,boxCenter.y + boxMaxVect.y);
  1729. point.z = TPE_keepInRange(point.z,
  1730. boxCenter.z - boxMaxVect.z,boxCenter.z + boxMaxVect.z);
  1731. return point;
  1732. }
  1733. TPE_Vec3 TPE_envInfiniteCylinder(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3
  1734. direction, TPE_Unit radius)
  1735. {
  1736. TPE_Vec3 d = TPE_vec3Minus(point,center);
  1737. d = TPE_vec3Minus(d,TPE_vec3Project(d,direction));
  1738. TPE_Unit l = TPE_LENGTH(d);
  1739. if (l <= radius)
  1740. return point;
  1741. radius = l - radius;
  1742. d.x = (d.x * radius) / l;
  1743. d.y = (d.y * radius) / l;
  1744. d.z = (d.z * radius) / l;
  1745. return TPE_vec3Minus(point,d);
  1746. }
  1747. TPE_Vec3 TPE_fakeSphereRotation(TPE_Vec3 position1, TPE_Vec3 position2,
  1748. TPE_Unit radius)
  1749. {
  1750. TPE_Vec3 m;
  1751. m.x = position1.z - position2.z;
  1752. m.y = 0;
  1753. m.z = position2.x - position1.x;
  1754. TPE_Unit l = TPE_sqrt(m.x * m.x + m.z * m.z);
  1755. if (l == 0)
  1756. return TPE_vec3(0,0,0);
  1757. TPE_Unit d = (TPE_DISTANCE(position1,position2) *
  1758. TPE_FRACTIONS_PER_UNIT) / (radius * 4);
  1759. m.x = (m.x * d) / l;
  1760. m.z = (m.z * d) / l;
  1761. return m;
  1762. }
  1763. TPE_Vec3 TPE_castEnvironmentRay(TPE_Vec3 rayPos, TPE_Vec3 rayDir,
  1764. TPE_ClosestPointFunction environment, TPE_Unit insideStepSize,
  1765. TPE_Unit rayMarchMaxStep, uint32_t maxSteps)
  1766. {
  1767. TPE_Vec3 p = rayPos;
  1768. TPE_Vec3 p2 = environment(rayPos,rayMarchMaxStep);
  1769. TPE_Unit totalD = 0;
  1770. TPE_vec3Normalize(&rayDir);
  1771. uint8_t found = 0; // 0 = nothing found, 1 = out/in found, 2 = in/out found
  1772. if (p2.x != p.x || p2.y != p.y || p2.z != p.z)
  1773. {
  1774. // outside ray: ray march
  1775. for (uint32_t i = 0; i < maxSteps; ++i)
  1776. {
  1777. TPE_Unit d = TPE_DISTANCE(p,p2);
  1778. if (d > rayMarchMaxStep)
  1779. d = rayMarchMaxStep;
  1780. totalD += d;
  1781. p2 = TPE_vec3Plus(rayPos,TPE_vec3Times(rayDir,totalD));
  1782. if (d == 0 ||
  1783. (p2.x == p.x && p2.y == p.y && p2.z == p.z))
  1784. return p2; // point not inside env but dist == 0, ideal case
  1785. TPE_Vec3 pTest = environment(p2,rayMarchMaxStep);
  1786. if (pTest.x == p2.x && pTest.y == p2.y && pTest.z == p2.z)
  1787. {
  1788. // stepped into env, will have to iterate
  1789. found = 1;
  1790. break;
  1791. }
  1792. p = p2;
  1793. p2 = pTest;
  1794. }
  1795. }
  1796. else if (insideStepSize != 0)
  1797. {
  1798. // inside ray: iterate by fixed steps
  1799. for (uint32_t i = 0; i < maxSteps; ++i)
  1800. {
  1801. totalD += insideStepSize;
  1802. p2 = TPE_vec3Plus(rayPos,TPE_vec3Times(rayDir,totalD));
  1803. TPE_Vec3 pTest = environment(p2,16);
  1804. if (p2.x != pTest.x || p2.y != pTest.y || p2.z != pTest.z)
  1805. {
  1806. found = 2;
  1807. break;
  1808. }
  1809. p = p2;
  1810. p2 = pTest;
  1811. }
  1812. }
  1813. if (found)
  1814. {
  1815. /* Here we've found two points (p, p2), each one the other side of the
  1816. env surface. Now iterate (binary search) to find the exact surface
  1817. pos. */
  1818. for (uint8_t i = 0; i < 128; ++i) // upper limit just in case
  1819. {
  1820. TPE_Vec3 middle = TPE_vec3Plus(p,p2);
  1821. middle.x /= 2;
  1822. middle.y /= 2;
  1823. middle.z /= 2;
  1824. if ((middle.x == p.x && middle.y == p.y && middle.z == p.z) ||
  1825. (middle.x == p2.x && middle.y == p2.y && middle.z == p2.z))
  1826. break; // points basically next to each other, don't continue
  1827. TPE_Vec3 pTest = environment(middle,16); // 16: just a small number
  1828. if ((found == 1) ==
  1829. (pTest.x == middle.x && pTest.y == middle.y && pTest.z == middle.z))
  1830. p2 = middle;
  1831. else
  1832. p = middle;
  1833. }
  1834. return (found == 1) ? p : p2;
  1835. }
  1836. return TPE_vec3(TPE_INFINITY,TPE_INFINITY,TPE_INFINITY);
  1837. }
  1838. TPE_Vec3 TPE_castBodyRay(TPE_Vec3 rayPos, TPE_Vec3 rayDir, int16_t excludeBody,
  1839. const TPE_World *world, uint16_t *bodyIndex, uint16_t *jointIndex)
  1840. {
  1841. TPE_Vec3 bestP = TPE_vec3(TPE_INFINITY,TPE_INFINITY,TPE_INFINITY);
  1842. TPE_Unit bestD = TPE_INFINITY;
  1843. if (bodyIndex != 0)
  1844. *bodyIndex = -1;
  1845. if (jointIndex != 0)
  1846. *jointIndex = -1;
  1847. TPE_vec3Normalize(&rayDir);
  1848. for (uint16_t i = 0; i < world->bodyCount; ++i)
  1849. {
  1850. TPE_Vec3 c, p;
  1851. TPE_Unit r, d;
  1852. TPE_bodyGetFastBSphere(&world->bodies[i],&c,&r);
  1853. c = TPE_vec3Minus(c,rayPos);
  1854. p = TPE_vec3ProjectNormalized(c,rayDir);
  1855. if (TPE_vec3Dot(p,rayDir) >= 0) // point is in ray's forward dir?
  1856. {
  1857. d = TPE_DISTANCE(p,c);
  1858. if (d <= r)
  1859. {
  1860. // bounding sphere hit, now check all joints:
  1861. const TPE_Joint *joint = world->bodies[i].joints;
  1862. for (uint16_t j = 0; j < world->bodies[i].jointCount; ++j)
  1863. {
  1864. c = joint->position;
  1865. c = TPE_vec3Minus(c,rayPos);
  1866. p = TPE_vec3ProjectNormalized(c,rayDir);
  1867. if (TPE_vec3Dot(p,rayDir) >= 0)
  1868. {
  1869. d = TPE_DISTANCE(p,c);
  1870. TPE_Unit js = TPE_JOINT_SIZE(*joint);
  1871. if (d <= js)
  1872. {
  1873. // joint hit, compute exact coordinates:
  1874. c = TPE_vec3Times(rayDir,TPE_sqrt(js * js - d * d));
  1875. // ^ offset vector to two intersections
  1876. p = TPE_vec3Plus(p,rayPos);
  1877. TPE_Vec3
  1878. i1 = TPE_vec3Plus(p,c), // intersection points
  1879. i2 = TPE_vec3Minus(p,c);
  1880. d = TPE_DISTANCE(rayPos,i1);
  1881. TPE_Unit d2 = TPE_DISTANCE(rayPos,i2);
  1882. if (d2 < d) // take the closer one
  1883. {
  1884. d = d2;
  1885. i1 = i2;
  1886. }
  1887. if (d < bestD)
  1888. {
  1889. bestD = d;
  1890. bestP = i1;
  1891. }
  1892. }
  1893. }
  1894. joint++;
  1895. }
  1896. }
  1897. }
  1898. }
  1899. return bestP;
  1900. }
  1901. void TPE_worldDeactivateAll(TPE_World *world)
  1902. {
  1903. for (uint16_t i = 0; i < world->bodyCount; ++i)
  1904. TPE_bodyDeactivate(&world->bodies[i]);
  1905. }
  1906. TPE_Unit TPE_worldGetNetSpeed(const TPE_World *world)
  1907. {
  1908. TPE_Unit result = 0;
  1909. for (uint16_t i = 0; i < world->bodyCount; ++i)
  1910. result += TPE_bodyGetNetSpeed(world->bodies + i);
  1911. return result;
  1912. }
  1913. TPE_Vec3 TPE_bodyGetLinearVelocity(const TPE_Body *body)
  1914. {
  1915. // TODO
  1916. }
  1917. #endif // guard