webgl_animation_cloth.html 14 KB

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