webgl_animation_skinning_blending.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - animation - skinning</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. a {
  10. color: #f00;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <div id="container"></div>
  16. <div id="info">
  17. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - Skeletal Animation Blending
  18. (model from <a href="https://www.mixamo.com/" target="_blank" rel="noopener">mixamo.com</a>)<br/>
  19. Note: crossfades are possible with blend weights being set to (1,0,0), (0,1,0) or (0,0,1)
  20. </div>
  21. <!-- Import maps polyfill -->
  22. <!-- Remove this when import maps will be widely supported -->
  23. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  24. <script type="importmap">
  25. {
  26. "imports": {
  27. "three": "../build/three.module.js",
  28. "three/addons/": "./jsm/"
  29. }
  30. }
  31. </script>
  32. <script type="module">
  33. import * as THREE from 'three';
  34. import Stats from 'three/addons/libs/stats.module.js';
  35. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  36. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  37. let scene, renderer, camera, stats;
  38. let model, skeleton, mixer, clock;
  39. const crossFadeControls = [];
  40. let idleAction, walkAction, runAction;
  41. let idleWeight, walkWeight, runWeight;
  42. let actions, settings;
  43. let singleStepMode = false;
  44. let sizeOfNextStep = 0;
  45. init();
  46. function init() {
  47. const container = document.getElementById( 'container' );
  48. camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
  49. camera.position.set( 1, 2, - 3 );
  50. camera.lookAt( 0, 1, 0 );
  51. clock = new THREE.Clock();
  52. scene = new THREE.Scene();
  53. scene.background = new THREE.Color( 0xa0a0a0 );
  54. scene.fog = new THREE.Fog( 0xa0a0a0, 10, 50 );
  55. const hemiLight = new THREE.HemisphereLight( 0xffffff, 0x444444 );
  56. hemiLight.position.set( 0, 20, 0 );
  57. scene.add( hemiLight );
  58. const dirLight = new THREE.DirectionalLight( 0xffffff );
  59. dirLight.position.set( - 3, 10, - 10 );
  60. dirLight.castShadow = true;
  61. dirLight.shadow.camera.top = 2;
  62. dirLight.shadow.camera.bottom = - 2;
  63. dirLight.shadow.camera.left = - 2;
  64. dirLight.shadow.camera.right = 2;
  65. dirLight.shadow.camera.near = 0.1;
  66. dirLight.shadow.camera.far = 40;
  67. scene.add( dirLight );
  68. // scene.add( new THREE.CameraHelper( dirLight.shadow.camera ) );
  69. // ground
  70. const mesh = new THREE.Mesh( new THREE.PlaneGeometry( 100, 100 ), new THREE.MeshPhongMaterial( { color: 0x999999, depthWrite: false } ) );
  71. mesh.rotation.x = - Math.PI / 2;
  72. mesh.receiveShadow = true;
  73. scene.add( mesh );
  74. const loader = new GLTFLoader();
  75. loader.load( 'models/gltf/Soldier.glb', function ( gltf ) {
  76. model = gltf.scene;
  77. scene.add( model );
  78. model.traverse( function ( object ) {
  79. if ( object.isMesh ) object.castShadow = true;
  80. } );
  81. //
  82. skeleton = new THREE.SkeletonHelper( model );
  83. skeleton.visible = false;
  84. scene.add( skeleton );
  85. //
  86. createPanel();
  87. //
  88. const animations = gltf.animations;
  89. mixer = new THREE.AnimationMixer( model );
  90. idleAction = mixer.clipAction( animations[ 0 ] );
  91. walkAction = mixer.clipAction( animations[ 3 ] );
  92. runAction = mixer.clipAction( animations[ 1 ] );
  93. actions = [ idleAction, walkAction, runAction ];
  94. activateAllActions();
  95. animate();
  96. } );
  97. renderer = new THREE.WebGLRenderer( { antialias: true } );
  98. renderer.setPixelRatio( window.devicePixelRatio );
  99. renderer.setSize( window.innerWidth, window.innerHeight );
  100. renderer.outputEncoding = THREE.sRGBEncoding;
  101. renderer.shadowMap.enabled = true;
  102. container.appendChild( renderer.domElement );
  103. stats = new Stats();
  104. container.appendChild( stats.dom );
  105. window.addEventListener( 'resize', onWindowResize );
  106. }
  107. function createPanel() {
  108. const panel = new GUI( { width: 310 } );
  109. const folder1 = panel.addFolder( 'Visibility' );
  110. const folder2 = panel.addFolder( 'Activation/Deactivation' );
  111. const folder3 = panel.addFolder( 'Pausing/Stepping' );
  112. const folder4 = panel.addFolder( 'Crossfading' );
  113. const folder5 = panel.addFolder( 'Blend Weights' );
  114. const folder6 = panel.addFolder( 'General Speed' );
  115. settings = {
  116. 'show model': true,
  117. 'show skeleton': false,
  118. 'deactivate all': deactivateAllActions,
  119. 'activate all': activateAllActions,
  120. 'pause/continue': pauseContinue,
  121. 'make single step': toSingleStepMode,
  122. 'modify step size': 0.05,
  123. 'from walk to idle': function () {
  124. prepareCrossFade( walkAction, idleAction, 1.0 );
  125. },
  126. 'from idle to walk': function () {
  127. prepareCrossFade( idleAction, walkAction, 0.5 );
  128. },
  129. 'from walk to run': function () {
  130. prepareCrossFade( walkAction, runAction, 2.5 );
  131. },
  132. 'from run to walk': function () {
  133. prepareCrossFade( runAction, walkAction, 5.0 );
  134. },
  135. 'use default duration': true,
  136. 'set custom duration': 3.5,
  137. 'modify idle weight': 0.0,
  138. 'modify walk weight': 1.0,
  139. 'modify run weight': 0.0,
  140. 'modify time scale': 1.0
  141. };
  142. folder1.add( settings, 'show model' ).onChange( showModel );
  143. folder1.add( settings, 'show skeleton' ).onChange( showSkeleton );
  144. folder2.add( settings, 'deactivate all' );
  145. folder2.add( settings, 'activate all' );
  146. folder3.add( settings, 'pause/continue' );
  147. folder3.add( settings, 'make single step' );
  148. folder3.add( settings, 'modify step size', 0.01, 0.1, 0.001 );
  149. crossFadeControls.push( folder4.add( settings, 'from walk to idle' ) );
  150. crossFadeControls.push( folder4.add( settings, 'from idle to walk' ) );
  151. crossFadeControls.push( folder4.add( settings, 'from walk to run' ) );
  152. crossFadeControls.push( folder4.add( settings, 'from run to walk' ) );
  153. folder4.add( settings, 'use default duration' );
  154. folder4.add( settings, 'set custom duration', 0, 10, 0.01 );
  155. folder5.add( settings, 'modify idle weight', 0.0, 1.0, 0.01 ).listen().onChange( function ( weight ) {
  156. setWeight( idleAction, weight );
  157. } );
  158. folder5.add( settings, 'modify walk weight', 0.0, 1.0, 0.01 ).listen().onChange( function ( weight ) {
  159. setWeight( walkAction, weight );
  160. } );
  161. folder5.add( settings, 'modify run weight', 0.0, 1.0, 0.01 ).listen().onChange( function ( weight ) {
  162. setWeight( runAction, weight );
  163. } );
  164. folder6.add( settings, 'modify time scale', 0.0, 1.5, 0.01 ).onChange( modifyTimeScale );
  165. folder1.open();
  166. folder2.open();
  167. folder3.open();
  168. folder4.open();
  169. folder5.open();
  170. folder6.open();
  171. }
  172. function showModel( visibility ) {
  173. model.visible = visibility;
  174. }
  175. function showSkeleton( visibility ) {
  176. skeleton.visible = visibility;
  177. }
  178. function modifyTimeScale( speed ) {
  179. mixer.timeScale = speed;
  180. }
  181. function deactivateAllActions() {
  182. actions.forEach( function ( action ) {
  183. action.stop();
  184. } );
  185. }
  186. function activateAllActions() {
  187. setWeight( idleAction, settings[ 'modify idle weight' ] );
  188. setWeight( walkAction, settings[ 'modify walk weight' ] );
  189. setWeight( runAction, settings[ 'modify run weight' ] );
  190. actions.forEach( function ( action ) {
  191. action.play();
  192. } );
  193. }
  194. function pauseContinue() {
  195. if ( singleStepMode ) {
  196. singleStepMode = false;
  197. unPauseAllActions();
  198. } else {
  199. if ( idleAction.paused ) {
  200. unPauseAllActions();
  201. } else {
  202. pauseAllActions();
  203. }
  204. }
  205. }
  206. function pauseAllActions() {
  207. actions.forEach( function ( action ) {
  208. action.paused = true;
  209. } );
  210. }
  211. function unPauseAllActions() {
  212. actions.forEach( function ( action ) {
  213. action.paused = false;
  214. } );
  215. }
  216. function toSingleStepMode() {
  217. unPauseAllActions();
  218. singleStepMode = true;
  219. sizeOfNextStep = settings[ 'modify step size' ];
  220. }
  221. function prepareCrossFade( startAction, endAction, defaultDuration ) {
  222. // Switch default / custom crossfade duration (according to the user's choice)
  223. const duration = setCrossFadeDuration( defaultDuration );
  224. // Make sure that we don't go on in singleStepMode, and that all actions are unpaused
  225. singleStepMode = false;
  226. unPauseAllActions();
  227. // If the current action is 'idle' (duration 4 sec), execute the crossfade immediately;
  228. // else wait until the current action has finished its current loop
  229. if ( startAction === idleAction ) {
  230. executeCrossFade( startAction, endAction, duration );
  231. } else {
  232. synchronizeCrossFade( startAction, endAction, duration );
  233. }
  234. }
  235. function setCrossFadeDuration( defaultDuration ) {
  236. // Switch default crossfade duration <-> custom crossfade duration
  237. if ( settings[ 'use default duration' ] ) {
  238. return defaultDuration;
  239. } else {
  240. return settings[ 'set custom duration' ];
  241. }
  242. }
  243. function synchronizeCrossFade( startAction, endAction, duration ) {
  244. mixer.addEventListener( 'loop', onLoopFinished );
  245. function onLoopFinished( event ) {
  246. if ( event.action === startAction ) {
  247. mixer.removeEventListener( 'loop', onLoopFinished );
  248. executeCrossFade( startAction, endAction, duration );
  249. }
  250. }
  251. }
  252. function executeCrossFade( startAction, endAction, duration ) {
  253. // Not only the start action, but also the end action must get a weight of 1 before fading
  254. // (concerning the start action this is already guaranteed in this place)
  255. setWeight( endAction, 1 );
  256. endAction.time = 0;
  257. // Crossfade with warping - you can also try without warping by setting the third parameter to false
  258. startAction.crossFadeTo( endAction, duration, true );
  259. }
  260. // This function is needed, since animationAction.crossFadeTo() disables its start action and sets
  261. // the start action's timeScale to ((start animation's duration) / (end animation's duration))
  262. function setWeight( action, weight ) {
  263. action.enabled = true;
  264. action.setEffectiveTimeScale( 1 );
  265. action.setEffectiveWeight( weight );
  266. }
  267. // Called by the render loop
  268. function updateWeightSliders() {
  269. settings[ 'modify idle weight' ] = idleWeight;
  270. settings[ 'modify walk weight' ] = walkWeight;
  271. settings[ 'modify run weight' ] = runWeight;
  272. }
  273. // Called by the render loop
  274. function updateCrossFadeControls() {
  275. if ( idleWeight === 1 && walkWeight === 0 && runWeight === 0 ) {
  276. crossFadeControls[ 0 ].disable();
  277. crossFadeControls[ 1 ].enable();
  278. crossFadeControls[ 2 ].disable();
  279. crossFadeControls[ 3 ].disable();
  280. }
  281. if ( idleWeight === 0 && walkWeight === 1 && runWeight === 0 ) {
  282. crossFadeControls[ 0 ].enable();
  283. crossFadeControls[ 1 ].disable();
  284. crossFadeControls[ 2 ].enable();
  285. crossFadeControls[ 3 ].disable();
  286. }
  287. if ( idleWeight === 0 && walkWeight === 0 && runWeight === 1 ) {
  288. crossFadeControls[ 0 ].disable();
  289. crossFadeControls[ 1 ].disable();
  290. crossFadeControls[ 2 ].disable();
  291. crossFadeControls[ 3 ].enable();
  292. }
  293. }
  294. function onWindowResize() {
  295. camera.aspect = window.innerWidth / window.innerHeight;
  296. camera.updateProjectionMatrix();
  297. renderer.setSize( window.innerWidth, window.innerHeight );
  298. }
  299. function animate() {
  300. // Render loop
  301. requestAnimationFrame( animate );
  302. idleWeight = idleAction.getEffectiveWeight();
  303. walkWeight = walkAction.getEffectiveWeight();
  304. runWeight = runAction.getEffectiveWeight();
  305. // Update the panel values if weights are modified from "outside" (by crossfadings)
  306. updateWeightSliders();
  307. // Enable/disable crossfade controls according to current weight values
  308. updateCrossFadeControls();
  309. // Get the time elapsed since the last frame, used for mixer update (if not in single step mode)
  310. let mixerUpdateDelta = clock.getDelta();
  311. // If in single step mode, make one step and then do nothing (until the user clicks again)
  312. if ( singleStepMode ) {
  313. mixerUpdateDelta = sizeOfNextStep;
  314. sizeOfNextStep = 0;
  315. }
  316. // Update the animation mixer, the stats panel, and render this frame
  317. mixer.update( mixerUpdateDelta );
  318. stats.update();
  319. renderer.render( scene, camera );
  320. }
  321. </script>
  322. </body>
  323. </html>