ThreeJS官方案例学习(2)webgl - animation-skinning

<!DOCTYPE html>
<html lang="en">
	<head>
		<title>three.js webgl - animation - skinning</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<link type="text/css" rel="stylesheet" href="main.css">
		<style>
			a {
				color: #f00;
			}
		</style>
	</head>
	<body>
		<div id="container"></div>
		

		<!-- Import maps polyfill -->
		<!-- Remove this when import maps will be widely supported -->
		<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>

		<script type="importmap">
			{
				"imports": {
					"three": "../build/three.module.js",
					"three/addons/": "./jsm/"
				}
			}
		</script>

		<script type="module">

			import * as THREE from 'three';

			import Stats from 'three/addons/libs/stats.module.js';
			import { GUI } from 'three/addons/libs/lil-gui.module.min.js';

			import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

			let scene, renderer, camera, stats;
			let model, skeleton, mixer, clock;

			const crossFadeControls = [];

			let idleAction, walkAction, runAction;
			let idleWeight, walkWeight, runWeight;
			let actions, settings;

			let singleStepMode = false;
			let sizeOfNextStep = 0;
			//初始化
			init();

			function init() {
				//获取文档的元素节点
				const container = document.getElementById( 'container' );
				//建立相机
				camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
				//相机的位置
				camera.position.set( 1, 2, - 3 );
				//设置世界空间中心的位置。
				camera.lookAt( 0, 1, 0 );
				//开启时钟
				clock = new THREE.Clock();
				//开启场景
				scene = new THREE.Scene();
				//设置颜色
				scene.background = new THREE.Color( 0xa0a0a0 );
				//设置颜色渐变
				scene.fog = new THREE.Fog( 0xa0a0a0, 1, 10 );
				//半球光 光源直接放置于场景之上,光照颜色从天空光线颜色渐变到地面光线颜色。
				const hemiLight = new THREE.HemisphereLight( 0xa0a0a0, 0x444444 );
				hemiLight.position.set( 0, 20, 0 );
				scene.add( hemiLight );
				//平行光是沿着特定方向发射的光。这种光的表现像是无限远,从它发出的光线都是平行的
				const dirLight = new THREE.DirectionalLight( 0xffffff );
				dirLight.position.set( - 3, 10, - 10 );
				dirLight.castShadow = true;
				dirLight.shadow.camera.top = 2;
				dirLight.shadow.camera.bottom = - 2;
				dirLight.shadow.camera.left = - 2;
				dirLight.shadow.camera.right = 2;
				dirLight.shadow.camera.near = 0.1;
				dirLight.shadow.camera.far = 40;
				scene.add( dirLight );
				
				//组合一个用于生成平面几何体与一种用于具有镜面高光的光泽表面的材质
				const mesh = new THREE.Mesh( new THREE.PlaneGeometry( 100, 100 ), new THREE.MeshPhongMaterial( { color: 0x999999, depthWrite: false } ) );
				//物体的局部旋转,以弧度来表示
				mesh.rotation.x = - Math.PI / 2;
				//材质是否接收阴影
				mesh.receiveShadow = true;
				scene.add( mesh );
				//用于载入glTF 2.0资源的加载器。
				const loader = new GLTFLoader();
				loader.load( 'models/gltf/Soldier.glb', function ( gltf ) {
					//console.log(gltf);
					model = gltf.scene;
					scene.add( model );
					
					//以一个object3D对象作为第一个参数的函数
					model.traverse( function ( object ) {
						//对象是否被渲染到阴影贴图中
						if ( object.isMesh ) object.castShadow = true;
					} );
					//用来模拟骨骼 Skeleton 的辅助对象
					skeleton = new THREE.SkeletonHelper( model );
					skeleton.visible = false;
					scene.add( skeleton );
					//调用方法
					createPanel();
					//
					const animations = gltf.animations;
					//动画混合器是用于场景中特定对象的动画的播放器。当场景中的多个对象独立动画时,每个对象都可以使用同一个动画混合器。
					mixer = new THREE.AnimationMixer( model );

					idleAction = mixer.clipAction( animations[ 0 ] );
					walkAction = mixer.clipAction( animations[ 3 ] );
					runAction = mixer.clipAction( animations[ 1 ] );
					
					actions = [ idleAction, walkAction, runAction ];

					activateAllActions();

					animate();

				} );
				//用WebGL渲染出你精心制作的场景。
				renderer = new THREE.WebGLRenderer( { antialias: true } );
				//设置设备像素比
				renderer.setPixelRatio( window.devicePixelRatio );
				renderer.setSize( window.innerWidth, window.innerHeight );
				//定义渲染器的输出编码
				renderer.outputEncoding = THREE.sRGBEncoding;
				//允许在场景中使用阴影贴图
				renderer.shadowMap.enabled = true;
				container.appendChild( renderer.domElement );
				//添加性能监视器
				stats = new Stats();
				container.appendChild( stats.dom );
				window.addEventListener( 'resize', onWindowResize );

			}
			//创建调试器GUITAR
			function createPanel() {
				const panel = new GUI( { width: 310 } );
				const folder1 = panel.addFolder( 'Visibility' );
				const folder2 = panel.addFolder( 'Activation/Deactivation' );
				const folder3 = panel.addFolder( 'Pausing/Stepping' );
				const folder4 = panel.addFolder( 'Crossfading' );
				const folder5 = panel.addFolder( 'Blend Weights' );
				const folder6 = panel.addFolder( 'General Speed' );
				settings = {
					'show model': true,
					'show skeleton': false,
					'deactivate all': deactivateAllActions,
					'activate all': activateAllActions,
					'pause/continue': pauseContinue,
					'make single step': toSingleStepMode,
					'modify step size': 0.05,
					'from walk to idle': function () {
						prepareCrossFade( walkAction, idleAction, 1.0 );
					},
					'from idle to walk': function () {
						prepareCrossFade( idleAction, walkAction, 0.5 );
					},
					'from walk to run': function () {
						prepareCrossFade( walkAction, runAction, 2.5 );
					},
					'from run to walk': function () {
						prepareCrossFade( runAction, walkAction, 5.0 );
					},
					'use default duration': true,
					'set custom duration': 3.5,
					'modify idle weight': 0.0,
					'modify walk weight': 1.0,
					'modify run weight': 0.0,
					'modify time scale': 1.0
				};
				folder1.add( settings, 'show model' ).onChange( showModel );
				folder1.add( settings, 'show skeleton' ).onChange( showSkeleton );
				folder2.add( settings, 'deactivate all' );
				folder2.add( settings, 'activate all' );
				folder3.add( settings, 'pause/continue' );
				folder3.add( settings, 'make single step' );
				folder3.add( settings, 'modify step size', 0.01, 0.1, 0.001 );
				crossFadeControls.push( folder4.add( settings, 'from walk to idle' ) );
				crossFadeControls.push( folder4.add( settings, 'from idle to walk' ) );
				crossFadeControls.push( folder4.add( settings, 'from walk to run' ) );
				crossFadeControls.push( folder4.add( settings, 'from run to walk' ) );
				folder4.add( settings, 'use default duration' );
				folder4.add( settings, 'set custom duration', 0, 10, 0.01 );
				folder5.add( settings, 'modify idle weight', 0.0, 1.0, 0.01 ).listen().onChange( function ( weight ) {
					setWeight( idleAction, weight );
				} );
				folder5.add( settings, 'modify walk weight', 0.0, 1.0, 0.01 ).listen().onChange( function ( weight ) {
					setWeight( walkAction, weight );
				} );
				folder5.add( settings, 'modify run weight', 0.0, 1.0, 0.01 ).listen().onChange( function ( weight ) {
					setWeight( runAction, weight );
				} );
				folder6.add( settings, 'modify time scale', 0.0, 1.5, 0.01 ).onChange( modifyTimeScale );
				folder1.open();
				folder2.open();
				folder3.open();
				folder4.open();
				folder5.open();
				folder6.open();

			}
			//显示模型
			function showModel( visibility ) {
				model.visible = visibility;
			}
			//显示骨骼
			function showSkeleton( visibility ) {
				skeleton.visible = visibility;
			}
			//修改时间刻度
			function modifyTimeScale( speed ) {
				mixer.timeScale = speed;
			}
			//禁用所有动作
			function deactivateAllActions() {
				actions.forEach( function ( action ) {
					action.stop();
				} );
			}
			//激活所有动作
			function activateAllActions() {
				setWeight( idleAction, settings[ 'modify idle weight' ] );
				setWeight( walkAction, settings[ 'modify walk weight' ] );
				setWeight( runAction, settings[ 'modify run weight' ] );
				actions.forEach( function ( action ) {
					action.play();
				} );
			}
			//暂停或者继续
			function pauseContinue() {
				if ( singleStepMode ) {
					singleStepMode = false;
					unPauseAllActions();
				} else {
					if ( idleAction.paused ) {
						unPauseAllActions();
					} else {
						pauseAllActions();
					}
				}
			}
			//暂停所有动作
			function pauseAllActions() {
				actions.forEach( function ( action ) {
					action.paused = true;
				} );
			}
			//取消暂停所有动作
			function unPauseAllActions() {
				actions.forEach( function ( action ) {
					action.paused = false;
				} );
			}
			//修改步长
			function toSingleStepMode() {
				unPauseAllActions();
				singleStepMode = true;
				sizeOfNextStep = settings[ 'modify step size' ];
			}

			function prepareCrossFade( startAction, endAction, defaultDuration ) {
				// 切换默认/自定义交叉渐变持续时间(根据用户选择)
				const duration = setCrossFadeDuration( defaultDuration );
				// 确保我们不在singleStepMode中继续,并且所有的动作都是未暂停的
				singleStepMode = false;
				unPauseAllActions();
				// 如果当前动作是“空闲”(持续时间4秒),立即执行;否则等待当前动作完成当前循环
				if ( startAction === idleAction ) {
					executeCrossFade( startAction, endAction, duration );
				} else {
					synchronizeCrossFade( startAction, endAction, duration );
				}
			}
			// 开关默认横向渐隐时间<->自定义横向渐隐时间
			function setCrossFadeDuration( defaultDuration ) {
				if ( settings[ 'use default duration' ] ) {
					return defaultDuration;
				} else {
					return settings[ 'set custom duration' ];
				}
			}
			//待当前动作完成当前循环
			function synchronizeCrossFade( startAction, endAction, duration ) {
				mixer.addEventListener( 'loop', onLoopFinished );
				function onLoopFinished( event ) {
					if ( event.action === startAction ) {
						mixer.removeEventListener( 'loop', onLoopFinished );
						executeCrossFade( startAction, endAction, duration );
					}
				}
			}
			//执行动作
			function executeCrossFade( startAction, endAction, duration ) {
				setWeight( endAction, 1 );
				endAction.time = 0;
				startAction.crossFadeTo( endAction, duration, true );

			}

			// This function is needed, since animationAction.crossFadeTo() disables its start action and sets
			// the start action's timeScale to ((start animation's duration) / (end animation's duration))

			function setWeight( action, weight ) {

				action.enabled = true;
				action.setEffectiveTimeScale( 1 );
				action.setEffectiveWeight( weight );

			}

			// Called by the render loop
			function updateWeightSliders() {

				settings[ 'modify idle weight' ] = idleWeight;
				settings[ 'modify walk weight' ] = walkWeight;
				settings[ 'modify run weight' ] = runWeight;

			}
			// Called by the render loop
			function updateCrossFadeControls() {
				if ( idleWeight === 1 && walkWeight === 0 && runWeight === 0 ) {
					crossFadeControls[ 0 ].disable();
					crossFadeControls[ 1 ].enable();
					crossFadeControls[ 2 ].disable();
					crossFadeControls[ 3 ].disable();
				}
				if ( idleWeight === 0 && walkWeight === 1 && runWeight === 0 ) {
					crossFadeControls[ 0 ].enable();
					crossFadeControls[ 1 ].disable();
					crossFadeControls[ 2 ].enable();
					crossFadeControls[ 3 ].disable();
				}
				if ( idleWeight === 0 && walkWeight === 0 && runWeight === 1 ) {
					crossFadeControls[ 0 ].disable();
					crossFadeControls[ 1 ].disable();
					crossFadeControls[ 2 ].disable();
					crossFadeControls[ 3 ].enable();
				}
			}

			function onWindowResize() {
				camera.aspect = window.innerWidth / window.innerHeight;
				camera.updateProjectionMatrix();
				renderer.setSize( window.innerWidth, window.innerHeight );
			}

			function animate() {
				// Render loop
				requestAnimationFrame( animate );
				idleWeight = idleAction.getEffectiveWeight();
				walkWeight = walkAction.getEffectiveWeight();
				runWeight = runAction.getEffectiveWeight();
				// Update the panel values if weights are modified from "outside" (by crossfadings)
				updateWeightSliders();
				// Enable/disable crossfade controls according to current weight values
				updateCrossFadeControls();
				// Get the time elapsed since the last frame, used for mixer update (if not in single step mode)
				let mixerUpdateDelta = clock.getDelta();
				// If in single step mode, make one step and then do nothing (until the user clicks again)
				if ( singleStepMode ) {
					mixerUpdateDelta = sizeOfNextStep;
					sizeOfNextStep = 0;
				}
				// Update the animation mixer, the stats panel, and render this frame
				mixer.update( mixerUpdateDelta );
				stats.update();
				renderer.render( scene, camera );
			}

		</script>

	</body>
</html>

你可能感兴趣的:(ThreeJS,学习,webgl)