webgl_animation_cloth.html 14 KB

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