webgl_physics_convex_break.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. <html lang="en">
  2. <head>
  3. <title>Convex object breaking example</title>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  6. <link type="text/css" rel="stylesheet" href="main.css">
  7. <style>
  8. body {
  9. color: #333;
  10. }
  11. </style>
  12. </head>
  13. <body>
  14. <div id="info">Physics threejs demo with convex objects breaking in real time<br />Press mouse to throw balls and move the camera.</div>
  15. <div id="container"></div>
  16. <script src="js/libs/ammo.js"></script>
  17. <script type="module">
  18. import * as THREE from '../build/three.module.js';
  19. import Stats from './jsm/libs/stats.module.js';
  20. import { OrbitControls } from './jsm/controls/OrbitControls.js';
  21. import { ConvexObjectBreaker } from './jsm/misc/ConvexObjectBreaker.js';
  22. import { ConvexBufferGeometry } from './jsm/geometries/ConvexGeometry.js';
  23. // - Global variables -
  24. // Graphics variables
  25. var container, stats;
  26. var camera, controls, scene, renderer;
  27. var textureLoader;
  28. var clock = new THREE.Clock();
  29. var mouseCoords = new THREE.Vector2();
  30. var raycaster = new THREE.Raycaster();
  31. var ballMaterial = new THREE.MeshPhongMaterial( { color: 0x202020 } );
  32. // Physics variables
  33. var gravityConstant = 7.8;
  34. var collisionConfiguration;
  35. var dispatcher;
  36. var broadphase;
  37. var solver;
  38. var physicsWorld;
  39. var margin = 0.05;
  40. var convexBreaker = new ConvexObjectBreaker();
  41. // Rigid bodies include all movable objects
  42. var rigidBodies = [];
  43. var pos = new THREE.Vector3();
  44. var quat = new THREE.Quaternion();
  45. var transformAux1;
  46. var tempBtVec3_1;
  47. var objectsToRemove = [];
  48. for ( var i = 0; i < 500; i ++ ) {
  49. objectsToRemove[ i ] = null;
  50. }
  51. var numObjectsToRemove = 0;
  52. var impactPoint = new THREE.Vector3();
  53. var impactNormal = new THREE.Vector3();
  54. // - Main code -
  55. Ammo().then( function ( AmmoLib ) {
  56. Ammo = AmmoLib;
  57. init();
  58. animate();
  59. } );
  60. // - Functions -
  61. function init() {
  62. initGraphics();
  63. initPhysics();
  64. createObjects();
  65. initInput();
  66. }
  67. function initGraphics() {
  68. container = document.getElementById( 'container' );
  69. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.2, 2000 );
  70. scene = new THREE.Scene();
  71. scene.background = new THREE.Color( 0xbfd1e5 );
  72. camera.position.set( - 14, 8, 16 );
  73. renderer = new THREE.WebGLRenderer();
  74. renderer.setPixelRatio( window.devicePixelRatio );
  75. renderer.setSize( window.innerWidth, window.innerHeight );
  76. renderer.shadowMap.enabled = true;
  77. container.appendChild( renderer.domElement );
  78. controls = new OrbitControls( camera, renderer.domElement );
  79. controls.target.set( 0, 2, 0 );
  80. controls.update();
  81. textureLoader = new THREE.TextureLoader();
  82. var ambientLight = new THREE.AmbientLight( 0x707070 );
  83. scene.add( ambientLight );
  84. var light = new THREE.DirectionalLight( 0xffffff, 1 );
  85. light.position.set( - 10, 18, 5 );
  86. light.castShadow = true;
  87. var d = 14;
  88. light.shadow.camera.left = - d;
  89. light.shadow.camera.right = d;
  90. light.shadow.camera.top = d;
  91. light.shadow.camera.bottom = - d;
  92. light.shadow.camera.near = 2;
  93. light.shadow.camera.far = 50;
  94. light.shadow.mapSize.x = 1024;
  95. light.shadow.mapSize.y = 1024;
  96. scene.add( light );
  97. stats = new Stats();
  98. stats.domElement.style.position = 'absolute';
  99. stats.domElement.style.top = '0px';
  100. container.appendChild( stats.domElement );
  101. //
  102. window.addEventListener( 'resize', onWindowResize, false );
  103. }
  104. function initPhysics() {
  105. // Physics configuration
  106. collisionConfiguration = new Ammo.btDefaultCollisionConfiguration();
  107. dispatcher = new Ammo.btCollisionDispatcher( collisionConfiguration );
  108. broadphase = new Ammo.btDbvtBroadphase();
  109. solver = new Ammo.btSequentialImpulseConstraintSolver();
  110. physicsWorld = new Ammo.btDiscreteDynamicsWorld( dispatcher, broadphase, solver, collisionConfiguration );
  111. physicsWorld.setGravity( new Ammo.btVector3( 0, - gravityConstant, 0 ) );
  112. transformAux1 = new Ammo.btTransform();
  113. tempBtVec3_1 = new Ammo.btVector3( 0, 0, 0 );
  114. }
  115. function createObject( mass, halfExtents, pos, quat, material ) {
  116. var object = new THREE.Mesh( new THREE.BoxBufferGeometry( halfExtents.x * 2, halfExtents.y * 2, halfExtents.z * 2 ), material );
  117. object.position.copy( pos );
  118. object.quaternion.copy( quat );
  119. convexBreaker.prepareBreakableObject( object, mass, new THREE.Vector3(), new THREE.Vector3(), true );
  120. createDebrisFromBreakableObject( object );
  121. }
  122. function createObjects() {
  123. // Ground
  124. pos.set( 0, - 0.5, 0 );
  125. quat.set( 0, 0, 0, 1 );
  126. var ground = createParalellepipedWithPhysics( 40, 1, 40, 0, pos, quat, new THREE.MeshPhongMaterial( { color: 0xFFFFFF } ) );
  127. ground.receiveShadow = true;
  128. textureLoader.load( "textures/grid.png", function ( texture ) {
  129. texture.wrapS = THREE.RepeatWrapping;
  130. texture.wrapT = THREE.RepeatWrapping;
  131. texture.repeat.set( 40, 40 );
  132. ground.material.map = texture;
  133. ground.material.needsUpdate = true;
  134. } );
  135. // Tower 1
  136. var towerMass = 1000;
  137. var towerHalfExtents = new THREE.Vector3( 2, 5, 2 );
  138. pos.set( - 8, 5, 0 );
  139. quat.set( 0, 0, 0, 1 );
  140. createObject( towerMass, towerHalfExtents, pos, quat, createMaterial( 0xB03014 ) );
  141. // Tower 2
  142. pos.set( 8, 5, 0 );
  143. quat.set( 0, 0, 0, 1 );
  144. createObject( towerMass, towerHalfExtents, pos, quat, createMaterial( 0xB03214 ) );
  145. //Bridge
  146. var bridgeMass = 100;
  147. var bridgeHalfExtents = new THREE.Vector3( 7, 0.2, 1.5 );
  148. pos.set( 0, 10.2, 0 );
  149. quat.set( 0, 0, 0, 1 );
  150. createObject( bridgeMass, bridgeHalfExtents, pos, quat, createMaterial( 0xB3B865 ) );
  151. // Stones
  152. var stoneMass = 120;
  153. var stoneHalfExtents = new THREE.Vector3( 1, 2, 0.15 );
  154. var numStones = 8;
  155. quat.set( 0, 0, 0, 1 );
  156. for ( var i = 0; i < numStones; i ++ ) {
  157. pos.set( 0, 2, 15 * ( 0.5 - i / ( numStones + 1 ) ) );
  158. createObject( stoneMass, stoneHalfExtents, pos, quat, createMaterial( 0xB0B0B0 ) );
  159. }
  160. // Mountain
  161. var mountainMass = 860;
  162. var mountainHalfExtents = new THREE.Vector3( 4, 5, 4 );
  163. pos.set( 5, mountainHalfExtents.y * 0.5, - 7 );
  164. quat.set( 0, 0, 0, 1 );
  165. var mountainPoints = [];
  166. mountainPoints.push( new THREE.Vector3( mountainHalfExtents.x, - mountainHalfExtents.y, mountainHalfExtents.z ) );
  167. mountainPoints.push( new THREE.Vector3( - mountainHalfExtents.x, - mountainHalfExtents.y, mountainHalfExtents.z ) );
  168. mountainPoints.push( new THREE.Vector3( mountainHalfExtents.x, - mountainHalfExtents.y, - mountainHalfExtents.z ) );
  169. mountainPoints.push( new THREE.Vector3( - mountainHalfExtents.x, - mountainHalfExtents.y, - mountainHalfExtents.z ) );
  170. mountainPoints.push( new THREE.Vector3( 0, mountainHalfExtents.y, 0 ) );
  171. var mountain = new THREE.Mesh( new ConvexBufferGeometry( mountainPoints ), createMaterial( 0xB03814 ) );
  172. mountain.position.copy( pos );
  173. mountain.quaternion.copy( quat );
  174. convexBreaker.prepareBreakableObject( mountain, mountainMass, new THREE.Vector3(), new THREE.Vector3(), true );
  175. createDebrisFromBreakableObject( mountain );
  176. }
  177. function createParalellepipedWithPhysics( sx, sy, sz, mass, pos, quat, material ) {
  178. var object = new THREE.Mesh( new THREE.BoxBufferGeometry( sx, sy, sz, 1, 1, 1 ), material );
  179. var shape = new Ammo.btBoxShape( new Ammo.btVector3( sx * 0.5, sy * 0.5, sz * 0.5 ) );
  180. shape.setMargin( margin );
  181. createRigidBody( object, shape, mass, pos, quat );
  182. return object;
  183. }
  184. function createDebrisFromBreakableObject( object ) {
  185. object.castShadow = true;
  186. object.receiveShadow = true;
  187. var shape = createConvexHullPhysicsShape( object.geometry.attributes.position.array );
  188. shape.setMargin( margin );
  189. var body = createRigidBody( object, shape, object.userData.mass, null, null, object.userData.velocity, object.userData.angularVelocity );
  190. // Set pointer back to the three object only in the debris objects
  191. var btVecUserData = new Ammo.btVector3( 0, 0, 0 );
  192. btVecUserData.threeObject = object;
  193. body.setUserPointer( btVecUserData );
  194. }
  195. function removeDebris( object ) {
  196. scene.remove( object );
  197. physicsWorld.removeRigidBody( object.userData.physicsBody );
  198. }
  199. function createConvexHullPhysicsShape( coords ) {
  200. var shape = new Ammo.btConvexHullShape();
  201. for ( var i = 0, il = coords.length; i < il; i += 3 ) {
  202. tempBtVec3_1.setValue( coords[ i ], coords[ i + 1 ], coords[ i + 2 ] );
  203. var lastOne = ( i >= ( il - 3 ) );
  204. shape.addPoint( tempBtVec3_1, lastOne );
  205. }
  206. return shape;
  207. }
  208. function createRigidBody( object, physicsShape, mass, pos, quat, vel, angVel ) {
  209. if ( pos ) {
  210. object.position.copy( pos );
  211. } else {
  212. pos = object.position;
  213. }
  214. if ( quat ) {
  215. object.quaternion.copy( quat );
  216. } else {
  217. quat = object.quaternion;
  218. }
  219. var transform = new Ammo.btTransform();
  220. transform.setIdentity();
  221. transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
  222. transform.setRotation( new Ammo.btQuaternion( quat.x, quat.y, quat.z, quat.w ) );
  223. var motionState = new Ammo.btDefaultMotionState( transform );
  224. var localInertia = new Ammo.btVector3( 0, 0, 0 );
  225. physicsShape.calculateLocalInertia( mass, localInertia );
  226. var rbInfo = new Ammo.btRigidBodyConstructionInfo( mass, motionState, physicsShape, localInertia );
  227. var body = new Ammo.btRigidBody( rbInfo );
  228. body.setFriction( 0.5 );
  229. if ( vel ) {
  230. body.setLinearVelocity( new Ammo.btVector3( vel.x, vel.y, vel.z ) );
  231. }
  232. if ( angVel ) {
  233. body.setAngularVelocity( new Ammo.btVector3( angVel.x, angVel.y, angVel.z ) );
  234. }
  235. object.userData.physicsBody = body;
  236. object.userData.collided = false;
  237. scene.add( object );
  238. if ( mass > 0 ) {
  239. rigidBodies.push( object );
  240. // Disable deactivation
  241. body.setActivationState( 4 );
  242. }
  243. physicsWorld.addRigidBody( body );
  244. return body;
  245. }
  246. function createRandomColor() {
  247. return Math.floor( Math.random() * ( 1 << 24 ) );
  248. }
  249. function createMaterial( color ) {
  250. color = color || createRandomColor();
  251. return new THREE.MeshPhongMaterial( { color: color } );
  252. }
  253. function initInput() {
  254. window.addEventListener( 'mousedown', function ( event ) {
  255. mouseCoords.set(
  256. ( event.clientX / window.innerWidth ) * 2 - 1,
  257. - ( event.clientY / window.innerHeight ) * 2 + 1
  258. );
  259. raycaster.setFromCamera( mouseCoords, camera );
  260. // Creates a ball and throws it
  261. var ballMass = 35;
  262. var ballRadius = 0.4;
  263. var ball = new THREE.Mesh( new THREE.SphereBufferGeometry( ballRadius, 14, 10 ), ballMaterial );
  264. ball.castShadow = true;
  265. ball.receiveShadow = true;
  266. var ballShape = new Ammo.btSphereShape( ballRadius );
  267. ballShape.setMargin( margin );
  268. pos.copy( raycaster.ray.direction );
  269. pos.add( raycaster.ray.origin );
  270. quat.set( 0, 0, 0, 1 );
  271. var ballBody = createRigidBody( ball, ballShape, ballMass, pos, quat );
  272. pos.copy( raycaster.ray.direction );
  273. pos.multiplyScalar( 24 );
  274. ballBody.setLinearVelocity( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
  275. }, false );
  276. }
  277. function onWindowResize() {
  278. camera.aspect = window.innerWidth / window.innerHeight;
  279. camera.updateProjectionMatrix();
  280. renderer.setSize( window.innerWidth, window.innerHeight );
  281. }
  282. function animate() {
  283. requestAnimationFrame( animate );
  284. render();
  285. stats.update();
  286. }
  287. function render() {
  288. var deltaTime = clock.getDelta();
  289. updatePhysics( deltaTime );
  290. renderer.render( scene, camera );
  291. }
  292. function updatePhysics( deltaTime ) {
  293. // Step world
  294. physicsWorld.stepSimulation( deltaTime, 10 );
  295. // Update rigid bodies
  296. for ( var i = 0, il = rigidBodies.length; i < il; i ++ ) {
  297. var objThree = rigidBodies[ i ];
  298. var objPhys = objThree.userData.physicsBody;
  299. var ms = objPhys.getMotionState();
  300. if ( ms ) {
  301. ms.getWorldTransform( transformAux1 );
  302. var p = transformAux1.getOrigin();
  303. var q = transformAux1.getRotation();
  304. objThree.position.set( p.x(), p.y(), p.z() );
  305. objThree.quaternion.set( q.x(), q.y(), q.z(), q.w() );
  306. objThree.userData.collided = false;
  307. }
  308. }
  309. for ( var i = 0, il = dispatcher.getNumManifolds(); i < il; i ++ ) {
  310. var contactManifold = dispatcher.getManifoldByIndexInternal( i );
  311. var rb0 = Ammo.castObject( contactManifold.getBody0(), Ammo.btRigidBody );
  312. var rb1 = Ammo.castObject( contactManifold.getBody1(), Ammo.btRigidBody );
  313. var threeObject0 = Ammo.castObject( rb0.getUserPointer(), Ammo.btVector3 ).threeObject;
  314. var threeObject1 = Ammo.castObject( rb1.getUserPointer(), Ammo.btVector3 ).threeObject;
  315. if ( ! threeObject0 && ! threeObject1 ) {
  316. continue;
  317. }
  318. var userData0 = threeObject0 ? threeObject0.userData : null;
  319. var userData1 = threeObject1 ? threeObject1.userData : null;
  320. var breakable0 = userData0 ? userData0.breakable : false;
  321. var breakable1 = userData1 ? userData1.breakable : false;
  322. var collided0 = userData0 ? userData0.collided : false;
  323. var collided1 = userData1 ? userData1.collided : false;
  324. if ( ( ! breakable0 && ! breakable1 ) || ( collided0 && collided1 ) ) {
  325. continue;
  326. }
  327. var contact = false;
  328. var maxImpulse = 0;
  329. for ( var j = 0, jl = contactManifold.getNumContacts(); j < jl; j ++ ) {
  330. var contactPoint = contactManifold.getContactPoint( j );
  331. if ( contactPoint.getDistance() < 0 ) {
  332. contact = true;
  333. var impulse = contactPoint.getAppliedImpulse();
  334. if ( impulse > maxImpulse ) {
  335. maxImpulse = impulse;
  336. var pos = contactPoint.get_m_positionWorldOnB();
  337. var normal = contactPoint.get_m_normalWorldOnB();
  338. impactPoint.set( pos.x(), pos.y(), pos.z() );
  339. impactNormal.set( normal.x(), normal.y(), normal.z() );
  340. }
  341. break;
  342. }
  343. }
  344. // If no point has contact, abort
  345. if ( ! contact ) continue;
  346. // Subdivision
  347. var fractureImpulse = 250;
  348. if ( breakable0 && ! collided0 && maxImpulse > fractureImpulse ) {
  349. var debris = convexBreaker.subdivideByImpact( threeObject0, impactPoint, impactNormal, 1, 2, 1.5 );
  350. var numObjects = debris.length;
  351. for ( var j = 0; j < numObjects; j ++ ) {
  352. var vel = rb0.getLinearVelocity();
  353. var angVel = rb0.getAngularVelocity();
  354. var fragment = debris[ j ];
  355. fragment.userData.velocity.set( vel.x(), vel.y(), vel.z() );
  356. fragment.userData.angularVelocity.set( angVel.x(), angVel.y(), angVel.z() );
  357. createDebrisFromBreakableObject( fragment );
  358. }
  359. objectsToRemove[ numObjectsToRemove ++ ] = threeObject0;
  360. userData0.collided = true;
  361. }
  362. if ( breakable1 && ! collided1 && maxImpulse > fractureImpulse ) {
  363. var debris = convexBreaker.subdivideByImpact( threeObject1, impactPoint, impactNormal, 1, 2, 1.5 );
  364. var numObjects = debris.length;
  365. for ( var j = 0; j < numObjects; j ++ ) {
  366. var vel = rb1.getLinearVelocity();
  367. var angVel = rb1.getAngularVelocity();
  368. var fragment = debris[ j ];
  369. fragment.userData.velocity.set( vel.x(), vel.y(), vel.z() );
  370. fragment.userData.angularVelocity.set( angVel.x(), angVel.y(), angVel.z() );
  371. createDebrisFromBreakableObject( fragment );
  372. }
  373. objectsToRemove[ numObjectsToRemove ++ ] = threeObject1;
  374. userData1.collided = true;
  375. }
  376. }
  377. for ( var i = 0; i < numObjectsToRemove; i ++ ) {
  378. removeDebris( objectsToRemove[ i ] );
  379. }
  380. numObjectsToRemove = 0;
  381. }
  382. </script>
  383. </body>
  384. </html>