当前位置:网站首页>webgl_ Enter the three-dimensional world (1)
webgl_ Enter the three-dimensional world (1)
2022-07-07 15:39:00 【Vegetable chicken on the road】
Excited heart, trembling hand , Start learning three-dimensional space today .
First, let's start with the simplest cube ;
A cube is made of triangles
First of all, we need to understand that three-dimensional objects are also composed of two-dimensional graphics ( Especially triangles ) Composed of . As shown in the figure ,12 Three triangles form a cube .
Then we may think , Since three-dimensional objects are composed of triangles , Then just draw each triangle that makes up the object one by one , Finally, you can draw the whole three-dimensional object . however , There is another significant difference between three-dimensional and two-dimensional ; When drawing two-dimensional graphics , Just consider the vertex x and y coordinate , When drawing three-dimensional objects , Also consider their depth information ( That is to say z Axis ). Secondly, there will be the concept of viewpoint and line of sight in the three-dimensional space station . You can understand being an observer , namely ﹔ Where is it 、 Where to look 、 How wide is the field of vision 、 How far can I see .
Viewpoint and line of sight
We call the position of the observer viewpoint , Rays that start from the viewpoint and follow the direction of observation are called sight .


Model matrix 
Model view matrix
If there are many vertices , Each vertex needs to calculate the view matrix × Model matrix , This step will cause unnecessary overhead . But no matter which vertex , type 7.1 The result of multiplying the two matrices in is the same . So let's calculate the result of multiplying these two matrices , Then pass it to vertex shader . The result of multiplying these two matrices is called the model view matrix :
Visual space 
Code to intuitively experience , Boxed visual space
var VSHADER_SOURCE = "" +
"attribute vec4 a_Position;\n" +//
"attribute vec4 a_Color;\n" +//
"uniform mat4 u_ViewModelMatrix ;\n" +
"varying vec4 v_Color;\n" +//
"void main(){\n" +
" gl_Position = u_ViewModelMatrix * a_Position;\n" +
" 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() {
var canvas = document.getElementById("triangle");
var nearFar = document.getElementById("nearFar");
var gl = getWebGLContext(canvas);
if(!gl){
console.log(" Your computer doesn't support WebGL!");
return;
}
if(!initShaders(gl,VSHADER_SOURCE,FSHADER_SOURCE)){
console.log(" Failed to initialize shader !");
return;
}
// Set information about vertices
var n = initVertexBuffers(gl);
if(n < 0){
console.log(" Unable to get the data of the point ");
return;
}
// obtain u_ViewMatrix The storage address of the variable
var u_ViewModelMatrix = gl.getUniformLocation(gl.program,'u_ViewModelMatrix');
// Set viewpoint , Line of sight and up direction
var viewMatrix = new Matrix4();
var modelMatrix = new Matrix4();
viewMatrix.setLookAt(0.2,0.25,0.25,0,0,0,0,1,0);
modelMatrix.setRotate(-50,0,0,1);
var viewModelMatrix = new Matrix4();//viewMatrix.multiply(modelMatrix);
// Register click events
document.onkeydown = function(ev){keydown(ev,gl,n,u_ViewModelMatrix,viewModelMatrix,nearFar)};
draw(gl,n,u_ViewModelMatrix,viewModelMatrix,nearFar);
// Pass the view matrix to u_ViewMatrix
// gl.uniformMatrix4fv(u_ViewModelMatrix,false,viewModelMatrix.elements);
// Draw triangle
// gl.drawArrays(gl.TRIANGLES,0,n);
}
var g_near = 0.0,g_far = 0.5;
function keydown(ev,gl,n,u_ViewModelMatrix,viewModelMatrix,nf){
switch(ev.keyCode){
case 39 : g_near += 0.01;break; // Right click
case 37 : g_near -= 0.01;break; // left-click
case 38 : g_far += 0.01;break; // Up key
case 40 : g_far -= 0.01;break; // Down key
default : return; // Other keys
}
draw(gl,n,u_ViewModelMatrix,viewModelMatrix,nearFar);
}
function draw(gl,n,u_ViewModelMatrix,viewModelMatrix,nf){
// Use matrix displacement to set the visual space
viewModelMatrix.setOrtho(-1,1,-1,1,g_near,g_far);
// Pass the view matrix to u_ViewMatrix
gl.uniformMatrix4fv(u_ViewModelMatrix,false,viewModelMatrix.elements);
gl.clear(gl.COLOR_BUFFER_BIT);
nf.innerHTML = 'near:' + Math.round(g_near *100)/100 + ",far:"+Math.round(g_far*100)/100
gl.drawArrays(gl.TRIANGLES,0,n);
}
function initVertexBuffers(gl) {
var verticesColors = new Float32Array([
// Position and texture data of four vertices
0.0,0.5,-0.4,0.4,1.0,0.4, // green , Back
-0.5,-0.5,-0.4,0.4,1.0,0.4,
0.5,-0.5,-0.4,1.0,0.4,0.4,
0.5,0.4,-0.2,1.0,0.4,0.4, // yellow , middle
-0.5,0.4,-0.2,1.0,1.0,0.4,
0.0,-0.6,-0.2,1.0,1.0,0.4,
0.0,0.5,0.0,0.4,0.4,1.0, // Blue , middle
-0.5,-0.5,0.0,0.4,0.4,1.0,
0.5,-0.5,0.0,1.0,0.4,0.4
]);
var n = 9;
var vertexColorBuffer = gl.createBuffer();
if(!vertexColorBuffer){
console.log(" Unable to create buffer ");
return -1;
}
gl.bindBuffer(gl.ARRAY_BUFFER,vertexColorBuffer);
gl.bufferData(gl.ARRAY_BUFFER,verticesColors,gl.STATIC_DRAW);
var a_Position = gl.getAttribLocation(gl.program,"a_Position");
if(a_Position < 0){
console.log(" Unable to get storage location ");
return;
}
// Get the number of bytes occupied by a value of the array
var fsize = verticesColors.BYTES_PER_ELEMENT;
// Assign the position of vertex coordinates
gl.vertexAttribPointer(a_Position,3,gl.FLOAT,false,fsize*6,0);
gl.enableVertexAttribArray(a_Position);
var a_Color = gl.getAttribLocation(gl.program,"a_Color");
if(a_Color < 0){
console.log(" Unable to get storage location ");
return;
}
// Assign the position of vertex coordinates
gl.vertexAttribPointer(a_Color,3,gl.FLOAT,false,fsize*6,3*fsize);
gl.enableVertexAttribArray(a_Color);
return n;
}

Code experience ( Adjust the details yourself ):
var VSHADER_SOURCE = "" +
"attribute vec4 a_Position;\n" +//
"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" +
" 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() {
var canvas = document.getElementById("webgl");
var gl = getWebGLContext(canvas);
if(!gl){
console.log(" Your computer doesn't support WebGL!");
return;
}
if(!initShaders(gl,VSHADER_SOURCE,FSHADER_SOURCE)){
console.log(" Failed to initialize shader !");
return;
}
// Set information about vertices
var n = initVertexBuffers(gl);
if(n < 0){
console.log(" Unable to get the data of the point ");
return;
}
// obtain u_ViewMatrix The storage address of the variable
var u_MvpMatrix = gl.getUniformLocation(gl.program, 'u_MvpMatrix');
// Set viewpoint , Line of sight and up direction
var modelMatrix = new Matrix4(); // Model
var viewMatrix = new Matrix4(); // View
var projMatrix = new Matrix4();// Projection
var mvpMatrix = new Matrix4(); // Model view projection
modelMatrix.setTranslate(0.75,0,0)
viewMatrix.setLookAt(0, 0, 1, 0, 0, -100, 0, 1, 0);
projMatrix.setPerspective(100, canvas.width/canvas.height, 1, 100);
mvpMatrix.set(projMatrix).multiply(viewMatrix).multiply(modelMatrix);
// Pass the view matrix to u_ViewMatrix
gl.uniformMatrix4fv(u_MvpMatrix, false, mvpMatrix.elements);
// Draw triangle
gl.drawArrays(gl.TRIANGLES,0,n);
}
function initVertexBuffers(gl) {
var verticesColors = new Float32Array([
// On the right side
0.75,1.0,-4.0,0.4,1.0,0.4, // green , Back
0.25,-1.0,-4.0,0.4,1.0,0.4,
1.25,-1.0,-4.0,1.0,0.4,0.4,
0.75,1.0,-2.0,1.0,0.4,0.4, // yellow , middle
0.25,-1.0,-2.0,1.0,1.0,0.4,
1.25,-1.0,-2.0,1.0,1.0,0.4,
0.75,1.0,0.0,0.4,0.4,1.0, // Blue , middle
0.25,-1.0,0.0,0.4,0.4,1.0,
1.25,-1.0,0.0,1.0,0.4,0.4,
// left
-0.75,1.0,-4.0,0.4,1.0,0.4, // green , Back
-0.25,-1.0,-4.0,0.4,1.0,0.4,
-1.25,-1.0,-4.0,1.0,0.4,0.4,
-0.75,1.0,-2.0,1.0,0.4,0.4, // yellow , middle
-0.25,-1.0,-2.0,1.0,1.0,0.4,
-1.25,-1.0,-2.0,1.0,1.0,0.4,
-0.75,1.0,0.0,0.4,0.4,1.0, // Blue , middle
-0.25,-1.0,0.0,0.4,0.4,1.0,
-1.25,-1.0,0.0,1.0,0.4,0.4
]);
var n = 18;
var vertexColorBuffer = gl.createBuffer();
if(!vertexColorBuffer){
console.log(" Unable to create buffer ");
return -1;
}
gl.bindBuffer(gl.ARRAY_BUFFER,vertexColorBuffer);
gl.bufferData(gl.ARRAY_BUFFER,verticesColors,gl.STATIC_DRAW);
var a_Position = gl.getAttribLocation(gl.program,"a_Position");
if(a_Position < 0){
console.log(" Unable to get storage location ");
return;
}
// Get the number of bytes occupied by a value of the array
var fsize = verticesColors.BYTES_PER_ELEMENT;
// Assign the position of vertex coordinates
gl.vertexAttribPointer(a_Position,3,gl.FLOAT,false,fsize*6,0);
gl.enableVertexAttribArray(a_Position);
var a_Color = gl.getAttribLocation(gl.program,"a_Color");
if(a_Color < 0){
console.log(" Unable to get storage location ");
return;
}
// Assign the position of vertex coordinates
gl.vertexAttribPointer(a_Color,3,gl.FLOAT,false,fsize*6,3*fsize);
gl.enableVertexAttribArray(a_Color);
return n;
}
边栏推荐
- [quick start of Digital IC Verification] 18. Basic grammar of SystemVerilog learning 5 (concurrent threads... Including practical exercises)
- How to create Apple Developer personal account P8 certificate
- 大表delete删数据导致数据库异常解决
- 【数字IC验证快速入门】22、SystemVerilog项目实践之AHB-SRAMC(2)(AMBA总线介绍)
- Ctfshow, information collection: web2
- [deep learning] semantic segmentation experiment: UNET network /msrc2 dataset
- 连接ftp服务器教程
- [quickstart to Digital IC Validation] 20. Basic syntax for system verilog Learning 7 (Coverage Driven... Including practical exercises)
- 【数据挖掘】视觉模式挖掘:Hog特征+余弦相似度/k-means聚类
- Bye, Dachang! I'm going to the factory today
猜你喜欢

写一篇万字长文《CAS自旋锁》送杰伦的新专辑登顶热榜

【数字IC验证快速入门】22、SystemVerilog项目实践之AHB-SRAMC(2)(AMBA总线介绍)

Steps to create P8 certificate and warehousing account

Ctfshow, information collection: web5

【数据挖掘】视觉模式挖掘:Hog特征+余弦相似度/k-means聚类

HW初级流量监控,到底该怎么做

知否|两大风控最重要指标与客群好坏的关系分析
MongoD管理数据库的方法介绍

【数字IC验证快速入门】20、SystemVerilog学习之基本语法7(覆盖率驱动...内含实践练习)

Super simple and fully automated generation super signature system (cloud Xiaoduo minclouds.com cloud service instance), free application in-house test app distribution and hosting platform, maintenan
随机推荐
Configure mongodb database in window environment
Pit avoidance: description of null values in in and not in SQL
Mathematical modeling -- what is mathematical modeling
Ctfshow, information collection: web13
The bank needs to build the middle office capability of the intelligent customer service module to drive the upgrade of the whole scene intelligent customer service
Ctfshow, information collection: web10
TypeScript 发布 4.8 beta 版本
leetcode 241. Different ways to add parentheses design priority for operational expressions (medium)
Comparable and comparator of sorting
How to release NFT in batches in opensea (rinkeby test network)
With 8 modules and 40 thinking models, you can break the shackles of thinking and meet the thinking needs of different stages and scenes of your work. Collect it quickly and learn it slowly
Points for attention in porting gd32 F4 series programs to gd32 F3 series
[understanding of opportunity -40]: direction, rules, choice, effort, fairness, cognition, ability, action, read the five layers of perception of 3GPP 6G white paper
Cocos makes Scrollview to realize the effect of zooming in the middle and zooming out on both sides
MySQL bit type resolution
Matlab experience summary
leetcode 241. Different Ways to Add Parentheses 为运算表达式设计优先级(中等)
[quick start of Digital IC Verification] 25. AHB sramc of SystemVerilog project practice (5) (AHB key review, key points refining)
Unity's ASE realizes cartoon flame
2. Basic knowledge of golang