tinyphysicsengine.h 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623
  1. #ifndef _TINYPHYSICSENGINE_H
  2. #define _TINYPHYSICSENGINE_H
  3. /**
  4. Conventions and formats are the same or similar to those of small3dlib so as
  5. to make them easily integrate with each other.
  6. Orientations/rotations are in extrinsic Euler angles in the ZXY order (by Z,
  7. then by X, then by Y).
  8. Where it matters (e.g. rotations about axes) we consider a left-handed coord.
  9. system (x right, y up, z forward).
  10. --------------------
  11. This work's goal is to never be encumbered by any exclusive intellectual
  12. property rights. The work is therefore provided under CC0 1.0 + additional
  13. WAIVER OF ALL INTELLECTUAL PROPERTY RIGHTS that waives the rest of
  14. intellectual property rights not already waived by CC0 1.0. The WAIVER OF ALL
  15. INTELLECTUAL PROPERTY RGHTS is as follows:
  16. Each contributor to this work agrees that they waive any exclusive rights,
  17. including but not limited to copyright, patents, trademark, trade dress,
  18. industrial design, plant varieties and trade secrets, to any and all ideas,
  19. concepts, processes, discoveries, improvements and inventions conceived,
  20. discovered, made, designed, researched or developed by the contributor either
  21. solely or jointly with others, which relate to this work or result from this
  22. work. Should any waiver of such right be judged legally invalid or
  23. ineffective under applicable law, the contributor hereby grants to each
  24. affected person a royalty-free, non transferable, non sublicensable, non
  25. exclusive, irrevocable and unconditional license to this right.
  26. */
  27. #include <stdint.h>
  28. typedef int32_t TPE_Unit;
  29. typedef int16_t TPE_UnitReduced; ///< Like TPE_Unit but saving space
  30. #define TPE_FRACTIONS_PER_UNIT 512
  31. #define TPE_JOINT_SIZE_MULTIPLIER 32
  32. #define TPE_JOINT_SIZE(joint) ((joint).sizeDivided * TPE_JOINT_SIZE_MULTIPLIER)
  33. #ifndef TPE_APPROXIMATE_LENGTH
  34. #define TPE_APPROXIMATE_LENGTH 0 /**< whether or not use length/distance
  35. approximation rather than exact
  36. calculation (1 is faster but less
  37. accurate) */
  38. #endif
  39. #if !TPE_APPROXIMATE_LENGTH
  40. #define TPE_DISTANCE TPE_dist
  41. #define TPE_LENGTH TPE_vec3Len
  42. #else
  43. #define TPE_DISTANCE TPE_distApprox
  44. #define TPE_LENGTH TPE_vec3LenApprox
  45. #endif
  46. // TODO: faster and more accurate distance approx function based on regions/LUT
  47. #ifndef TPE_LOG
  48. #define TPE_LOG(s) ;
  49. #endif
  50. #ifndef TPE_LOW_SPEED
  51. /** Speed, in TPE_Units per ticks, that is considered low (used e.g. for auto
  52. disabling bodies). */
  53. #define TPE_LOW_SPEED 30
  54. #endif
  55. #ifndef TPE_RESHAPE_TENSION_LIMIT
  56. /** Tension limit, in TPE_Units, after which a non-soft body will be reshaped.
  57. Smaller number will keep more stable shapes but will cost more performance. */
  58. #define TPE_RESHAPE_TENSION_LIMIT 20
  59. #endif
  60. #ifndef TPE_RESHAPE_ITERATIONS
  61. /** How many iterations of reshaping will be performed by the step function if
  62. the body's shape needs to be reshaped. Greater number will keep shapes more
  63. stable but will cost some performance. */
  64. #define TPE_RESHAPE_ITERATIONS 3
  65. #endif
  66. #ifndef TPE_DEACTIVATE_AFTER
  67. /** After how many ticks of low speed should a body be disabled. This mustn't
  68. be greater than 255. */
  69. #define TPE_DEACTIVATE_AFTER 64
  70. #endif
  71. #ifndef TPE_LIGHT_DEACTIVATION
  72. /** When a body is activated by a collision, its deactivation counter will be
  73. set to this value, i.e. after a collision the body will be prone to deactivate
  74. sooner than normally. This is to handle situations with many bodies touching
  75. each other that would normally keep activating each other, never coming to
  76. rest. */
  77. #define TPE_LIGHT_DEACTIVATION \
  78. (TPE_DEACTIVATE_AFTER - TPE_DEACTIVATE_AFTER / 10)
  79. #endif
  80. #ifndef TPE_TENSION_ACCELERATION_DIVIDER
  81. /** Number by which the base acceleration (TPE_FRACTIONS_PER_UNIT per tick
  82. squared) caused by the connection tension will be divided. This should be power
  83. of 2. */
  84. #define TPE_TENSION_ACCELERATION_DIVIDER 32
  85. #endif
  86. #ifndef TPE_TENSION_ACCELERATION_THRESHOLD
  87. /** Limit within which acceleration caused by connection tension won't be
  88. applied. */
  89. #define TPE_TENSION_ACCELERATION_THRESHOLD 5
  90. #endif
  91. #ifndef TPE_COLLISION_RESOLUTION_ITERATIONS
  92. /** Maximum number of iterations to try to uncollide two colliding bodies. */
  93. #define TPE_COLLISION_RESOLUTION_ITERATIONS 3
  94. #endif
  95. #ifndef TPE_COLLISION_RESOLUTION_MARGIN
  96. /** Margin, in TPE_Units, by which a body will be shifted back to get out of
  97. collision. */
  98. #define TPE_COLLISION_RESOLUTION_MARGIN (TPE_FRACTIONS_PER_UNIT / 64)
  99. #endif
  100. #define TPE_PRINTF_VEC3(v) printf("[%d %d %d]",(v).x,(v).y,(v).z);
  101. typedef struct
  102. {
  103. TPE_Unit x;
  104. TPE_Unit y;
  105. TPE_Unit z;
  106. } TPE_Vec3;
  107. typedef struct
  108. {
  109. TPE_Vec3 position;
  110. TPE_UnitReduced velocity[3];
  111. uint8_t sizeDivided; /**< size (radius, ...), for saving space divided by
  112. TPE_JOINT_SIZE_MULTIPLIER */
  113. } TPE_Joint;
  114. typedef struct
  115. {
  116. uint8_t joint1;
  117. uint16_t joint2;
  118. uint16_t length; ///< connection's preferred length, uint16_t saves space
  119. } TPE_Connection;
  120. #define TPE_BODY_FLAG_DEACTIVATED 1 /**< Not being updated due to low energy,
  121. "sleeping", will be woken by
  122. collisions etc. */
  123. #define TPE_BODY_FLAG_NONROTATING 2 /**< When set, the body won't rotate, will
  124. only move linearly. */
  125. #define TPE_BODY_FLAG_DISABLED 4 /**< Disabled, not taking part in
  126. simulation. */
  127. #define TPE_BODY_FLAG_SOFT 8 /**< Soft connections, effort won't be made
  128. to keep the body's shape. */
  129. /** Function used for defining static environment, working similarly to an SDF
  130. (signed distance function). The parameters are: 3D point P, max distance D.
  131. The function should behave like this: if P is inside the solid environment
  132. volume, P will be returned; otherwise closest point (by Euclidean distance) to
  133. the solid environment volume from P will be returned, except for a case when
  134. this closest point would be further away than D, in which case any arbitrary
  135. point further away than D may be returned (this allows for potentially
  136. potentially faster implementation). */
  137. typedef TPE_Vec3 (*TPE_ClosestPointFunction)(TPE_Vec3, TPE_Unit);
  138. /** Function used by the debug drawing functions to draw individual pixels to
  139. the screen. The parameters are following: pixel x, pixel y, pixel color. */
  140. typedef void (*TPE_DebugDrawFunction)(uint16_t, uint16_t, uint8_t);
  141. typedef struct
  142. {
  143. TPE_Joint *joints;
  144. uint8_t jointCount;
  145. TPE_Connection *connections;
  146. uint8_t connectionCount;
  147. TPE_UnitReduced jointMass;
  148. TPE_UnitReduced friction;
  149. TPE_UnitReduced elasticity;
  150. uint8_t flags;
  151. uint8_t deactivateCount;
  152. } TPE_Body;
  153. typedef struct
  154. {
  155. TPE_Body *bodies;
  156. uint16_t bodyCount;
  157. TPE_ClosestPointFunction environmentFunction;
  158. } TPE_World;
  159. void TPE_bodyInit(TPE_Body *body,
  160. TPE_Joint *joints, uint8_t jointCount,
  161. TPE_Connection *connections, uint8_t connectionCount,
  162. TPE_Unit mass);
  163. void TPE_worldInit(TPE_World *world,
  164. TPE_Body *bodies, uint16_t bodyCount,
  165. TPE_ClosestPointFunction environmentFunction);
  166. void TPE_vec3Normalize(TPE_Vec3 *v);
  167. void TPE_getVelocitiesAfterCollision(
  168. TPE_Unit *v1,
  169. TPE_Unit *v2,
  170. TPE_Unit m1,
  171. TPE_Unit m2,
  172. TPE_Unit elasticity);
  173. TPE_Vec3 TPE_vec3(TPE_Unit x, TPE_Unit y, TPE_Unit z);
  174. TPE_Vec3 TPE_vec3Minus(TPE_Vec3 v1, TPE_Vec3 v2);
  175. TPE_Vec3 TPE_vec3Plus(TPE_Vec3 v1, TPE_Vec3 v2);
  176. TPE_Vec3 TPE_vec3Cross(TPE_Vec3 v1, TPE_Vec3 v2);
  177. TPE_Vec3 TPE_vec3Project(TPE_Vec3 v, TPE_Vec3 base);
  178. TPE_Vec3 TPE_vec3Times(TPE_Vec3 v, TPE_Unit units);
  179. TPE_Vec3 TPE_vec3TimesNonNormalized(TPE_Vec3 v, TPE_Unit q);
  180. TPE_Vec3 TPE_vec3Normalized(TPE_Vec3 v);
  181. /* Computes orientation/rotation (see docs for orientation format) from two
  182. vectors (which should be at least a close to being perpensicular and do NOT
  183. need to be normalized). */
  184. TPE_Vec3 TPE_orientationFromVecs(TPE_Vec3 forward, TPE_Vec3 right);
  185. TPE_Unit TPE_vec3Dot(TPE_Vec3 v1, TPE_Vec3 v2);
  186. TPE_Unit TPE_sqrt(TPE_Unit value);
  187. TPE_Unit TPE_vec3Len(TPE_Vec3 v);
  188. TPE_Unit TPE_vec3LenApprox(TPE_Vec3 v);
  189. static inline TPE_Unit TPE_nonZero(TPE_Unit x);
  190. static inline TPE_Unit TPE_dist(TPE_Vec3 p1, TPE_Vec3 p2);
  191. static inline TPE_Unit TPE_distApprox(TPE_Vec3 p1, TPE_Vec3 p2);
  192. TPE_Joint TPE_joint(TPE_Vec3 position, TPE_Unit size);
  193. uint8_t TPE_jointsResolveCollision(TPE_Joint *j1, TPE_Joint *j2,
  194. TPE_Unit mass1, TPE_Unit mass2, TPE_Unit elasticity, TPE_Unit friction);
  195. uint8_t TPE_jointEnvironmentResolveCollision(TPE_Joint *joint, TPE_Unit elasticity,
  196. TPE_Unit friction, TPE_ClosestPointFunction env);
  197. uint8_t TPE_bodyEnvironmentResolveCollision(TPE_Body *body,
  198. TPE_ClosestPointFunction env);
  199. uint8_t TPE_bodiesResolveCollision(TPE_Body *b1, TPE_Body *b2);
  200. // -----------------------------------------------------------------------------
  201. // body generation functions:
  202. void TPE_makeBox(TPE_Joint joints[8], TPE_Connection connections[16],
  203. TPE_Unit width, TPE_Unit depth, TPE_Unit height, TPE_Unit jointSize);
  204. void TPE_makeCenterBox(TPE_Joint joints[9], TPE_Connection connections[18],
  205. TPE_Unit width, TPE_Unit depth, TPE_Unit height, TPE_Unit jointSize);
  206. void TPE_makeRect(TPE_Joint joints[4], TPE_Connection connections[6],
  207. TPE_Unit width, TPE_Unit depth, TPE_Unit jointSize);
  208. void TPE_makeTriangle(TPE_Joint joints[3], TPE_Connection connections[3],
  209. TPE_Unit sideLength, TPE_Unit jointSize);
  210. void TPE_makeCenterRect(TPE_Joint joints[5], TPE_Connection connections[8],
  211. TPE_Unit width, TPE_Unit depth, TPE_Unit jointSize);
  212. void TPE_make2Line(TPE_Joint joints[2], TPE_Connection connections[1],
  213. TPE_Unit length, TPE_Unit jointSize);
  214. //------------------------------------------------------------------------------
  215. // environment functions:
  216. TPE_Vec3 TPE_envAABoxInside(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 size);
  217. TPE_Vec3 TPE_envSphere(TPE_Vec3 point, TPE_Vec3 center, TPE_Unit radius);
  218. TPE_Vec3 TPE_envHalfPlane(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 normal);
  219. //---------------------------
  220. void TPE_worldStep(TPE_World *world);
  221. TPE_Unit TPE_bodyNetSpeed(const TPE_Body *body);
  222. TPE_Unit TPE_bodyAverageSpeed(const TPE_Body *body);
  223. void TPE_bodyDeactivate(TPE_Body *body);
  224. void TPE_bodyLimitAverageSpeed(TPE_Body *body, TPE_Unit speedMin,
  225. TPE_Unit speedMax);
  226. void TPE_bodyMultiplyNetSpeed(TPE_Body *body, TPE_Unit factor);
  227. /** Attempts to shift the joints of a soft body so that the tension of all
  228. strings becomes zero while keeping the joints near their current position. This
  229. function performs one iteration of the equalizing algorithm and doesn't
  230. guarantee a perfect solution, it may help to run multiple iterations (call this
  231. function multiple times). */
  232. void TPE_bodyReshape(TPE_Body *body, TPE_ClosestPointFunction
  233. environmentFunction);
  234. /** Move a soft body by certain offset. */
  235. void TPE_bodyMove(TPE_Body *body, TPE_Vec3 offset);
  236. /** Zero velocities of all soft body joints. */
  237. void TPE_bodyStop(TPE_Body *body);
  238. void TPE_bodyActivate(TPE_Body *body);
  239. /** Add velocity to a soft body. */
  240. void TPE_bodyAccelerate(TPE_Body *body, TPE_Vec3 velocity);
  241. /** Add angular velocity to a soft body. The rotation vector specifies the axis
  242. of rotation by its direction and angular velocity by its magnitude (magnitude
  243. of TPE_FRACTIONS_PER_UNIT will add linear velocity of TPE_FRACTIONS_PER_UNIT per
  244. tick to a point in the distance of TPE_FRACTIONS_PER_UNIT from the rotation
  245. axis). */
  246. void TPE_bodySpin(TPE_Body *body, TPE_Vec3 rotation);
  247. /** Instantly rotate soft body, the rotation vector specifies the rotation axis
  248. by its direction and the rotation angle by its magnitude (TPE_FRACTIONS_PER_UNIT
  249. stands for full angle, i.e. 2 * PI x). */
  250. void TPE_bodyRotate(TPE_Body *body, TPE_Vec3 rotation);
  251. /** Compute the center of mass of a soft body. */
  252. TPE_Vec3 TPE_bodyGetCenter(const TPE_Body *body);
  253. /** Compute sine, TPE_FRACTIONS_PER_UNIT as argument corresponds to 2 * PI
  254. radians. Returns a number from -TPE_FRACTIONS_PER_UNIT to
  255. TPE_FRACTIONS_PER_UNIT. */
  256. TPE_Unit TPE_sin(TPE_Unit x);
  257. TPE_Unit TPE_cos(TPE_Unit x);
  258. TPE_Unit TPE_atan(TPE_Unit x);
  259. void TPE_worldDebugDraw(
  260. TPE_World *world,
  261. TPE_DebugDrawFunction drawFunc,
  262. TPE_Vec3 camPos,
  263. TPE_Vec3 camRot,
  264. TPE_Vec3 camView);
  265. //------------------------------------------------------------------------------
  266. static inline TPE_Unit TPE_nonZero(TPE_Unit x)
  267. {
  268. return x != 0 ? x : 1;
  269. }
  270. TPE_Joint TPE_joint(TPE_Vec3 position, TPE_Unit size)
  271. {
  272. TPE_Joint result;
  273. result.velocity[0] = 0;
  274. result.velocity[1] = 0;
  275. result.velocity[2] = 0;
  276. result.position = position;
  277. size /= TPE_JOINT_SIZE_MULTIPLIER;
  278. if (size > 0xff)
  279. TPE_LOG("WARNING: joint size too big in TPE_joint");
  280. result.sizeDivided = size;
  281. return result;
  282. }
  283. TPE_Vec3 TPE_vec3(TPE_Unit x, TPE_Unit y, TPE_Unit z)
  284. {
  285. TPE_Vec3 r;
  286. r.x = x;
  287. r.y = y;
  288. r.z = z;
  289. return r;
  290. }
  291. TPE_Unit TPE_sqrt(TPE_Unit value)
  292. {
  293. int8_t sign = 1;
  294. if (value < 0)
  295. {
  296. sign = -1;
  297. value *= -1;
  298. }
  299. uint32_t result = 0;
  300. uint32_t a = value;
  301. uint32_t b = 1u << 30;
  302. while (b > a)
  303. b >>= 2;
  304. while (b != 0)
  305. {
  306. if (a >= result + b)
  307. {
  308. a -= result + b;
  309. result = result + 2 * b;
  310. }
  311. b >>= 2;
  312. result >>= 1;
  313. }
  314. return result * sign;
  315. }
  316. TPE_Unit TPE_vec3Len(TPE_Vec3 v)
  317. {
  318. return TPE_sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
  319. }
  320. TPE_Unit TPE_vec3LenApprox(TPE_Vec3 v)
  321. {
  322. if (v.x < 0)
  323. v.x *= -1;
  324. if (v.y < 0)
  325. v.y *= -1;
  326. if (v.z < 0)
  327. v.z *= -1;
  328. TPE_Unit sum = v.x + v.y + v.z;
  329. v.x = (v.x > v.y) ?
  330. (v.x > v.z ? v.x : v.z) :
  331. (v.y > v.z ? v.y : v.z);
  332. return (v.x + sum) / 2;
  333. }
  334. TPE_Unit TPE_dist(TPE_Vec3 p1, TPE_Vec3 p2)
  335. {
  336. p1 = TPE_vec3Minus(p1,p2);
  337. return TPE_vec3Len(p1);
  338. }
  339. TPE_Unit TPE_distApprox(TPE_Vec3 p1, TPE_Vec3 p2)
  340. {
  341. p1 = TPE_vec3Minus(p1,p2);
  342. return TPE_vec3LenApprox(p1);
  343. }
  344. void TPE_bodyInit(TPE_Body *body,
  345. TPE_Joint *joints, uint8_t jointCount,
  346. TPE_Connection *connections, uint8_t connectionCount,
  347. TPE_Unit mass)
  348. {
  349. body->joints = joints;
  350. body->jointCount = jointCount;
  351. body->connections = connections;
  352. body->connectionCount = connectionCount;
  353. body->deactivateCount = 0;
  354. body->friction = TPE_FRACTIONS_PER_UNIT / 2;
  355. body->elasticity = TPE_FRACTIONS_PER_UNIT / 2;
  356. body->flags = 0;
  357. body->jointMass = mass / jointCount;
  358. if (body->jointMass == 0)
  359. body->jointMass = 1;
  360. for (uint32_t i = 0; i < connectionCount; ++i)
  361. {
  362. TPE_Unit d = TPE_DISTANCE(
  363. joints[connections[i].joint1].position,
  364. joints[connections[i].joint2].position);
  365. if (d > 0xffff)
  366. TPE_LOG("WARNING: joint distance too long in TPE_bodyInit");
  367. connections[i].length = d != 0 ? d : 1; // prevent later division by zero
  368. }
  369. }
  370. void TPE_worldInit(TPE_World *world,
  371. TPE_Body *bodies, uint16_t bodyCount,
  372. TPE_ClosestPointFunction environmentFunction)
  373. {
  374. world->bodies = bodies;
  375. world->bodyCount = bodyCount;
  376. world->environmentFunction = environmentFunction;
  377. }
  378. #define C(n,a,b) connections[n].joint1 = a; connections[n].joint2 = b;
  379. void TPE_make2Line(TPE_Joint joints[2], TPE_Connection connections[1],
  380. TPE_Unit length, TPE_Unit jointSize)
  381. {
  382. joints[0] = TPE_joint(TPE_vec3(length / 2,0,0),jointSize);
  383. joints[1] = TPE_joint(TPE_vec3(length / -2,0,0),jointSize);
  384. C(0, 0,1)
  385. }
  386. void TPE_makeRect(TPE_Joint joints[4], TPE_Connection connections[6],
  387. TPE_Unit width, TPE_Unit depth, TPE_Unit jointSize)
  388. {
  389. width /= 2;
  390. depth /= 2;
  391. for (uint8_t i = 0; i < 4; ++i)
  392. joints[i] = TPE_joint(
  393. TPE_vec3((i % 2) ? -1 * width : width,
  394. 0,(i / 2) ? - 1 * depth : depth),
  395. jointSize);
  396. C(0, 0,1) C(1, 0,2) C (2, 3,1) C(3, 3,2)
  397. C(4, 0,3) C(5, 1,2)
  398. }
  399. void TPE_makeCenterRect(TPE_Joint joints[5], TPE_Connection connections[8],
  400. TPE_Unit width, TPE_Unit depth, TPE_Unit jointSize)
  401. {
  402. TPE_makeRect(joints,connections,width,depth,jointSize);
  403. joints[4] = TPE_joint(TPE_vec3(0,0,0),jointSize);
  404. C(6, 0,4) C(7, 3,4)
  405. }
  406. void TPE_makeTriangle(TPE_Joint joints[3], TPE_Connection connections[3],
  407. TPE_Unit sideLength, TPE_Unit jointSize)
  408. {
  409. joints[0] = TPE_joint(TPE_vec3(sideLength / 2,0,
  410. TPE_sqrt((sideLength * sideLength) / 2) / 2),
  411. jointSize);
  412. joints[1] = joints[0];
  413. joints[1].position.x *= -1;
  414. joints[2] = TPE_joint(TPE_vec3(0,0,-1 * joints[0].position.z),jointSize);
  415. C(0, 0,1) C(1, 1,2) C(2, 2,0)
  416. }
  417. void TPE_makeBox(TPE_Joint joints[8], TPE_Connection connections[16],
  418. TPE_Unit width, TPE_Unit depth, TPE_Unit height, TPE_Unit jointSize)
  419. {
  420. width /= 2;
  421. depth /= 2;
  422. height /= 2;
  423. for (uint8_t i = 0; i < 8; ++i)
  424. joints[i] = TPE_joint(
  425. TPE_vec3(
  426. (i % 2) ? width : (-1 * width),
  427. ((i >> 2) % 2) ? height : (-1 * height),
  428. ((i >> 1) % 2) ? depth : (-1 * depth)),
  429. jointSize);
  430. C(0, 0,1) C(1, 1,3) C(2, 3,2) C(3, 2,0) // top
  431. C(4, 4,5) C(5, 5,7) C(6, 7,6) C(7, 6,4) // bottom
  432. C(8, 0,4) C(9, 1,5) C(10,3,7) C(11,2,6) // middle
  433. C(12,0,7) C(13,1,6) C(14,2,5) C(15,3,4) // diagonal
  434. }
  435. void TPE_makeCenterBox(TPE_Joint joints[9], TPE_Connection connections[18],
  436. TPE_Unit width, TPE_Unit depth, TPE_Unit height, TPE_Unit jointSize)
  437. {
  438. TPE_makeBox(joints,connections,width,depth,height,jointSize);
  439. joints[8] = TPE_joint(TPE_vec3(0,0,0),jointSize);
  440. C(16, 0,8) C(17, 7,8)
  441. }
  442. #undef C
  443. void TPE_bodyDeactivate(TPE_Body *body)
  444. {
  445. body->flags |= TPE_BODY_FLAG_DEACTIVATED;
  446. }
  447. void TPE_worldStep(TPE_World *world)
  448. {
  449. for (uint16_t i = 0; i < world->bodyCount; ++i)
  450. {
  451. TPE_Body *body = world->bodies + i;
  452. if (body->flags & (TPE_BODY_FLAG_DEACTIVATED | TPE_BODY_FLAG_DISABLED))
  453. continue;
  454. TPE_Joint *joint = body->joints, *joint2;
  455. for (uint16_t j = 0; j < body->jointCount; ++j) // apply velocities
  456. {
  457. joint->position.x += joint->velocity[0];
  458. joint->position.y += joint->velocity[1];
  459. joint->position.z += joint->velocity[2];
  460. joint++;
  461. }
  462. TPE_Connection *connection = body->connections;
  463. for (uint16_t j = 0; j < world->bodyCount; ++j)
  464. {
  465. if (j > i || (world->bodies[j].flags & TPE_BODY_FLAG_DEACTIVATED))
  466. if (TPE_bodiesResolveCollision(body,world->bodies + j)) // TODO: nested if
  467. {
  468. TPE_bodyActivate(body);
  469. body->deactivateCount = TPE_LIGHT_DEACTIVATION;
  470. TPE_bodyActivate(world->bodies + j);
  471. world->bodies[j].deactivateCount = TPE_LIGHT_DEACTIVATION;
  472. }
  473. }
  474. TPE_bodyEnvironmentResolveCollision(body,
  475. world->environmentFunction);
  476. TPE_Unit bodyTension = 0;
  477. for (uint16_t j = 0; j < body->connectionCount; ++j) // update velocities
  478. {
  479. joint = &(body->joints[connection->joint1]);
  480. joint2 = &(body->joints[connection->joint2]);
  481. TPE_Vec3 dir = TPE_vec3Minus(joint2->position,joint->position);
  482. TPE_Unit len = TPE_LENGTH(dir);
  483. len = (len * TPE_FRACTIONS_PER_UNIT) /
  484. connection->length - TPE_FRACTIONS_PER_UNIT;
  485. bodyTension += len > 0 ? len : -len;
  486. if (
  487. len > TPE_TENSION_ACCELERATION_THRESHOLD ||
  488. len < -1 * TPE_TENSION_ACCELERATION_THRESHOLD)
  489. {
  490. TPE_vec3Normalize(&dir);
  491. dir.x /= TPE_TENSION_ACCELERATION_DIVIDER;
  492. dir.y /= TPE_TENSION_ACCELERATION_DIVIDER;
  493. dir.z /= TPE_TENSION_ACCELERATION_DIVIDER;
  494. if (len < 0)
  495. {
  496. dir.x *= -1;
  497. dir.y *= -1;
  498. dir.z *= -1;
  499. }
  500. joint->velocity[0] += dir.x;
  501. joint->velocity[1] += dir.y;
  502. joint->velocity[2] += dir.z;
  503. joint2->velocity[0] -= dir.x;
  504. joint2->velocity[1] -= dir.y;
  505. joint2->velocity[2] -= dir.z;
  506. }
  507. connection++;
  508. }
  509. if (body->connectionCount > 0 && !(body->flags & TPE_BODY_FLAG_SOFT))
  510. {
  511. TPE_bodyReshape(body,world->environmentFunction);
  512. bodyTension /= body->connectionCount;
  513. if (bodyTension > TPE_RESHAPE_TENSION_LIMIT)
  514. for (uint8_t k = 0; k < TPE_RESHAPE_ITERATIONS; ++k)
  515. TPE_bodyReshape(body,world->environmentFunction);
  516. }
  517. if (body->deactivateCount >= TPE_DEACTIVATE_AFTER)
  518. {
  519. TPE_bodyStop(body);
  520. body->deactivateCount = 0;
  521. body->flags |= TPE_BODY_FLAG_DEACTIVATED;
  522. }
  523. else if (TPE_bodyAverageSpeed(body) <= TPE_LOW_SPEED) // TODO: optimize
  524. body->deactivateCount++;
  525. else
  526. body->deactivateCount = 0;
  527. }
  528. }
  529. void TPE_bodyActivate(TPE_Body *body)
  530. {
  531. // the if check has to be here, don't remove it
  532. if (body->flags & TPE_BODY_FLAG_DEACTIVATED)
  533. {
  534. TPE_bodyStop(body);
  535. body->flags &= ~TPE_BODY_FLAG_DEACTIVATED;
  536. body->deactivateCount = 0;
  537. }
  538. }
  539. TPE_Unit TPE_bodyNetSpeed(const TPE_Body *body)
  540. {
  541. TPE_Unit velocity = 0;
  542. const TPE_Joint *joint = body->joints;
  543. for (uint16_t i = 0; i < body->jointCount; ++i)
  544. {
  545. velocity += TPE_LENGTH(
  546. TPE_vec3(joint->velocity[0],joint->velocity[1],joint->velocity[2]));
  547. joint++;
  548. }
  549. return velocity;
  550. }
  551. TPE_Unit TPE_bodyAverageSpeed(const TPE_Body *body)
  552. {
  553. return TPE_bodyNetSpeed(body) / body->jointCount;
  554. }
  555. void TPE_bodyMultiplyNetSpeed(TPE_Body *body, TPE_Unit factor)
  556. {
  557. TPE_Joint *joint = body->joints;
  558. for (uint16_t j = 0; j < body->jointCount; ++j)
  559. {
  560. for (uint8_t k = 0; k < 3; ++k)
  561. joint->velocity[k] =
  562. (((TPE_Unit) joint->velocity[k]) * factor) /
  563. TPE_FRACTIONS_PER_UNIT;
  564. joint++;
  565. }
  566. }
  567. void TPE_bodyLimitAverageSpeed(TPE_Body *body, TPE_Unit speedMin,
  568. TPE_Unit speedMax)
  569. {
  570. for (uint8_t i = 0; i < 16; ++i)
  571. {
  572. TPE_Unit speed = TPE_bodyAverageSpeed(body);
  573. if (speed >= speedMin && speed <= speedMax)
  574. return;
  575. TPE_Unit fraction =
  576. (((speedMax + speedMin) / 2) * TPE_FRACTIONS_PER_UNIT) /
  577. TPE_nonZero(speed);
  578. TPE_bodyMultiplyNetSpeed(body,fraction);
  579. }
  580. }
  581. void TPE_bodyReshape(TPE_Body *body,
  582. TPE_ClosestPointFunction environmentFunction)
  583. {
  584. for (uint16_t i = 0; i < body->connectionCount; ++i)
  585. {
  586. TPE_Connection *c = &body->connections[i];
  587. TPE_Joint *j1 = &(body->joints[c->joint1]);
  588. TPE_Joint *j2 = &(body->joints[c->joint2]);
  589. TPE_Vec3 dir = TPE_vec3Minus(j2->position,j1->position);
  590. TPE_Vec3 middle = TPE_vec3Plus(j1->position,j2->position);
  591. middle.x /= 2;
  592. middle.y /= 2;
  593. middle.z /= 2;
  594. TPE_vec3Normalize(&dir);
  595. dir.x = (dir.x * c->length) / TPE_FRACTIONS_PER_UNIT;
  596. dir.y = (dir.y * c->length) / TPE_FRACTIONS_PER_UNIT;
  597. dir.z = (dir.z * c->length) / TPE_FRACTIONS_PER_UNIT;
  598. TPE_Vec3 positionBackup = j1->position;
  599. j1->position.x = middle.x - dir.x / 2;
  600. j1->position.y = middle.y - dir.y / 2;
  601. j1->position.z = middle.z - dir.z / 2;
  602. if (environmentFunction != 0 &&
  603. TPE_LENGTH(TPE_vec3Minus(j1->position,environmentFunction(j1->position,TPE_JOINT_SIZE(*j1))))
  604. < TPE_JOINT_SIZE(*j1))
  605. j1->position = positionBackup;
  606. positionBackup = j2->position;
  607. j2->position.x = j1->position.x + dir.x;
  608. j2->position.y = j1->position.y + dir.y;
  609. j2->position.z = j1->position.z + dir.z;
  610. if (environmentFunction != 0 &&
  611. TPE_LENGTH(TPE_vec3Minus(j2->position,environmentFunction(j2->position,TPE_JOINT_SIZE(*j2))))
  612. < TPE_JOINT_SIZE(*j2))
  613. j2->position = positionBackup;
  614. }
  615. }
  616. TPE_Vec3 TPE_vec3Plus(TPE_Vec3 v1, TPE_Vec3 v2)
  617. {
  618. v1.x += v2.x;
  619. v1.y += v2.y;
  620. v1.z += v2.z;
  621. return v1;
  622. }
  623. TPE_Vec3 TPE_vec3Minus(TPE_Vec3 v1, TPE_Vec3 v2)
  624. {
  625. v1.x -= v2.x;
  626. v1.y -= v2.y;
  627. v1.z -= v2.z;
  628. return v1;
  629. }
  630. void TPE_vec3Normalize(TPE_Vec3 *v)
  631. {
  632. TPE_Unit l = TPE_LENGTH(*v);
  633. if (l != 0)
  634. {
  635. v->x = (v->x * TPE_FRACTIONS_PER_UNIT) / l;
  636. v->y = (v->y * TPE_FRACTIONS_PER_UNIT) / l;
  637. v->z = (v->z * TPE_FRACTIONS_PER_UNIT) / l;
  638. }
  639. }
  640. TPE_Vec3 TPE_bodyGetCenter(const TPE_Body *body)
  641. {
  642. // TODO: take into account possibly different joint sizes? does it even matter?
  643. TPE_Vec3 result = TPE_vec3(0,0,0);
  644. const TPE_Joint *j = body->joints;
  645. for (uint16_t i = 0; i < body->jointCount; ++i)
  646. {
  647. result = TPE_vec3Plus(result,j->position);
  648. j++;
  649. }
  650. result.x /= body->jointCount;
  651. result.y /= body->jointCount;
  652. result.z /= body->jointCount;
  653. return result;
  654. }
  655. void TPE_bodySpin(TPE_Body *body, TPE_Vec3 rotation)
  656. {
  657. TPE_Vec3 center = TPE_bodyGetCenter(body);
  658. TPE_Unit anuglarV = TPE_LENGTH(rotation);
  659. for (uint16_t i = 0; i < body->jointCount; ++i)
  660. {
  661. TPE_Joint *j = body->joints + i;
  662. TPE_Vec3 toPoint = TPE_vec3Minus(j->position,center);
  663. toPoint = TPE_vec3Project(toPoint,rotation);
  664. toPoint = TPE_vec3Plus(center,toPoint);
  665. toPoint = TPE_vec3Minus(j->position,toPoint);
  666. toPoint = TPE_vec3Cross(toPoint,rotation);
  667. j->velocity[0] += toPoint.x;
  668. j->velocity[1] += toPoint.y;
  669. j->velocity[2] += toPoint.z;
  670. }
  671. }
  672. void TPE_bodyRotate(TPE_Body *body, TPE_Vec3 rotation)
  673. {
  674. TPE_Vec3 bodyCenter = TPE_bodyGetCenter(body);
  675. TPE_Unit angle = TPE_LENGTH(rotation);
  676. TPE_vec3Normalize(&rotation);
  677. for (uint16_t i = 0; i < body->jointCount; ++i)
  678. {
  679. TPE_Joint *j = body->joints + i;
  680. TPE_Vec3 toPoint = TPE_vec3Minus(j->position,bodyCenter);
  681. toPoint = TPE_vec3Project(toPoint,rotation);
  682. TPE_Vec3 rotationCenter = TPE_vec3Plus(bodyCenter,toPoint);
  683. toPoint = TPE_vec3Minus(j->position,rotationCenter);
  684. TPE_Vec3 toPoint2 = TPE_vec3Cross(toPoint,rotation);
  685. j->position =
  686. TPE_vec3Plus(rotationCenter,
  687. TPE_vec3Plus(
  688. TPE_vec3Times(toPoint,TPE_cos(angle)),
  689. TPE_vec3Times(toPoint2,TPE_sin(angle))
  690. )
  691. );
  692. }
  693. }
  694. TPE_Vec3 TPE_vec3Cross(TPE_Vec3 v1, TPE_Vec3 v2)
  695. {
  696. TPE_Vec3 r;
  697. r.x = (v1.y * v2.z - v1.z * v2.y) / TPE_FRACTIONS_PER_UNIT;
  698. r.y = (v1.z * v2.x - v1.x * v2.z) / TPE_FRACTIONS_PER_UNIT;
  699. r.z = (v1.x * v2.y - v1.y * v2.x) / TPE_FRACTIONS_PER_UNIT;
  700. return r;
  701. }
  702. TPE_Vec3 TPE_vec3Project(TPE_Vec3 v, TPE_Vec3 base)
  703. {
  704. TPE_Vec3 r;
  705. TPE_vec3Normalize(&base);
  706. TPE_Unit p = TPE_vec3Dot(v,base);
  707. r.x = (p * base.x) / TPE_FRACTIONS_PER_UNIT;
  708. r.y = (p * base.y) / TPE_FRACTIONS_PER_UNIT;
  709. r.z = (p * base.z) / TPE_FRACTIONS_PER_UNIT;
  710. return r;
  711. }
  712. void TPE_bodyMove(TPE_Body *body, TPE_Vec3 offset)
  713. {
  714. for (uint16_t i = 0; i < body->jointCount; ++i)
  715. body->joints[i].position = TPE_vec3Plus(body->joints[i].position,
  716. offset);
  717. }
  718. void TPE_bodyAccelerate(TPE_Body *body, TPE_Vec3 velocity)
  719. {
  720. TPE_bodyActivate(body);
  721. for (uint16_t i = 0; i < body->jointCount; ++i)
  722. {
  723. body->joints[i].velocity[0] += velocity.x;
  724. body->joints[i].velocity[1] += velocity.y;
  725. body->joints[i].velocity[2] += velocity.z;
  726. }
  727. }
  728. void TPE_bodyStop(TPE_Body *body)
  729. {
  730. for (uint16_t i = 0; i < body->jointCount; ++i)
  731. {
  732. body->joints[i].velocity[0] = 0;
  733. body->joints[i].velocity[1] = 0;
  734. body->joints[i].velocity[2] = 0;
  735. }
  736. }
  737. TPE_Unit TPE_vec3Dot(TPE_Vec3 v1, TPE_Vec3 v2)
  738. {
  739. return (v1.x * v2.x + v1.y * v2.y + v1.z * v2.z) / TPE_FRACTIONS_PER_UNIT;
  740. }
  741. TPE_Unit TPE_cos(TPE_Unit x)
  742. {
  743. return TPE_sin(x + TPE_FRACTIONS_PER_UNIT / 4);
  744. }
  745. TPE_Unit TPE_sin(TPE_Unit x)
  746. {
  747. int8_t sign = 1;
  748. if (x < 0) // odd function
  749. {
  750. x *= -1;
  751. sign = -1;
  752. }
  753. x %= TPE_FRACTIONS_PER_UNIT;
  754. if (x > TPE_FRACTIONS_PER_UNIT / 2)
  755. {
  756. x -= TPE_FRACTIONS_PER_UNIT / 2;
  757. sign *= -1;
  758. }
  759. TPE_Unit tmp = TPE_FRACTIONS_PER_UNIT - 2 * x;
  760. #define _PI2 ((TPE_Unit) (9.8696044 * TPE_FRACTIONS_PER_UNIT))
  761. return sign * // Bhaskara's approximation
  762. (((32 * x * _PI2) / TPE_FRACTIONS_PER_UNIT) * tmp) /
  763. ((_PI2 * (5 * TPE_FRACTIONS_PER_UNIT - (8 * x * tmp) /
  764. TPE_FRACTIONS_PER_UNIT)) / TPE_FRACTIONS_PER_UNIT);
  765. #undef _PI2
  766. }
  767. uint8_t TPE_bodiesResolveCollision(TPE_Body *b1, TPE_Body *b2)
  768. {
  769. // TODO: bounding sphere (or AABB? maybe ifdef)
  770. uint8_t r = 0;
  771. for (uint16_t i = 0; i < b1->jointCount; ++i)
  772. for (uint16_t j = 0; j < b2->jointCount; ++j)
  773. {
  774. r |= TPE_jointsResolveCollision(
  775. &(b1->joints[i]),
  776. &(b2->joints[j]),
  777. b1->jointMass,
  778. b2->jointMass,
  779. 512,
  780. (b1->friction + b2->friction) / 2
  781. );
  782. }
  783. return r;
  784. }
  785. uint8_t TPE_jointsResolveCollision(TPE_Joint *j1, TPE_Joint *j2,
  786. TPE_Unit mass1, TPE_Unit mass2, TPE_Unit elasticity, TPE_Unit friction)
  787. {
  788. TPE_Vec3 dir = TPE_vec3Minus(j2->position,j1->position);
  789. TPE_Unit d = TPE_LENGTH(dir) - TPE_JOINT_SIZE(*j1) - TPE_JOINT_SIZE(*j2);
  790. if (d < 0) // collision?
  791. {
  792. // separate bodies, the shift distance will depend on the weight ratio:
  793. d = -1 * d + TPE_COLLISION_RESOLUTION_MARGIN;
  794. TPE_vec3Normalize(&dir);
  795. TPE_Unit ratio = (mass2 * TPE_FRACTIONS_PER_UNIT) /
  796. TPE_nonZero(mass1 + mass2);
  797. TPE_Unit shiftDistance = (ratio * d) / TPE_FRACTIONS_PER_UNIT;
  798. TPE_Vec3 shift = TPE_vec3Times(dir,shiftDistance);
  799. j1->position = TPE_vec3Minus(j1->position,shift);
  800. shiftDistance = d - shiftDistance;
  801. shift = TPE_vec3Times(dir,shiftDistance);
  802. j2->position = TPE_vec3Plus(j2->position,shift);
  803. // compute new velocities:
  804. TPE_Unit v1, v2;
  805. TPE_Vec3 vel = TPE_vec3(j1->velocity[0],j1->velocity[1],j1->velocity[2]);
  806. vel = TPE_vec3Project(vel,dir);
  807. j1->velocity[0] = j1->velocity[0] - vel.x;
  808. j1->velocity[1] = j1->velocity[1] - vel.y;
  809. j1->velocity[2] = j1->velocity[2] - vel.z;
  810. /* friction explanation: Not physically correct (doesn't depend on load),
  811. friction basically means we weighted average the velocities of the bodies
  812. in the direction perpendicular to the hit normal, in the ratio of their
  813. masses, friction coefficient just says how much of this effect we apply
  814. (it multiplies the friction vectors we are subtracting) */
  815. TPE_Vec3 frictionVec =
  816. TPE_vec3(j1->velocity[0],j1->velocity[1],j1->velocity[2]);
  817. v1 = TPE_vec3Dot(vel,dir);
  818. vel = TPE_vec3(j2->velocity[0],j2->velocity[1],j2->velocity[2]);
  819. vel = TPE_vec3Project(vel,dir);
  820. j2->velocity[0] = j2->velocity[0] - vel.x;
  821. j2->velocity[1] = j2->velocity[1] - vel.y;
  822. j2->velocity[2] = j2->velocity[2] - vel.z;
  823. frictionVec = TPE_vec3Minus(
  824. TPE_vec3(j2->velocity[0],j2->velocity[1],j2->velocity[2]),
  825. frictionVec);
  826. v2 = TPE_vec3Dot(vel,dir);
  827. TPE_getVelocitiesAfterCollision(&v1,&v2,mass1,mass2,elasticity);
  828. vel = TPE_vec3Times(dir,v1);
  829. #define assignVec(j,i,d,o) \
  830. j->velocity[i] = j->velocity[i] + vel.d o (((frictionVec.d * ratio) / \
  831. TPE_FRACTIONS_PER_UNIT) * friction) / TPE_FRACTIONS_PER_UNIT;
  832. assignVec(j1,0,x,+)
  833. assignVec(j1,1,y,+)
  834. assignVec(j1,2,z,+)
  835. vel = TPE_vec3Times(dir,v2);
  836. ratio = TPE_FRACTIONS_PER_UNIT - ratio;
  837. assignVec(j2,0,x,-)
  838. assignVec(j2,1,y,-)
  839. assignVec(j2,2,z,-)
  840. #undef assignVec
  841. return 1;
  842. }
  843. return 0;
  844. }
  845. TPE_Vec3 TPE_vec3Times(TPE_Vec3 v, TPE_Unit units)
  846. {
  847. v.x = (v.x * units) / TPE_FRACTIONS_PER_UNIT;
  848. v.y = (v.y * units) / TPE_FRACTIONS_PER_UNIT;
  849. v.z = (v.z * units) / TPE_FRACTIONS_PER_UNIT;
  850. return v;
  851. }
  852. TPE_Vec3 TPE_vec3TimesNonNormalized(TPE_Vec3 v, TPE_Unit q)
  853. {
  854. v.x *= q;
  855. v.y *= q;
  856. v.z *= q;
  857. return v;
  858. }
  859. void TPE_getVelocitiesAfterCollision(
  860. TPE_Unit *v1,
  861. TPE_Unit *v2,
  862. TPE_Unit m1,
  863. TPE_Unit m2,
  864. TPE_Unit elasticity
  865. )
  866. {
  867. /* in the following a lot of TPE_FRACTIONS_PER_UNIT cancel out, feel free to
  868. check if confused */
  869. TPE_Unit m1Pm2 = TPE_nonZero(m1 + m2);
  870. TPE_Unit v2Mv1 = TPE_nonZero(*v2 - *v1);
  871. TPE_Unit m1v1Pm2v2 = ((m1 * *v1) + (m2 * *v2));
  872. *v1 = (((elasticity * m2 / TPE_FRACTIONS_PER_UNIT) * v2Mv1)
  873. + m1v1Pm2v2) / m1Pm2;
  874. *v2 = (((elasticity * m1 / TPE_FRACTIONS_PER_UNIT) * -1 * v2Mv1)
  875. + m1v1Pm2v2) / m1Pm2;
  876. }
  877. uint8_t TPE_jointEnvironmentResolveCollision(TPE_Joint *joint, TPE_Unit elasticity,
  878. TPE_Unit friction, TPE_ClosestPointFunction env)
  879. {
  880. TPE_Vec3 toJoint = TPE_vec3Minus(joint->position,env(joint->position,TPE_JOINT_SIZE(*joint)));
  881. TPE_Unit len = TPE_LENGTH(toJoint);
  882. if (len <= TPE_JOINT_SIZE(*joint))
  883. {
  884. // colliding
  885. TPE_Vec3 positionBackup = joint->position, shift;
  886. uint8_t success = 0;
  887. if (len > 0)
  888. {
  889. /* Joint center is still outside the geometry so we can determine the
  890. normal and use it to shift it outside. This can still leave the joint
  891. colliding though, so try to repeat it a few times. */
  892. for (int i = 0; i < TPE_COLLISION_RESOLUTION_ITERATIONS; ++i)
  893. {
  894. shift = toJoint;
  895. TPE_vec3Normalize(&shift);
  896. shift = TPE_vec3Times(shift,TPE_JOINT_SIZE(*joint) - len +
  897. TPE_FRACTIONS_PER_UNIT / TPE_COLLISION_RESOLUTION_MARGIN);
  898. joint->position = TPE_vec3Plus(joint->position,shift);
  899. toJoint = TPE_vec3Minus(joint->position,env(joint->position,TPE_JOINT_SIZE(*joint)));
  900. len = TPE_LENGTH(toJoint); // still colliding?
  901. if (len >= TPE_JOINT_SIZE(*joint))
  902. {
  903. success = 1;
  904. break;
  905. }
  906. }
  907. }
  908. if (!success)
  909. {
  910. /* Shifting along normal was unsuccessfull, now try different approach:
  911. shift back by joint velocity. */
  912. shift = TPE_vec3(-1 * joint->velocity[0],-1 * joint->velocity[1],
  913. -1 * joint->velocity[2]);
  914. for (int i = 0; i < TPE_COLLISION_RESOLUTION_ITERATIONS; ++i)
  915. {
  916. joint->position = TPE_vec3Plus(joint->position,shift);
  917. toJoint = TPE_vec3Minus(joint->position,env(joint->position,TPE_JOINT_SIZE(*joint)));
  918. len = TPE_LENGTH(toJoint); // still colliding?
  919. if (len >= TPE_JOINT_SIZE(*joint))
  920. {
  921. success = 1;
  922. break;
  923. }
  924. shift.x /= 2; // decrease the step a bit
  925. shift.y /= 2;
  926. shift.z /= 2;
  927. }
  928. }
  929. if (success)
  930. {
  931. TPE_Vec3 vel = TPE_vec3(joint->velocity[0],joint->velocity[1],
  932. joint->velocity[2]);
  933. vel = TPE_vec3Project(vel,shift);
  934. TPE_Vec3 vel2 = TPE_vec3Minus
  935. (
  936. TPE_vec3(joint->velocity[0],joint->velocity[1],joint->velocity[2]),
  937. vel
  938. );
  939. vel2 = TPE_vec3Times(vel2,friction);
  940. vel = TPE_vec3Times(vel,TPE_FRACTIONS_PER_UNIT + elasticity);
  941. joint->velocity[0] -= vel.x + vel2.x;
  942. joint->velocity[1] -= vel.y + vel2.y;
  943. joint->velocity[2] -= vel.z + vel2.z;
  944. }
  945. else
  946. {
  947. TPE_LOG("WARNING: joint-environment collision couldn't be resolved");
  948. joint->position = positionBackup;
  949. joint->velocity[0] = 0;
  950. joint->velocity[1] = 0;
  951. joint->velocity[2] = 0;
  952. }
  953. return 1;
  954. }
  955. return 0;
  956. }
  957. uint8_t TPE_bodyEnvironmentResolveCollision(TPE_Body *body,
  958. TPE_ClosestPointFunction env)
  959. {
  960. // TODO: bounding sphere
  961. uint8_t collision = 0;
  962. for (uint16_t i = 0; i < body->jointCount; ++i)
  963. collision |= TPE_jointEnvironmentResolveCollision(
  964. body->joints + i,body->elasticity,body->friction,env);
  965. return collision;
  966. }
  967. TPE_Vec3 TPE_vec3Normalized(TPE_Vec3 v)
  968. {
  969. TPE_vec3Normalize(&v);
  970. return v;
  971. }
  972. TPE_Unit TPE_atan(TPE_Unit x)
  973. {
  974. /* atan approximation by polynomial
  975. WARNING: this will break with different value of TPE_FRACTIONS_PER_UNIT */
  976. TPE_Unit sign = 1, x2 = x * x;
  977. if (x < 0)
  978. {
  979. x *= -1;
  980. sign = -1;
  981. }
  982. if (x > 30000) // anti overflow
  983. return sign * (TPE_FRACTIONS_PER_UNIT / 4);
  984. return sign *
  985. (307 * x + x2) / ((267026 + 633 * x + x2) / 128);
  986. }
  987. void _TPE_vec2Rotate(TPE_Unit *x, TPE_Unit *y, TPE_Unit angle)
  988. {
  989. TPE_Unit tmp = *x;
  990. TPE_Unit s = TPE_sin(angle);
  991. TPE_Unit c = TPE_cos(angle);
  992. *x = (c * *x - s * *y) / TPE_FRACTIONS_PER_UNIT;
  993. *y = (s * tmp + c * *y) / TPE_FRACTIONS_PER_UNIT;
  994. }
  995. TPE_Unit _TPE_vec2Angle(TPE_Unit x, TPE_Unit y)
  996. {
  997. TPE_Unit r = 0;
  998. if (x != 0)
  999. {
  1000. r = TPE_atan((y * TPE_FRACTIONS_PER_UNIT) / x);
  1001. if (x < 0)
  1002. r += TPE_FRACTIONS_PER_UNIT / 2;
  1003. else if (r < 0)
  1004. r += TPE_FRACTIONS_PER_UNIT;
  1005. }
  1006. else
  1007. {
  1008. if (y < 0)
  1009. r = (3 * TPE_FRACTIONS_PER_UNIT) / 4;
  1010. else if (y > 0)
  1011. r = TPE_FRACTIONS_PER_UNIT / 4;
  1012. // else (y == 0) r stays 0
  1013. }
  1014. return r;
  1015. }
  1016. TPE_Vec3 TPE_orientationFromVecs(TPE_Vec3 forward, TPE_Vec3 right)
  1017. {
  1018. TPE_Vec3 result;
  1019. // get rotation around Y:
  1020. result.y = _TPE_vec2Angle(forward.z,-1 * forward.x);
  1021. // now rotate back by this angle to align with x = 0 plane:
  1022. _TPE_vec2Rotate(&forward.z,&forward.x,result.y);
  1023. _TPE_vec2Rotate(&right.z,&right.x,result.y);
  1024. // now do the same for the second axis:
  1025. result.x =
  1026. _TPE_vec2Angle(forward.z,forward.y);
  1027. _TPE_vec2Rotate(&right.z,&right.y,-1 * result.x);
  1028. result.z = _TPE_vec2Angle(right.x,-1 * right.y);
  1029. return result;
  1030. }
  1031. TPE_Vec3 _TPE_project3DPoint(TPE_Vec3 p, TPE_Vec3 camPos, TPE_Vec3 camRot,
  1032. TPE_Vec3 camView)
  1033. {
  1034. // transform to camera space:
  1035. p = TPE_vec3Minus(p,camPos);
  1036. _TPE_vec2Rotate(&p.z,&p.x,camRot.y);
  1037. _TPE_vec2Rotate(&p.z,&p.y,-1 * camRot.x);
  1038. _TPE_vec2Rotate(&p.y,&p.x,-1 * camRot.z);
  1039. if (p.z <= 0)
  1040. return p;
  1041. p.x = (p.x * camView.z) / p.z;
  1042. p.y = (p.y * camView.z) / p.z;
  1043. p.x = camView.x / 2 + (p.x * camView.x) / (2 * TPE_FRACTIONS_PER_UNIT);
  1044. p.y = camView.y / 2 - (p.y * camView.x) / (2 * TPE_FRACTIONS_PER_UNIT);
  1045. // ^ x here intentional
  1046. return p;
  1047. }
  1048. void _TPE_drawDebugPixel(
  1049. TPE_Unit x, TPE_Unit y, TPE_Unit w, TPE_Unit h, uint8_t c,
  1050. TPE_DebugDrawFunction f)
  1051. {
  1052. if (x >= 0 && x < w && y >= 0 && y < h)
  1053. f(x,y,c);
  1054. }
  1055. void TPE_worldDebugDraw(
  1056. TPE_World *world,
  1057. TPE_DebugDrawFunction drawFunc,
  1058. TPE_Vec3 camPos,
  1059. TPE_Vec3 camRot,
  1060. TPE_Vec3 camView)
  1061. {
  1062. if (world->environmentFunction != 0)
  1063. {
  1064. // environment:
  1065. TPE_Vec3 testPoint;
  1066. #define D 256
  1067. #define N 16
  1068. TPE_Vec3 center = TPE_vec3(0,TPE_sin(camRot.x),TPE_cos(camRot.x));
  1069. _TPE_vec2Rotate(&center.x,&center.z,camRot.y);
  1070. center = TPE_vec3Times(center,(D * N) / 2);
  1071. center = TPE_vec3Plus(camPos,center);
  1072. center.x = (center.x / D) * D;
  1073. center.y = (center.y / D) * D;
  1074. center.z = (center.z / D) * D;
  1075. testPoint.y = center.y - (D * N) / 2; //(camPos.y / D) * D - (D * N) / 2;
  1076. for (uint8_t j = 0; j < N; ++j)
  1077. {
  1078. testPoint.x = center.x - (D * N) / 2;//(camPos.x / D) * D - (D * N) / 2;
  1079. for (uint8_t k = 0; k < N; ++k)
  1080. {
  1081. testPoint.z = center.z - (D * N) / 2; //(camPos.z / D) * D - (D * N) / 2;
  1082. for (uint8_t l = 0; l < N; ++l)
  1083. {
  1084. TPE_Vec3 r = world->environmentFunction(testPoint,D);
  1085. if ((r.x != testPoint.x || r.y != testPoint.y || r.z != testPoint.z)
  1086. ) // && TPE_DISTANCE(testPoint,r) < D)
  1087. {
  1088. // TODO: accel. by testing cheb dist first?
  1089. r = _TPE_project3DPoint(r,camPos,camRot,camView);
  1090. if (r.z > 0)
  1091. _TPE_drawDebugPixel(r.x,r.y,camView.x,camView.y,2,drawFunc);
  1092. }
  1093. testPoint.z += D;
  1094. }
  1095. testPoint.x += D;
  1096. }
  1097. testPoint.y += D;
  1098. }
  1099. #undef N
  1100. #undef D
  1101. }
  1102. for (uint16_t i = 0; i < world->bodyCount; ++i)
  1103. {
  1104. // connections:
  1105. for (uint16_t j = 0; j < world->bodies[i].connectionCount; ++j)
  1106. {
  1107. TPE_Vec3
  1108. p1 = world->bodies[i].joints[world->bodies[i].connections[j].joint1].position,
  1109. p2 = world->bodies[i].joints[world->bodies[i].connections[j].joint2].position;
  1110. p1 = _TPE_project3DPoint(p1,camPos,camRot,camView);
  1111. p2 = _TPE_project3DPoint(p2,camPos,camRot,camView);
  1112. if (p1.z <= 0 || p2.z <= 0)
  1113. continue;
  1114. TPE_Vec3 diff = TPE_vec3Minus(p2,p1);
  1115. #define SEGS 16
  1116. for (uint16_t k = 0; k < SEGS; ++k)
  1117. {
  1118. p2.x = p1.x + (diff.x * k) / SEGS;
  1119. p2.y = p1.y + (diff.y * k) / SEGS;
  1120. if (p2.z > 0)
  1121. _TPE_drawDebugPixel(p2.x,p2.y,camView.x,camView.y,0,drawFunc);
  1122. }
  1123. #undef SEGS
  1124. }
  1125. // joints:
  1126. for (uint16_t j = 0; j < world->bodies[i].jointCount; ++j)
  1127. {
  1128. TPE_Vec3 p = _TPE_project3DPoint(world->bodies[i].joints[j].position,
  1129. camPos,camRot,camView);
  1130. if (p.z > 0)
  1131. {
  1132. _TPE_drawDebugPixel(p.x,p.y,camView.x,camView.y,1,drawFunc);
  1133. TPE_Unit size = TPE_JOINT_SIZE(world->bodies[i].joints[j]) / 2;
  1134. size = (size * camView.x) / TPE_FRACTIONS_PER_UNIT;
  1135. size = (size * camView.z) / p.z;
  1136. #define SEGS 4
  1137. for (uint8_t k = 0; k < SEGS + 1; ++k)
  1138. {
  1139. TPE_Unit
  1140. dx = (TPE_sin(TPE_FRACTIONS_PER_UNIT * k / (8 * SEGS)) * size)
  1141. / TPE_FRACTIONS_PER_UNIT,
  1142. dy = (TPE_cos(TPE_FRACTIONS_PER_UNIT * k / (8 * SEGS)) * size)
  1143. / TPE_FRACTIONS_PER_UNIT;
  1144. #define dp(a,b,c,d) \
  1145. _TPE_drawDebugPixel(p.x a b,p.y c d,camView.x,camView.y,1,drawFunc);
  1146. dp(+,dx,+,dy) dp(+,dx,-,dy) dp(-,dx,+,dy) dp(-,dx,-,dy)
  1147. dp(+,dy,+,dx) dp(+,dy,-,dx) dp(-,dy,+,dx) dp(-,dy,-,dx)
  1148. #undef dp
  1149. #undef SEGS
  1150. }
  1151. }
  1152. }
  1153. }
  1154. }
  1155. TPE_Vec3 TPE_envAABoxInside(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 size)
  1156. {
  1157. size.x /= 2;
  1158. size.y /= 2;
  1159. size.z /= 2;
  1160. TPE_Vec3 shifted = TPE_vec3Minus(point,center);
  1161. TPE_Vec3 a = TPE_vec3Minus(size,shifted),
  1162. b = TPE_vec3Plus(shifted,size);
  1163. int8_t sx = 1, sy = 1, sz = 1;
  1164. if (b.x < a.x)
  1165. {
  1166. a.x = b.x;
  1167. sx = -1;
  1168. }
  1169. if (b.y < a.y)
  1170. {
  1171. a.y = b.y;
  1172. sy = -1;
  1173. }
  1174. if (b.z < a.z)
  1175. {
  1176. a.z = b.z;
  1177. sz = -1;
  1178. }
  1179. if (a.x < 0 || a.y < 0 || a.z < 0)
  1180. return point;
  1181. if (a.x < a.y)
  1182. {
  1183. if (a.x < a.z)
  1184. point.x = center.x + sx * size.x;
  1185. else
  1186. point.z = center.z + sz * size.z;
  1187. }
  1188. else
  1189. {
  1190. if (a.y < a.z)
  1191. point.y = center.y + sy * size.y;
  1192. else
  1193. point.z = center.z + sz * size.z;
  1194. }
  1195. return point;
  1196. }
  1197. TPE_Vec3 TPE_envSphere(TPE_Vec3 point, TPE_Vec3 center, TPE_Unit radius)
  1198. {
  1199. // TODO: optim?
  1200. TPE_Vec3 dir = TPE_vec3Minus(point,center);
  1201. TPE_Unit l = TPE_LENGTH(dir);
  1202. if (l <= radius)
  1203. return point;
  1204. dir.x = (dir.x * radius) / l;
  1205. dir.y = (dir.y * radius) / l;
  1206. dir.z = (dir.z * radius) / l;
  1207. return TPE_vec3Plus(center,dir);
  1208. }
  1209. TPE_Vec3 TPE_envHalfPlane(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 normal)
  1210. {
  1211. TPE_Vec3 point2 = TPE_vec3Minus(point,center);
  1212. TPE_Unit tmp = point2.x * normal.x + point2.y * normal.y + point2.z * normal.z;
  1213. if (tmp < 0)
  1214. return point;
  1215. TPE_Unit l = TPE_LENGTH(normal);
  1216. tmp /= l;
  1217. normal.x = (normal.x * TPE_FRACTIONS_PER_UNIT) / l;
  1218. normal.y = (normal.y * TPE_FRACTIONS_PER_UNIT) / l;
  1219. normal.z = (normal.z * TPE_FRACTIONS_PER_UNIT) / l;
  1220. return TPE_vec3Minus(point,
  1221. TPE_vec3Times(normal,tmp));
  1222. }
  1223. #endif // guard