threejs官方demo解析(二)

发布时间:2024年01月17日

效果图:
在这里插入图片描述
代码解析:

<!DOCTYPE html>
<html lang="en">
	<head>
		<title>three.js webgl - additive 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: blue;
			}
			.control-inactive button {
				color: #888;
			}
		</style>
	</head>
	<body>
		<div id="container"></div>
		<div id="info">
			<a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - Skeletal Additive Animation Blending
			(model from <a href="https://www.mixamo.com/" target="_blank" rel="noopener">mixamo.com</a>)<br/>
		</div>

		<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 { OrbitControls } from 'three/addons/controls/OrbitControls.js'; 
			import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

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

			const crossFadeControls = [];

			let currentBaseAction = 'idle';
			const allActions = [];
			const baseActions = { //第一个控制面板的值
				idle: { weight: 1 },
				walk: { weight: 0 },
				run: { weight: 0 }
			};
			const additiveActions = {  //添加到右上角交互的选项
				sneak_pose: { weight: 0 },
				sad_pose: { weight: 0 },
				agree: { weight: 0 },
				headShake: { weight: 0 }
			};
			let panelSettings, numAnimations;

			init();

			function init() {

				const container = document.getElementById( 'container' );
				clock = new THREE.Clock();

				scene = new THREE.Scene();
				scene.background = new THREE.Color( 0xa0a0a0 );
				/*
				1. 线性雾,密度随着距离的增加呈线性增长。参数为:雾的颜色,开始的地方,浓度的加深程度。
				scene.fog = new THREE.Fog(0xffffff, 0.015, 100); 

				2.指数雾,密度随距离呈指数级增长。参数为:雾的颜色,浓度
				scene.fog = new THREE. FogExp2 (0xffffff, 0.015);
				*/
				scene.fog = new THREE.Fog( 0xa0a0a0, 10, 50 ); //雾化效果,可以渲染出一层雾气,隐层远处的的物体,

				const hemiLight = new THREE.HemisphereLight( 0xffffff, 0x8d8d8d, 3 ); //半球光,从天空到地面两个颜色之间的渐变,与物体材质的颜色作叠加后得到最终的颜色效果。
				hemiLight.position.set( 0, 20, 0 );
				scene.add( hemiLight );

				const dirLight = new THREE.DirectionalLight( 0xffffff, 3 );//方向光,常常用来表现太阳光照的效果。(颜色,强度)
				dirLight.position.set( 3, 10, 10 );
				dirLight.castShadow = true; //此属性设置为 true 灯光将投射阴影,需要通过调整让阴影看起来正确。 (代价比较高)

				// 设置一些shadow属性来正确的显示模型的阴影
				dirLight.shadow.camera.top = 2;
				dirLight.shadow.camera.bottom = - 2;  //.shadow对象,用于计算该平行光产生的阴影
				dirLight.shadow.camera.left = - 2;
				dirLight.shadow.camera.right = 2;
				dirLight.shadow.camera.near = 0.1;
				dirLight.shadow.camera.far = 40;
				scene.add( dirLight );

				// ground

				/*
					PlaneGeometry:生成平面几何体的类
					MeshPhongMaterial:具有镜面高光的光泽表面的材质
				*/
				const mesh = new THREE.Mesh( new THREE.PlaneGeometry( 100, 100 ), new THREE.MeshPhongMaterial( { color: 0xcbcbcb, depthWrite: false } ) );  //生成的是视觉上的地面
				mesh.rotation.x = - Math.PI / 2;  //改变角度
				mesh.receiveShadow = true; //设置接收阴影效果的模型   对应castShadow:产生阴影的模型(该demo中应该让引入的人体模型设置castShadow)
				scene.add( mesh );

				const loader = new GLTFLoader();
				loader.load( 'models/gltf/Xbot.glb', function ( gltf ) { //引入模型

					model = gltf.scene;
					scene.add( model );

					model.traverse( function ( object ) {  //遍历模型所有节点设置可以产生阴影
						if ( object.isMesh ) object.castShadow = true; //可以产生阴影

					} );

					skeleton = new THREE.SkeletonHelper( model ); // SkeletonHelper会可视化参数模型对象所包含的所有骨骼关节,从效果上本demo里面实是骨骼的连接线
					skeleton.visible = false;
					scene.add( skeleton );

					const animations = gltf.animations; //获取动画,模型中带了动画(包括idle、run等,即设定的baseActions)

					console.log(animations,'animations===')
					mixer = new THREE.AnimationMixer( model );//动画帧播放器

					numAnimations = animations.length;

					for ( let i = 0; i !== numAnimations; ++ i ) {

						let clip = animations[ i ]; //遍历模型动画
						const name = clip.name;//动画名称

						if ( baseActions[ name ] ) {
							const action = mixer.clipAction( clip ); //动画对象
							activateAction( action );
							baseActions[ name ].action = action; //baseActions添加上我们模型中的动画
							allActions.push( action );

						} else if ( additiveActions[ name ] ) {//同样的给additiveActions 赋值上动画

							// Make the clip additive and remove the reference frame

							//将给定动画剪辑的关键帧转换为附加格式。
							THREE.AnimationUtils.makeClipAdditive( clip );

							if ( clip.name.endsWith( '_pose' ) ) {
							// subclip:创建一个新的片段,仅包含所给定帧之间的原始剪辑片段。.subclip ( clip : AnimationClip, name : String, startFrame : Number, endFrame : Number, fps : Number ) : AnimationClip
							// 去掉这行,可以看到我们改变Pose的时候任人物一直抖动 应该是从模型中的动画帧中取出了2-3的动画帧(取1-2发现人物是站直没有变化,说明模型给的动画是站直和弯下的连续动画,所以取出弯下的动画帧)
								clip = THREE.AnimationUtils.subclip( clip, clip.name, 2, 3, 30 );

							}

							const action = mixer.clipAction( clip );
							activateAction( action );  //赋值前对动画帧进行处理,设置属性时间等属性
							additiveActions[ name ].action = action;//赋值
							allActions.push( action );

						}

					}

					createPanel(); //创建右上角的控制面板,调试器

					animate(); //动画

				} );

				renderer = new THREE.WebGLRenderer( { antialias: true } );
				renderer.setPixelRatio( window.devicePixelRatio );
				renderer.setSize( window.innerWidth, window.innerHeight );
				renderer.shadowMap.enabled = true; //显示阴影,设置为false,则不显示阴影了
				container.appendChild( renderer.domElement );

				// camera
				camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 100 );
				camera.position.set( - 1, 2, 3 );

				const controls = new OrbitControls( camera, renderer.domElement );
				controls.enablePan = false;//禁止右键拖拽
				controls.enableZoom = false;//禁止缩放
				// controls.enableRotate = false; //禁止旋转
				controls.target.set( 0, 1, 0 ); //对应的就是相机的.lookAt()观察目标,
				controls.update(); //相机空间内部会执行camera.lookAt(controls.target)

				stats = new Stats(); //性能监视器,可以看到帧率
				container.appendChild( stats.dom );

				window.addEventListener( 'resize', onWindowResize );

			}

			function createPanel() {

				const panel = new GUI( { width: 310 } );//调试器

				// 创建右上角的调试器分组,可以看到分为三组
				const folder1 = panel.addFolder( 'Base Actions' );  //.addFolder创建一个分组,可以将同一对象的属性创建在同一个分组中
				const folder2 = panel.addFolder( 'Additive Action Weights' );
				const folder3 = panel.addFolder( 'General Speed' );

				panelSettings = {
					'modify time scale': 1.0
				};

				const baseNames = [ 'None', ...Object.keys( baseActions ) ]; 

				for ( let i = 0, l = baseNames.length; i !== l; ++ i ) {

					const name = baseNames[ i ];
					const settings = baseActions[ name ];
					panelSettings[ name ] = function () { //直接设置的动画,所以点击的时候就运行动画了不用监听

						const currentSettings = baseActions[ currentBaseAction ];
						const currentAction = currentSettings ? currentSettings.action : null;
						const action = settings ? settings.action : null;

						if ( currentAction !== action ) {

							prepareCrossFade( currentAction, action, 0.35 ); 

						}

					};

					
					crossFadeControls.push( folder1.add( panelSettings, name ) ); //第一个面板的每个按钮都添加到里面

				}

				for ( const name of Object.keys( additiveActions ) ) {

					const settings = additiveActions[ name ];

					panelSettings[ name ] = settings.weight;
					//添加控制面板,并监听change事件
					folder2.add( panelSettings, name, 0.0, 1.0, 0.01 ).listen().onChange( function ( weight ) {

						setWeight( settings.action, weight );
						settings.weight = weight;

					} );

				}

				folder3.add( panelSettings, 'modify time scale', 0.0, 1.5, 0.01 ).onChange( modifyTimeScale );

				folder1.open();//展开状态
				folder2.open();
				folder3.open();

				crossFadeControls.forEach( function ( control ) {//注:gui控制面板是正常元素,不是canvas

					control.setInactive = function () {  //没选中的元素设置类名

						control.domElement.classList.add( 'control-inactive' );

					};

					control.setActive = function () {//选中的时候移除类名

						control.domElement.classList.remove( 'control-inactive' );

					};

					const settings = baseActions[ control.property ];

					if ( ! settings || ! settings.weight ) {

						control.setInactive();

					}

				} );



			}

			function activateAction( action ) {

				const clip = action.getClip(); //返回存有此动作的动画数据的剪辑
				const settings = baseActions[ clip.name ] || additiveActions[ clip.name ];
				setWeight( action, settings.weight );//给动画设置权重等属性
				action.play();

			}

			function modifyTimeScale( speed ) {

				mixer.timeScale = speed; //时间(time)的比例因子. 值为0时会使动画暂停。值为负数时动画会反向执行。默认值是1。


			}
				/*

				*/
			function prepareCrossFade( startAction, endAction, duration ) {

				// If the current action is 'idle', execute the crossfade immediately;
				// else wait until the current action has finished its current loop
				//如果当前动作为'idle',立即执行crossfade;
				//否则等待当前动作完成当前循环

				if ( currentBaseAction === 'idle' || ! startAction || ! endAction ) {

					executeCrossFade( startAction, endAction, duration ); //设置淡入淡出效果

				} else {

					synchronizeCrossFade( startAction, endAction, duration );

				}

				// Update control colors

				if ( endAction ) {

					const clip = endAction.getClip();
					currentBaseAction = clip.name;

				} else {

					currentBaseAction = 'None';

				}

				//给第一个控制面板的设置激活状态
				crossFadeControls.forEach( function ( control ) {
					

					const name = control.property;

					if ( name === currentBaseAction ) {

						control.setActive();

					} else {

						control.setInactive();

					}

				} );

			}

			function synchronizeCrossFade( startAction, endAction, duration ) {

				mixer.addEventListener( 'loop', onLoopFinished );//这个动作结束调用onLoopFinished

				function onLoopFinished( event ) {

					if ( event.action === startAction ) {

						mixer.removeEventListener( 'loop', onLoopFinished );

						executeCrossFade( startAction, endAction, duration );

					}

				}

			}

			function executeCrossFade( startAction, endAction, duration ) {

				// Not only the start action, but also the end action must get a weight of 1 before fading
				// (concerning the start action this is already guaranteed in this place)

				if ( endAction ) {

					setWeight( endAction, 1 );
					endAction.time = 0;

					if ( startAction ) {

						// Crossfade with warping
						// 在传入的时间段内,让此动作淡出,同时让另外一个动作淡入
						startAction.crossFadeTo( endAction, duration, true );

					} else {

						// Fade in
					//在传入的时间间隔内,逐渐将此动作的权重(weight)由0升到1。淡入
						endAction.fadeIn( duration );

					}

				} else {

					// Fade out
					//淡出
					startAction.fadeOut( duration );

				}

			}

			// 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 ) {
				// 相关参数解释地址:http://localhost:8080/docs/?q=setWeight#api/zh/animation/AnimationAction.getEffectiveWeight
				action.enabled = true; //如果改成false 那么我们改变weights可以看到没有变化
				action.setEffectiveTimeScale( 1 ); //设置时间比例
				/*
				如果启用属性(enabled)为true, 那么有效权重(一个内部属性) 也会被设为该值; 否则有效权重 (直接影响当前动画)将会被设为0
				启用值enabled不会被自动改为false。
				enabled:设置为false,会禁用动作,true允许动作
				*/
				action.setEffectiveWeight( weight );//设置权重,权重:动作的影响程度,0-1 可以用来混合多个动作,默认值为1

			}

			function onWindowResize() {

				camera.aspect = window.innerWidth / window.innerHeight;
				camera.updateProjectionMatrix();

				renderer.setSize( window.innerWidth, window.innerHeight );

			}

			// 动画
			function animate() {

				// Render loop

				requestAnimationFrame( animate );

				for ( let i = 0; i !== numAnimations; ++ i ) {

					const action = allActions[ i ];
					const clip = action.getClip();
					const settings = baseActions[ clip.name ] || additiveActions[ clip.name ];
					settings.weight = action.getEffectiveWeight();

				}

				// Get the time elapsed since the last frame, used for mixer update

				const mixerUpdateDelta = clock.getDelta();

				// Update the animation mixer, the stats panel, and render this frame

				mixer.update( mixerUpdateDelta );

				stats.update();

				renderer.render( scene, camera );

			}

		</script>

	</body>
</html>
文章来源:https://blog.csdn.net/Pure_White520/article/details/135654647
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。