[WebGL Primer] 11, shader compilers and connectors

Source: Internet
Author: User
Tags script tag

Note: The article translates http://wgld.org/, the original author Sambonja 広 (doxas). The article assumes that I have additional instructions. I will add [Lufy:]. Other than that. The WEBGL study is not deep enough. Some professional words, assuming the translation is wrong. You are welcome to correct me.


Repetition of something repeated

This is already the 11th article, because just said some of the main things. Until now, even a polygon has not been drawn. Ah ah ah ...
Anyway, whatever. The basics are very important. That's on the basis of that. To draw a polygon bar. The knowledge needed to be prepared has been introduced. 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
In the steps listed above, what has not been described so far is the last two, the section on drawing commands and the Canvas Update section. Later. I'll talk about their main concepts.

Although these steps look quite complicated. But this is the basic step of rendering with WebGL.

The article this time. Just take a look at the first three steps from top to bottom, and start with the compiler shader.

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


processing of HTML and canvas

About the processing of HTML and canvas. In the previous article (seven. Context initialization) has also been spoken. There is basically no change. Let's talk about it here.

>html Code

The HTML code is like this. The head tag refers to two JavaScript files, one for WebGL's processing file script.js, and one for the minmatrix.js of the matrix calculations written by the site itself.



processing of vertex shaders

Next, the code for the vertex shader and fragment shader appears. First, start with a vertex shader of type 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. The inside is the vertex position. The three elements of a vector are X, y, respectively. Z coordinate.

There is also a variable Mvpmatrix declared by the uniform. 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. Use the multiplication operation.

At this point, in order to multiply position and matrices, using the VEC4 function, first turn it into a 4-dimensional vector and multiply it. Finally, the result of the calculation is put into gl_position, and the processing of the vertex shader is finished.


processing of fragment shaders

Then say fragment shader.

This. The model that is drawn is a simple triangle that is not colored, but is filled with only 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.

Since the general use of RGB or RGBA, there are four elements required. This time using the VEC4 is all the parameters are 1.0 vector, the color is white [red, green. Blue. The opacity of each element is maximum = 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. Only functions that need to be called within WebGL can be compiled. Prepare a function, from the shader's compilation, to the actual shader generation of this sequence of processes, all in this function to complete. The following 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, return if (!scriptelement) {return;}            Infer the type attribute of the script tag switch (scriptelement.type) {///vertex shader when case ' X-shader/x-vertex ': 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); Infer 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. The ID of the script tag needs to be passed in as a parameter, and the specified label is obtained from the function.
When the shader is generated. Use the function Createshader in WebGL. This function, when generating a shader, passes in different parameters depending on the vertex shader and fragment shader. The number of references is specified as GL. A vertex shader is generated when Vertex_shader, and the number of references is specified as GL. The fragment shader is generated when Fragment_shader.

First of all. When the code is assigned to the generated shader. The Shadersource function is used. There are two, the first parameter is the shader object, and the second is the code for the shader. This time Simply assigning the shader's code to the shader is not compiled yet. When compiling, the Compileshader function is used to pass the shader object as a parameter to the function. will be able to compile the shader.

Whether the shader was compiled successfully. Can be inferred by the number of parameters in the shader. The time to get this number. Use the Getshaderparameter function and use the constant compile_status that exists in WebGL as the parameter. Suppose the return value at this time is false. It indicates that the compilation failed for any reason. To see why, pass the shader into the Getshaderinfolog function to confirm the log.

This self-defining function. Either the vertex shader or the fragment shader. are able to compile.

In fact, the Createshader function is where the vertex shader and fragment shader are handled differently. The rest of the place is the same.


generation and connection 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 basics of the shader) also touched slightly, using variables defined with the varying modifier. The ability to pass data from the vertex shader to the fragment shader.

In fact, the implementation of passing data from one shader to another shader is not something else, it's 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 build program object. and passes the shader to the program object. The shader is then 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);        Infers 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{                //Assuming failure, 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. Assigns a shader.

When the shader is generated. Use the function Createprogram in WebGL. Use the function Attachshader when assigning shaders to program objects. The first parameter of the Attachshader function is the program object, and the second parameter is the shader.
After the shader assignment ends. Depending on the program object, to connect Two shaders, this time using the Linkprogram function, the parameter is the program object.

and generate shaders. To infer whether the connection to the shader was 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. Attention. Assuming this function is not run, the program object is not recognized in WEBGL. 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 HTML code introduces the necessary JavaScript files, 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 an inference whether it is handled correctly.


Next. Prepare the vertex data, i.e. prepare the model data and transform it to VBO. Follow the steps mentioned above and understand all steps in one step. It should be all right, come on.


reprint Please specify: transfer lufy_legend the blog http://blog.csdn.net/lufy_legend

[WebGL Primer] 11, shader compilers and connectors

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.