rb_bullet_api.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  1. /*
  2. * This program is free software; you can redistribute it and/or
  3. * modify it under the terms of the GNU General Public License
  4. * as published by the Free Software Foundation; either version 2
  5. * of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program; if not, write to the Free Software Foundation,
  14. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  15. *
  16. * The Original Code is Copyright (C) 2013 Blender Foundation
  17. * All rights reserved.
  18. */
  19. /** \file
  20. * \ingroup RigidBody
  21. * \brief Rigid Body API implementation for Bullet
  22. */
  23. /*
  24. * Bullet Continuous Collision Detection and Physics Library
  25. * Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
  26. *
  27. * This software is provided 'as-is', without any express or implied warranty. In no event will the
  28. * authors be held liable for any damages arising from the use of this software. Permission is
  29. * granted to anyone to use this software for any purpose, including commercial applications, and
  30. * to alter it and redistribute it freely, subject to the following restrictions:
  31. *
  32. * 1. The origin of this software must not be misrepresented; you must not claim that you wrote the
  33. * original software. If you use this software in a product, an acknowledgment in the product
  34. * documentation would be appreciated but is not required.
  35. * 2. Altered source versions must be plainly marked as such, and must not be misrepresented as
  36. * being the original software.
  37. * 3. This notice may not be removed or altered from any source distribution.
  38. */
  39. /* This file defines the "RigidBody interface" for the
  40. * Bullet Physics Engine. This API is designed to be used
  41. * from C-code in Blender as part of the Rigid Body simulation
  42. * system.
  43. *
  44. * It is based on the Bullet C-API, but is heavily modified to
  45. * give access to more data types and to offer a nicer interface.
  46. *
  47. * -- Joshua Leung, June 2010
  48. */
  49. #include <stdio.h>
  50. #include <errno.h>
  51. #include "RBI_api.h"
  52. #include "btBulletDynamicsCommon.h"
  53. #include "LinearMath/btVector3.h"
  54. #include "LinearMath/btScalar.h"
  55. #include "LinearMath/btMatrix3x3.h"
  56. #include "LinearMath/btTransform.h"
  57. #include "LinearMath/btConvexHullComputer.h"
  58. #include "BulletCollision/Gimpact/btGImpactShape.h"
  59. #include "BulletCollision/Gimpact/btGImpactCollisionAlgorithm.h"
  60. #include "BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h"
  61. struct rbDynamicsWorld {
  62. btDiscreteDynamicsWorld *dynamicsWorld;
  63. btDefaultCollisionConfiguration *collisionConfiguration;
  64. btDispatcher *dispatcher;
  65. btBroadphaseInterface *pairCache;
  66. btConstraintSolver *constraintSolver;
  67. btOverlapFilterCallback *filterCallback;
  68. };
  69. struct rbRigidBody {
  70. btRigidBody *body;
  71. int col_groups;
  72. };
  73. struct rbVert {
  74. float x, y, z;
  75. };
  76. struct rbTri {
  77. int v0, v1, v2;
  78. };
  79. struct rbMeshData {
  80. btTriangleIndexVertexArray *index_array;
  81. rbVert *vertices;
  82. rbTri *triangles;
  83. int num_vertices;
  84. int num_triangles;
  85. };
  86. struct rbCollisionShape {
  87. btCollisionShape *cshape;
  88. rbMeshData *mesh;
  89. };
  90. struct rbFilterCallback : public btOverlapFilterCallback {
  91. virtual bool needBroadphaseCollision(btBroadphaseProxy *proxy0, btBroadphaseProxy *proxy1) const
  92. {
  93. rbRigidBody *rb0 = (rbRigidBody *)((btRigidBody *)proxy0->m_clientObject)->getUserPointer();
  94. rbRigidBody *rb1 = (rbRigidBody *)((btRigidBody *)proxy1->m_clientObject)->getUserPointer();
  95. bool collides;
  96. collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
  97. collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
  98. collides = collides && (rb0->col_groups & rb1->col_groups);
  99. return collides;
  100. }
  101. };
  102. static inline void copy_v3_btvec3(float vec[3], const btVector3 &btvec)
  103. {
  104. vec[0] = (float)btvec[0];
  105. vec[1] = (float)btvec[1];
  106. vec[2] = (float)btvec[2];
  107. }
  108. static inline void copy_quat_btquat(float quat[4], const btQuaternion &btquat)
  109. {
  110. quat[0] = btquat.getW();
  111. quat[1] = btquat.getX();
  112. quat[2] = btquat.getY();
  113. quat[3] = btquat.getZ();
  114. }
  115. /* ********************************** */
  116. /* Dynamics World Methods */
  117. /* Setup ---------------------------- */
  118. rbDynamicsWorld *RB_dworld_new(const float gravity[3])
  119. {
  120. rbDynamicsWorld *world = new rbDynamicsWorld;
  121. /* collision detection/handling */
  122. world->collisionConfiguration = new btDefaultCollisionConfiguration();
  123. world->dispatcher = new btCollisionDispatcher(world->collisionConfiguration);
  124. btGImpactCollisionAlgorithm::registerAlgorithm((btCollisionDispatcher *)world->dispatcher);
  125. world->pairCache = new btDbvtBroadphase();
  126. world->filterCallback = new rbFilterCallback();
  127. world->pairCache->getOverlappingPairCache()->setOverlapFilterCallback(world->filterCallback);
  128. /* constraint solving */
  129. world->constraintSolver = new btSequentialImpulseConstraintSolver();
  130. /* world */
  131. world->dynamicsWorld = new btDiscreteDynamicsWorld(
  132. world->dispatcher, world->pairCache, world->constraintSolver, world->collisionConfiguration);
  133. RB_dworld_set_gravity(world, gravity);
  134. return world;
  135. }
  136. void RB_dworld_delete(rbDynamicsWorld *world)
  137. {
  138. /* bullet doesn't like if we free these in a different order */
  139. delete world->dynamicsWorld;
  140. delete world->constraintSolver;
  141. delete world->pairCache;
  142. delete world->dispatcher;
  143. delete world->collisionConfiguration;
  144. delete world->filterCallback;
  145. delete world;
  146. }
  147. /* Settings ------------------------- */
  148. /* Gravity */
  149. void RB_dworld_get_gravity(rbDynamicsWorld *world, float g_out[3])
  150. {
  151. copy_v3_btvec3(g_out, world->dynamicsWorld->getGravity());
  152. }
  153. void RB_dworld_set_gravity(rbDynamicsWorld *world, const float g_in[3])
  154. {
  155. world->dynamicsWorld->setGravity(btVector3(g_in[0], g_in[1], g_in[2]));
  156. }
  157. /* Constraint Solver */
  158. void RB_dworld_set_solver_iterations(rbDynamicsWorld *world, int num_solver_iterations)
  159. {
  160. btContactSolverInfo &info = world->dynamicsWorld->getSolverInfo();
  161. info.m_numIterations = num_solver_iterations;
  162. }
  163. /* Split Impulse */
  164. void RB_dworld_set_split_impulse(rbDynamicsWorld *world, int split_impulse)
  165. {
  166. btContactSolverInfo &info = world->dynamicsWorld->getSolverInfo();
  167. info.m_splitImpulse = split_impulse;
  168. }
  169. /* Simulation ----------------------- */
  170. void RB_dworld_step_simulation(rbDynamicsWorld *world,
  171. float timeStep,
  172. int maxSubSteps,
  173. float timeSubStep)
  174. {
  175. world->dynamicsWorld->stepSimulation(timeStep, maxSubSteps, timeSubStep);
  176. }
  177. /* Export -------------------------- */
  178. /**
  179. * Exports entire dynamics world to Bullet's "*.bullet" binary format
  180. * which is similar to Blender's SDNA system.
  181. *
  182. * \param world Dynamics world to write to file
  183. * \param filename Assumed to be a valid filename, with .bullet extension
  184. */
  185. void RB_dworld_export(rbDynamicsWorld *world, const char *filename)
  186. {
  187. // create a large enough buffer. There is no method to pre-calculate the buffer size yet.
  188. int maxSerializeBufferSize = 1024 * 1024 * 5;
  189. btDefaultSerializer *serializer = new btDefaultSerializer(maxSerializeBufferSize);
  190. world->dynamicsWorld->serialize(serializer);
  191. FILE *file = fopen(filename, "wb");
  192. if (file) {
  193. fwrite(serializer->getBufferPointer(), serializer->getCurrentBufferSize(), 1, file);
  194. fclose(file);
  195. }
  196. else {
  197. fprintf(stderr, "RB_dworld_export: %s\n", strerror(errno));
  198. }
  199. }
  200. /* ********************************** */
  201. /* Rigid Body Methods */
  202. /* Setup ---------------------------- */
  203. void RB_dworld_add_body(rbDynamicsWorld *world, rbRigidBody *object, int col_groups)
  204. {
  205. btRigidBody *body = object->body;
  206. object->col_groups = col_groups;
  207. world->dynamicsWorld->addRigidBody(body);
  208. }
  209. void RB_dworld_remove_body(rbDynamicsWorld *world, rbRigidBody *object)
  210. {
  211. btRigidBody *body = object->body;
  212. world->dynamicsWorld->removeRigidBody(body);
  213. }
  214. /* Collision detection */
  215. void RB_world_convex_sweep_test(rbDynamicsWorld *world,
  216. rbRigidBody *object,
  217. const float loc_start[3],
  218. const float loc_end[3],
  219. float v_location[3],
  220. float v_hitpoint[3],
  221. float v_normal[3],
  222. int *r_hit)
  223. {
  224. btRigidBody *body = object->body;
  225. btCollisionShape *collisionShape = body->getCollisionShape();
  226. /* only convex shapes are supported, but user can specify a non convex shape */
  227. if (collisionShape->isConvex()) {
  228. btCollisionWorld::ClosestConvexResultCallback result(
  229. btVector3(loc_start[0], loc_start[1], loc_start[2]),
  230. btVector3(loc_end[0], loc_end[1], loc_end[2]));
  231. btQuaternion obRot = body->getWorldTransform().getRotation();
  232. btTransform rayFromTrans;
  233. rayFromTrans.setIdentity();
  234. rayFromTrans.setRotation(obRot);
  235. rayFromTrans.setOrigin(btVector3(loc_start[0], loc_start[1], loc_start[2]));
  236. btTransform rayToTrans;
  237. rayToTrans.setIdentity();
  238. rayToTrans.setRotation(obRot);
  239. rayToTrans.setOrigin(btVector3(loc_end[0], loc_end[1], loc_end[2]));
  240. world->dynamicsWorld->convexSweepTest(
  241. (btConvexShape *)collisionShape, rayFromTrans, rayToTrans, result, 0);
  242. if (result.hasHit()) {
  243. *r_hit = 1;
  244. v_location[0] = result.m_convexFromWorld[0] +
  245. (result.m_convexToWorld[0] - result.m_convexFromWorld[0]) *
  246. result.m_closestHitFraction;
  247. v_location[1] = result.m_convexFromWorld[1] +
  248. (result.m_convexToWorld[1] - result.m_convexFromWorld[1]) *
  249. result.m_closestHitFraction;
  250. v_location[2] = result.m_convexFromWorld[2] +
  251. (result.m_convexToWorld[2] - result.m_convexFromWorld[2]) *
  252. result.m_closestHitFraction;
  253. v_hitpoint[0] = result.m_hitPointWorld[0];
  254. v_hitpoint[1] = result.m_hitPointWorld[1];
  255. v_hitpoint[2] = result.m_hitPointWorld[2];
  256. v_normal[0] = result.m_hitNormalWorld[0];
  257. v_normal[1] = result.m_hitNormalWorld[1];
  258. v_normal[2] = result.m_hitNormalWorld[2];
  259. }
  260. else {
  261. *r_hit = 0;
  262. }
  263. }
  264. else {
  265. /* we need to return a value if user passes non convex body, to report */
  266. *r_hit = -2;
  267. }
  268. }
  269. /* ............ */
  270. rbRigidBody *RB_body_new(rbCollisionShape *shape, const float loc[3], const float rot[4])
  271. {
  272. rbRigidBody *object = new rbRigidBody;
  273. /* current transform */
  274. btTransform trans;
  275. trans.setOrigin(btVector3(loc[0], loc[1], loc[2]));
  276. trans.setRotation(btQuaternion(rot[1], rot[2], rot[3], rot[0]));
  277. /* create motionstate, which is necessary for interpolation (includes reverse playback) */
  278. btDefaultMotionState *motionState = new btDefaultMotionState(trans);
  279. /* make rigidbody */
  280. btRigidBody::btRigidBodyConstructionInfo rbInfo(1.0f, motionState, shape->cshape);
  281. object->body = new btRigidBody(rbInfo);
  282. object->body->setUserPointer(object);
  283. return object;
  284. }
  285. void RB_body_delete(rbRigidBody *object)
  286. {
  287. btRigidBody *body = object->body;
  288. /* motion state */
  289. btMotionState *ms = body->getMotionState();
  290. if (ms)
  291. delete ms;
  292. /* collision shape is done elsewhere... */
  293. /* body itself */
  294. /* manually remove constraint refs of the rigid body, normally this happens when removing
  295. * constraints from the world
  296. * but since we delete everything when the world is rebult, we need to do it manually here */
  297. for (int i = body->getNumConstraintRefs() - 1; i >= 0; i--) {
  298. btTypedConstraint *con = body->getConstraintRef(i);
  299. body->removeConstraintRef(con);
  300. }
  301. delete body;
  302. delete object;
  303. }
  304. /* Settings ------------------------- */
  305. void RB_body_set_collision_shape(rbRigidBody *object, rbCollisionShape *shape)
  306. {
  307. btRigidBody *body = object->body;
  308. /* set new collision shape */
  309. body->setCollisionShape(shape->cshape);
  310. /* recalculate inertia, since that depends on the collision shape... */
  311. RB_body_set_mass(object, RB_body_get_mass(object));
  312. }
  313. /* ............ */
  314. float RB_body_get_mass(rbRigidBody *object)
  315. {
  316. btRigidBody *body = object->body;
  317. /* there isn't really a mass setting, but rather 'inverse mass'
  318. * which we convert back to mass by taking the reciprocal again
  319. */
  320. float value = (float)body->getInvMass();
  321. if (value)
  322. value = 1.0f / value;
  323. return value;
  324. }
  325. void RB_body_set_mass(rbRigidBody *object, float value)
  326. {
  327. btRigidBody *body = object->body;
  328. btVector3 localInertia(0, 0, 0);
  329. /* calculate new inertia if non-zero mass */
  330. if (value) {
  331. btCollisionShape *shape = body->getCollisionShape();
  332. shape->calculateLocalInertia(value, localInertia);
  333. }
  334. body->setMassProps(value, localInertia);
  335. body->updateInertiaTensor();
  336. }
  337. float RB_body_get_friction(rbRigidBody *object)
  338. {
  339. btRigidBody *body = object->body;
  340. return body->getFriction();
  341. }
  342. void RB_body_set_friction(rbRigidBody *object, float value)
  343. {
  344. btRigidBody *body = object->body;
  345. body->setFriction(value);
  346. }
  347. float RB_body_get_restitution(rbRigidBody *object)
  348. {
  349. btRigidBody *body = object->body;
  350. return body->getRestitution();
  351. }
  352. void RB_body_set_restitution(rbRigidBody *object, float value)
  353. {
  354. btRigidBody *body = object->body;
  355. body->setRestitution(value);
  356. }
  357. float RB_body_get_linear_damping(rbRigidBody *object)
  358. {
  359. btRigidBody *body = object->body;
  360. return body->getLinearDamping();
  361. }
  362. void RB_body_set_linear_damping(rbRigidBody *object, float value)
  363. {
  364. RB_body_set_damping(object, value, RB_body_get_linear_damping(object));
  365. }
  366. float RB_body_get_angular_damping(rbRigidBody *object)
  367. {
  368. btRigidBody *body = object->body;
  369. return body->getAngularDamping();
  370. }
  371. void RB_body_set_angular_damping(rbRigidBody *object, float value)
  372. {
  373. RB_body_set_damping(object, RB_body_get_linear_damping(object), value);
  374. }
  375. void RB_body_set_damping(rbRigidBody *object, float linear, float angular)
  376. {
  377. btRigidBody *body = object->body;
  378. body->setDamping(linear, angular);
  379. }
  380. float RB_body_get_linear_sleep_thresh(rbRigidBody *object)
  381. {
  382. btRigidBody *body = object->body;
  383. return body->getLinearSleepingThreshold();
  384. }
  385. void RB_body_set_linear_sleep_thresh(rbRigidBody *object, float value)
  386. {
  387. RB_body_set_sleep_thresh(object, value, RB_body_get_angular_sleep_thresh(object));
  388. }
  389. float RB_body_get_angular_sleep_thresh(rbRigidBody *object)
  390. {
  391. btRigidBody *body = object->body;
  392. return body->getAngularSleepingThreshold();
  393. }
  394. void RB_body_set_angular_sleep_thresh(rbRigidBody *object, float value)
  395. {
  396. RB_body_set_sleep_thresh(object, RB_body_get_linear_sleep_thresh(object), value);
  397. }
  398. void RB_body_set_sleep_thresh(rbRigidBody *object, float linear, float angular)
  399. {
  400. btRigidBody *body = object->body;
  401. body->setSleepingThresholds(linear, angular);
  402. }
  403. /* ............ */
  404. void RB_body_get_linear_velocity(rbRigidBody *object, float v_out[3])
  405. {
  406. btRigidBody *body = object->body;
  407. copy_v3_btvec3(v_out, body->getLinearVelocity());
  408. }
  409. void RB_body_set_linear_velocity(rbRigidBody *object, const float v_in[3])
  410. {
  411. btRigidBody *body = object->body;
  412. body->setLinearVelocity(btVector3(v_in[0], v_in[1], v_in[2]));
  413. }
  414. void RB_body_get_angular_velocity(rbRigidBody *object, float v_out[3])
  415. {
  416. btRigidBody *body = object->body;
  417. copy_v3_btvec3(v_out, body->getAngularVelocity());
  418. }
  419. void RB_body_set_angular_velocity(rbRigidBody *object, const float v_in[3])
  420. {
  421. btRigidBody *body = object->body;
  422. body->setAngularVelocity(btVector3(v_in[0], v_in[1], v_in[2]));
  423. }
  424. void RB_body_set_linear_factor(rbRigidBody *object, float x, float y, float z)
  425. {
  426. btRigidBody *body = object->body;
  427. body->setLinearFactor(btVector3(x, y, z));
  428. }
  429. void RB_body_set_angular_factor(rbRigidBody *object, float x, float y, float z)
  430. {
  431. btRigidBody *body = object->body;
  432. body->setAngularFactor(btVector3(x, y, z));
  433. }
  434. /* ............ */
  435. void RB_body_set_kinematic_state(rbRigidBody *object, int kinematic)
  436. {
  437. btRigidBody *body = object->body;
  438. if (kinematic)
  439. body->setCollisionFlags(body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
  440. else
  441. body->setCollisionFlags(body->getCollisionFlags() & ~btCollisionObject::CF_KINEMATIC_OBJECT);
  442. }
  443. /* ............ */
  444. void RB_body_set_activation_state(rbRigidBody *object, int use_deactivation)
  445. {
  446. btRigidBody *body = object->body;
  447. if (use_deactivation)
  448. body->forceActivationState(ACTIVE_TAG);
  449. else
  450. body->setActivationState(DISABLE_DEACTIVATION);
  451. }
  452. void RB_body_activate(rbRigidBody *object)
  453. {
  454. btRigidBody *body = object->body;
  455. body->setActivationState(ACTIVE_TAG);
  456. }
  457. void RB_body_deactivate(rbRigidBody *object)
  458. {
  459. btRigidBody *body = object->body;
  460. body->setActivationState(ISLAND_SLEEPING);
  461. }
  462. /* ............ */
  463. /* Simulation ----------------------- */
  464. /* The transform matrices Blender uses are OpenGL-style matrices,
  465. * while Bullet uses the Right-Handed coordinate system style instead.
  466. */
  467. void RB_body_get_transform_matrix(rbRigidBody *object, float m_out[4][4])
  468. {
  469. btRigidBody *body = object->body;
  470. btMotionState *ms = body->getMotionState();
  471. btTransform trans;
  472. ms->getWorldTransform(trans);
  473. trans.getOpenGLMatrix((btScalar *)m_out);
  474. }
  475. void RB_body_set_loc_rot(rbRigidBody *object, const float loc[3], const float rot[4])
  476. {
  477. btRigidBody *body = object->body;
  478. btMotionState *ms = body->getMotionState();
  479. /* set transform matrix */
  480. btTransform trans;
  481. trans.setOrigin(btVector3(loc[0], loc[1], loc[2]));
  482. trans.setRotation(btQuaternion(rot[1], rot[2], rot[3], rot[0]));
  483. ms->setWorldTransform(trans);
  484. }
  485. void RB_body_set_scale(rbRigidBody *object, const float scale[3])
  486. {
  487. btRigidBody *body = object->body;
  488. /* apply scaling factor from matrix above to the collision shape */
  489. btCollisionShape *cshape = body->getCollisionShape();
  490. if (cshape) {
  491. cshape->setLocalScaling(btVector3(scale[0], scale[1], scale[2]));
  492. /* GIimpact shapes have to be updated to take scaling into account */
  493. if (cshape->getShapeType() == GIMPACT_SHAPE_PROXYTYPE)
  494. ((btGImpactMeshShape *)cshape)->updateBound();
  495. }
  496. }
  497. /* ............ */
  498. /* Read-only state info about status of simulation */
  499. void RB_body_get_position(rbRigidBody *object, float v_out[3])
  500. {
  501. btRigidBody *body = object->body;
  502. copy_v3_btvec3(v_out, body->getWorldTransform().getOrigin());
  503. }
  504. void RB_body_get_orientation(rbRigidBody *object, float v_out[4])
  505. {
  506. btRigidBody *body = object->body;
  507. copy_quat_btquat(v_out, body->getWorldTransform().getRotation());
  508. }
  509. /* ............ */
  510. /* Overrides for simulation */
  511. void RB_body_apply_central_force(rbRigidBody *object, const float v_in[3])
  512. {
  513. btRigidBody *body = object->body;
  514. body->applyCentralForce(btVector3(v_in[0], v_in[1], v_in[2]));
  515. }
  516. /* ********************************** */
  517. /* Collision Shape Methods */
  518. /* Setup (Standard Shapes) ----------- */
  519. rbCollisionShape *RB_shape_new_box(float x, float y, float z)
  520. {
  521. rbCollisionShape *shape = new rbCollisionShape;
  522. shape->cshape = new btBoxShape(btVector3(x, y, z));
  523. shape->mesh = NULL;
  524. return shape;
  525. }
  526. rbCollisionShape *RB_shape_new_sphere(float radius)
  527. {
  528. rbCollisionShape *shape = new rbCollisionShape;
  529. shape->cshape = new btSphereShape(radius);
  530. shape->mesh = NULL;
  531. return shape;
  532. }
  533. rbCollisionShape *RB_shape_new_capsule(float radius, float height)
  534. {
  535. rbCollisionShape *shape = new rbCollisionShape;
  536. shape->cshape = new btCapsuleShapeZ(radius, height);
  537. shape->mesh = NULL;
  538. return shape;
  539. }
  540. rbCollisionShape *RB_shape_new_cone(float radius, float height)
  541. {
  542. rbCollisionShape *shape = new rbCollisionShape;
  543. shape->cshape = new btConeShapeZ(radius, height);
  544. shape->mesh = NULL;
  545. return shape;
  546. }
  547. rbCollisionShape *RB_shape_new_cylinder(float radius, float height)
  548. {
  549. rbCollisionShape *shape = new rbCollisionShape;
  550. shape->cshape = new btCylinderShapeZ(btVector3(radius, radius, height));
  551. shape->mesh = NULL;
  552. return shape;
  553. }
  554. /* Setup (Convex Hull) ------------ */
  555. rbCollisionShape *RB_shape_new_convex_hull(
  556. float *verts, int stride, int count, float margin, bool *can_embed)
  557. {
  558. btConvexHullComputer hull_computer = btConvexHullComputer();
  559. // try to embed the margin, if that fails don't shrink the hull
  560. if (hull_computer.compute(verts, stride, count, margin, 0.0f) < 0.0f) {
  561. hull_computer.compute(verts, stride, count, 0.0f, 0.0f);
  562. *can_embed = false;
  563. }
  564. rbCollisionShape *shape = new rbCollisionShape;
  565. btConvexHullShape *hull_shape = new btConvexHullShape(&(hull_computer.vertices[0].getX()),
  566. hull_computer.vertices.size());
  567. shape->cshape = hull_shape;
  568. shape->mesh = NULL;
  569. return shape;
  570. }
  571. /* Setup (Triangle Mesh) ---------- */
  572. /* Need to call RB_trimesh_finish() after creating triangle mesh and adding vertices and triangles
  573. */
  574. rbMeshData *RB_trimesh_data_new(int num_tris, int num_verts)
  575. {
  576. rbMeshData *mesh = new rbMeshData;
  577. mesh->vertices = new rbVert[num_verts];
  578. mesh->triangles = new rbTri[num_tris];
  579. mesh->num_vertices = num_verts;
  580. mesh->num_triangles = num_tris;
  581. return mesh;
  582. }
  583. static void RB_trimesh_data_delete(rbMeshData *mesh)
  584. {
  585. delete mesh->index_array;
  586. delete[] mesh->vertices;
  587. delete[] mesh->triangles;
  588. delete mesh;
  589. }
  590. void RB_trimesh_add_vertices(rbMeshData *mesh, float *vertices, int num_verts, int vert_stride)
  591. {
  592. for (int i = 0; i < num_verts; i++) {
  593. float *vert = (float *)(((char *)vertices + i * vert_stride));
  594. mesh->vertices[i].x = vert[0];
  595. mesh->vertices[i].y = vert[1];
  596. mesh->vertices[i].z = vert[2];
  597. }
  598. }
  599. void RB_trimesh_add_triangle_indices(rbMeshData *mesh, int num, int index0, int index1, int index2)
  600. {
  601. mesh->triangles[num].v0 = index0;
  602. mesh->triangles[num].v1 = index1;
  603. mesh->triangles[num].v2 = index2;
  604. }
  605. void RB_trimesh_finish(rbMeshData *mesh)
  606. {
  607. mesh->index_array = new btTriangleIndexVertexArray(mesh->num_triangles,
  608. (int *)mesh->triangles,
  609. sizeof(rbTri),
  610. mesh->num_vertices,
  611. (float *)mesh->vertices,
  612. sizeof(rbVert));
  613. }
  614. rbCollisionShape *RB_shape_new_trimesh(rbMeshData *mesh)
  615. {
  616. rbCollisionShape *shape = new rbCollisionShape;
  617. /* triangle-mesh we create is a BVH wrapper for triangle mesh data (for faster lookups) */
  618. // RB_TODO perhaps we need to allow saving out this for performance when rebuilding?
  619. btBvhTriangleMeshShape *unscaledShape = new btBvhTriangleMeshShape(
  620. mesh->index_array, true, true);
  621. shape->cshape = new btScaledBvhTriangleMeshShape(unscaledShape, btVector3(1.0f, 1.0f, 1.0f));
  622. shape->mesh = mesh;
  623. return shape;
  624. }
  625. void RB_shape_trimesh_update(rbCollisionShape *shape,
  626. float *vertices,
  627. int num_verts,
  628. int vert_stride,
  629. float min[3],
  630. float max[3])
  631. {
  632. if (shape->mesh == NULL || num_verts != shape->mesh->num_vertices)
  633. return;
  634. for (int i = 0; i < num_verts; i++) {
  635. float *vert = (float *)(((char *)vertices + i * vert_stride));
  636. shape->mesh->vertices[i].x = vert[0];
  637. shape->mesh->vertices[i].y = vert[1];
  638. shape->mesh->vertices[i].z = vert[2];
  639. }
  640. if (shape->cshape->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE) {
  641. btScaledBvhTriangleMeshShape *scaled_shape = (btScaledBvhTriangleMeshShape *)shape->cshape;
  642. btBvhTriangleMeshShape *mesh_shape = scaled_shape->getChildShape();
  643. mesh_shape->refitTree(btVector3(min[0], min[1], min[2]), btVector3(max[0], max[1], max[2]));
  644. }
  645. else if (shape->cshape->getShapeType() == GIMPACT_SHAPE_PROXYTYPE) {
  646. btGImpactMeshShape *mesh_shape = (btGImpactMeshShape *)shape->cshape;
  647. mesh_shape->updateBound();
  648. }
  649. }
  650. rbCollisionShape *RB_shape_new_gimpact_mesh(rbMeshData *mesh)
  651. {
  652. rbCollisionShape *shape = new rbCollisionShape;
  653. btGImpactMeshShape *gimpactShape = new btGImpactMeshShape(mesh->index_array);
  654. gimpactShape->updateBound(); // TODO: add this to the update collision margin call?
  655. shape->cshape = gimpactShape;
  656. shape->mesh = mesh;
  657. return shape;
  658. }
  659. /* Cleanup --------------------------- */
  660. void RB_shape_delete(rbCollisionShape *shape)
  661. {
  662. if (shape->cshape->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE) {
  663. btBvhTriangleMeshShape *child_shape =
  664. ((btScaledBvhTriangleMeshShape *)shape->cshape)->getChildShape();
  665. if (child_shape)
  666. delete child_shape;
  667. }
  668. if (shape->mesh)
  669. RB_trimesh_data_delete(shape->mesh);
  670. delete shape->cshape;
  671. delete shape;
  672. }
  673. /* Settings --------------------------- */
  674. float RB_shape_get_margin(rbCollisionShape *shape)
  675. {
  676. return shape->cshape->getMargin();
  677. }
  678. void RB_shape_set_margin(rbCollisionShape *shape, float value)
  679. {
  680. shape->cshape->setMargin(value);
  681. }
  682. /* ********************************** */
  683. /* Constraints */
  684. /* Setup ----------------------------- */
  685. void RB_dworld_add_constraint(rbDynamicsWorld *world, rbConstraint *con, int disable_collisions)
  686. {
  687. btTypedConstraint *constraint = reinterpret_cast<btTypedConstraint *>(con);
  688. world->dynamicsWorld->addConstraint(constraint, disable_collisions);
  689. }
  690. void RB_dworld_remove_constraint(rbDynamicsWorld *world, rbConstraint *con)
  691. {
  692. btTypedConstraint *constraint = reinterpret_cast<btTypedConstraint *>(con);
  693. world->dynamicsWorld->removeConstraint(constraint);
  694. }
  695. /* ............ */
  696. static void make_constraint_transforms(btTransform &transform1,
  697. btTransform &transform2,
  698. btRigidBody *body1,
  699. btRigidBody *body2,
  700. float pivot[3],
  701. float orn[4])
  702. {
  703. btTransform pivot_transform = btTransform();
  704. pivot_transform.setOrigin(btVector3(pivot[0], pivot[1], pivot[2]));
  705. pivot_transform.setRotation(btQuaternion(orn[1], orn[2], orn[3], orn[0]));
  706. transform1 = body1->getWorldTransform().inverse() * pivot_transform;
  707. transform2 = body2->getWorldTransform().inverse() * pivot_transform;
  708. }
  709. rbConstraint *RB_constraint_new_point(float pivot[3], rbRigidBody *rb1, rbRigidBody *rb2)
  710. {
  711. btRigidBody *body1 = rb1->body;
  712. btRigidBody *body2 = rb2->body;
  713. btVector3 pivot1 = body1->getWorldTransform().inverse() *
  714. btVector3(pivot[0], pivot[1], pivot[2]);
  715. btVector3 pivot2 = body2->getWorldTransform().inverse() *
  716. btVector3(pivot[0], pivot[1], pivot[2]);
  717. btTypedConstraint *con = new btPoint2PointConstraint(*body1, *body2, pivot1, pivot2);
  718. return (rbConstraint *)con;
  719. }
  720. rbConstraint *RB_constraint_new_fixed(float pivot[3],
  721. float orn[4],
  722. rbRigidBody *rb1,
  723. rbRigidBody *rb2)
  724. {
  725. btRigidBody *body1 = rb1->body;
  726. btRigidBody *body2 = rb2->body;
  727. btTransform transform1;
  728. btTransform transform2;
  729. make_constraint_transforms(transform1, transform2, body1, body2, pivot, orn);
  730. btFixedConstraint *con = new btFixedConstraint(*body1, *body2, transform1, transform2);
  731. return (rbConstraint *)con;
  732. }
  733. rbConstraint *RB_constraint_new_hinge(float pivot[3],
  734. float orn[4],
  735. rbRigidBody *rb1,
  736. rbRigidBody *rb2)
  737. {
  738. btRigidBody *body1 = rb1->body;
  739. btRigidBody *body2 = rb2->body;
  740. btTransform transform1;
  741. btTransform transform2;
  742. make_constraint_transforms(transform1, transform2, body1, body2, pivot, orn);
  743. btHingeConstraint *con = new btHingeConstraint(*body1, *body2, transform1, transform2);
  744. return (rbConstraint *)con;
  745. }
  746. rbConstraint *RB_constraint_new_slider(float pivot[3],
  747. float orn[4],
  748. rbRigidBody *rb1,
  749. rbRigidBody *rb2)
  750. {
  751. btRigidBody *body1 = rb1->body;
  752. btRigidBody *body2 = rb2->body;
  753. btTransform transform1;
  754. btTransform transform2;
  755. make_constraint_transforms(transform1, transform2, body1, body2, pivot, orn);
  756. btSliderConstraint *con = new btSliderConstraint(*body1, *body2, transform1, transform2, true);
  757. return (rbConstraint *)con;
  758. }
  759. rbConstraint *RB_constraint_new_piston(float pivot[3],
  760. float orn[4],
  761. rbRigidBody *rb1,
  762. rbRigidBody *rb2)
  763. {
  764. btRigidBody *body1 = rb1->body;
  765. btRigidBody *body2 = rb2->body;
  766. btTransform transform1;
  767. btTransform transform2;
  768. make_constraint_transforms(transform1, transform2, body1, body2, pivot, orn);
  769. btSliderConstraint *con = new btSliderConstraint(*body1, *body2, transform1, transform2, true);
  770. con->setUpperAngLimit(-1.0f); // unlock rotation axis
  771. return (rbConstraint *)con;
  772. }
  773. rbConstraint *RB_constraint_new_6dof(float pivot[3],
  774. float orn[4],
  775. rbRigidBody *rb1,
  776. rbRigidBody *rb2)
  777. {
  778. btRigidBody *body1 = rb1->body;
  779. btRigidBody *body2 = rb2->body;
  780. btTransform transform1;
  781. btTransform transform2;
  782. make_constraint_transforms(transform1, transform2, body1, body2, pivot, orn);
  783. btTypedConstraint *con = new btGeneric6DofConstraint(
  784. *body1, *body2, transform1, transform2, true);
  785. return (rbConstraint *)con;
  786. }
  787. rbConstraint *RB_constraint_new_6dof_spring(float pivot[3],
  788. float orn[4],
  789. rbRigidBody *rb1,
  790. rbRigidBody *rb2)
  791. {
  792. btRigidBody *body1 = rb1->body;
  793. btRigidBody *body2 = rb2->body;
  794. btTransform transform1;
  795. btTransform transform2;
  796. make_constraint_transforms(transform1, transform2, body1, body2, pivot, orn);
  797. btTypedConstraint *con = new btGeneric6DofSpringConstraint(
  798. *body1, *body2, transform1, transform2, true);
  799. return (rbConstraint *)con;
  800. }
  801. rbConstraint *RB_constraint_new_6dof_spring2(float pivot[3],
  802. float orn[4],
  803. rbRigidBody *rb1,
  804. rbRigidBody *rb2)
  805. {
  806. btRigidBody *body1 = rb1->body;
  807. btRigidBody *body2 = rb2->body;
  808. btTransform transform1;
  809. btTransform transform2;
  810. make_constraint_transforms(transform1, transform2, body1, body2, pivot, orn);
  811. btTypedConstraint *con = new btGeneric6DofSpring2Constraint(
  812. *body1, *body2, transform1, transform2);
  813. return (rbConstraint *)con;
  814. }
  815. rbConstraint *RB_constraint_new_motor(float pivot[3],
  816. float orn[4],
  817. rbRigidBody *rb1,
  818. rbRigidBody *rb2)
  819. {
  820. btRigidBody *body1 = rb1->body;
  821. btRigidBody *body2 = rb2->body;
  822. btTransform transform1;
  823. btTransform transform2;
  824. make_constraint_transforms(transform1, transform2, body1, body2, pivot, orn);
  825. btGeneric6DofConstraint *con = new btGeneric6DofConstraint(
  826. *body1, *body2, transform1, transform2, true);
  827. /* unlock constraint axes */
  828. for (int i = 0; i < 6; i++) {
  829. con->setLimit(i, 0.0f, -1.0f);
  830. }
  831. /* unlock motor axes */
  832. con->getTranslationalLimitMotor()->m_upperLimit.setValue(-1.0f, -1.0f, -1.0f);
  833. return (rbConstraint *)con;
  834. }
  835. /* Cleanup ----------------------------- */
  836. void RB_constraint_delete(rbConstraint *con)
  837. {
  838. btTypedConstraint *constraint = reinterpret_cast<btTypedConstraint *>(con);
  839. delete constraint;
  840. }
  841. /* Settings ------------------------- */
  842. void RB_constraint_set_enabled(rbConstraint *con, int enabled)
  843. {
  844. btTypedConstraint *constraint = reinterpret_cast<btTypedConstraint *>(con);
  845. constraint->setEnabled(enabled);
  846. }
  847. void RB_constraint_set_limits_hinge(rbConstraint *con, float lower, float upper)
  848. {
  849. btHingeConstraint *constraint = reinterpret_cast<btHingeConstraint *>(con);
  850. // RB_TODO expose these
  851. float softness = 0.9f;
  852. float bias_factor = 0.3f;
  853. float relaxation_factor = 1.0f;
  854. constraint->setLimit(lower, upper, softness, bias_factor, relaxation_factor);
  855. }
  856. void RB_constraint_set_limits_slider(rbConstraint *con, float lower, float upper)
  857. {
  858. btSliderConstraint *constraint = reinterpret_cast<btSliderConstraint *>(con);
  859. constraint->setLowerLinLimit(lower);
  860. constraint->setUpperLinLimit(upper);
  861. }
  862. void RB_constraint_set_limits_piston(
  863. rbConstraint *con, float lin_lower, float lin_upper, float ang_lower, float ang_upper)
  864. {
  865. btSliderConstraint *constraint = reinterpret_cast<btSliderConstraint *>(con);
  866. constraint->setLowerLinLimit(lin_lower);
  867. constraint->setUpperLinLimit(lin_upper);
  868. constraint->setLowerAngLimit(ang_lower);
  869. constraint->setUpperAngLimit(ang_upper);
  870. }
  871. void RB_constraint_set_limits_6dof(rbConstraint *con, int axis, float lower, float upper)
  872. {
  873. btGeneric6DofConstraint *constraint = reinterpret_cast<btGeneric6DofConstraint *>(con);
  874. constraint->setLimit(axis, lower, upper);
  875. }
  876. void RB_constraint_set_limits_6dof_spring2(rbConstraint *con, int axis, float lower, float upper)
  877. {
  878. btGeneric6DofSpring2Constraint *constraint = reinterpret_cast<btGeneric6DofSpring2Constraint *>(
  879. con);
  880. constraint->setLimit(axis, lower, upper);
  881. }
  882. void RB_constraint_set_stiffness_6dof_spring(rbConstraint *con, int axis, float stiffness)
  883. {
  884. btGeneric6DofSpringConstraint *constraint = reinterpret_cast<btGeneric6DofSpringConstraint *>(
  885. con);
  886. constraint->setStiffness(axis, stiffness);
  887. }
  888. void RB_constraint_set_damping_6dof_spring(rbConstraint *con, int axis, float damping)
  889. {
  890. btGeneric6DofSpringConstraint *constraint = reinterpret_cast<btGeneric6DofSpringConstraint *>(
  891. con);
  892. // invert damping range so that 0 = no damping
  893. damping = (damping > 1.0f) ? 0.0f : 1.0f - damping;
  894. constraint->setDamping(axis, damping);
  895. }
  896. void RB_constraint_set_spring_6dof_spring(rbConstraint *con, int axis, int enable)
  897. {
  898. btGeneric6DofSpringConstraint *constraint = reinterpret_cast<btGeneric6DofSpringConstraint *>(
  899. con);
  900. constraint->enableSpring(axis, enable);
  901. }
  902. void RB_constraint_set_equilibrium_6dof_spring(rbConstraint *con)
  903. {
  904. btGeneric6DofSpringConstraint *constraint = reinterpret_cast<btGeneric6DofSpringConstraint *>(
  905. con);
  906. constraint->setEquilibriumPoint();
  907. }
  908. void RB_constraint_set_stiffness_6dof_spring2(rbConstraint *con, int axis, float stiffness)
  909. {
  910. btGeneric6DofSpring2Constraint *constraint = reinterpret_cast<btGeneric6DofSpring2Constraint *>(
  911. con);
  912. constraint->setStiffness(axis, stiffness);
  913. }
  914. void RB_constraint_set_damping_6dof_spring2(rbConstraint *con, int axis, float damping)
  915. {
  916. btGeneric6DofSpring2Constraint *constraint = reinterpret_cast<btGeneric6DofSpring2Constraint *>(
  917. con);
  918. constraint->setDamping(axis, damping);
  919. }
  920. void RB_constraint_set_spring_6dof_spring2(rbConstraint *con, int axis, int enable)
  921. {
  922. btGeneric6DofSpring2Constraint *constraint = reinterpret_cast<btGeneric6DofSpring2Constraint *>(
  923. con);
  924. constraint->enableSpring(axis, enable);
  925. }
  926. void RB_constraint_set_equilibrium_6dof_spring2(rbConstraint *con)
  927. {
  928. btGeneric6DofSpring2Constraint *constraint = reinterpret_cast<btGeneric6DofSpring2Constraint *>(
  929. con);
  930. constraint->setEquilibriumPoint();
  931. }
  932. void RB_constraint_set_solver_iterations(rbConstraint *con, int num_solver_iterations)
  933. {
  934. btTypedConstraint *constraint = reinterpret_cast<btTypedConstraint *>(con);
  935. constraint->setOverrideNumSolverIterations(num_solver_iterations);
  936. }
  937. void RB_constraint_set_breaking_threshold(rbConstraint *con, float threshold)
  938. {
  939. btTypedConstraint *constraint = reinterpret_cast<btTypedConstraint *>(con);
  940. constraint->setBreakingImpulseThreshold(threshold);
  941. }
  942. void RB_constraint_set_enable_motor(rbConstraint *con, int enable_lin, int enable_ang)
  943. {
  944. btGeneric6DofConstraint *constraint = reinterpret_cast<btGeneric6DofConstraint *>(con);
  945. constraint->getTranslationalLimitMotor()->m_enableMotor[0] = enable_lin;
  946. constraint->getRotationalLimitMotor(0)->m_enableMotor = enable_ang;
  947. }
  948. void RB_constraint_set_max_impulse_motor(rbConstraint *con,
  949. float max_impulse_lin,
  950. float max_impulse_ang)
  951. {
  952. btGeneric6DofConstraint *constraint = reinterpret_cast<btGeneric6DofConstraint *>(con);
  953. constraint->getTranslationalLimitMotor()->m_maxMotorForce.setX(max_impulse_lin);
  954. constraint->getRotationalLimitMotor(0)->m_maxMotorForce = max_impulse_ang;
  955. }
  956. void RB_constraint_set_target_velocity_motor(rbConstraint *con,
  957. float velocity_lin,
  958. float velocity_ang)
  959. {
  960. btGeneric6DofConstraint *constraint = reinterpret_cast<btGeneric6DofConstraint *>(con);
  961. constraint->getTranslationalLimitMotor()->m_targetVelocity.setX(velocity_lin);
  962. constraint->getRotationalLimitMotor(0)->m_targetVelocity = velocity_ang;
  963. }
  964. /* ********************************** */