tinyphysicsengine.h 41 KB

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