1. An overview of the

It has to be said that now 3d graphics rendering technology update is really too fast,OpenGL has not had time to learn a lot of information has been a little outdated. The NeHe tutorial and the previous OpenGL Programming Guide 7th edition (aka the Little Red Book) are excellent, but they all start with fixed pipelines; The technology of programmable pipelines is now a very common base technology. Later I also read the “OpenGL programming Guide” eighth edition (white paper), this tutorial from the programmable pipeline (shader) began to talk about, look at the time feel that there is no previous foundation, is very obscure, far less than the little Red Book to understand. I am ashamed to say that I have failed many times to get started.

That’s why I’ve written this tutorial, hoping to extract something really useful from the material (and hopefully help you too). I think WebGL is a good entry point to learn OpenGL series 3D graphics rendering technology. WebGL is the browser version of OpenGL, which can basically be considered as a subset of OpenGL. The technology that can be retained by WebGL without being removed must be the essence of 3D graphics rendering technology. I highly recommend the WebGL Programming Guide as the basis for this tutorial.

When learning OpenGL/WebGL, I also felt that the examples given in many materials were too simple. It was easy to understand at first glance, but I could not solve the actual problems. I still think solving problems in practice can deepen the understanding of knowledge. Recently, I have been studying terrain rendering in GIS, so I will summarize WebGL knowledge by using an example of terrain rendering step by step. It doesn’t matter if you don’t know the terms OF GIS, just know that my ultimate goal here is to draw a geodetic elevation model, a set of points with XYZ coordinates, representing the topography.

2. Example: Draw a point

Writing a WebGL program is the same as writing a Web front-end program, consisting of HTML and JavaScript, and debugging through the browser.

1) HelloPoint1.html

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Draw a point (1)</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="HelloPoint1.js"></script>
  </body>
</html>
Copy the code

This piece of HTML is very simple and creates a canvas in practical terms. Is a draw tag introduced in HTML5 that allows you to draw arbitrary shapes on a canvas. It is through elements that WebGL draws. Otherwise, this code passes

2) HelloPoint1.js

// Vertex shader program
var VSHADER_SOURCE = 
  'void main() {\n' +
  'gl_Position = vec4(0.0, 0.0, 0.0, 1.0); \n' + // Set the vertex coordinates of the point
  'gl_PointSize = 10.0; \n' +                    // Set the point size
  '}\n';

// Chip shader program
var FSHADER_SOURCE =
  'void main() {\n' +
  'gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); \n' + // Set the point color
  '}\n';

function main() {
  // Get the 
      
        element
      
  var canvas = document.getElementById('webgl');

  // Get the WebGL rendering context
  var gl = getWebGLContext(canvas);
  if(! gl) {console.log('Failed to get the rendering context for WebGL');
    return;
  }

  // Initialize the shader
  if(! initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {console.log('Failed to intialize shaders.');
    return;
  }

  // specify to clear the color of 
      
  gl.clearColor(0.0.0.0.0.0.1.0);

  / / to empty < canvas >
  gl.clear(gl.COLOR_BUFFER_BIT);

  // Draw a point
  gl.drawArrays(gl.POINTS, 0.1);
}
Copy the code

The main content of this JS code is the aforementioned main function, which executes once the HTML has been loaded by the browser. The main function has the following steps:

(1) Preparation

Document.getelementbyid (‘ webGL ‘) : a function of the DOCUMENT object model DOM to retrieve the elements of the HTML page. GetWebGLContext (Canvas) : Gets the WebGL rendering context, stored in a GL variable. Because the fetching functions differ from browser to browser, the behavior is unified through the functions provided by the component cuon-utils.

(2) the shader

InitShaders: Initializes the shader.

The first thing to know is what a shader is. If you’ve only learned about fixed pipelines or other two-dimensional drawing components such as GDI, you’ll be confused about what shaders are and why you use them at all. For example, in a fixed pipeline, the drawPoint is the drawPoint, and the drawLine is the drawLine. In WebGL, rendering is broken down into vertex shaders and slice shaders.

At the start of JS program, the first drawing work into the vertex shader, in the vertex shader to describe the vertex characteristics (such as position, color, etc.), the vertex is the point of three-dimensional space, such as the three vertices of the triangle; It then goes to the pixel shader, which processes pixels (e.g. illumination, shadow, occlusion) pixel by pixel. The last slice is passed into the color buffer for display. The rendering process is as follows:

This process is called a rendering Pipeline because it is similar to a flow of water. In addition, this process needs to be controlled programmatically. For example, the viewer’s perspective changes need to be controlled in the vertex shader. The change of light to color needs to be adjusted in the chip shader, etc. Thus, this process is a programmable pipeline. Through the shader program, 3d image rendering is more flexible and powerful.

In the initShaders() function, the pre-defined JS strings VSHADER_SOURCE and FSHADER_SOURCE are passed in. Note that the shader program is run as a string embedded in a JS file. This function, also provided by the cuon-utils component, tells the WebGL system that the shader is set up and ready to use.

(3) Vertex shaders

Vertex shaders are defined as follows:

// Vertex shader program
var VSHADER_SOURCE = 
  'void main() {\n' +
  'gl_Position = vec4(0.0, 0.0, 0.0, 1.0); \n' + // Set the vertex coordinates of the point
  'gl_PointSize = 10.0; \n' +                    // Set the point size
  '}\n';
Copy the code

The vertex shader program is embedded in JS, so it is essentially GLSL (OpenGL Shading Language). Since it is a language, it has its own definition of functions and variables. The main () function is an entry defined by each shader program. In the main function, the coordinates of the vertex are assigned to the built-in variable gl_Position and the dimensions of the point are assigned to the built-in variable gl_PointSize.

Note that gl_Position must be assigned or the shader will not work properly. The assignment is of type VEC4, which is a four-dimensional vector. In general, only three dimensional vectors are needed to describe point positions, but in many cases, homogeneous coordinates of four components are required. Homogeneous coordinates (x,y,z,w) are equivalent to three-dimensional coordinates (x/w,y/w,z/w). So if the fourth component is one, then it’s normal three dimensional coordinates; If the fourth component is 0, it represents the point at infinity.

(4) Chip shader

A slice shader is defined as follows:

// Chip shader program
var FSHADER_SOURCE =
  'void main() {\n' +
  'gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); \n' + // Set the point color
  '}\n';
Copy the code

Like vertex shaders, the slice shader assigns the color of the point to the gl_FragColor variable, which is the only built-in variable of the slice shader that controls the final color of the pixel on the screen.

(5) Clear the buffer

Gl.clearcolor () : Sets the clear background color. Gl.clear (GL.color_BUFFer_bit) : Clears the color buffer.

(6) Drawing operation

Gl.drawarrays (gl.POINTS, 0, 1): Draws a point. The vertex shader simply specifies which vertices to draw, and needs to specify whether the vertices are points, lines, or planes. Gl.drawarrays () is one such function that tells the WebGL system to draw a point.

Results 3.

The final result is simple. Open helloPoint1.html in Chrome and the page displays a window that draws a point:

4. Reference

Some of the original code and illustrations come from the WebGL Programming Guide. Code and data addresses

The original link