three.js官方案例(animation / skinning / additive / blendin)animation_skinning_additive_blending.html学习记录

       

目录

1 SkeletonHelper

1.1构造函数

1.2 属性

2 打印model和animals及动作数量

3 动画部分分析

3.1 AnimationUtils

3.2 UI处理动画切换逻辑

3.2.1 基础动画部分

​编辑

3.2.2 附加动作部分

3.2.3 速度

3.3 AnimationClip

3.4 AnimationAction

5 全部脚本加注释


这一篇的主要是介绍用到的SkeletonHelper(模拟骨骼),AnimationUtils(一个提供各种动画辅助方法的对象),本片案例的重点在于动画处理部分。

1 SkeletonHelper

用来模拟骨骼 Skeleton 的辅助对象. 该辅助对象使用 LineBasicMaterial 材质

1.1构造函数

SkeletonHelper( object : Object3D )

object -- 通常是 SkinnedMesh的实例. 实际上, 只要子级存在Bones的任何 Object3D 的实例都可以,(参考 Object3D.children).

1.2 属性

.bones : Array

辅助对象使用 Lines 渲染的骨数组.

.isSkeletonHelper : Boolean

只读属性,用以检查该给定对象是否是 SkeletonHelper.

.root : Object3D

构造函数传入的对象.

2 打印model和animals及动作数量

  console.log(model);

  console.log(animations);

可以看到包含了7个动画。

3 动画部分分析

3.1 AnimationUtils

一个提供各种动画辅助方法的对象,内部使用。(附加动画脚本处用到了THREE.AnimationUtils的makeClipAdditive方法和subclip方法)

.makeClipAdditive ( targetClip : AnimationClip, referenceFrame : Number, referenceClip : AnimationClip, fps : Number ) : AnimationClip

将给定动画剪辑的关键帧转换为加法格式。

.subclip ( clip : AnimationClip, name : String, startFrame : Number, endFrame : Number, fps : Number ) : AnimationClip

创建一个新的片段,仅包含所给定帧之间的原始剪辑片段。

3.2 UI处理动画切换逻辑

3.2.1 基础动画部分

console.log(Object.keys( baseActions ));

 console.log(panelSettings);

3.2.2 附加动作部分

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

3.3 AnimationClip

动画剪辑(AnimationClip)是一个可重用的关键帧轨道集,它代表动画。

3.4 AnimationAction

AnimationActions 用来调度存储在AnimationClips中的动画。

说明: AnimationAction的大多数方法都可以链式调用

5 全部脚本加注释

<!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="../three.js-r163/examples/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": "../three.js-r163//build/three.module.js",
					"three/addons/": "../three.js-r163/examples//jsm/"
				}
			}
		</script>

		<script type="module">

			import * as THREE from 'three';
            //性能检测
			import Stats from 'three/addons/libs/stats.module.js';
            //UI 
			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;
            //模型, 骨骼辅助对象,动画混合器 , clock对象用于跟踪时间
			let model, skeleton, mixer, clock;
            //交叉淡入淡出控件组
			const crossFadeControls = [];
            //当前基础动作
			let currentBaseAction = 'idle';

			//AnimationObjectGroup  接收共享动画状态的一组对象
            //所有动作  
			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 );
				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;
				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 );

				// ground 地面

				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;
				scene.add( mesh );
                //模型加载
				const loader = new GLTFLoader();
				loader.load( '../three.js-r163/examples/models/gltf/Xbot.glb', function ( gltf ) {
                  
					model = gltf.scene;
					scene.add( model );
                    console.log(model);
					model.traverse( function ( object ) {

						if ( object.isMesh ) object.castShadow = true;//对象是否被渲染到阴影贴图中

					} );
                    //用来模拟骨骼 Skeleton 的辅助对象. 该辅助对象使用 LineBasicMaterial 材质
					skeleton = new THREE.SkeletonHelper( model );
					skeleton.visible = false;//先不显示
					scene.add( skeleton );
                    //动画
					const animations = gltf.animations;
                    console.log(animations);
					mixer = new THREE.AnimationMixer( model );

					numAnimations = animations.length;
                    console.log(numAnimations);
					for ( let i = 0; i !== numAnimations; ++ i ) {

						let clip = animations[ i ];
						const name = clip.name;
                        //如果是基础动作
						if ( baseActions[ name ] ) {

							const action = mixer.clipAction( clip );//返回所传入的剪辑参数的AnimationAction
                            //AnimationActions 用来调度存储在AnimationClips中的动画
							activateAction( action );
							baseActions[ name ].action = action;
							allActions.push( action );

						} 
                         //如果是附加动作
                        else if ( additiveActions[ name ] ) {

							// Make the clip additive and remove the reference frame
                             //一个提供各种动画辅助方法的对象,内部使用
                             //动画剪辑  将给定动画片段的关键帧转换为附加格式。
							THREE.AnimationUtils.makeClipAdditive( clip );

							if ( clip.name.endsWith( '_pose' ) ) {
                               // 动画剪辑   创建一个新片段,仅包含给定帧之间原始片段的片段。 开始帧 结束帧  帧数
							   //创建一个新的片段,仅包含所给定帧之间的原始剪辑片段
								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;
				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.target.set( 0, 1, 0 );
				controls.update();
                //性能检测
				stats = new Stats();
				container.appendChild( stats.dom );
                //窗口大小监听
				window.addEventListener( 'resize', onWindowResize );
			}

            //UI 面板  操作动画
			function createPanel() {

				const panel = new GUI( { width: 310 } );

                const folder0= panel.addFolder( '骨骼' );//

				const folder1 = panel.addFolder( 'Base Actions' );//基础动画部分
				const folder2 = panel.addFolder( 'Additive Action Weights' ); //附加的动作
				const folder3 = panel.addFolder( 'General Speed' ); //速度

			    folder0.add(skeleton,'visible',false);

				panelSettings = {
					'modify time scale': 1.0
				}; //
                console.log(Object.keys( baseActions ));
				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 );

						}

					};
                     
					//console.log(folder1.add( panelSettings, name));
					crossFadeControls.push( folder1.add( panelSettings, name) );//放入数组					
				}
				panelSettings['测试']=function(){
					console.log("测试");	
					//executeCrossFade(baseActions[currentBaseAction].action,baseActions['run'].action,0.35);
					//prepareCrossFade(baseActions[currentBaseAction].action,baseActions['run'].action,0.35);
				}	
				folder1.add( panelSettings, '测试')			 
				//crossFadeControls.push(folder1.add( panelSettings, '测试'));
                //附加动作部分
				for ( const name of Object.keys( additiveActions ) ) {

					const settings = additiveActions[ name ];

					panelSettings[ name ] = settings.weight;
					folder2.add( panelSettings, name, 0.0, 1.0, 0.01 ).listen().onChange( function ( weight ) {

						setWeight( settings.action, weight );//设置权重
						settings.weight = weight;//动作的影响程度 (取值范围[0, 1]). 0 (无影响)到1(完全影响)之间的值可以用来混合多个动作。默认值是1

					} );

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

				 //console.log(panelSettings);

				folder1.open();
				folder2.open();
				folder3.open();

				//控制文字明暗
				crossFadeControls.forEach( function ( control ) {
                   //绑定setInactive方法  暗
					control.setInactive = function () {
                        //console.log( control, 11);
						control.domElement.classList.add( 'control-inactive' );

					};
                    //绑定setActive方法  明
					control.setActive = function () {
						//console.log(control,22);
						control.domElement.classList.remove( 'control-inactive' ); 

					};

					const settings = baseActions[ control.property ];//获取每个基础动作

                    console.log( control.property, ! settings || ! settings.weight );
					if ( ! settings || ! settings.weight ) {
						//console.log(control,33);
						control.setInactive();//设置为暗
					}

				} );

			}
            //AnimationActions 用来调度存储在AnimationClips中的动画
			function activateAction( action ) {
           //getClip () : AnimationClip返回存有此动作的动画数据的剪辑
				const clip = action.getClip();
				const settings = baseActions[ clip.name ] || additiveActions[ clip.name ];
                //设置权重
				setWeight( action, settings.weight );
				action.play();//播放动作

			}

			function modifyTimeScale( speed ) {

				mixer.timeScale = speed;

			}

			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;//property属性  获取对应的动画名称
                     //当前动画
					if ( name === currentBaseAction ) {
                        console.log(name +'亮');
						control.setActive();//亮

					} else {

						control.setInactive();//文字变暗

					}

				} );

			}
            //同步淡入淡出
			function synchronizeCrossFade( startAction, endAction, duration ) {

				mixer.addEventListener( 'loop', onLoopFinished );//循环

				function onLoopFinished( event ) {

					if ( event.action === startAction ) {

						mixer.removeEventListener( 'loop', onLoopFinished );//移除startAction监听

						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)
				//不仅开始动作,结束动作的权重也必须为1
//(关于启动动作,这个地方已经保证了)

				if ( endAction ) {

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

					if ( startAction ) {

						// Crossfade with warping  淡入淡出
						//在传入的时间段内, 让此动作淡出(fade out),同时让另一个动作淡入。此方法可链式调用。
                        //如果warpBoolean值是true, 额外的 warping (时间比例的渐变)将会被应用。
                        //说明: 与 fadeIn/fadeOut一样, 淡入淡出动作开始/结束时的权重是1.
						startAction.crossFadeTo( endAction, duration, true );//个人理解是startAction谈出   endAction淡入

					} else {

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

					}

				} else {

					// Fade out
					//在传入的时间间隔内,逐渐将此动作的权重(weight)由1降至0。此方法可链式调用
					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))
//这个函数是必需的,因为animationAction.crossFadeTo()会禁用它的开始动作和设置
//开始动作的时间刻度到((开始动画的持续时间)/(结束动画的持续时间))
			function setWeight( action, weight ) {

				action.enabled = true;
                //.setEffectiveTimeScale ( timeScale : Number ) : this
//设置时间比例(timeScale)以及停用所有的变形)。 此方法可以链式调用。
//如果暂停 (paused)值为false, 有效的时间比例(一个内部属性) 也会被设为该值; 否则有效时间比例 (直接影响当前动画 将会被设为0.
//说明: 如果时间比例.timeScale 被此方法设为0,暂停值paused不会被自动改为true。
				action.setEffectiveTimeScale( 1 );
                //.setEffectiveWeight ( weight : Number ) : this
//设置权重(weight)以及停止所有淡入淡出。该方法可以链式调用。
//如果启用属性(enabled)为true, 那么有效权重(一个内部属性) 也会被设为该值; 否则有效权重 (直接影响当前动画)将会被设为0.
//说明: 如果该方法将权重weight值设为0,启用值enabled不会被自动改为false。
				action.setEffectiveWeight( weight );

			}

			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>

  • 27
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hemy1989

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值