webgl_animation_cloth.html 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - cloth simulation</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. <style>
  9. body {
  10. background-color: #cce0ff;
  11. color: #000;
  12. }
  13. a {
  14. color: #080;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="info">Simple Cloth Simulation<br/>
  20. Verlet integration with relaxed constraints<br/>
  21. </div>
  22. <script src="../build/three.js"></script>
  23. <script src="js/WebGL.js"></script>
  24. <script src="js/controls/OrbitControls.js"></script>
  25. <script src="js/libs/stats.min.js"></script>
  26. <script src="js/libs/dat.gui.min.js"></script>
  27. <script>
  28. /*
  29. * Cloth Simulation using a relaxed constraints solver
  30. */
  31. // Suggested Readings
  32. // Advanced Character Physics by Thomas Jakobsen Character
  33. // http://freespace.virgin.net/hugo.elias/models/m_cloth.htm
  34. // http://en.wikipedia.org/wiki/Cloth_modeling
  35. // http://cg.alexandra.dk/tag/spring-mass-system/
  36. // Real-time Cloth Animation http://www.darwin3d.com/gamedev/articles/col0599.pdf
  37. var params = {
  38. enableWind: true,
  39. showBall: false,
  40. tooglePins: togglePins
  41. };
  42. var DAMPING = 0.03;
  43. var DRAG = 1 - DAMPING;
  44. var MASS = 0.1;
  45. var restDistance = 25;
  46. var xSegs = 10;
  47. var ySegs = 10;
  48. var clothFunction = plane( restDistance * xSegs, restDistance * ySegs );
  49. var cloth = new Cloth( xSegs, ySegs );
  50. var GRAVITY = 981 * 1.4;
  51. var gravity = new THREE.Vector3( 0, - GRAVITY, 0 ).multiplyScalar( MASS );
  52. var TIMESTEP = 18 / 1000;
  53. var TIMESTEP_SQ = TIMESTEP * TIMESTEP;
  54. var pins = [];
  55. var windForce = new THREE.Vector3( 0, 0, 0 );
  56. var ballPosition = new THREE.Vector3( 0, - 45, 0 );
  57. var ballSize = 60; //40
  58. var tmpForce = new THREE.Vector3();
  59. var lastTime;
  60. function plane( width, height ) {
  61. return function ( u, v, target ) {
  62. var x = ( u - 0.5 ) * width;
  63. var y = ( v + 0.5 ) * height;
  64. var z = 0;
  65. target.set( x, y, z );
  66. };
  67. }
  68. function Particle( x, y, z, mass ) {
  69. this.position = new THREE.Vector3();
  70. this.previous = new THREE.Vector3();
  71. this.original = new THREE.Vector3();
  72. this.a = new THREE.Vector3( 0, 0, 0 ); // acceleration
  73. this.mass = mass;
  74. this.invMass = 1 / mass;
  75. this.tmp = new THREE.Vector3();
  76. this.tmp2 = new THREE.Vector3();
  77. // init
  78. clothFunction( x, y, this.position ); // position
  79. clothFunction( x, y, this.previous ); // previous
  80. clothFunction( x, y, this.original );
  81. }
  82. // Force -> Acceleration
  83. Particle.prototype.addForce = function ( force ) {
  84. this.a.add(
  85. this.tmp2.copy( force ).multiplyScalar( this.invMass )
  86. );
  87. };
  88. // Performs Verlet integration
  89. Particle.prototype.integrate = function ( timesq ) {
  90. var newPos = this.tmp.subVectors( this.position, this.previous );
  91. newPos.multiplyScalar( DRAG ).add( this.position );
  92. newPos.add( this.a.multiplyScalar( timesq ) );
  93. this.tmp = this.previous;
  94. this.previous = this.position;
  95. this.position = newPos;
  96. this.a.set( 0, 0, 0 );
  97. };
  98. var diff = new THREE.Vector3();
  99. function satisfyConstraints( p1, p2, distance ) {
  100. diff.subVectors( p2.position, p1.position );
  101. var currentDist = diff.length();
  102. if ( currentDist === 0 ) return; // prevents division by 0
  103. var correction = diff.multiplyScalar( 1 - distance / currentDist );
  104. var correctionHalf = correction.multiplyScalar( 0.5 );
  105. p1.position.add( correctionHalf );
  106. p2.position.sub( correctionHalf );
  107. }
  108. function Cloth( w, h ) {
  109. w = w || 10;
  110. h = h || 10;
  111. this.w = w;
  112. this.h = h;
  113. var particles = [];
  114. var constraints = [];
  115. var u, v;
  116. // Create particles
  117. for ( v = 0; v <= h; v ++ ) {
  118. for ( u = 0; u <= w; u ++ ) {
  119. particles.push(
  120. new Particle( u / w, v / h, 0, MASS )
  121. );
  122. }
  123. }
  124. // Structural
  125. for ( v = 0; v < h; v ++ ) {
  126. for ( u = 0; u < w; u ++ ) {
  127. constraints.push( [
  128. particles[ index( u, v ) ],
  129. particles[ index( u, v + 1 ) ],
  130. restDistance
  131. ] );
  132. constraints.push( [
  133. particles[ index( u, v ) ],
  134. particles[ index( u + 1, v ) ],
  135. restDistance
  136. ] );
  137. }
  138. }
  139. for ( u = w, v = 0; v < h; v ++ ) {
  140. constraints.push( [
  141. particles[ index( u, v ) ],
  142. particles[ index( u, v + 1 ) ],
  143. restDistance
  144. ] );
  145. }
  146. for ( v = h, u = 0; u < w; u ++ ) {
  147. constraints.push( [
  148. particles[ index( u, v ) ],
  149. particles[ index( u + 1, v ) ],
  150. restDistance
  151. ] );
  152. }
  153. // While many systems use shear and bend springs,
  154. // the relaxed constraints model seems to be just fine
  155. // using structural springs.
  156. // Shear
  157. // var diagonalDist = Math.sqrt(restDistance * restDistance * 2);
  158. // for (v=0;v<h;v++) {
  159. // for (u=0;u<w;u++) {
  160. // constraints.push([
  161. // particles[index(u, v)],
  162. // particles[index(u+1, v+1)],
  163. // diagonalDist
  164. // ]);
  165. // constraints.push([
  166. // particles[index(u+1, v)],
  167. // particles[index(u, v+1)],
  168. // diagonalDist
  169. // ]);
  170. // }
  171. // }
  172. this.particles = particles;
  173. this.constraints = constraints;
  174. function index( u, v ) {
  175. return u + v * ( w + 1 );
  176. }
  177. this.index = index;
  178. }
  179. function simulate( time ) {
  180. if ( ! lastTime ) {
  181. lastTime = time;
  182. return;
  183. }
  184. var i, j, il, particles, particle, constraints, constraint;
  185. // Aerodynamics forces
  186. if ( params.enableWind ) {
  187. var indx;
  188. var normal = new THREE.Vector3();
  189. var indices = clothGeometry.index;
  190. var normals = clothGeometry.attributes.normal;
  191. particles = cloth.particles;
  192. for ( i = 0, il = indices.count; i < il; i += 3 ) {
  193. for ( j = 0; j < 3; j ++ ) {
  194. indx = indices.getX( i + j );
  195. normal.fromBufferAttribute( normals, indx );
  196. tmpForce.copy( normal ).normalize().multiplyScalar( normal.dot( windForce ) );
  197. particles[ indx ].addForce( tmpForce );
  198. }
  199. }
  200. }
  201. for ( particles = cloth.particles, i = 0, il = particles.length; i < il; i ++ ) {
  202. particle = particles[ i ];
  203. particle.addForce( gravity );
  204. particle.integrate( TIMESTEP_SQ );
  205. }
  206. // Start Constraints
  207. constraints = cloth.constraints;
  208. il = constraints.length;
  209. for ( i = 0; i < il; i ++ ) {
  210. constraint = constraints[ i ];
  211. satisfyConstraints( constraint[ 0 ], constraint[ 1 ], constraint[ 2 ] );
  212. }
  213. // Ball Constraints
  214. ballPosition.z = - Math.sin( Date.now() / 600 ) * 90; //+ 40;
  215. ballPosition.x = Math.cos( Date.now() / 400 ) * 70;
  216. if ( params.showBall ) {
  217. sphere.visible = true;
  218. for ( particles = cloth.particles, i = 0, il = particles.length; i < il; i ++ ) {
  219. particle = particles[ i ];
  220. var pos = particle.position;
  221. diff.subVectors( pos, ballPosition );
  222. if ( diff.length() < ballSize ) {
  223. // collided
  224. diff.normalize().multiplyScalar( ballSize );
  225. pos.copy( ballPosition ).add( diff );
  226. }
  227. }
  228. } else {
  229. sphere.visible = false;
  230. }
  231. // Floor Constraints
  232. for ( particles = cloth.particles, i = 0, il = particles.length; i < il; i ++ ) {
  233. particle = particles[ i ];
  234. pos = particle.position;
  235. if ( pos.y < - 250 ) {
  236. pos.y = - 250;
  237. }
  238. }
  239. // Pin Constraints
  240. for ( i = 0, il = pins.length; i < il; i ++ ) {
  241. var xy = pins[ i ];
  242. var p = particles[ xy ];
  243. p.position.copy( p.original );
  244. p.previous.copy( p.original );
  245. }
  246. }
  247. /* testing cloth simulation */
  248. var pinsFormation = [];
  249. var pins = [ 6 ];
  250. pinsFormation.push( pins );
  251. pins = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
  252. pinsFormation.push( pins );
  253. pins = [ 0 ];
  254. pinsFormation.push( pins );
  255. pins = []; // cut the rope ;)
  256. pinsFormation.push( pins );
  257. pins = [ 0, cloth.w ]; // classic 2 pins
  258. pinsFormation.push( pins );
  259. pins = pinsFormation[ 1 ];
  260. function togglePins() {
  261. pins = pinsFormation[ ~ ~ ( Math.random() * pinsFormation.length ) ];
  262. }
  263. if ( WEBGL.isWebGLAvailable() === false ) {
  264. document.body.appendChild( WEBGL.getWebGLErrorMessage() );
  265. }
  266. var container, stats;
  267. var camera, scene, renderer;
  268. var clothGeometry;
  269. var sphere;
  270. var object;
  271. init();
  272. animate();
  273. function init() {
  274. container = document.createElement( 'div' );
  275. document.body.appendChild( container );
  276. // scene
  277. scene = new THREE.Scene();
  278. scene.background = new THREE.Color( 0xcce0ff );
  279. scene.fog = new THREE.Fog( 0xcce0ff, 500, 10000 );
  280. // camera
  281. camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 1, 10000 );
  282. camera.position.set( 1000, 50, 1500 );
  283. // lights
  284. scene.add( new THREE.AmbientLight( 0x666666 ) );
  285. var light = new THREE.DirectionalLight( 0xdfebff, 1 );
  286. light.position.set( 50, 200, 100 );
  287. light.position.multiplyScalar( 1.3 );
  288. light.castShadow = true;
  289. light.shadow.mapSize.width = 1024;
  290. light.shadow.mapSize.height = 1024;
  291. var d = 300;
  292. light.shadow.camera.left = - d;
  293. light.shadow.camera.right = d;
  294. light.shadow.camera.top = d;
  295. light.shadow.camera.bottom = - d;
  296. light.shadow.camera.far = 1000;
  297. scene.add( light );
  298. // cloth material
  299. var loader = new THREE.TextureLoader();
  300. var clothTexture = loader.load( 'textures/patterns/circuit_pattern.png' );
  301. clothTexture.anisotropy = 16;
  302. var clothMaterial = new THREE.MeshLambertMaterial( {
  303. map: clothTexture,
  304. side: THREE.DoubleSide,
  305. alphaTest: 0.5
  306. } );
  307. // cloth geometry
  308. clothGeometry = new THREE.ParametricBufferGeometry( clothFunction, cloth.w, cloth.h );
  309. // cloth mesh
  310. object = new THREE.Mesh( clothGeometry, clothMaterial );
  311. object.position.set( 0, 0, 0 );
  312. object.castShadow = true;
  313. scene.add( object );
  314. object.customDepthMaterial = new THREE.MeshDepthMaterial( {
  315. depthPacking: THREE.RGBADepthPacking,
  316. map: clothTexture,
  317. alphaTest: 0.5
  318. } );
  319. // sphere
  320. var ballGeo = new THREE.SphereBufferGeometry( ballSize, 32, 16 );
  321. var ballMaterial = new THREE.MeshLambertMaterial();
  322. sphere = new THREE.Mesh( ballGeo, ballMaterial );
  323. sphere.castShadow = true;
  324. sphere.receiveShadow = true;
  325. sphere.visible = false;
  326. scene.add( sphere );
  327. // ground
  328. var groundTexture = loader.load( 'textures/terrain/grasslight-big.jpg' );
  329. groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping;
  330. groundTexture.repeat.set( 25, 25 );
  331. groundTexture.anisotropy = 16;
  332. var groundMaterial = new THREE.MeshLambertMaterial( { map: groundTexture } );
  333. var mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 20000, 20000 ), groundMaterial );
  334. mesh.position.y = - 250;
  335. mesh.rotation.x = - Math.PI / 2;
  336. mesh.receiveShadow = true;
  337. scene.add( mesh );
  338. // poles
  339. var poleGeo = new THREE.BoxBufferGeometry( 5, 375, 5 );
  340. var poleMat = new THREE.MeshLambertMaterial();
  341. var mesh = new THREE.Mesh( poleGeo, poleMat );
  342. mesh.position.x = - 125;
  343. mesh.position.y = - 62;
  344. mesh.receiveShadow = true;
  345. mesh.castShadow = true;
  346. scene.add( mesh );
  347. var mesh = new THREE.Mesh( poleGeo, poleMat );
  348. mesh.position.x = 125;
  349. mesh.position.y = - 62;
  350. mesh.receiveShadow = true;
  351. mesh.castShadow = true;
  352. scene.add( mesh );
  353. var mesh = new THREE.Mesh( new THREE.BoxBufferGeometry( 255, 5, 5 ), poleMat );
  354. mesh.position.y = - 250 + ( 750 / 2 );
  355. mesh.position.x = 0;
  356. mesh.receiveShadow = true;
  357. mesh.castShadow = true;
  358. scene.add( mesh );
  359. var gg = new THREE.BoxBufferGeometry( 10, 10, 10 );
  360. var mesh = new THREE.Mesh( gg, poleMat );
  361. mesh.position.y = - 250;
  362. mesh.position.x = 125;
  363. mesh.receiveShadow = true;
  364. mesh.castShadow = true;
  365. scene.add( mesh );
  366. var mesh = new THREE.Mesh( gg, poleMat );
  367. mesh.position.y = - 250;
  368. mesh.position.x = - 125;
  369. mesh.receiveShadow = true;
  370. mesh.castShadow = true;
  371. scene.add( mesh );
  372. // renderer
  373. renderer = new THREE.WebGLRenderer( { antialias: true } );
  374. renderer.setPixelRatio( window.devicePixelRatio );
  375. renderer.setSize( window.innerWidth, window.innerHeight );
  376. container.appendChild( renderer.domElement );
  377. renderer.gammaInput = true;
  378. renderer.gammaOutput = true;
  379. renderer.shadowMap.enabled = true;
  380. // controls
  381. var controls = new THREE.OrbitControls( camera, renderer.domElement );
  382. controls.maxPolarAngle = Math.PI * 0.5;
  383. controls.minDistance = 1000;
  384. controls.maxDistance = 5000;
  385. // performance monitor
  386. stats = new Stats();
  387. container.appendChild( stats.dom );
  388. //
  389. window.addEventListener( 'resize', onWindowResize, false );
  390. //
  391. var gui = new dat.GUI();
  392. gui.add( params, 'enableWind' );
  393. gui.add( params, 'showBall' );
  394. gui.add( params, 'tooglePins' );
  395. }
  396. //
  397. function onWindowResize() {
  398. camera.aspect = window.innerWidth / window.innerHeight;
  399. camera.updateProjectionMatrix();
  400. renderer.setSize( window.innerWidth, window.innerHeight );
  401. }
  402. //
  403. function animate() {
  404. requestAnimationFrame( animate );
  405. var time = Date.now();
  406. var windStrength = Math.cos( time / 7000 ) * 20 + 40;
  407. windForce.set( Math.sin( time / 2000 ), Math.cos( time / 3000 ), Math.sin( time / 1000 ) );
  408. windForce.normalize();
  409. windForce.multiplyScalar( windStrength );
  410. simulate( time );
  411. render();
  412. stats.update();
  413. }
  414. function render() {
  415. var p = cloth.particles;
  416. for ( var i = 0, il = p.length; i < il; i ++ ) {
  417. var v = p[ i ].position;
  418. clothGeometry.attributes.position.setXYZ( i, v.x, v.y, v.z );
  419. }
  420. clothGeometry.attributes.position.needsUpdate = true;
  421. clothGeometry.computeVertexNormals();
  422. sphere.position.copy( ballPosition );
  423. renderer.render( scene, camera );
  424. }
  425. </script>
  426. </body>
  427. </html>