57
OpenGL/GLSL Shader Programing CSE 5542

OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

  • Upload
    vocong

  • View
    228

  • Download
    0

Embed Size (px)

Citation preview

Page 1: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

OpenGL/GLSL pShader Programing

CSE 5542

Page 2: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

OpenGL Shading Language (GLSL)(GLSL)

Platform independent Platform independent Compared to Cg (nVidia) or HLSL (Microsoft)A C lik l d i t d i t A C-like language and incorporated into OpenGL 2.0 U d t it Used to write Vertex/fragment shader programs

G / ll i h d Geometry/tessellation shader programs

Page 3: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

O GL/GLSL h dOpenGL/GLSL shader programs

Let’s look at a very simple shader example Let s look at a very simple shader example do_nothing.vert, do_nothing.fragH t i t th h d d li k t How to import the shader program and link to your OpenGL program

SD b Si l C h d S t C SDcubeSimple.C; shaderSetup.C How to pass the vertex attributes from VBOs

to a shader programto a shader program SDcubeSimple.C

Page 4: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

d thi tdo_nothing.vert A very simple shader program A very simple shader program Replace vertex processing in the fixed function

pipelinepipeline Does nothing except passing the vertex position

and color to the fragment shaderand color to the fragment shader This program does not even perform local to clip

space transformation. It assumes that the inputspace transformation. It assumes that the input vertex position is already in clip space This is not a norm; typically you will at least transform

the vertex position to the clip space

Page 5: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

d thi tdo_nothing.vertattribute vec4 position; // the vertex position and color are passed from an opengl programattribute vec4 position; // the vertex position and color are passed from an opengl program

attribute vec4 color;

varying vec4 pcolor; // this is the output variable to the fragment shadervarying vec4 pcolor; // this is the output variable to the fragment shader

// this shader just pass the vertex position and color along, doesn't actually do anything // Note that this means the vertex position is assumed to be already in clip space //

void main(){gl_Position = position; pcolor = color;

}

Page 6: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

d thi fdo_nothing.frag

Replace fragment processing in the fixed Replace fragment processing in the fixed function pipeline Th i t t th f t The input to the fragment program are interpolated attributes from the vertices for the fragmentthe fragment

This fragment program essentially does nothing except passing the fragment color tonothing except passing the fragment color to the frame buffer

Page 7: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

d thi fdo_nothing.fragvarying vec4 pcolor; // Need to match the name with the desired variable fromvarying vec4 pcolor; // Need to match the name with the desired variable from

// the vertex program //// This fragment shader just passes the already interpolated fragment color// This fragment shader just passes the already interpolated fragment color //void main() {

gl FragColor = pcolor; // note that gl FragColor is a default name forgl_FragColor pcolor; // note that gl_FragColor is a default name for // the final fragment color

}

Page 8: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Why do you want me to look at th i l h d ??these simple shader programs??

I want you to learn how to import and link the I want you to learn how to import and link the shader program with an OpenGL program I t t l h t th t I want you to learn how to pass the vertex attributes (position and color in this example) to the shaderto the shader

Page 9: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

S t f Sh d PSetup of Shader Prgorams A shader is defined as an array of strings A shader is defined as an array of strings Steps to use shaders

1 Create a shader program1. Create a shader program 2. Create shader objects (vertex and fragment)3. Send source code to the shader objects4. Compile the shader

1. Create program object by linking compiled shaders togethershaders together

2. Use the linked program object

Page 10: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Create Shader Program and Sh d Obj tShader Objects

• Create a shader program• Create a shader program• Later a vertex and a fragment shader will be attached

to this shader program

GLuint programObject;programObject = glCreateProgram(); // create an overall shader program

p g

programObject glCreateProgram(); // create an overall shader program

if (programObject == 0) { // error checking printf(" Error creating shader program object \n");printf( Error creating shader program object.\n ); exit(1);

} else printf(" Succeeded creating shader program object \n");else printf( Succeeded creating shader program object.\n );

Page 11: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Create Shader Program and Sh d Obj t ( t’d)Shader Objects (cont’d)

• Create vertex and fragment shader objectsGLuint vertexShaderObject;GLuint fragmentShaderObject;

• Create vertex and fragment shader objects

vertexShaderObject = glCreateShader(GL_VERTEX_SHADER);if (vertexShaderObject == 0) { // error checking printf(" Error creating vertex shader object.\n"); exit(1);

} else printf(" Succeeded creating vertex shader object.\n");

fragmentShaderObject = glCreateShader(GL_FRAGMENT_SHADER);if (fragmentShaderObject == 0) { // error checking printf(" Error creating fragment shader object.\n"); exit(1);exit(1);

}

else printf(" Succeeded creating fragment shader object.\n");

Page 12: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Send the source to the shader d iland compile

You need to read the source (.vert and .frag files i ii f t) i t t i fi tin ascii format) into strings first For example, into the following char arrays

GLchar *vertexShaderSource;GLchar vertexShaderSource;GLchar *fragmentShaderSource;

Remember how to use C fopen and fread? something likefh f ( " ")fh = fopen(name, "r");if (fh==NULL) return -1;//// Get the shader from a file.fseek(fh, 0, SEEK_SET);count = fread(shaderText, 1, size, fh);shaderText[count] = '\0';if (ferror(fh)) count = 0;fclose(fh);

Check shaderSetup.C in the example

Page 13: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Send the source to the shader d il ( ’td)and compile (con’td)

Now compile the shaders Now compile the shaders // After reading the shader files, send the source to the shader objects glShaderSource(vertexShaderObject,1,(co nst GLchar**)&vertexShaderSource,NULL);glShaderSource(vertexShaderObject,1,(co nst GLchar )&vertexShaderSource,NULL);glShaderSource(fragmentShaderObject,1,(const GLchar**)&fragmentShaderSource,NULL);

// now compile the shader code; vertex shader first, followed by fragment shader glCompileShader(vertexShaderObject);glCompileShader(vertexShaderObject);glCompileShader(fragmentShaderObject);

Remember you need to do some error checking Remember you need to do some error checking, check shaderSetup.C to see how to do it

Page 14: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Finally, attach and link the h dshader program

Attach the vertex and fragment shader Attach the vertex and fragment shader objects to the shader program and link togethertogether glAttachShader(programObject, vertexShaderObject);glAttachShader(programObject, fragmentShaderObject);glAttachShader(programObject, fragmentShaderObject);glLinkProgram(programObject);

Later you can use the shader program any time before ate you ca use t e s ade p og a a y t e be o eyou render your geometry (See SDcubeSimple.C)… glUseProgram(programObject);g g ( g j )… // OpenGL drawing

Page 15: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Sh d S t SShaders Setup SummaryGLhandle glCreateProgramObject();Glhandle glCreateShaderObject(GL_VERTEX_SHADER);GLhandle glCreateShaderObjectARB(GL_FRAGMENT_SHADER);void glShaderSource(GLhandle shader, GLsizei nstrings, const

GLchar **strings, const GLint *lengths)

//if lengths==NULL, assumed to be null-terminatedvoid glCompileShader(GLhandle shader);id lAtt hObj tARB(GLh dl GLh dl h d )void glAttachObjectARB(GLhandle program, GLhandle shader);

//twice, once for vertex shader & once for fragment shader

void glLinkProgram(GLhandle program);// d t//program now ready to use

void glUseProgramObject(GLhandle program);//switches on shader, bypasses FFP//if 0 h d t d ff t t FFP//if program==0, shaders turned off, returns to FFP

Page 16: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Sh d S t SShaders Setup Summary

Page 17: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Let’s go back to look at the h dshaders

How to pass the vertex attributes to the How to pass the vertex attributes to the vertex shader?

attribute vec4 position; //input: the vertex position and color, passed from an opengl program

attribute vec4 color;varying vec4 pcolor; // this is the output to the fragment shader

void main(){gl_Position = position; pcolor = color;

}

Page 18: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Passing vertex attributes to th ( t ) h dthe (vertex) shader

In your OpenGL program do the following: In your OpenGL program, do the following: 1. ID = Query the location of the shader variable2 Enable the attribute array2. Enable the attribute array 3. Map the attribute array to ID GLuint c0 = glGetAttribLocation(programObject, "position"); GLuint c1 = glGetAttribLocation(programObject, "color”)…glEnableVertexAttribArray(c0); g y( );glEnableVertexAttribArray(c1); …glVertexAttribPointer(c0,4,GL_FLOAT, GL_FALSE, sizeof(Vertex),(char*) NULL+0)glVertexAttribPointer(c1 4 GL FLOAT GL FALSE sizeof(Vertex) (char*) NULL+16);glVertexAttribPointer(c1,4,GL_FLOAT, GL_FALSE, sizeof(Vertex),(char ) NULL+16); …

glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_BYTE, (char*) NULL+0);

Page 19: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

S t f Att ib t V i blSetup of Attribute VariablesReturn Function Name ParametersReturn type

Function Name Parameters

GLint glGetAttribLocation GLuint programconst GLchar * name

void glVertexAttribPointer GLuint index, GLint sizeGLenum typeGlboolean normalized, GLsizei strideconst GLvoid * pointer

void glEnableVertexAttribArray GLuint index

1. Get ID of the attribute2 M th i t t th f t tt ib t t thi ID2. Map the pointer to the array of per-vertex attribute to this ID3. Enable this attribute

Page 20: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

How do vertex and fragment h d i t ?shaders communicate?

Through the varying variable Through the varying variable

attribute vec4 position; varying vec4 pcolor; attribute vec4 color;

varying vec4 pcolorvoid main(){

void main(){

gl_FragColor = pcolor; }

gl_Position = position; pcolor = color;

}

Vertex Program Fragment Program

Page 21: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Let’s make the vertex shader ddo more Transform the vertex position from local space to clip Transform the vertex position from local space to clip

space Any vertex program is expected to perform the transformation

Assume you use the OpenGL fixed function pipeline (like in Lab 2) and set up GL_MODELVIEW and GL PROJECTIONGL_PROJECTION

attribute vec4 position; attribute vec4 color;

i 4 lvarying vec4 pcolor;

void main(){pcolor = color; gl_Position = gl_ModelViewProjectionMatrix * position;

}

Page 22: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Use your own transformation t imatrix

Need to pass the modelview projection matrix Need to pass the modelview projection matrix (projection*modelview) to the vertex shader

Let’s look at the vertex program first Let s look at the vertex program firstattribute vec4 position; attribute vec4 color; uniform mat4 local2clip; // this is the concatenated modlview projection matrix passed from youruniform mat4 local2clip; // this is the concatenated modlview projection matrix passed from your

// OpenGL program

varying vec4 pcolor;

void main(){ pcolor = color1; gl_Position = local2clip * position;

}

Page 23: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

How to pass the matrices to th t h dthe vertex shader

You can pass any matrices to the shader as You can pass any matrices to the shader as desired For example modeling matrix viewing matrix For example, modeling matrix, viewing matrix,

projection matrix, modelview matrix, or modelviewprojection matrix p j

These matrices are uniform variable Uniform variables remain the same values for Uniform variables remain the same values for

all vertices/fragments i.e., you cannot change their values between i.e., you cannot change their values between

vertices (between glBegin/glEnd or within VBOs

Page 24: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Set the values of uniform variables to shaders (a glm example)glUseProgram(programObject);

…// get the location of the uniform variable in the shader

GLuint m1 = glGetUniformLocation(programObject, "local2clip"); …glm::mat4 projection = glm::perspective(60 0f 1 0f 1f 100 0f);glm::mat4 projection glm::perspective(60.0f,1.0f,.1f,100.0f); glm::mat4 view = glm::lookAt(glm::vec3(0.0, 0.0, 5.0),

glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.0, 0.0));

glm::mat4 model = glm::mat4(1 0f);glm::mat4 model = glm::mat4(1.0f); model = glm::rotate(model, x_angle, glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::rotate(model, y_angle, glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::scale(model, scale_size, scale_size, scale_size);

// construct the modelview and modelview projection matrices glm::mat4 modelview = view * model; glm::mat4 modelview_projection = projection * modelview;

// pass the modelview_projection matrix to the shader as a uniform glUniformMatrix4fv(m1, 1, GL_FALSE, &modelview_projection[0][0]);

Page 25: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

S t f U if V i blSetup of Uniform VariableU if V i bl Th S C t t f ll V ti /F t

attribute: varying varying:

Uniform Variable: The Same Content for all Vertices/Fragments

vertices

Vertex Shader

Fragment Shader

vertices

primitives

TransformAnd Lighting Clipping

PrimitiveAssembly

AndRasterization

TextureStages

FragmentTesting

Return type Function Name Parameters

GLint glGetUniformLocation GLuint programconst GLchar * name

void glUniformXX GLint locationDepends on XX

Page 26: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Vertex Shader: F tt ib t t iFrom attribute to varying

attribute: • input to the vertex shader;• Defined per vertex;

varying • Output of vertex shader

varying:Input of fragment shader per fragment

vertices

Vertex Shader

Fragment Shader

Output of vertex shader• Defined per vertex

vertices

primitives

TransformAnd Lighting Clipping

PrimitiveAssembly

AndRasterization

TextureStages

FragmentTesting

varying variables will be interpolated in a perspective-correct p pfashion across the primitives Rasterization of Lines/Polygons

http://iloveshaders.blogspot.com/2011/05/how-rasterization-process-works.html

Page 27: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Lighting ExampleV t Sh dVertex Shadervarying vec4 diffuseColor;y gvarying vec3 fragNormal;varying vec3 lightVector;

uniform vec3 eyeSpaceLightVector;uniform vec3 eyeSpaceLightVector;

void main(){

vec3 eyeSpaceVertex= vec3(gl_ModelViewMatrix * gl_Vertex);lightVector= vec3(normalize(eyeSpaceLightVector -eyeSpaceVertex));fragNormal = normalize(gl_NormalMatrix * gl_Normal);

diffuseColor = gl_Color;gl Position = gl ModelViewProjectionMatrix * gl Vertex;gl_Position = gl_ModelViewProjectionMatrix gl_Vertex;

}

Page 28: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Lighting ExampleF t Sh dFragment Shadervarying vec4 diffuseColor;y gvarying vec3 lightVector;varying vec3 fragNormal;

void main(){void main(){

floatperFragmentLighting=max(dot(lightVector,fragNormal),0.0);;

gl_FragColor = diffuseColor * lightingFactor;

}

Page 29: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

T Sh di E lToon Shading Example Toon Shading Toon Shading Characterized by abrupt

change of colors Vertex Shader computes

the vertex intensity (declared as varying)( y g)

Fragment Shader computes colors for the fragment based on thefragment based on the interpolated intensity

Page 30: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

V t Sh dVertex Shader

uniform vec3 lightDir;uniform vec3 lightDir;varying float intensity;void main() {

vec3 ld; intensity = dot(lightDir,gl_Normal); gl_Position = ftransform();

}

Page 31: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

F t Sh dFragment Shadervarying float intensity;varying float intensity;

void main() {void main() { vec4 color; if (intensity > 0.95) color = vec4(1.0,0.5,0.5,1.0); else if (intensity > 0.5) color = vec4(0.6,0.3,0.3,1.0); else if (intensity > 0.25) color = vec4(0.4,0.2,0.2,1.0); l l 4(0 2 0 1 0 1 1 0)else color = vec4(0.2,0.1,0.1,1.0);

gl_FragColor = color;}}

Page 32: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

V i V i bl E lVarying Variable ExampleDetermine color based on x y z coordinatesDetermine color based on x y z coordinates

Page 33: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

V t Sh dVertex Shadervarying float xpos;varying float xpos; varying float ypos; varying float zpos;varying float zpos;

void main(void) { xpos = clamp(gl_Vertex.x,0.0,1.0); ypos = clamp(gl_Vertex.y,0.0,1.0); zpos = clamp(gl_Vertex.z,0.0,1.0); gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;

}}

Page 34: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

F t Sh dFragment Shader

i fl tvarying float xpos; varying float ypos; varying float zpos;varying float zpos;

void main (void) { ( ) {gl_FragColor = vec4 (xpos, ypos, zpos, 1.0);

}

Page 35: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

C l K E lColor Key Example

Set a certain color (say FF00FF as Set a certain color (say FF00FF as transparent

Page 36: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

V t Sh dVertex Shader

void main(void) {

gl_TexCoord[0] = gl_MultiTexCoord0;

gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;

}}

Page 37: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

F t Sh dFragment Shaderuniform sampler2D myTexture;uniform sampler2D myTexture;

#define epsilon 0.0001

void main (void) {vec4 value = texture2D(myTexture, v

2( l T C d[0]))ec2(gl_TexCoord[0])); if (value[0] > 1.0-epsilon) && (value[2] > 1.0-epsilon))

discard; gl_FragColor = value;

}

Page 38: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Color Map ExampleColor Map Example

Suppose you want to render an object such Suppose you want to render an object such that its surface is colored by the temperature. You have the temperatures at the vertices. You have the temperatures at the vertices. You want the color to be interpolated between the

coolest and the hottest colors. Previously, you would calculate the colors of

the vertices in your program, and say y p g yglColor().

Now, lets do it in the vertex and pixel , pshaders…

Page 39: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Vertex shaderVertex shader// uniform qualified variables are changed at most once// per primitiveuniform float CoolestTemp;uniform float TempRange;p g ;

// attribute qualified variables are typically changed per vertexattribute float VertexTemp;attribute float VertexTemp;

// varying qualified variables communicate from the vertex// h d t th f t h d// shader to the fragment shadervarying float Temperature;

Page 40: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Vertex shaderVertex shadervoid main(){

// compute a temperature to be interpolated per fragment,// in the range [0.0, 1.0]T t (V t T C l tT ) / T RTemperature = (VertexTemp - CoolestTemp) / TempRange;/*The vertex position written in the application using glVertex() can be read from the built in variable gl Vertex Use this value andbe read from the built-in variable gl_Vertex. Use this value and the current model view transformation matrix to tell the rasterizer where this vertex is. Could use ftransform(). */gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;g _ g _ j g _

}

Page 41: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Fragment ShaderFragment Shader// uniform qualified variables are changed at most// once per primitive by the application, and vec3// declares a vector of three floating-point numbersuniform vec3 CoolestColor;uniform vec3 CoolestColor;uniform vec3 HottestColor;

// Temperature contains the now interpolated// per-fragment value of temperature set by the// vertex shader// vertex shadervarying float Temperature;

Page 42: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Fragment ShaderFragment Shadervoid main(){

// get a color between coolest and hottest colors, using// the mix() built-in function()vec3 color = mix(CoolestColor, HottestColor, Temperature);// make a vector of 4 floating-point numbers by appending an// alpha of 1 0 and set this fragment’s color// alpha of 1.0, and set this fragment s colorgl_FragColor = vec4(color, 1.0);

}

Page 43: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Additi l GLSL I fAdditional GLSL Info

Built-in names for accessing OpenGL states and for communicating with OpenGL fixed functionality

l P iti gl_Position gl_FragCoord/gl_FrontFacing/gl_ClipDistance[]/gl_PointCoord/gl

_PrimitiveID/gl_SampleID/gl_SamplePosition/gl_SampleMaskIn[];;

Type qualifiers attribute, uniform, and varying O i / t i O GL 3 X/4 X Or in/out in OpenGL 3.X/4.X

Page 44: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

TTypes Vector types are supported for floats integers and Vector types are supported for floats, integers, and

booleans Can be 2-, 3-, or 4- components float vec2 vec3 vec4 float, vec2, vec3, vec4 int, ivec2, ivec3, ivec4 bool, bvec2, bvec3, bvec4

Matrix types mat2, mat3, mat4

Texture access sampler1D, sampler2D, sampler3D

The complete list of GLSL data types functions are in Section 4 of GLSL Spec 4.2.

Page 45: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

B ilt i F tiBuilt-in Functions

Trigonometry/angle radians, degrees, sin, cos, tan, asin, acos, atan

Exponential pow, exp2, log2, sqrt, inversesqrt

Geometric and matrix length distance dot cross normalize ftransformGeometric and matrix length, distance, dot, cross, normalize, ftransform, faceforward, reflect, matrixCompMult

Misc abs, sign, floor, ceil, fract, mod, min, max, clamp, mix, step, smoothstep

The complete list of build-in functions are in Section 8 of GLSL Spec 4.2.

Page 46: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Vertex Program CapabilitiesVertex Program Capabilities Vertex program can do general processing, including things like:

Vertex transformation Normal transformation, normalization and rescaling Lighting Color material application Clamping of colors Texture coordinate generationg Texture coordinate transformation

Vertex Fragment

vertices

Shader

Primitive

gShader

primitives

TransformAnd Lighting Clipping Assembly

AndRasterization

TextureStages

FragmentTesting

Page 47: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Varialbe Qualifies: From attributet i d ifto varying under uniform

attribute: • input to the vertex shader;• Defined per vertex;Defined per vertex;• E.g vertex

color/normal/coordinates varying

O fVertex Shader

Fragment Shader

• Output of vertex shader• Defined per vertex

vertices

primitives

TransformAnd Lighting Clipping

PrimitiveAssembly

AndRasterization

TextureStages

FragmentTesting

Uniform: The same information used by all vertices/fragment.e.g ModelView transformation matrices

Page 48: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Vertex shader: Example Usage of Att ib t /V i /U ifAttribute/Varying/Uniform// uniform qualified variables are changed at void main()q g

most once// per primitiveuniform float CoolestTemp;uniform float TempRange;

{/*compute a temperature to be interpolated per fragment,in the range [0.0, 1.0]p g ;

// attribute qualified variables are typically changed per vertex

attribute float VertexTemp;

g [ , ]*/Temperature = (VertexTemp - CoolestTemp) / TempRange;

gl Position = ftransform();p;

// varying qualified variables communicate from the vertex

// shader to the fragment shader

gl_Position ftransform();}

gvarying float Temperature;

Page 49: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Intervening Fixed FunctionalityIntervening Fixed Functionality Results from vertex processing undergo:

Perspective division on clip coordinates Viewport mapping Clipping, including user clipping Color clamping or masking (for built-in varying variables that deal with color, but p g g ( y g ,

not user-defined varying variables) Depth range Front face determination and culling Interpolate colors texture coordinate and user-defined varying variables Interpolate colors, texture coordinate, and user defined varying variables Etc.

vertices

Vertex Shader

Fragment Shader

vertices

primitives

TransformAnd Lighting Clipping

PrimitiveAssembly

AndRasterization

TextureStages

FragmentTesting

Page 50: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Intervening Fixed Functionality: R t i tiRasterization

Rasterization of Lines1Rasterization of Lines/Polygons2Rasterization of Lines1 Lines/Polygons2

1. OpenGL 4.2 SPEC, 08/22/2011.2. http://iloveshaders.blogspot.com/2011/05/how-rasterization-process-works.html

Page 51: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Fragment Program CapabilitiesFragment Program CapabilitiesFragment shader can do general processing, like:

Operations on interpolated values Texture access Texture applicationpp Fog Color sum Color matrix Discard fragment etc

vertices

Vertex Shader

Fragment Shader

vertices

primitives

TransformAnd Lighting Clipping

PrimitiveAssembly

AndRasterization

TextureStages

FragmentTesting

Page 52: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

F t PFragment Program Output of vertex shader is the input to the fragment Output of vertex shader is the input to the fragment

shader Compatibility is checked when linking occurs Compatibility between the two is based on varying variables that Compatibility between the two is based on varying variables that

are defined in both shaders and that match in type and name

F t h d i t d f h f t Fragment shader is executed for each fragment produced by rasterization

For each fragment, fragment shader has access to the interpolated value for each varying variable Color normal texture coordinates arbitrary values Color, normal, texture coordinates, arbitrary values

Page 53: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Fragment Processor OutputFragment Processor Output

In OpenGL 2.Xp Output of the fragment processor goes on to the fixed

function fragment operations and frame buffer operations using built-in variablesoperations using built in variables

gl_FragColor – computed R, G, B, A for the fragment gl_FragDepth – computed depth value for the fragment gl FragData[n] – arbitrary data per fragment stored in multiple gl_FragData[n] – arbitrary data per fragment, stored in multiple

render targets

Page 54: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

F t Sh d E lFragment Shader: Example// uniform qualified variables are changed at

tvoid main()

most// once per primitive by the application, and vec3// declares a vector of three floating-point

numbersuniform vec3 CoolestColor;

(){

// get a color between coolest and hottest colors, using// the mix() built-in function

uniform vec3 HottestColor;

// Temperature contains the now interpolated// per-fragment value of temperature set by the// vertex shader

()vec3 color = mix(CoolestColor, HottestColor, Temperature);// make a vector of 4 floating-point numbers by appending an// vertex shader

varying float Temperature; // alpha of 1.0, and set this fragment’s colorgl_FragColor = vec4(color, 1.0);

}

Page 55: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

Fragment Program CapabilitiesFragment Program Capabilities Pass the fragment shader output to framebuffers for the g p

following test Scissor test/Alpha test/Depth test/Stencil test/Blending, etc. Values are destined for writing into the frame buffer if all back Values are destined for writing into the frame buffer if all back

end tests (stencil, depth etc.) pass

Cl i f t i t th t t b ff i d Clamping or format conversion to the target buffer is done automatically outside of the fragment shader

vertices

Vertex Shader

Fragment Shader

vertices

primitives

TransformAnd Lighting Clipping

PrimitiveAssembly

AndRasterization

TextureStages

FragmentTesting

Page 56: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

GLSL f O GL 3 X/4 XGLSL for OpenGL 3.X/4.X Two profiles for shader languages Two profiles for shader languages Compatibility (1.X/2.X) Core (3.X/4.X)

Main changes Main changes Reduction of built-in states

No transformation matrix,No lighting No lighting,

No built-in attributes for vertex/colors/normals, etc Change of type qualifiers

Additi l bl t Additional programmable stages Geometry/Tessellation shader

Much more …

The features for compatibility profile are listed in GLSL Spec 4.2.

Page 57: OpenGL/GLSL Shader Programingweb.cse.ohio-state.edu/~wang.3602/courses/cse5542-2013-spring/13... · varying vec4 pcolor;varying vec4 pcolor; // this is the output variable to the

O GL 3 X T Q lifiOpenGL 3.X: Type Qualifiers in

for function parameters copied into a function, but not copied out

out for function parameters copied out of a function but not copied in for function parameters copied out of a function, but not copied in

Can be combined with auxiliary storage qualifiers centroid/sample/patch

Vertex Shader

Fragment Shader

attribute(in) varying(out) varying(in) out

verticesTransform Clipping

PrimitiveAssembly Texture Fragment

primitivesAnd Lighting Clipping y

AndRasterization

Stagesg

Testing

The complete list of GLSL data types functions are in Section 4.3 of GLSL Spec 4.2.