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