[Getting Started with WebGL] 15, applying a color to a polygon (specified by vertex color)

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.



The results of this demo run

increase the number of vertex attributes

Last time, we finally drew a triangle, but only a pure white polygon was drawn.
This time, to add a color attribute to the vertices of the polygon, basically doing the same thing as in the previous article, just a little bit more step.
First, as repeated many times before, vertices can contain many kinds of intelligence (reference: vertex cache and Base), and each intelligence is called a vertex attribute. In the previous demo, the vertex species contains only the location information, a vertex attribute, which adds a color vertex property at a time.
A vertex attribute that needs to have something to do with it, remember.
The answer is vertex caching (VBO). In the previous article prepared to save the location of the VBO for rendering, this time to prepare another VBO, while the location of information Vbo and color information Vbo are passed to the vertex shader, to the polygon coloring.


modification of shader code

Well, let's start with the shader code.
This time, you need two attribute variables. To receive the position and color of the vertex, respectively.
> Code for Vertex shaders

Attribute vec3 position;attribute vec4 color;uniform   mat4 mvpmatrix;varying   vec4 vcolor;void Main (void) {    Vcolor = color;    gl_position = Mvpmatrix * VEC4 (Position, 1.0);}
As you can see, the two attribute variables are declared together, and the position is the same as the last one, with no change and a color underneath it to handle the vertex colors.
The varying variable, which did not appear in the previous article, also appeared this time. Think of it as a review, and then briefly, the varying variable is the bridge between the vertex shader and the fragment shader. Take a look at the code in the main function to know that you simply assign the color of the vertex in the attribute variable directly to the varying variable.
with this processing, the vertex properties in the vertex shader can be passed to the fragment shader. Of course, there is no processing required in the vertex shader to pass data to the fragment shader, which is one of the advantages of an editable rendering pipeline.
Next, look at the fragment shader.
code for the > Fragment shader

Precision Mediump float;varying vec4 vcolor;void Main (void) {    gl_fragcolor = Vcolor;}
The fragment shader used in the previous article, directly substituting the color data into the gl_fragcolor, so the triangles are painted in monochrome. This time, using the variable vcolor of the varying type from the vertex shader, the color properties of the vertex affect the polygon.
* Although the varying variable of the same name is used in the vertex shader and fragment shader, it is actually two completely different variables.

>> specifying the accuracy of the precision

This time in the first line of the fragment shader, there is a strange precision, the precision is the keyword used to specify the precision of the numeric value, followed by the precision modifier followed by precision.
There are three kinds of modifiers, and the simple point is to specify the accuracy for top, middle, and bottom. In fact, when the decimals used in a variable change (that is, the number of bits of the processed value increases or decreases), the results are not uniform depending on the environment in which they are run.
LOWP: Low Accuracy
Mediump: in precision
HIGHP: High Accuracy
In the fragment shader code above, precision is followed by mediump float, which means that the precision of the value of the float type in the fragment shader is used in accordance with mediump.
No matter what special processing is done in the fragment shader, the first thing to do is to write the precision related settings, otherwise it will be wrong to compile the shader. It's like a magic spell that can't escape.


Vertex Cache-related processing

After the shader, it's VBO. Although here add some content, in fact, just the same thing done two times, look carefully, you will understand, with the last time basically no change it.
> The matrix of vertex data

Get Attributelocationvar attlocation = new Array (2) from the array, attlocation[0] = gl.getattriblocation (PRG, ' position '); ATTLOCATION[1] = gl.getattriblocation (PRG, ' color ');//Save the number of elements attribute to the array var attstride = new Array (2); attstride[0] = 3; ATTSTRIDE[1] = 4;//The location of the saved Vertex intelligence array var vertex_position = [     0.0, 1.0, 0.0,     1.0, 0.0, 0.0,    -1.0, 0.0, 0.0];//save vertex Array of color information var vertex_color = [    1.0, 0.0, 0.0, 1.0,    0.0, 1.0, 0.0, 1.0,    0.0, 0.0, 1.0, 1.0];
The last vertex attribute has only one, so saving the ordinal of the vertex attribute is a purely variable. This time, the vertex attribute has two, so an array is used. The color is made up of four elements of Rgba, so the array length of the color intelligence is [vertex number x 4].
After you save the vertex data to an array, the next step is to generate the VBO from the array. Here is the code.
> Generating VBO based on an array of vertex data
Generate Vbovar Position_vbo = Create_vbo (vertex_position); var Color_vbo = Create_vbo (Vertex_color);//VBO Binding (location Intelligence) Gl.bindbuffer (GL. Array_buffer, Position_vbo); Gl.enablevertexattribarray (attlocation[0]); Gl.vertexattribpointer (attLocation[0), ATTSTRIDE[0], GL. FLOAT, False, 0, 0);//VBO binding (color Intelligence) Gl.bindbuffer (GL. Array_buffer, Color_vbo); Gl.enablevertexattribarray (attlocation[1]); Gl.vertexattribpointer (attLocation[1), ATTSTRIDE[1], GL. FLOAT, False, 0, 0);
after the generation of VBO, binding, writing data processing, location intelligence and color intelligence are the same, so it is repeated two times the same processing. Some people see here may have some ideas, vbo around the processing, you can directly into a function, the array as a parameter passed in basically solved.

Summary

Above, is the change point compared with the content of the previous article. The main thing is that the processing around the shader and Vbo has little change. If you add another new attribute to the vertex, just follow the gourd, like the contents of this time, according to the same steps, repeat it again, so that you can give the vertex free to add attributes.
Finally, post the demo of this article all the code, links are also given at the end, we can refer to.


Next time, you can draw multiple models by manipulating the model transformation matrix.


HTML code for >demo


>demo's JavaScript code

onload = function () {//Canvas object gets var c = document.getElementById (' canvas ');    C.width = 300;    C.height = 300; WebGL context gets var gl = c.getcontext (' WebGL ') | |        C.getcontext (' Experimental-webgl ');        Sets the color of the canvas initialization gl.clearcolor (0.0, 0.0, 0.0, 1.0);        Sets the depth gl.cleardepth (1.0) when the canvas is initialized; The initialization of the canvas gl.clear (GL. Color_buffer_bit | Gl.        Depth_buffer_bit);    Generation of vertex shader and fragment shader var v_shader = Create_shader (' vs ');        var f_shader = Create_shader (' FS ');        Program object generation and connection var PRG = Create_program (V_shader, F_shader);    Attributelocation gets the var attlocation = new Array (2);    Attlocation[0] = gl.getattriblocation (PRG, ' position ');    ATTLOCATION[1] = gl.getattriblocation (PRG, ' color '); Save the number of elements attribute to the array var attstride = new Array (2), attstride[0] = 3;attstride[1] = 4;//The position of the vertex to save the information array var vertex_position = [0.0, 1.0, 0.0, 1.0, 0.0, 0.0,-1.0, 0.0, 0.0];//Save the vertex's color intelligence array var vertex_color = [1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0];    Generate VBO var Position_vbo = Create_vbo (vertex_position);        var Color_vbo = Create_vbo (Vertex_color); VBO binding (location Intelligence) Gl.bindbuffer (GL.    Array_buffer, Position_vbo);    Gl.enablevertexattribarray (Attlocation[0]); Gl.vertexattribpointer (Attlocation[0], attstride[0], GL.        FLOAT, False, 0, 0); VBO binding (color Intelligence) Gl.bindbuffer (GL.    Array_buffer, Color_vbo);    Gl.enablevertexattribarray (attlocation[1]); Gl.vertexattribpointer (Attlocation[1], attstride[1], GL.        FLOAT, False, 0, 0);        Generate var m = new Mativ () using minmatrix.js to the related processing//Mativ object of the matrix;    Generation and initialization of various matrices var Mmatrix = m.identity (M.create ());    var Vmatrix = m.identity (M.create ());    var PMatrix = m.identity (M.create ());        var Mvpmatrix = m.identity (M.create ());        View transformation coordinate matrix M.lookat ([0.0, 1.0, 3.0], [0, 0, 0], [0, 1, 0], Vmatrix);     Projective coordinate transformation matrix m.perspective (C.width/c.height, 0.1, PMatrix);   Each matrix is formed to obtain the final coordinate transformation matrix m.multiply (PMatrix, Vmatrix, Mvpmatrix);        M.multiply (Mvpmatrix, Mmatrix, Mvpmatrix);        Uniformlocation gain var unilocation = gl.getuniformlocation (PRG, ' Mvpmatrix ');        The Coordinate transformation matrix GL.UNIFORMMATRIX4FV (Unilocation, False, Mvpmatrix) is passed into the uniformlocation; Draw Model Gl.drawarrays (GL.        Triangles, 0, 3);        Context refresh Gl.flush ();                Generate Shader function Create_shader (ID) {//variable var shader to hold 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;} Determine the type attribute of the script tag switch (scriptelement.type) {//vertex shader when case ' X-shader/x-ver Tex ': 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)); }}///program object generation and shader connection functions function Create_program (VS, FS) {//Program object generation var programs = Gl.createprog                Ram ();        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); Return program Object return ProGram        }else{//If failed, pop-up error message alert (Gl.getprograminfolog (program));                }}//Generate VBO function Create_vbo (data) {//Generate cache object var Vbo = Gl.createbuffer (); Bind Cache Gl.bindbuffer (GL.                Array_buffer, VBO); Writes data to the cache Gl.bufferdata (GL. Array_buffer, new Float32array (data), GL.                Static_draw); Set the bound cache to an invalid Gl.bindbuffer (GL.                Array_buffer, NULL);    Returns the generated VBO return VBO; }};

Add a color to the vertex and then draw the Triangle's demo

http://wgld.org/s/sample_003/


reprint Please specify: transfer 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.