[WebGL Primer] 11, shader compilation and connection

Source: Internet
Author: User
Tags script tag

Note: The article is translated from http://wgld.org/, the original author Sambonja 広 (doxas), the article if there is my additional instructions, I will add [Lufy:], in addition, The WEBGL research is not deep enough, some professional words, if the translation is wrong, you are welcome to correct.


something that repeats repeatedly.

This is the 11th article, because only said a few basic things, so far even a polygon has not been drawn out. Ah ah ah ...
Anyway, the basics are very important. Let's draw a polygon based on these. The knowledge that needs to be prepared has been introduced, and the rest is to follow the steps to start drawing polygons. First, confirm the steps to draw.
? Get the Canvas object from the HTML
? Get the context of WEBGL from the canvas
? Compiling shaders
? Preparing model data
? vertex cache (VBO) generation and notification
? generation and notification of coordinate transformation matrices
? Issue drawing commands
? update Canvas and Render
Among the steps listed above, the last two, the part of the drawing command and the Canvas Update section, are not covered so far. Later on, I will say a few words about their basic concepts. While these steps may seem complicated, this is the basic step of rendering using WebGL.

This article, from top to bottom, take a look at the first three steps, first of all the compiler shader.

* There are several steps in the sequence that can change, now take a look at this order first.


processing of HTML and canvas

The processing of HTML and canvas has also been discussed in previous articles (seven, context initialization). Basically there will be no change, here again.

>html Code

The HTML code is the above, the head tag refers to two JavaScript files, one is WebGL processing file script.js, and the other is the Web site of the matrix calculation of the library minmatrix.js.

processing of vertex shaders

Next, the code for the vertex shader and fragment shader appears. First, start with the type is the vertex shader for X-shader/x-vertex. The following is the code for the vertex shader section.

> Code for Vertex shaders

Attribute vec3 position;uniform   mat4 mvpmatrix;void Main (void) {    gl_position = Mvpmatrix * VEC4 (position, 1.0);}
A attribute variable and a uniform variable are used here.
VariablepositionThe type is VEC3, which is a 3-dimensional vector. Inside is the vertex position, and the three elements of the vector are X, y, z coordinates respectively.

Another uniform declares the variable Mvpmatrix, and the type is MAT4, so it is a 4x4 phalanx. is the coordinate transformation matrix of the model, view, and projection of each transformation matrix.

This time, the vertex shader only uses the coordinate transformation matrix to transform the vertex's coordinate position, using the multiplication operation. At this point, in order to multiply the Position and the matrix, using the VEC4 function, we first turn it into a 4-dimensional vector, then multiply it, and finally put the result into gl_position, and the processing of the vertex shader ends.


processing of fragment shaders

Then say fragment shader.

This time, the drawn model is a simple triangle that is not colored, but is filled with white. So, the processing in the fragment shader simply passes the white information to the Gl_fragcolor. The following is the code for the fragment shader.

Code for the > Fragment shader

void Main (void) {    Gl_fragcolor = VEC4 (1.0, 1.0, 1.0, 1.0);}
With regard to color, basically use VEC3 or VEC4 case is more. Because it is usually using RGB or RGBA, you need four or three elements. This time using the VEC4 is all the parameters are 1.0 of the vector, the color is white [red, green, blue, opacity of the elements are the largest = white].

compiling code, generating shaders

Next, we look at the compilation of the vertex shader and fragment shader.

Compiling does not require any particular compiler, just call the functions within WEBGL to compile. Prepare a function, from the shader's compilation, to the actual shader generation of this sequence of processes, all in this function to complete. Here is the code for this function.

* GL in the following function is obtained in advance from the context of WebGL.

> Functions for Generating and compiling shaders

function Create_shader (ID) {//variable var shader to save the shader;        Gets the specified script tag from HTML based on id var scriptelement = document.getElementById (ID);        If the specified script tag does not exist, returns if (!scriptelement) {return;}            Case ' X-shader/x-vertex ' when judging the type attribute of the script tag switch (scriptelement.type) {//vertex shader): Shader = Gl.createshader (gl.            Vertex_shader);                    Break Fragment shader when case ' x-shader/x-fragment ': shader = Gl.createshader (gl.            Fragment_shader);        Break    Default:return;        }//Assign the code in the tag to the generated shader Gl.shadersource (shader, Scriptelement.text);        Compiler shader Gl.compileshader (shader); Determine if the shader compiles successfully if (Gl.getshaderparameter (shader, GL.    Compile_status)) {//compile successfully, return the shader return shader;    }else{//compilation failed, pop-up error message alert (Gl.getshaderinfolog (shader)); }}
When using this function, you need to pass in the ID of the script tag as the parameter, and the function will get the specified label based on that ID.
When generating shaders, use the function Createshader in WebGL. This function, when generating a shader, passes in different parameters depending on the vertex shader and the fragment shader. The parameter is specified as GL. A vertex shader is generated when Vertex_shader, and the parameter is specified as GL. The fragment shader is generated when Fragment_shader.

First, when you assign code to the generated shader, you use the Shadersource function with two arguments, the first parameter is the shader object, and the second parameter is the code for the shader. At this point, the shader's code is simply assigned to the shader and not compiled. When compiling, using the Compileshader function to pass the shader object as a parameter to the function, you can compile the shader.

If the shader compiles successfully, it can be judged by the parameters in the shader, using the Getshaderparameter function when getting this parameter, and using the constant compile_status that exists in WebGL as a parameter. If the return value at this time is false, it means that for some reason the compilation failed, if you want to see the reason, pass the shader into the Getshaderinfolog function, you can confirm the log.

This custom function, whether it is a vertex shader or a fragment shader, can be compiled. In fact, the Createshader function is the difference between the vertex shader and the fragment shader, and the other places are exactly the same.


Building and linking of program objects

After the shader is generated, the program object is then generated. What is the object of a program that suddenly appears here?

The previous article (eight, the description and the basis of the shader) also touched slightly, using variables defined with the varying modifier to pass data from the vertex shader to the fragment shader. In fact, the implementation of passing data from one shader to another, not something else, is a program object. A program object is an important object that manages the interaction between a vertex shader and a fragment shader, or a WEBGL program and individual shaders to communicate data.

Then, the program object is generated and the shader is passed to the program object, and then the shader is connected and the processing is functional.

> Generation of Program objects and shader connections the function

function Create_program (VS, FS) {    //Program object generation    var programs = Gl.createprogram ();        Assigns shader    Gl.attachshader (program, VS) to the Application object;    Gl.attachshader (program, FS);        Connect the shader to the    Gl.linkprogram (program);        Determines if the connection to the shader is successful    if (Gl.getprogramparameter (program, GL). Link_status)) {            //successfully set the program object to a valid        gl.useprogram (programs);                Returns the program object return to Programs        ;    } else{                //if failed, pop-up error message        alert (Gl.getprograminfolog (program));}    }
This function receives two parameters of the vertex shader and fragment shader. Then, the program object is generated first, and the shader is assigned. When generating shaders, use the function Createprogram in WebGL to assign shaders to program objects using thefunctionThe first argument to the Attachshader,attachshader function is the program object, and the second parameter is the shader.
After the shader assignment ends, depending on the program object, you want toConnectionTwo shaders, this time using the Linkprogram function, the parameter is the program object.

As with generating shaders, to determine if a shader's connection is successful, use the Getprogramparameter function and pass in the constant link_status. If there is no problem, use the Useprogram function in order to set the program object to be valid. Note that this program object is not recognized in WebGL if this function is not executed. If the connection fails, the error message pops up, using the Getprograminfolog function to get the log.


Summary

To summarize the contents of this article briefly.

The necessary JavaScript files are introduced in the HTML code, as well as the code that describes the shader.

The compiler function for the shader is prepared and the function associated with the program object that joins the shader . Each function has a judgment of whether it is handled correctly.


Next time, prepare the vertex data, that is, prepare the model data, and then transform to VBO. According to the above steps, step by step all understand, it should be no problem, come on.


reprint Please specify: from Lufy_legend's blog http://blog.csdn.net/lufy_legend

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.