physics_ammo_break.html 16 KB

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