webgl_animation_cloth.html 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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 GRAVITY = 981 * 1.4;
  49. const gravity = new THREE.Vector3( 0, - GRAVITY, 0 ).multiplyScalar( MASS );
  50. const TIMESTEP = 18 / 1000;
  51. const TIMESTEP_SQ = TIMESTEP * TIMESTEP;
  52. let pins = [];
  53. const windForce = new THREE.Vector3( 0, 0, 0 );
  54. const ballPosition = new THREE.Vector3( 0, - 45, 0 );
  55. const ballSize = 60; //40
  56. const tmpForce = new THREE.Vector3();
  57. const diff = new THREE.Vector3();
  58. class Particle {
  59. constructor( x, y, z, mass ) {
  60. this.position = new THREE.Vector3();
  61. this.previous = new THREE.Vector3();
  62. this.original = new THREE.Vector3();
  63. this.a = new THREE.Vector3( 0, 0, 0 ); // acceleration
  64. this.mass = mass;
  65. this.invMass = 1 / mass;
  66. this.tmp = new THREE.Vector3();
  67. this.tmp2 = new THREE.Vector3();
  68. // init
  69. clothFunction( x, y, this.position ); // position
  70. clothFunction( x, y, this.previous ); // previous
  71. clothFunction( x, y, this.original );
  72. }
  73. // Force -> Acceleration
  74. addForce( force ) {
  75. this.a.add(
  76. this.tmp2.copy( force ).multiplyScalar( this.invMass )
  77. );
  78. }
  79. // Performs Verlet integration
  80. integrate( timesq ) {
  81. const newPos = this.tmp.subVectors( this.position, this.previous );
  82. newPos.multiplyScalar( DRAG ).add( this.position );
  83. newPos.add( this.a.multiplyScalar( timesq ) );
  84. this.tmp = this.previous;
  85. this.previous = this.position;
  86. this.position = newPos;
  87. this.a.set( 0, 0, 0 );
  88. }
  89. }
  90. class Cloth {
  91. constructor( w = 10, h = 10 ) {
  92. this.w = w;
  93. this.h = h;
  94. const particles = [];
  95. const constraints = [];
  96. // Create particles
  97. for ( let v = 0; v <= h; v ++ ) {
  98. for ( let u = 0; u <= w; u ++ ) {
  99. particles.push(
  100. new Particle( u / w, v / h, 0, MASS )
  101. );
  102. }
  103. }
  104. // Structural
  105. for ( let v = 0; v < h; v ++ ) {
  106. for ( let u = 0; u < w; u ++ ) {
  107. constraints.push( [
  108. particles[ index( u, v ) ],
  109. particles[ index( u, v + 1 ) ],
  110. restDistance
  111. ] );
  112. constraints.push( [
  113. particles[ index( u, v ) ],
  114. particles[ index( u + 1, v ) ],
  115. restDistance
  116. ] );
  117. }
  118. }
  119. for ( let u = w, v = 0; v < h; v ++ ) {
  120. constraints.push( [
  121. particles[ index( u, v ) ],
  122. particles[ index( u, v + 1 ) ],
  123. restDistance
  124. ] );
  125. }
  126. for ( let v = h, u = 0; u < w; u ++ ) {
  127. constraints.push( [
  128. particles[ index( u, v ) ],
  129. particles[ index( u + 1, v ) ],
  130. restDistance
  131. ] );
  132. }
  133. // While many systems use shear and bend springs,
  134. // the relaxed constraints model seems to be just fine
  135. // using structural springs.
  136. // Shear
  137. // const diagonalDist = Math.sqrt(restDistance * restDistance * 2);
  138. // for (v=0;v<h;v++) {
  139. // for (u=0;u<w;u++) {
  140. // constraints.push([
  141. // particles[index(u, v)],
  142. // particles[index(u+1, v+1)],
  143. // diagonalDist
  144. // ]);
  145. // constraints.push([
  146. // particles[index(u+1, v)],
  147. // particles[index(u, v+1)],
  148. // diagonalDist
  149. // ]);
  150. // }
  151. // }
  152. this.particles = particles;
  153. this.constraints = constraints;
  154. function index( u, v ) {
  155. return u + v * ( w + 1 );
  156. }
  157. this.index = index;
  158. }
  159. }
  160. function plane( width, height ) {
  161. return function ( u, v, target ) {
  162. const x = ( u - 0.5 ) * width;
  163. const y = ( v + 0.5 ) * height;
  164. const z = 0;
  165. target.set( x, y, z );
  166. };
  167. }
  168. function satisfyConstraints( p1, p2, distance ) {
  169. diff.subVectors( p2.position, p1.position );
  170. const currentDist = diff.length();
  171. if ( currentDist === 0 ) return; // prevents division by 0
  172. const correction = diff.multiplyScalar( 1 - distance / currentDist );
  173. const correctionHalf = correction.multiplyScalar( 0.5 );
  174. p1.position.add( correctionHalf );
  175. p2.position.sub( correctionHalf );
  176. }
  177. function simulate( now ) {
  178. const 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. // Aerodynamics forces
  183. const particles = cloth.particles;
  184. if ( params.enableWind ) {
  185. let indx;
  186. const normal = new THREE.Vector3();
  187. const indices = clothGeometry.index;
  188. const normals = clothGeometry.attributes.normal;
  189. for ( let i = 0, il = indices.count; i < il; i += 3 ) {
  190. for ( let j = 0; j < 3; j ++ ) {
  191. indx = indices.getX( i + j );
  192. normal.fromBufferAttribute( normals, indx );
  193. tmpForce.copy( normal ).normalize().multiplyScalar( normal.dot( windForce ) );
  194. particles[ indx ].addForce( tmpForce );
  195. }
  196. }
  197. }
  198. for ( let i = 0, il = particles.length; i < il; i ++ ) {
  199. const particle = particles[ i ];
  200. particle.addForce( gravity );
  201. particle.integrate( TIMESTEP_SQ );
  202. }
  203. // Start Constraints
  204. const constraints = cloth.constraints;
  205. const il = constraints.length;
  206. for ( let i = 0; i < il; i ++ ) {
  207. const constraint = constraints[ i ];
  208. satisfyConstraints( constraint[ 0 ], constraint[ 1 ], constraint[ 2 ] );
  209. }
  210. // Ball Constraints
  211. ballPosition.z = - Math.sin( now / 600 ) * 90; //+ 40;
  212. ballPosition.x = Math.cos( now / 400 ) * 70;
  213. if ( params.showBall ) {
  214. sphere.visible = true;
  215. for ( let i = 0, il = particles.length; i < il; i ++ ) {
  216. const particle = particles[ i ];
  217. const pos = particle.position;
  218. diff.subVectors( pos, ballPosition );
  219. if ( diff.length() < ballSize ) {
  220. // collided
  221. diff.normalize().multiplyScalar( ballSize );
  222. pos.copy( ballPosition ).add( diff );
  223. }
  224. }
  225. } else {
  226. sphere.visible = false;
  227. }
  228. // Floor Constraints
  229. for ( let i = 0, il = particles.length; i < il; i ++ ) {
  230. const particle = particles[ i ];
  231. const pos = particle.position;
  232. if ( pos.y < - 250 ) {
  233. pos.y = - 250;
  234. }
  235. }
  236. // Pin Constraints
  237. for ( let i = 0, il = pins.length; i < il; i ++ ) {
  238. const xy = pins[ i ];
  239. const p = particles[ xy ];
  240. p.position.copy( p.original );
  241. p.previous.copy( p.original );
  242. }
  243. }
  244. /* testing cloth simulation */
  245. const cloth = new Cloth( xSegs, ySegs );
  246. const pinsFormation = [];
  247. 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. let container, stats;
  262. let camera, scene, renderer;
  263. let clothGeometry;
  264. let sphere;
  265. let 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. const 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. const 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. const loader = new THREE.TextureLoader();
  295. const clothTexture = loader.load( 'textures/patterns/circuit_pattern.png' );
  296. clothTexture.anisotropy = 16;
  297. const 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. const ballGeo = new THREE.SphereGeometry( ballSize, 32, 16 );
  316. const 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. const 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. const groundMaterial = new THREE.MeshLambertMaterial( { map: groundTexture } );
  329. let mesh = new THREE.Mesh( new THREE.PlaneGeometry( 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. const poleGeo = new THREE.BoxGeometry( 5, 375, 5 );
  336. const poleMat = new THREE.MeshLambertMaterial();
  337. 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. 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. mesh = new THREE.Mesh( new THREE.BoxGeometry( 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. const gg = new THREE.BoxGeometry( 10, 10, 10 );
  356. 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. 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. const 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 );
  385. //
  386. const 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. //
  392. function onWindowResize() {
  393. camera.aspect = window.innerWidth / window.innerHeight;
  394. camera.updateProjectionMatrix();
  395. renderer.setSize( window.innerWidth, window.innerHeight );
  396. }
  397. //
  398. function animate( now ) {
  399. requestAnimationFrame( animate );
  400. simulate( now );
  401. render();
  402. stats.update();
  403. }
  404. function render() {
  405. const p = cloth.particles;
  406. for ( let i = 0, il = p.length; i < il; i ++ ) {
  407. const v = p[ i ].position;
  408. clothGeometry.attributes.position.setXYZ( i, v.x, v.y, v.z );
  409. }
  410. clothGeometry.attributes.position.needsUpdate = true;
  411. clothGeometry.computeVertexNormals();
  412. sphere.position.copy( ballPosition );
  413. renderer.render( scene, camera );
  414. }
  415. </script>
  416. </body>
  417. </html>