初探Threejs

4 篇文章 0 订阅
这是从 three.js官网上的 (model from mixamo.com)copy下来的代码,加了自己的注释!应该算半个原创吧~
	<script type="module">

		import * as THREE from '../build/three.module.js';

		import Stats from './jsm/libs/stats.module.js';//帧率
		import { GUI } from './jsm/libs/dat.gui.module.js';//GUI界面

		import { GLTFLoader } from './jsm/loaders/GLTFLoader.js';//3d模型导入插件

		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, 10, 50 );

			const hemiLight = new THREE.HemisphereLight( 0xffffff, 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;// 产生动态阴影
			//阴影产生面积(left — 摄像机视锥体左侧面。
           // right — 摄像机视锥体右侧面。
           // top — 摄像机视锥体上侧面。
           // bottom — 摄像机视锥体下侧面。)
			dirLight.shadow.camera.top = 2;
			dirLight.shadow.camera.bottom = - 2;
			dirLight.shadow.camera.left = - 2;
			dirLight .shadow.camera.right = 2;			
            // near — 摄像机视锥体近端面。
            // far — 摄像机视锥体远端面。
			dirLight.shadow.camera.near = 0.1;
			dirLight.shadow.camera.far = 40;
			scene.add( dirLight );
			// scene.add( new THREE.CameraHelper( dirLight.shadow.camera ) );

			// ground


            //PlaneGeometry(平面几何体)  MeshPhongMaterial(一种用于具有镜面高光的光泽表面的材质)
			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 );

			const loader = new GLTFLoader();
			loader.load( 'models/gltf/Soldier.glb', function ( gltf ) {
				
				model = gltf.scene;
				scene.add( model );

				model.traverse( function ( object ) {
					if ( object.isMesh ) object.castShadow = true;

				} );

				//

				skeleton = new THREE.SkeletonHelper( model );//骨骼材质
				skeleton.visible = false;
				scene.add( skeleton );

				//

				createPanel();


				//

				const animations = gltf.animations;//model导入的动画,为一个数组对象

				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();
			} );

			renderer = new THREE.WebGLRenderer( { antialias: true } );//WebGRL渲染图形,antialias为抗锯齿属性
			renderer.setPixelRatio( window.devicePixelRatio );//设置设备像素比,window.devicePixelRatio为浏览器的像素属性
			renderer.setSize( window.innerWidth, window.innerHeight );
			renderer.outputEncoding = THREE.sRGBEncoding;//将render颜色渲染模式从linear转化成sRGBEncoding(色差补偿)(Gamma矫正)  https://cloud.tencent.com/developer/article/1543647
			renderer.shadowMap.enabled = true;//使用阴影贴图
			container.appendChild( renderer.domElement );

			stats = new Stats();
			container.appendChild( stats.dom );

			window.addEventListener( 'resize', onWindowResize );

		}
		//GUI配置

		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();

			crossFadeControls.forEach( function ( control ) {

				control.classList1 = control.domElement.parentElement.parentElement.classList;
				control.classList2 = control.domElement.previousElementSibling.classList;

				control.setDisabled = function () {

					control.classList1.add( 'no-pointer-events' );
					control.classList2.add( 'control-disabled' );

				};

				control.setEnabled = function () {

					control.classList1.remove( 'no-pointer-events' );
					control.classList2.remove( 'control-disabled' );

				};

			} );

		}


		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 ) {

			// Switch default / custom crossfade duration (according to the user's choice)

			const duration = setCrossFadeDuration( defaultDuration );

			// Make sure that we don't go on in singleStepMode, and that all actions are unpaused

			singleStepMode = false;
			unPauseAllActions();

			// If the current action is 'idle' (duration 4 sec), execute the crossfade immediately;
			// else wait until the current action has finished its current loop

			if ( startAction === idleAction ) {

				executeCrossFade( startAction, endAction, duration );

			} else {

				synchronizeCrossFade( startAction, endAction, duration );

			}

		}

		function setCrossFadeDuration( defaultDuration ) {

			// Switch default crossfade duration <-> custom crossfade duration

			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 ) {

			// 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)

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

			// Crossfade with warping - you can also try without warping by setting the third parameter to false

			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() {

			crossFadeControls.forEach( function ( control ) {

				control.setDisabled();

			} );

			if ( idleWeight === 1 && walkWeight === 0 && runWeight === 0 ) {

				crossFadeControls[ 1 ].setEnabled();

			}

			if ( idleWeight === 0 && walkWeight === 1 && runWeight === 0 ) {

				crossFadeControls[ 0 ].setEnabled();
				crossFadeControls[ 2 ].setEnabled();

			}

			if ( idleWeight === 0 && walkWeight === 0 && runWeight === 1 ) {

				crossFadeControls[ 3 ].setEnabled();

			}

		}

		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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值