在以前的教程中,都是經過物體的包圍盒來設置模型視圖投影矩陣(MVP矩陣),來肯定物體合適的位置的。可是在不少狀況下,使用包圍盒並不方便計算,能夠利用包圍盒再生成一個包圍球,利用包圍球來設置MVP矩陣。html
在《WebGL簡易教程(十):光照》中,給地形賦予了固定方向的平行光。這篇教程的例子就是想模擬在平行光的視角下地形的狀況。對於點光源光,能夠用透視投影來實現渲染的效果;而平行光就須要經過正射投影來模擬。而且,這種正射並非垂直到達地面,而是附帶必定角度[1]:
java
在這種狀況下使用包圍盒來計算合適的位置有點難度,使用包圍球來設置MVP矩陣更加方便。git
包圍球是利用包圍盒生成的,因此首先須要定義一個球體對象:github
//定義一個球體 function Sphere(cuboid) { this.centerX = cuboid.CenterX(); this.centerY = cuboid.CenterY(); this.centerZ = cuboid.CenterZ(); this.radius = Math.max(Math.max(cuboid.LengthX(), cuboid.LengthY()), cuboid.LengthZ()) / 2.0; } Sphere.prototype = { constructor: Sphere }
這個球體對象的構造函數傳入了一個包圍盒對象,以包圍盒的中心爲球體的中心,包圍盒長、寬、高的最大值做爲包圍球的直徑。在構造出包圍盒以後,利用包圍盒參數構造出包圍球,將其保存在自定義的Terrain對象中:web
var terrain = new Terrain(); //.... terrain.cuboid = new Cuboid(minX, maxX, minY, maxY, minZ, maxZ); terrain.sphere = new Sphere(terrain.cuboid);
接下來就是改進設置MVP矩陣的函數setMVPMatrix()了。若是仍然想像以前那樣進行透視投影,幾乎能夠不用作改動:編程
//設置MVP矩陣 function setMVPMatrix(gl, canvas, sphere, lightDirection) { //... //投影矩陣 var fovy = 60; var projMatrix = new Matrix4(); projMatrix.setPerspective(fovy, canvas.width / canvas.height, 1, 10000); //計算lookAt()函數初始視點的高度 var angle = fovy / 2 * Math.PI / 180.0; var eyeHight = (sphere.radius * 2 * 1.1) / 2.0 / angle; //視圖矩陣 var viewMatrix = new Matrix4(); // View matrix viewMatrix.lookAt(0, 0, eyeHight, 0, 0, 0, 0, 1, 0); //... }
以前是經過透視變換的張角和包圍盒的Y方向長度來計算合適的視野高度,如今只不過將包圍盒的Y方向長度換成包圍球的直徑。這樣的寫法兼容性更高,由於包圍球的直徑是包圍盒XYZ三個方向的最大長度。這個時候的初始渲染狀態爲:
最後實現下特定角度平行光視角下的地形渲染狀況。前面說到過這種狀況下是須要設置正射投影的,具體設置過程以下:canvas
//設置MVP矩陣 function setMVPMatrix(gl, canvas, sphere, lightDirection) { //... //模型矩陣 var modelMatrix = new Matrix4(); modelMatrix.scale(curScale, curScale, curScale); modelMatrix.rotate(currentAngle[0], 1.0, 0.0, 0.0); // Rotation around x-axis modelMatrix.rotate(currentAngle[1], 0.0, 1.0, 0.0); // Rotation around y-axis modelMatrix.translate(-sphere.centerX, -sphere.centerY, -sphere.centerZ); //視圖矩陣 var viewMatrix = new Matrix4(); var r = sphere.radius + 10; viewMatrix.lookAt(lightDirection.elements[0] * r, lightDirection.elements[1] * r, lightDirection.elements[2] * r, 0, 0, 0, 0, 1, 0); //投影矩陣 var projMatrix = new Matrix4(); var diameter = sphere.radius * 2.1; var ratioWH = canvas.width / canvas.height; var nearHeight = diameter; var nearWidth = nearHeight * ratioWH; projMatrix.setOrtho(-nearWidth / 2, nearWidth / 2, -nearHeight / 2, nearHeight / 2, 1, 10000); //... }
這個時候的初始渲染狀態爲:
數組
具體實現代碼以下:瀏覽器
// 頂點着色器程序 var VSHADER_SOURCE = 'attribute vec4 a_Position;\n' + //位置 'attribute vec4 a_Color;\n' + //顏色 'attribute vec4 a_Normal;\n' + //法向量 'uniform mat4 u_MvpMatrix;\n' + 'varying vec4 v_Color;\n' + 'varying vec4 v_Normal;\n' + 'void main() {\n' + ' gl_Position = u_MvpMatrix * a_Position;\n' + //設置頂點的座標 ' v_Color = a_Color;\n' + ' v_Normal = a_Normal;\n' + '}\n'; // 片元着色器程序 var FSHADER_SOURCE = 'precision mediump float;\n' + 'uniform vec3 u_DiffuseLight;\n' + // 漫反射光顏色 'uniform vec3 u_LightDirection;\n' + // 漫反射光的方向 'uniform vec3 u_AmbientLight;\n' + // 環境光顏色 'varying vec4 v_Color;\n' + 'varying vec4 v_Normal;\n' + 'void main() {\n' + //對法向量歸一化 ' vec3 normal = normalize(v_Normal.xyz);\n' + //計算光線向量與法向量的點積 ' float nDotL = max(dot(u_LightDirection, normal), 0.0);\n' + //計算漫發射光的顏色 ' vec3 diffuse = u_DiffuseLight * v_Color.rgb * nDotL;\n' + //計算環境光的顏色 ' vec3 ambient = u_AmbientLight * v_Color.rgb;\n' + ' gl_FragColor = vec4(diffuse+ambient, v_Color.a);\n' + '}\n'; //定義一個矩形體:混合構造函數原型模式 function Cuboid(minX, maxX, minY, maxY, minZ, maxZ) { this.minX = minX; this.maxX = maxX; this.minY = minY; this.maxY = maxY; this.minZ = minZ; this.maxZ = maxZ; } Cuboid.prototype = { constructor: Cuboid, CenterX: function () { return (this.minX + this.maxX) / 2.0; }, CenterY: function () { return (this.minY + this.maxY) / 2.0; }, CenterZ: function () { return (this.minZ + this.maxZ) / 2.0; }, LengthX: function () { return (this.maxX - this.minX); }, LengthY: function () { return (this.maxY - this.minY); }, LengthZ: function () { return (this.maxZ - this.minZ); } } //定義一個球體 function Sphere(cuboid) { this.centerX = cuboid.CenterX(); this.centerY = cuboid.CenterY(); this.centerZ = cuboid.CenterZ(); this.radius = Math.max(Math.max(cuboid.LengthX(), cuboid.LengthY()), cuboid.LengthZ()) / 2.0; } Sphere.prototype = { constructor: Sphere } //定義DEM function Terrain() { } Terrain.prototype = { constructor: Terrain, setWH: function (col, row) { this.col = col; this.row = row; } } var currentAngle = [0.0, 0.0]; // 繞X軸Y軸的旋轉角度 ([x-axis, y-axis]) var curScale = 1.0; //當前的縮放比例 function main() { var demFile = document.getElementById('demFile'); if (!demFile) { console.log("Failed to get demFile element!"); return; } demFile.addEventListener("change", function (event) { //判斷瀏覽器是否支持FileReader接口 if (typeof FileReader == 'undefined') { console.log("你的瀏覽器不支持FileReader接口!"); return; } var input = event.target; var reader = new FileReader(); reader.onload = function () { if (reader.result) { //讀取 var terrain = new Terrain(); if (!readDEMFile(reader.result, terrain)) { console.log("文件格式有誤,不能讀取該文件!"); } //繪製 onDraw(gl, canvas, terrain); } } reader.readAsText(input.files[0]); }); // 獲取 <canvas> 元素 var canvas = document.getElementById('webgl'); // 獲取WebGL渲染上下文 var gl = getWebGLContext(canvas); if (!gl) { console.log('Failed to get the rendering context for WebGL'); return; } // 初始化着色器 if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) { console.log('Failed to intialize shaders.'); return; } // 指定清空<canvas>的顏色 gl.clearColor(0.0, 0.0, 0.0, 1.0); // 開啓深度測試 gl.enable(gl.DEPTH_TEST); //清空顏色和深度緩衝區 gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); } //繪製函數 function onDraw(gl, canvas, terrain) { // 設置頂點位置 var n = initVertexBuffers(gl, terrain); if (n < 0) { console.log('Failed to set the positions of the vertices'); return; } //註冊鼠標事件 initEventHandlers(canvas); //設置燈光 var lightDirection = setLight(gl); //繪製函數 var tick = function () { //設置MVP矩陣 setMVPMatrix(gl, canvas, terrain.sphere, lightDirection); //清空顏色和深度緩衝區 gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); //繪製矩形體 gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_SHORT, 0); //請求瀏覽器調用tick requestAnimationFrame(tick); }; //開始繪製 tick(); } //設置燈光 function setLight(gl) { var u_AmbientLight = gl.getUniformLocation(gl.program, 'u_AmbientLight'); var u_DiffuseLight = gl.getUniformLocation(gl.program, 'u_DiffuseLight'); var u_LightDirection = gl.getUniformLocation(gl.program, 'u_LightDirection'); if (!u_DiffuseLight || !u_LightDirection || !u_AmbientLight) { console.log('Failed to get the storage location'); return; } //設置漫反射光 gl.uniform3f(u_DiffuseLight, 1.0, 1.0, 1.0); // 設置光線方向(世界座標系下的) var solarAltitude = 45.0; var solarAzimuth = 315.0; var fAltitude = solarAltitude * Math.PI / 180; //光源高度角 var fAzimuth = solarAzimuth * Math.PI / 180; //光源方位角 var arrayvectorX = Math.cos(fAltitude) * Math.cos(fAzimuth); var arrayvectorY = Math.cos(fAltitude) * Math.sin(fAzimuth); var arrayvectorZ = Math.sin(fAltitude); var lightDirection = new Vector3([arrayvectorX, arrayvectorY, arrayvectorZ]); lightDirection.normalize(); // Normalize gl.uniform3fv(u_LightDirection, lightDirection.elements); //設置環境光 gl.uniform3f(u_AmbientLight, 0.2, 0.2, 0.2); return lightDirection; } //讀取DEM函數 function readDEMFile(result, terrain) { var stringlines = result.split("\n"); if (!stringlines || stringlines.length <= 0) { return false; } //讀取頭信息 var subline = stringlines[0].split("\t"); if (subline.length != 6) { return false; } var col = parseInt(subline[4]); //DEM寬 var row = parseInt(subline[5]); //DEM高 var verticeNum = col * row; if (verticeNum + 1 > stringlines.length) { return false; } terrain.setWH(col, row); //讀取點信息 var ci = 0; var pSize = 9; terrain.verticesColors = new Float32Array(verticeNum * pSize); for (var i = 1; i < stringlines.length; i++) { if (!stringlines[i]) { continue; } var subline = stringlines[i].split(','); if (subline.length != pSize) { continue; } for (var j = 0; j < pSize; j++) { terrain.verticesColors[ci] = parseFloat(subline[j]); ci++; } } if (ci !== verticeNum * pSize) { return false; } //包圍盒 var minX = terrain.verticesColors[0]; var maxX = terrain.verticesColors[0]; var minY = terrain.verticesColors[1]; var maxY = terrain.verticesColors[1]; var minZ = terrain.verticesColors[2]; var maxZ = terrain.verticesColors[2]; for (var i = 0; i < verticeNum; i++) { minX = Math.min(minX, terrain.verticesColors[i * pSize]); maxX = Math.max(maxX, terrain.verticesColors[i * pSize]); minY = Math.min(minY, terrain.verticesColors[i * pSize + 1]); maxY = Math.max(maxY, terrain.verticesColors[i * pSize + 1]); minZ = Math.min(minZ, terrain.verticesColors[i * pSize + 2]); maxZ = Math.max(maxZ, terrain.verticesColors[i * pSize + 2]); } terrain.cuboid = new Cuboid(minX, maxX, minY, maxY, minZ, maxZ); terrain.sphere = new Sphere(terrain.cuboid); return true; } //註冊鼠標事件 function initEventHandlers(canvas) { var dragging = false; // Dragging or not var lastX = -1, lastY = -1; // Last position of the mouse //鼠標按下 canvas.onmousedown = function (ev) { var x = ev.clientX; var y = ev.clientY; // Start dragging if a moue is in <canvas> var rect = ev.target.getBoundingClientRect(); if (rect.left <= x && x < rect.right && rect.top <= y && y < rect.bottom) { lastX = x; lastY = y; dragging = true; } }; //鼠標離開時 canvas.onmouseleave = function (ev) { dragging = false; }; //鼠標釋放 canvas.onmouseup = function (ev) { dragging = false; }; //鼠標移動 canvas.onmousemove = function (ev) { var x = ev.clientX; var y = ev.clientY; if (dragging) { var factor = 100 / canvas.height; // The rotation ratio var dx = factor * (x - lastX); var dy = factor * (y - lastY); currentAngle[0] = currentAngle[0] + dy; currentAngle[1] = currentAngle[1] + dx; } lastX = x, lastY = y; }; //鼠標縮放 canvas.onmousewheel = function (event) { if (event.wheelDelta > 0) { curScale = curScale * 1.1; } else { curScale = curScale * 0.9; } }; } //設置MVP矩陣 function setMVPMatrix(gl, canvas, sphere, lightDirection) { // Get the storage location of u_MvpMatrix var u_MvpMatrix = gl.getUniformLocation(gl.program, 'u_MvpMatrix'); if (!u_MvpMatrix) { console.log('Failed to get the storage location of u_MvpMatrix'); return; } //模型矩陣 var modelMatrix = new Matrix4(); modelMatrix.scale(curScale, curScale, curScale); modelMatrix.rotate(currentAngle[0], 1.0, 0.0, 0.0); // Rotation around x-axis modelMatrix.rotate(currentAngle[1], 0.0, 1.0, 0.0); // Rotation around y-axis modelMatrix.translate(-sphere.centerX, -sphere.centerY, -sphere.centerZ); /* //----------------------透視--------------------- //投影矩陣 var fovy = 60; var projMatrix = new Matrix4(); projMatrix.setPerspective(fovy, canvas.width / canvas.height, 1, 10000); //計算lookAt()函數初始視點的高度 var angle = fovy / 2 * Math.PI / 180.0; var eyeHight = (sphere.radius * 2 * 1.1) / 2.0 / angle; //視圖矩陣 var viewMatrix = new Matrix4(); // View matrix viewMatrix.lookAt(0, 0, eyeHight, 0, 0, 0, 0, 1, 0); //----------------------透視--------------------- */ //----------------------正射--------------------- //視圖矩陣 var viewMatrix = new Matrix4(); var r = sphere.radius + 10; viewMatrix.lookAt(lightDirection.elements[0] * r, lightDirection.elements[1] * r, lightDirection.elements[2] * r, 0, 0, 0, 0, 1, 0); //投影矩陣 var projMatrix = new Matrix4(); var diameter = sphere.radius * 2.1; var ratioWH = canvas.width / canvas.height; var nearHeight = diameter; var nearWidth = nearHeight * ratioWH; projMatrix.setOrtho(-nearWidth / 2, nearWidth / 2, -nearHeight / 2, nearHeight / 2, 1, 10000); //----------------------正射--------------------- //MVP矩陣 var mvpMatrix = new Matrix4(); mvpMatrix.set(projMatrix).multiply(viewMatrix).multiply(modelMatrix); //將MVP矩陣傳輸到着色器的uniform變量u_MvpMatrix gl.uniformMatrix4fv(u_MvpMatrix, false, mvpMatrix.elements); } // function initVertexBuffers(gl, terrain) { //DEM的一個網格是由兩個三角形組成的 // 0------1 1 // | | // | | // col col------col+1 var col = terrain.col; var row = terrain.row; var indices = new Uint16Array((row - 1) * (col - 1) * 6); var ci = 0; for (var yi = 0; yi < row - 1; yi++) { //for (var yi = 0; yi < 10; yi++) { for (var xi = 0; xi < col - 1; xi++) { indices[ci * 6] = yi * col + xi; indices[ci * 6 + 1] = (yi + 1) * col + xi; indices[ci * 6 + 2] = yi * col + xi + 1; indices[ci * 6 + 3] = (yi + 1) * col + xi; indices[ci * 6 + 4] = (yi + 1) * col + xi + 1; indices[ci * 6 + 5] = yi * col + xi + 1; ci++; } } // var verticesColors = terrain.verticesColors; var FSIZE = verticesColors.BYTES_PER_ELEMENT; //數組中每一個元素的字節數 // 建立緩衝區對象 var vertexColorBuffer = gl.createBuffer(); var indexBuffer = gl.createBuffer(); if (!vertexColorBuffer || !indexBuffer) { console.log('Failed to create the buffer object'); return -1; } // 將緩衝區對象綁定到目標 gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer); // 向緩衝區對象寫入數據 gl.bufferData(gl.ARRAY_BUFFER, verticesColors, gl.STATIC_DRAW); //獲取着色器中attribute變量a_Position的地址 var a_Position = gl.getAttribLocation(gl.program, 'a_Position'); if (a_Position < 0) { console.log('Failed to get the storage location of a_Position'); return -1; } // 將緩衝區對象分配給a_Position變量 gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, FSIZE * 9, 0); // 鏈接a_Position變量與分配給它的緩衝區對象 gl.enableVertexAttribArray(a_Position); //獲取着色器中attribute變量a_Color的地址 var a_Color = gl.getAttribLocation(gl.program, 'a_Color'); if (a_Color < 0) { console.log('Failed to get the storage location of a_Color'); return -1; } // 將緩衝區對象分配給a_Color變量 gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, FSIZE * 9, FSIZE * 3); // 鏈接a_Color變量與分配給它的緩衝區對象 gl.enableVertexAttribArray(a_Color); // 向緩衝區對象分配a_Normal變量,傳入的這個變量要在着色器使用才行 var a_Normal = gl.getAttribLocation(gl.program, 'a_Normal'); if (a_Normal < 0) { console.log('Failed to get the storage location of a_Normal'); return -1; } gl.vertexAttribPointer(a_Normal, 3, gl.FLOAT, false, FSIZE * 9, FSIZE * 6); //開啓a_Normal變量 gl.enableVertexAttribArray(a_Normal); // 將頂點索引寫入到緩衝區對象 gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW); return indices.length; }
原本部分代碼和插圖來自《WebGL編程指南》,源代碼連接:地址 。會在此共享目錄中持續更新後續的內容。