官术网_书友最值得收藏!

Defining the shaders

I walked through everything that's being done by the shaders in the previous section. You may want to go through that section again as a refresher. The next part of the code defines the vertex shader code and the fragment shader code in multiline JavaScript strings. Here is the vertex shader code:

var vertex_shader_code = `
precision mediump float;
attribute vec4 a_position;
attribute vec2 a_texcoord;
varying vec2 v_texcoord;
uniform vec4 u_translate;

void main() {
gl_Position = u_translate + a_position;
v_texcoord = a_texcoord;
}
`;

The fragment shader code is as follows:

var fragment_shader_code = `
precision mediump float;
varying vec2 v_texcoord;
uniform sampler2D u_texture;

void main() {
gl_FragColor = texture2D(u_texture, v_texcoord);
}
`;

Let's take a look at the attribute in the vertex shader code:

attribute vec4 a_position;
attribute vec2 a_texcoord;

Those two attributes will be passed in from the data in Float32Array. One of the neat tricks in WebGL is that if you are not using all four position variables (x,y,z,w), you can pass in the two you are using (x,y) and the GPU will know how to use appropriate values in the other two positions. These shaders will require passing in two attributes:

attribute vec4 a_position;
attribute vec2 a_texcoord;

Once again, we will be doing this using buffers and Float32Array. We will also need to pass in two uniform variables. The u_translate variable will be used by the vertex shader to translate the position of the sprite, and u_texture is a texture buffer that will be used by the fragment shader. These shaders are almost as simple as they get. Many tutorials start you out without a texture and just hardcode the color output of the fragment shader, like this:

gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);

Making this change would cause the fragment shader to always output a red color, so please don't make this change. The only things I can think of that could have made this tutorial simpler are not loading the texture and rendering a solid color, and not allowing the geometry to be moved.

主站蜘蛛池模板: 临猗县| 蓬莱市| 日喀则市| 惠安县| 鄂托克旗| 五指山市| 霍州市| 望江县| 夏河县| 高州市| 霍城县| 阿拉善右旗| 曲水县| 固安县| 桂林市| 正蓝旗| 普陀区| 利辛县| 常德市| 上林县| 泽普县| 富源县| 三原县| 綦江县| 和田县| 兰溪市| 襄汾县| 蓝田县| 新余市| 定远县| 读书| 洛浦县| 汉阴县| 岐山县| 海南省| 富锦市| 克什克腾旗| 北票市| 都江堰市| 南丰县| 敦煌市|