-
Notifications
You must be signed in to change notification settings - Fork 26
Shaders
Shaders are simple programs that describe the traits of either a vertex or a fragment (pixel).
Vertex shaders describe the traits (position, texture coordinates, colors, etc.) of a vertex, while fragment shaders describe the traits (color, z-depth and alpha value) of a pixel.
All shaders have basic abstract class Shader
.
Lets create a new shader for coloring image to the defined color.
Create a new subfolder or package in your prospective shader package. For example: source
Using GLSL shader language write vertex and fragment shaders.
Vertex shader: colorify.vs
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}
Fragment Shader: colorify.fs
uniform vec3 color;
uniform sampler2D tDiffuse;
varying vec2 vUv;
void main() {
vec4 texel = texture2D( tDiffuse, vUv );
vec3 luma = vec3( 0.299, 0.587, 0.114 );
float v = dot( texel.xyz, luma );
gl_FragColor = vec4( v * color, texel.w );
}
public final class ColorifyShader extends Shader
{
interface Resources extends DefaultResources
{
Resources INSTANCE = GWT.create(Resources.class);
@Source("source/colorify.vs")
TextResource getVertexShader();
@Source("source/colorify.fs")
TextResource getFragmentShader();
}
public ParticleBasicShader()
{
super(Resources.INSTANCE);
}
@Override
protected void initUniforms()
{
this.addUniform("tDiffuse", new Uniform(Uniform.TYPE.T ));
this.addUniform("color", new Uniform(Uniform.TYPE.C, new Color( 0xffffff )));
}
}
Sometimes is needed to update or generate shader source dynamically.
To do this you should insert special mark [*]
into shader source:
uniform vec3 diffuse;
uniform float opacity;
[*]
void main() {
gl_FragColor = vec4( diffuse, opacity );
[*]
}
Then override updateVertexSource
or updateFragmentSource
methods in your shader class:
@Override
protected void updateVertexSource(String src)
{
String firstIns = "//The first insert";
String secondIns = "//The second insert";
super.updateVertexSource(Shader.updateShaderSource(src, firstIns, secondIns));
}
Basically shaders are used as materials for different objects. Or you can use shaders for postprocessing purpose.
If you want to use shaders as material you should use ShaderMaterial
class.
FresnelShader shader = new FresnelShader();
shader.getUniforms().get("tCube").setValue(textureCube);
ShaderMaterial material = new ShaderMaterial( shader );
Mesh mesh = new Mesh( new SphereGeometry( 100, 32, 16 ), material );