目錄javascript
在上一篇教程《WebGL簡易教程(五):圖形變換(模型、視圖、投影變換)》中,詳細講解了OpenGL\WebGL關於繪製場景的模型變換、視圖變換以及投影變換的過程。不過那篇教程是純理論知識,這裏就具體結合一個實際的例子,進一步理解WebGL中是如何經過圖形變換讓一個真正的三維場景顯示出來。html
繼續改進以前的代碼,此次就更進一步,在一個場景中繪製了三個三角形。java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Hello Triangle</title> </head> <body onload="main()"> <canvas id="webgl" width="400" height="400"> Please use a browser that supports "canvas" </canvas> <script src="../lib/webgl-utils.js"></script> <script src="../lib/webgl-debug.js"></script> <script src="../lib/cuon-utils.js"></script> <script src="../lib/cuon-matrix.js"></script> <script src="Triangle_MVPMatrix.js"></script> </body> </html>
與之間的代碼相比,這段代碼主要是引入了一個cuon-matrix.js,這個是一個圖形矩陣的處理庫,可以方便與GLSL進行交互。web
// 頂點着色器程序 var VSHADER_SOURCE = 'attribute vec4 a_Position;\n' + // attribute variable 'attribute vec4 a_Color;\n' + 'uniform mat4 u_MvpMatrix;\n' + 'varying vec4 v_Color;\n' + 'void main() {\n' + ' gl_Position = u_MvpMatrix * a_Position;\n' + // Set the vertex coordinates of the point ' v_Color = a_Color;\n' + '}\n'; // 片元着色器程序 var FSHADER_SOURCE = 'precision mediump float;\n' + 'varying vec4 v_Color;\n' + 'void main() {\n' + ' gl_FragColor = v_Color;\n' + '}\n'; function main() { // 獲取 <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; } // 設置頂點位置 var n = initVertexBuffers(gl); if (n < 0) { console.log('Failed to set the positions of the vertices'); return; } //設置MVP矩陣 setMVPMatrix(gl,canvas); // 指定清空<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); // 繪製三角形 gl.drawArrays(gl.TRIANGLES, 0, n); } //設置MVP矩陣 function setMVPMatrix(gl,canvas) { // 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.setTranslate(0.75, 0, 0); //視圖矩陣 var viewMatrix = new Matrix4(); // View matrix viewMatrix.setLookAt(0, 0, 5, 0, 0, -100, 0, 1, 0); //投影矩陣 var projMatrix = new Matrix4(); // Projection matrix projMatrix.setPerspective(30, canvas.width / canvas.height, 1, 100); //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) { // 頂點座標和顏色 var verticesColors = new Float32Array([ 0.0, 1.0, -4.0, 0.4, 1.0, 0.4, //綠色在後 -0.5, -1.0, -4.0, 0.4, 1.0, 0.4, 0.5, -1.0, -4.0, 1.0, 0.4, 0.4, 0.0, 1.0, -2.0, 1.0, 1.0, 0.4, //黃色在中 -0.5, -1.0, -2.0, 1.0, 1.0, 0.4, 0.5, -1.0, -2.0, 1.0, 0.4, 0.4, 0.0, 1.0, 0.0, 0.4, 0.4, 1.0, //藍色在前 -0.5, -1.0, 0.0, 0.4, 0.4, 1.0, 0.5, -1.0, 0.0, 1.0, 0.4, 0.4, ]); // var n = 9; // 點的個數 var FSIZE = verticesColors.BYTES_PER_ELEMENT; //數組中每一個元素的字節數 // 建立緩衝區對象 var vertexBuffer = gl.createBuffer(); if (!vertexBuffer) { console.log('Failed to create the buffer object'); return -1; } // 將緩衝區對象綁定到目標 gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); // 向緩衝區對象寫入數據 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 * 6, 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 * 6, FSIZE * 3); // 鏈接a_Color變量與分配給它的緩衝區對象 gl.enableVertexAttribArray(a_Color); // 解除綁定 gl.bindBuffer(gl.ARRAY_BUFFER, null); return n; }
相比以前的代碼,主要作了3點改進:編程
以前繪製的三角形,只有X座標和Y座標,Z值座標自動補足爲默認爲0的。在這裏會繪製了3個三角形,每一個三角形的深度不一樣。以下代碼所示,定義了3個三角形9個點,每一個點包含xyz信息和rgb信息:canvas
// 頂點座標和顏色 var verticesColors = new Float32Array([ 0.0, 1.0, -4.0, 0.4, 1.0, 0.4, //綠色在後 -0.5, -1.0, -4.0, 0.4, 1.0, 0.4, 0.5, -1.0, -4.0, 1.0, 0.4, 0.4, 0.0, 1.0, -2.0, 1.0, 1.0, 0.4, //黃色在中 -0.5, -1.0, -2.0, 1.0, 1.0, 0.4, 0.5, -1.0, -2.0, 1.0, 0.4, 0.4, 0.0, 1.0, 0.0, 0.4, 0.4, 1.0, //藍色在前 -0.5, -1.0, 0.0, 0.4, 0.4, 1.0, 0.5, -1.0, 0.0, 1.0, 0.4, 0.4, ]);
這意味着與着色器傳輸變量的函數gl.vertexAttribPointer()的參數也得相應的變化。注意要深刻理解這個函數每一個參數表明的含義:數組
// ... // 將緩衝區對象分配給a_Position變量 gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, FSIZE * 6, 0); // ... // 將緩衝區對象分配給a_Color變量 gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, FSIZE * 6, FSIZE * 3);
在默認狀況下,WebGL是根據頂點在緩衝區的順序來進行繪製的,後繪製的圖形會覆蓋已經繪製好的圖形。可是這樣每每與實際物體遮擋狀況不一樣,形成一些很怪異的現象,好比遠的物體反而遮擋了近的物體。因此WebGL提供了一種深度檢測(DEPTH_TEST)的功能,啓用該功能就會檢測物體(實際是每一個像素)的深度,來決定是否繪製。其啓用函數爲:
除此以外,還應該注意在繪製每一幀以前都應該清除深度緩衝區(depth buffer)。WebGL有多種緩衝區。咱們以前用到的與頂點着色器交互的緩衝區對象就是頂點緩衝區,每次從新繪製刷新的就是顏色緩衝區。深度緩衝區記錄的就是每一個幾何圖形的深度信息,每繪製一幀,都應清除深度緩衝區:
在本例中的相關代碼爲:瀏覽器
// ... // 開啓深度測試 gl.enable(gl.DEPTH_TEST); // 清空顏色和深度緩衝區 gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // ...
在上一篇教程中提到過,WebGL的任何圖形變換過程影響的都是物體的頂點,模型變換、視圖變換、投影變換都是在頂點着色器中實現的。因爲每一個頂點都是要進行模型視圖投影變換的,因此能夠合併成一個MVP矩陣,將其傳入到頂點着色器中的:函數
//... 'uniform mat4 u_MvpMatrix;\n' + 'void main() {\n' + ' gl_Position = u_MvpMatrix * a_Position;\n' + // Set the vertex coordinates of the point //... '}\n';
在函數setMVPMatrix()中,建立了MVP矩陣,並將其傳入到着色器:測試
//設置MVP矩陣 function setMVPMatrix(gl,canvas) { // 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.setTranslate(0.75, 0, 0); //視圖矩陣 var viewMatrix = new Matrix4(); // View matrix viewMatrix.setLookAt(0, 0, 5, 0, 0, -100, 0, 1, 0); //投影矩陣 var projMatrix = new Matrix4(); // Projection matrix projMatrix.setPerspective(30, canvas.width / canvas.height, 1, 100); //MVP矩陣 var mvpMatrix = new Matrix4(); mvpMatrix.set(projMatrix).multiply(viewMatrix).multiply(modelMatrix); //將MVP矩陣傳輸到着色器的uniform變量u_MvpMatrix gl.uniformMatrix4fv(u_MvpMatrix, false, mvpMatrix.elements); }
在上述代碼中,依次分別設置了:
三者級聯,獲得MVP矩陣,將其傳入到頂點着色器中。
用瀏覽器打開Triangle_MVPMatrix.html,就會發現瀏覽器頁面顯示了一個由遠及近,近大遠小的三個三角形。如圖所示:
原本部分代碼和插圖來自《WebGL編程指南》,源代碼連接:https://share.weiyun.com/5VjlUKo ,密碼:sw0x2x。會在此共享目錄中持續更新後續的內容。