欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

three.js 04-06 之 MeshLambertMaterial 材质

程序员文章站 2024-03-16 21:51:40
...

    关于 three.js 库中的基础材质类型基本上就已经介绍完了。本篇开始介绍 three.js 库中提供的高级材质。例如比较常用的 MeshPhongMaterial 和 MeshLambertMaterial 两种材质。以及另一种最通用,但却最难用的 ShaderMaterial 材质,通过它,你可以创建自己的着色程序、定义材质以及物体如何显示等。

    我们先来看看 MeshLambertMaterial 这种用于暗淡、不光亮表面的材质。这种材质会对光源产生反应。这种材质除了前面提到的 color、opacity、transparent、flatShading、blending、depthTest、depthWrite、wirreframe、wireframeLinewidth、wireframeLinecap、wireframeLinejoin、vertexColors 及 fog 等属性外,还有两个比较特殊的 ambient 及 emissive 属性,具体参考如下表所示描述:

属性 描述
ambient (环境光颜色) 这仅仅是该材质的环境色。跟之前提到过的 AmbientLight 光源一起使用。这个颜色会与 AmbientLight 光源的颜色相乘。默认为白色
emissive (自发光颜色) 这个是材质自发光的颜色。它其实并不像一个光源,只是一种不受光源照射影响的纯粹的颜色
这个材质创建的方法跟其他材质创建的方法基本无异,所以不再嗷述。下面给出一个具体的示例,代码如下:

<!DOCTYPE html>
<html>
<head>
    <title>示例 04.06 - MeshLambertMaterial</title>
	<script src="../build/three.js"></script>
	<script src="../build/js/controls/OrbitControls.js"></script>
	<script src="../build/js/libs/stats.min.js"></script>
	<script src="../build/js/libs/dat.gui.min.js"></script>
	<script src="../jquery/jquery-3.2.1.min.js"></script>
    <style>
        body {
            /* 设置 margin 为 0,并且 overflow 为 hidden,来完成页面样式 */
            margin: 0;
            overflow: hidden;
        }
		/* 统计对象的样式 */
		#Stats-output {
			position: absolute;
			left: 0px;
			top: 0px;
		}
    </style>
</head>
<body>

<!-- 用于 WebGL 输出的 Div -->
<div id="webgl-output"></div>
<!-- 用于统计 FPS 输出的 Div -->
<div id="stats-output"></div>

<!-- 运行 Three.js 示例的 Javascript 代码 -->
<script type="text/javascript">

	var scene;
	var camera;
	var render;
	var webglRender;
	var canvasRender;
	var controls;
	var stats;
	var guiParams;
	
	var ground;
	var cube;
	var sphere;
	var plane;
	var activeMesh;
	
	var meshMaterial;
	
	var ambientLight;
	var spotLight;
	var cameraHelper;

    $(function() {
		stats = initStats();
		scene = new THREE.Scene();
		
		webglRender = new THREE.WebGLRenderer( {antialias: true, alpha: true} ); // antialias 抗锯齿
		webglRender.setSize(window.innerWidth, window.innerHeight);
		webglRender.setClearColor(0xeeeeee, 1.0);
		webglRender.shadowMap.enabled = true; // 允许阴影投射
		render = webglRender;
		
		camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 30, 1000); // 2147483647
		camera.position.set(-45.5, 68.2, 90.9);
		
		var target = new THREE.Vector3(0, 0 , 0);
		controls = new THREE.OrbitControls(camera, render.domElement);
		controls.target = target;
		camera.lookAt(target);
		
		$('#webgl-output')[0].appendChild(render.domElement);
		window.addEventListener('resize', onWindowResize, false);
		
		ambientLight = new THREE.AmbientLight(0x0c0c0c);
		scene.add(ambientLight);
		
		spotLight = new THREE.SpotLight(0xffffff);
        spotLight.position.set(-30, 60, 60);
        spotLight.castShadow = true;
        scene.add(spotLight);
		cameraHelper = new THREE.CameraHelper(spotLight.shadow.camera);
		scene.add(cameraHelper);
		
		// 加入一个平面
		var groundGeometry = new THREE.PlaneGeometry(100, 100, 4, 4);
		var groundMaterial = new THREE.MeshBasicMaterial({color: 0x777777});
		ground = new THREE.Mesh(groundGeometry, groundMaterial);
		ground.rotation.set(-0.5 * Math.PI, 0, 0); // 沿着 X轴旋转-90°
		scene.add(ground);
		
		// 定义 cube, sphere, plane
        var cubeGeometry = new THREE.BoxGeometry(15, 15, 15);
		var sphereGeometry = new THREE.SphereGeometry(14, 20, 20);
        var planeGeometry = new THREE.PlaneGeometry(14, 14, 4, 4);

		// 材质
        meshMaterial = new THREE.MeshLambertMaterial({color: 0x7777ff, transparent: true, opacity: 0.5});
        cube = new THREE.Mesh(cubeGeometry, meshMaterial);
        sphere = new THREE.Mesh(sphereGeometry, meshMaterial);
        plane = new THREE.Mesh(planeGeometry, meshMaterial);
		cube.castShadow = true;
		sphere.castShadow = true;
		plane.castShadow = true;

        cube.position.set(0, 12, 0);
        sphere.position.set(0, 14, 0);
        plane.position.set(0, 12, 0);
		
		/** 用来保存那些需要修改的变量 */
		guiParams = new function() {
			this.rotationSpeed = 0.02;
			this.opacity = meshMaterial.opacity;
			this.transparent = meshMaterial.transparent;
			this.visible = meshMaterial.visible;
			this.ambient = '#ff0000';
			this.emissive = '#c31111';
			this.side = 'front';
			this.color = '#7777ff';
			this.selectedMesh = 'cube';
			this.spotLight = true;
			
			this.addMesh = function(e) {
				scene.remove(activeMesh);

				switch (e) {
					case "cube":
						activeMesh = cube;
						break;
					case "sphere":
						activeMesh = sphere;
						break;
					case "plane":
						activeMesh = plane;
						break;
				}
				scene.add(activeMesh);
			};
			this.updateMaterial = function() {
				meshMaterial.opacity = this.opacity;
				meshMaterial.transparent = this.transparent;
				meshMaterial.visible = this.visible;
				meshMaterial.ambient = new THREE.Color(this.ambient);
				meshMaterial.emissive = new THREE.Color(this.emissive);
				meshMaterial.color = new THREE.Color(this.color);
				switch (this.side) {
					case "front":
						meshMaterial.side = THREE.FrontSide;
						break;
					case "back":
						meshMaterial.side = THREE.BackSide;
						break;
					case "double":
						meshMaterial.side = THREE.DoubleSide;
						break;
				}
				meshMaterial.needsUpdate = true;
			}
		}
		/** 定义 dat.GUI 对象,并绑定 guiParams 的几个属性 */
		var gui = new dat.GUI();
		var folder = gui.addFolder('Mesh');
		folder.open();
		folder.add(guiParams, 'opacity', 0.1, 1.0).onChange(function(e) {
			guiParams.updateMaterial();
		});
		folder.add(guiParams, 'transparent').onChange(function(e) {
			guiParams.updateMaterial();
		});
		folder.addColor(guiParams, 'ambient').onChange(function(e) {
			guiParams.updateMaterial();
		});
		folder.addColor(guiParams, 'emissive').onChange(function(e) {
			guiParams.updateMaterial();
		});
		folder.add(guiParams, 'visible').onChange(function(e) {
			guiParams.updateMaterial();
		});
		folder.add(guiParams, 'side', ['front', 'back', 'double']).onChange(function(e) {
			console.log(e);
            guiParams.updateMaterial();
		});
		folder.addColor(guiParams, 'color').onChange(function(e) {
			guiParams.updateMaterial();
		});
		folder.add(guiParams, 'selectedMesh', ['cube', 'sphere', 'plane']).onChange(function(e) {
			guiParams.addMesh(e);
		});
		gui.add(guiParams, 'spotLight').onChange(function(e) {
			scene.remove(spotLight);
			scene.remove(cameraHelper);
			if (e) {
				scene.add(spotLight);
				scene.add(cameraHelper);
			}
		});
		
		guiParams.updateMaterial();
		guiParams.addMesh(guiParams.selectedMesh);
		
		renderScene();
    });
	
	/** 渲染场景 */
	function renderScene() {
		stats.update();
		rotateMesh(); // 旋转物体
		
		requestAnimationFrame(renderScene);
		render.render(scene, camera);
	}
	
	/** 初始化 stats 统计对象 */
	function initStats() {
		stats = new Stats();
		stats.setMode(0); // 0 为监测 FPS;1 为监测渲染时间
		$('#stats-output').append(stats.domElement);
		return stats;
	}
	
	/** 当浏览器窗口大小变化时触发 */
	function onWindowResize() {
		camera.aspect = window.innerWidth / window.innerHeight;
		camera.updateProjectionMatrix();
		render.setSize(window.innerWidth, window.innerHeight);
	}
	
	/** 旋转物体 */
	function rotateMesh() {
		scene.traverse(function(mesh) {
			if (mesh instanceof THREE.Mesh && mesh != ground) {
				//mesh.rotation.x += guiParams.rotationSpeed;
				mesh.rotation.y += guiParams.rotationSpeed;
				//mesh.rotation.z += guiParams.rotationSpeed;
			}
		});
	}

</script>
</body>
</html>
对于初学者来说,由于其中 ambient、emissive 及 color 三个属性在试验时不太好理解。基于此,结合本示例,特给出几种引导方法。一、对于 color 属性,可以尝试通过右上角菜单 spotLight 开关开启并关闭聚光灯,再通过调整 color 属性以观察改变 color 属性时的不同反应;二、在关掉 spotLight 的情况下,再去改变 color 属性几乎看不出任何效果。但此时调整 emissive 属性效果明显;三、在开启 spotLight 的情况下,再去改变 color 属性,可以看出对光源产生的反应明显。此时再去调整 emissive 属性效果也比较明显;四、无论哪种情况下,调整 ambient 属性,效果都不易察觉。


未完待续···