GLSL寫vertex shader和fragment shader
阿新 • • 發佈:2018-11-10
0.一般來說vertex shader處理頂點座標,然後向後傳輸,經過光柵化之後,傳給fragment shader,其負責顏色、紋理、光照等等。
前者處理之後變成裁剪座標系(三維),光柵化之後一般認為變成二維的裝置座標系
1.每個頂點有多個屬性時的頂點著色器:
1 #version 330 core 2 layout (location = 0) in vec3 aPos; 3 layout (location = 1) in vec3 aColor; 4 layout (location = 2) in vec2 aTexCoord; 5 6 out vec3 ourColor;View Code7 out vec2 TexCoord; 8 9 void main() 10 { 11 gl_Position = vec4(aPos, 1.0); 12 ourColor = aColor; 13 TexCoord = aTexCoord; 14 }
2.只處理紋理的片元著色器:
1 #version 330 core 2 out vec4 FragColor; 3 4 in vec3 ourColor; 5 in vec2 TexCoord; 6 7 uniform sampler2D ourTexture;View Code8 9 void main() 10 { 11 FragColor = texture(ourTexture, TexCoord); 12 }
3.將2中的紋理新增之後再加入頂點的顏色,片元著色器咋寫呢:
1 #version 330 core 2 out vec4 FragColor; 3 4 in vec3 ourColor; 5 in vec2 TexCoord; 6 7 uniform sampler2D ourTexture; 8 9 void main() 10 { 11 FragColor = texture(ourTexture, TexCoord);View Code12 FragColor = texture(ourTexture, TexCoord) * vec4(ourColor, 1.0); 13 }
4.渲染多個紋理咋辦呢?
1 #version 330 core 2 ... 3 4 uniform sampler2D texture1; 5 uniform sampler2D texture2; 6 7 void main() 8 { 9 FragColor = mix(texture(texture1, TexCoord), texture(texture2, TexCoord), 0.2); 10 }View Code