OpenGL/GLSL p Shader Programing

boringtarpSoftware and s/w Development

Dec 13, 2013 (3 years and 7 months ago)

247 views

O
p
enGL/GLSL
p
Shader Programing
CSE 5542
OpenGL Shading Language
(GLSL)
(GLSL)
Platformindependent

Platform

independent


Compared to Cg (nVidia) or HLSL (Microsoft)
AC
liklditdit

A

C
-
lik
e
l
anguage an
d

i
ncorpora
t
e
d

i
n
t
o
OpenGL 2.0
Udtit

U
se
d

t
o wr
it
e

Vertex/fragment shader programs
G/llihd

G
eometry
/
tesse
ll
at
i
on s
h
a
d
er programs
OGL/GLSLhd
O
pen
GL/GLSL
s
h
a
d
er programs
Let

slookataverysimpleshaderexample

Lets

look

at

a

very

simple

shader

example

do_nothing.vert, do_nothing.frag
Htitthhddlikt

H
ow
t
o
i
mpor
t

th
e s
h
a
d
er program an
d

li
n
k

t
o
your OpenGL program
SDbSilChdStC

SD
cu
b
e
Si
mp
l
e.
C
; s
h
a
d
er
S
e
t
up.
C

How to pass the vertex attributes from VBOs
toashaderprogram
to

a

shader

program


SDcubeSimple.C
dthit
d
o_no
thi
ng.ver
t

Averysimpleshaderprogram

A

very

simple

shader

program

Replace vertex processing in the fixed function
pipeline
pipeline


Does nothing except passing the vertex position
andcolortothefragmentshader
and

color

to

the

fragment

shader


This program does not even perform local to clip
spacetransformation.Itassumesthattheinput
space

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
dthit
d
o_no
thi
ng.ver
t
attributevec4position;/
/thevertexpositionandcolorarepassedfromanopenglprogram
attribute

vec4

position;

/
/

the

vertex

position

and

color

are

passed

from

an

opengl

program

attribute vec4 color;
varyingvec4pcolor;
//thisistheoutputvariabletothefragmentshader
varying

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;
}
dthif
d
o_no
thi
ng.
f
rag
Replacefragmentprocessinginthefixed

Replace

fragment

processing

in

the

fixed

function pipeline
Thittthft

Th
e
i
npu
t

t
o
th
e
f
ragmen
t
program are
interpolated attributes from the vertices for
thefragment
the

fragment

This fragment program essentially does
nothingexceptpassingthefragmentcolorto
nothing

except

passing

the

fragment

color

to

the frame buffer
dthif
d
o_no
thi
ng.
f
rag
varyingvec4pcolor;//Needtomatchthenamewiththedesiredvariablefrom
varying

vec4

pcolor;

//

Need

to

match

the

name

with

the

desired

variable

from

// the vertex program
//
//Thisfragmentshaderjustpassesthealreadyinterpolatedfragmentcolor
//

This

fragment

shader

just

passes

the

already

interpolated

fragment

color

//
void main() {
glFragColor
=
pcolor;//notethat
glFragColor
isadefaultnamefor
gl
_
FragColor

pcolor;

//

note

that

gl
_
FragColor
is

a

default

name

for

// the final fragment color
}
Why do you want me to look at
thilhd??
th
ese s
i
mp
l
e s
h
a
d
er programs
??
Iwantyoutolearnhowtoimportandlinkthe

I

want

you

to

learn

how

to

import

and

link

the

shader program with an OpenGL program
Ittlhttht

I
wan
t
you
t
o
l
earn
h
ow
t
o pass
th
e ver
t
ex
attributes (position and color in this example)
totheshader
to

the

shader

StfShdP
S
e
t
up o
f

Sh
a
d
er
P
rgorams

Ashaderisdefinedasanarrayofstrings

A

shader

is

defined

as

an

array

of

strings

Steps to use shaders
1
Createashaderprogram
1
.
Create

a

shader

program

2.
Create shader objects(vertex and fragment)
3.
Send sourcecode to the shader objects
4.
Compile the shade
r
1.
Create program objectby linking compiled
shaderstogether
shaders

together
2.
Use the linked program object
Create Shader Program and
ShdObjt
Sh
a
d
er
Obj
ec
t
s

Createashaderprogram

Create

a

shader

program
•Later a vertex and a fragment shader will be attached
to this shader
p
ro
g
ram
GLuint programObject;
programObject
=
glCreateProgram();//createanoverallshaderprogram
pg
programObject

glCreateProgram();

//

create

an

overall

shader

program
if (programObject == 0) { // error checking
printf(
"
Errorcreatingshaderprogramobject
\
n
"
);
printf(

Error

creating

shader

program

object
.
\
n);

exit(1);
}
elseprintf(
"
Succeededcreatingshaderprogramobject
\
n
"
);
else

printf(

Succeeded

creating

shader

program

object
.
\
n);

Create Shader Program and
ShdObjt(t’d)
Sh
a
d
er
Obj
ec
t
s
(
con
t’d)

Createvertexandfragmentshaderobjects
GLuint 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");
Send the source to the shader
dil
an
d
comp
il
e

You need to read the source (.vert and .frag files
iiift)ittifit
i
n asc
ii

f
orma
t)

i
n
t
o s
t
r
i
ngs
fi
rs
t


For example, into the following char arrays
GLchar
*
vertexShaderSource;
GLchar

vertexShaderSource;
GLchar *fragmentShaderSource;

Remember how to use C fopen and fread? something like
fhf("")
fh
=
f
open
(
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
Send the source to the shader
dil(’td)
an
d
comp
il
e
(
con
’td)
Nowcompiletheshaders

Now

compile

the

shaders

// After reading the shader files, send the source to the shader objects
glShaderSource(vertexShaderObject,1,(constGLchar
**
)&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);

剥浥浢敲祯y湥敤瑯摯獯浥敲牯ec桥捫楮h

剥浥浢敲

祯y

湥敤





獯浥

敲牯e

捨散歩湧

捨散欠獨慤敲卥瑵瀮䌠瑯⁳敥⁨潷⁴漠摯⁩c
Finally, attach and link the
hd
s
h
a
d
er program
Attachthevertexandfragmentshader

Attach

the

vertex

and

fragment

shader

objects to the shader program and link
together
together

glAttachShader(programObject, vertexShaderObject);
glAttachShader(programObject,fragmentShaderObject);
glAttachShader(programObject,

fragmentShaderObject);
glLinkProgram(programObject);

L
ate
r
you

ca
n
use

t
h
e

s
h
ade
r
p
r
og
r
a
m
a
n
y

t
im
e

be
f
o
r
e

ateyoucausetesadepogaaytebeoe
you render your geometry (See SDcubeSimple.C)…
g
lUsePro
g
ram
(
pro
g
ramOb
j
ect
)
;
gg(gj)
… // OpenGL drawing
ShdStS
Sh
a
d
ers
S
e
t
up
S
ummary
GLhandle 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-terminated
void glCompileShader(GLhandle shader);
idlAtthObjtARB(GLhdlGLhdlhd)
vo
id
g
lAtt
ac
hObj
ec
tARB(GLh
an
dl
e program,
GLh
an
dl
e s
h
a
d
er
)
;
//twice, once for vertex shader & once for fragment shader
void glLinkProgram(GLhandle program);
//dt
//
program now rea
d
y
t
o use
void glUseProgramObject(GLhandle program);
//switches on shader, bypasses FFP
//if0hdtdffttFFP
//if
program==
0
, s
h
a
d
ers
t
urne
d
o
ff
, re
t
urns
t
o
FFP
ShdStS
Sh
a
d
ers
S
e
t
up
S
ummary
Let’s go back to look at the
hd
s
h
a
d
ers
Howtopassthevertexattributestothe

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;
}
Passing vertex attributes to
th(t)hd
th
e
(
ver
t
ex
)
s
h
a
d
e
r
InyourOpenGLprogramdothefollowing:

In

your

OpenGL

program
,
do

the

following:

1.
ID = Query the location of the shader variable
2
Enabletheattributearray
2
.
Enable

the

attribute

array

3.
Map the attribute array to ID
GLuint c0 = glGetAttribLocation(programObject, "position");
GLuint c1 = glGetAttribLocation(programObject, "color”)

g
lEnableVertexAttribArra
y(
c0
);

gy();
glEnableVertexAttribArray(c1);

glVertexAttribPointer(c0,4,GL_FLOAT, GL_FALSE, sizeof(Vertex),(char*) NULL+0)
glVertexAttribPointer(c14GLFLOATGLFALSEsizeof(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);
Stf
Attibt
Vibl
S
e
t
up o
f

Att
r
ib
u
t
e
V
ar
i
a
bl
es
Return
FunctionName
Parameters
Return

type
Function

Name
Parameters
GLint glGetAttribLocationGLuint program
const GLchar * name
void glVertexAttribPointerGLuint index,
GLint size
GLenum type
Glboolean normalized,
GLsizei stride
const GLvoid * pointer
void glEnableVertexAttribArrayGLuint index
1.Get ID of the attribute
2
Mthittthf
tttibttthiID
2
.
M
ap
th
e po
i
n
t
er
t
o
th
e array o
f
pe
r
-ver
t
ex a
tt
r
ib
u
t
e
t
o
thi
s
ID
3.Enable this attribute
How do vertex and fragment
hdit?
s
h
a
d
ers commun
i
ca
t
e
?


Throughthe
varying
variable

Through

the

varying
variable

attribute vec4 position;
varying vec4 pcolor;
attribute vec4 color;
varying vec4 pcolor
void main()
{
void main()
{
gl_FragColor = pcolor;
}
gl_Position = position;
pcolor = color;
}
Vertex Program
Fragment Program
Let’s make the vertex shader
d
d
o more

Transformthevertexpositionfromlocalspacetoclip

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
GLPROJECTION
GL
_
PROJECTION
attribute vec4 position;
attribute vec4 color;
i4l
vary
i
ng vec
4
pco
l
or;
void main(){
pcolor = color;
gl_Position = gl_ModelViewProjectionMatrix * position;
}
Use your own transformation
ti
ma
t
r
i
x

Needtopassthemodelviewprojectionmatrix

Need

to

pass

the

modelview

projection

matrix

(projection*modelview) to the vertex shader

䱥L
’
s汯潫慴瑨tv敲瑥ep牯杲慭晩牳f

䱥Ls

汯潫



瑨t

癥牴數

灲潧牡p

晩牳f
慴瑲楢畴攠癥挴a灯獩瑩潮㬠
慴瑲楢畴攠癥挴e捯汯爻c
uniformmat4local2clip
;//thisistheconcatenatedmodlviewprojectionmatrixpassedfromyour
uniform

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;
}
How to pass the matrices to
ththd
th
e ver
t
ex s
h
a
d
e
r
Youcanpassanymatricestotheshaderas

You

can

pass

any

matrices

to

the

shader

as

desired

䙯Fe硡浰汥浯摥汩湧m慴物av楥睩湧浡瑲楸

䙯F

數慭灬e

浯摥汩湧

浡瑲楸

癩敷楮v

浡瑲楸

灲潪散瑩潮慴物砬潤敬癩敷慴物砬爠
浯摥汶楥m
p

j
散瑩潮慴物砠


These matrices are uniformvariable

啮楦潲Uv慲楡扬敳牥浡楮瑨ts慭av慬略a景f

啮楦潲U

癡物慢汥v

牥浡楮

瑨t

獡浥

癡汵敳

景f

慬氠癥牴楣敳⽦牡杭敮瑳

椮攮iy潵捡湮潴捨慮来瑨敩tv慬略a扥瑷敥b

椮攮i

祯y

捡湮潴

捨慮来

瑨敩t

癡汵敳

扥瑷敥b

癥牴楣敳
扥瑷敥渠杬䉥杩港杬䕮搠潲⁷楴桩渠噂佳†
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::mat4projection
=
glm::perspective(600f10f1f1000f);
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::mat4model=glm::mat4(10f);
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]);
Stf
Uif
Vibl
S
e
t
up o
f

U
n
if
orm
V
ar
i
a
bl
e
UifViblThSCttfllVti/Ft
attribute:
varying
varying:
U
n
if
orm
V
ar
i
a
bl
e:
Th
e
S
ame
C
on
t
en
t

f
or a
ll

V
er
ti
ces
/F
ragmen
t
s
vertices
V
ertex
Shader
Fragment
Shader
vertices
primitives
Transform
And Lighting
Clipping
Primitive
Assembly
And
Rasterization
Texture
Stages
Fragment
Testing
Return typeFunction NameParameters
GLint glGetUniformLocationGLuint program
const GLchar * name
void glUniformXXGLint location
Depends on XX
Vertex Shader:
F
ttibt
t
i
F
rom a
tt
r
ib
u
t
e
t
o vary
i
n
g
attribute:
•input to the vertex shader;
•Defined per vertex;
varying

Outputofvertexshader
varying:
Input of fragment shaderper fragment
vertices
V
ertex
Shader
Fragment
Shader
Output

of

vertex

shader
•Defined per vertex
vertices
primitives
Transform
And Lighting
Clipping
Primitive
Assembly
And
Rasterization
Texture
Stages
Fragment
Testing
varyingvariables will
be interpolatedin a
p
ers
p
ective-correct
pp
fashion across the
primitives
Rasterization of Lines/Polygons
http://iloveshaders.blogspot.com/2011/05/how-rasterization-process-works.html
Lighting Example
VtShd
V
er
t
ex
Sh
a
d
er
var
y
in
g
vec4diffuseColor;
yg
varying vec3fragNormal;
varying vec3lightVector;
uniformvec3
eyeSpaceLightVector;
uniform

vec3
eyeSpaceLightVector;
voidmain(){
vec3eyeSpaceVertex= vec3(gl_ModelViewMatrix*
gl_Vertex);
lightVector= vec3(normalize(eyeSpaceLightVector -
eyeSpaceVertex));
fragNormal = normalize(gl_NormalMatrix* gl_Normal);
diffuseColor = gl_Color;
glPosition
=
glModelViewProjectionMatrix
*
glVertex
;
gl
_
Position
=

gl
_
ModelViewProjectionMatrix

gl
_
Vertex
;
}
Lighting Example
FtShd
F
ragmen
t

Sh
a
d
er
var
y
in
g
vec4diffuseColor;
yg
varying vec3lightVector;
varying vec3fragNormal;
void
main(){
void
main(){
float
perFragmentLighting=max(dot(lightVector,fragNormal),0.0)
;
;
gl_FragColor = diffuseColor * lightingFactor;
}
TShdiEl
T
oon
Sh
a
di
ng
E
xamp
l
e

ToonShading

Toon

Shading

Characterized by abrupt
change of colors

Vertex Shader computes
the vertex intensity
(
declared as var
y
in
g)
(yg)

Fragment Shader
computes colors for the
fragmentbasedonthe
fragment

based

on

the

interpolated intensity
VtShd
V
er
t
ex
Sh
a
d
e
r
uniform
vec3lightDir;
uniform
vec3

lightDir;
varyingfloat intensity;
void main() {
vec3ld;
intensity = dot(lightDir,gl_Normal);
gl_Position= ftransform();
}
FtShd
F
ragmen
t

Sh
a
d
e
r
varying
floatintensity;
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);
ll4(02010110)
e
l
se co
l
or = vec
4(0
.
2
,
0
.
1
,
0
.
1
,
1
.
0)
;
gl_FragColor= color;
}
}

ViViblEl
V
ary
i
ng
V
ar
i
a
bl
e
E
xamp
l
e
Determinecolorbasedonxyzcoordinates
Determine

color

based

on

x

y

z

coordinates
VtShd
V
er
t
ex
Sh
a
d
e
r
varyingfloatxpos;
varying

float

xpos;

varying float ypos;
varyingfloatzpos;
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;
}
}

FtShd
F
ragmen
t

Sh
a
d
e
r
iflt
vary
i
ng
fl
oa
t
xpos;
varying float ypos;
varyingfloatzpos;
varying

float

zpos;
void main
(
void
)

{

(){
gl_FragColor = vec4 (xpos, ypos, zpos, 1.0);
}
ClKEl
C
o
l
or
K
ey
E
xamp
l
e
Setacertaincolor(sayFF00FFas

Set

a

certain

color

(say

FF00FF

as

transparent
VtShd
V
er
t
ex
Sh
a
d
e
r
void main(void) {
gl_TexCoord[0] = gl_MultiTexCoord0;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
}

FtShd
F
ragmen
t

Sh
a
d
e
r
uniformsampler2DmyTexture;
uniform

sampler2D

myTexture;

#define epsilon 0.0001
void main (void) {
vec4 value = texture2D(myTexture, v
2(lTCd[0]))
ec
2(
g
l
_
T
ex
C
oor
d[0]))
;
if (value[0] > 1.0-epsilon) && (value[2] > 1.0-epsilon))
discard;
gl_FragColor = value;
}
ColorMapExample
Color

Map

Example

Supposeyouwanttorenderanobjectsuch

Suppose

you

want

to

render

an

object

such

that its surface is colored by the temperature.

You桡癥t桥瑥浰敲慴畲敳慴瑨tv敲瑩捥献

奯u

桡癥

瑨t

瑥浰敲慴畲敳



瑨t

癥牴楣敳v

You want the color to be interpolated between the
coolest and the hottest colors.

Previously, you would calculate the colors of
the vertices in
y
our
p
ro
g
ram, and sa
y

ypgy
glColor().

Now
,
lets do it in the vertex and
p
ixel
,p
shaders…
Vertexshader
Vertex

shader
// uniform qualified variables are changed at most once
// per primitive
uniformfloat CoolestTemp;
uniformfloat Tem
p
Ran
g
e
;
pg;
// attribute qualified variables are typically changed per vertex
attribute
floatVertexTemp;
attribute
float

VertexTemp;
// varying qualified variables communicate from the vertex
//hdtthfthd
//
s
h
a
d
er
t
o
th
e
f
ragmen
t
s
h
a
d
e
r
varyingfloat Temperature;
Vertexshader
Vertex

shader
void main()
{
// compute a temperature to be interpolated per fragment,
// in the range [0.0, 1.0]
Tt(VtT
CltT)/TR
T
empera
t
ure =
(V
er
t
ex
T
emp -
C
oo
l
es
tT
emp
)

/

T
emp
R
ange;
/*
The vertex position written in the application using glVertex() can
bereadfromthebuilt
invariableglVertexUsethisvalueand
be

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().
*/
g
l
_
Position =
g
l
_
ModelViewPro
j
ectionMatrix *
g
l
_
Vertex;
g_g_jg_
}
FragmentShader
Fragment

Shader
// uniform qualified variables are changed at most
// once per primitive by the application, and vec3
// declares a vector of three floating-point numbers
uniform
vec3CoolestColor;
uniform
vec3

CoolestColor;
uniformvec3 HottestColor;
// Temperature contains the now interpolated
// per-fragment value of temperature set by the
//vertexshader
//

vertex

shader
varyingfloat Temperature;
FragmentShader
Fragment

Shader
void main()
{
// get a color between coolest and hottest colors, using
// the mix
()
built-in function
()
vec3color = mix(CoolestColor, HottestColor, Temperature);
// make a vector of 4 floating-point numbers by appending an
//alphaof10andsetthisfragment

scolor
//

alpha

of

1
.
0
,
and

set

this

fragments

color
gl_FragColor= vec4(color, 1.0);
}
AdditilGLSLIf
Additi
ona
l

GLSL

I
n
f
o

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

g
l
_
P
os
iti
on

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
iOGL3X/4X

O
r
i
n
/
ou
t
i
n
O
pen
GL

3
.
X/4
.
X
T
T
ypes

Vectortypesaresupportedforfloatsintegersand

Vector

types

are

supported

for

floats
,
integers
,
and

booleans

Can be 2-, 3-, or 4-components

晬潡f癥挲癥挳癥挴

晬潡f

癥挲

癥挳

癥挴

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.
Bilt
iFti
B
u
ilt
-
i
n
F
unc
ti
ons
Trigonometry/angle
radians, degrees, sin, cos, tan, asin, acos, atan
Exponential
pow, exp2, log2, sqrt, inversesqrt
Geometricandmatrix
lengthdistancedotcrossnormalizeftransform
Geometric

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.
VertexProgramCapabilities
Vertex

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
g
eneration
g

Texture coordinate transformation
V
ertex
Fra
g
ment
vertices
Shader
Primitive
g
Shader
primitives
Transform
And Lighting
Clipping
Assembly
And
Rasterization
Texture
Stages
Fragment
Testing
VarialbeQualifies: From attribute
t
i
d
if
t
o vary
i
ng un
d
er un
if
orm
attribute:
•input to the vertex shader;

Definedpervertex;
Defined

per

vertex;
•E.gvertex
color/normal/coordinates
varying
Of
Vertex
Shader
Fragment
Shader

O
utput o
f
vertex shade
r
•Defined per vertex
vertices
primitives
Transform
And Lighting
Clipping
Primitive
Assembly
And
Rasterization
Texture
Stages
Fragment
Testing
Uniform: The same information used by all vertices/fragment.
e.g ModelView transformation matrices
Vertex shader: Example Usage of
Attibt/Vi/Uif
Att
r
ib
u
t
e
/V
ary
i
ng
/U
n
if
orm
// uniform
q
ualified variables are chan
g
ed at
void main()
qg
most once
// per primitive
uniformfloat CoolestTemp;
uniformfloat Tem
p
Ran
g
e
;
{
/*
compute a temperature to be interpolated
per fragment,
in the ran
g
e
[
0.0
,
1.0
]
pg;
// attribute qualified variables are typically
changed per vertex
attributefloat VertexTem
p;
g[,]
*/
Temperature = (VertexTemp -CoolestTemp)
/ TempRange;
glPosition
=
ftransform
();
p;
// varying qualified variables communicate from
the vertex
// shader to the fra
g
ment shader
gl
_
Position

ftransform
();
}
g
varyingfloat Temperature;
InterveningFixedFunctionality
Intervening

Fixed

Functionality

Results from vertex processing undergo:

Perspective division on clip coordinates

Viewport mapping

Clipping, including user clipping

Color clam
p
in
g
or maskin
g

(
for built-in var
y
in
g
variables that deal with color
,
but
pgg(
yg,
not user-defined varying variables)

Depth range

Front face determination and culling

䥮瑥牰潬慴Ic潬潲ot數瑵牥捯潲摩湡瑥慮a畳敲
-
摥晩湥d癡特楮vv慲楡扬敳

䥮瑥牰潬慴I

捯汯牳

瑥硴畲t

捯潲摩湡瑥

慮a

畳敲
摥晩湥d

癡特楮v

癡物慢汥v

Etc.
vertices
V
ertex
Shader
Fragment
Shader
vertices
primitives
Transform
And Lighting
Clipping
Primitive
Assembly
And
Rasterization
Texture
Stages
Fragment
Testing
Intervening Fixed Functionality:
Rtiti
R
as
t
er
i
za
ti
on
RasterizationofLines
1
Rasterization of
Lines/Polygons
2
Rasterization

of

Lines
1
Lines/Polygons
2
1.OpenGL 4.2 SPEC, 08/22/2011.
2.http://iloveshaders.blogspot.com/2011/05/how-rasterization-process-works.html
FragmentProgramCapabilities
Fragment

Program

Capabilities
Fragment shader can do general processing, like:

Operations on interpolated values

Texture access

Texture a
pp
lication
pp

Fog

Color sum

Color matrix

Discard fragment

etc
vertices
V
ertex
Shader
Fragment
Shader
vertices
primitives
Transform
And Lighting
Clipping
Primitive
Assembly
And
Rasterization
Texture
Stages
Fragment
Testing
FtP
F
ragmen
t

P
rogram

Outputofvertexshaderistheinputtothefragment

Output

of

vertex

shader

is

the

input

to

the

fragment

shader

Compatibility is checked when linking occurs

䍯浰慴楢楬楴C扥瑷敥b瑨tt睯楳扡獥b潮
癡特楮vv慲楡扬敳
瑨慴

䍯浰慴楢楬楴C

扥瑷敥b

瑨t

瑷t



扡獥b



癡特楮v

癡物慢汥v
瑨慴

慲攠摥晩湥搠楮⁢潴栠獨慤敲猠慮搠瑨慴d浡瑣栠楮⁴祰攠慮搠湡浥
䙴hditdfhft

F
ragmen
t
s
h
a
d
er
i
s execu
t
e
d

f
or eac
h

f
ragmen
t

produced by rasterization

For each fragment, fragment shader has access to the
interpolated value for each varying variable

䍯汯C湯牭慬t數瑵牥捯潲摩湡瑥c慲扩瑲慲av慬略a

䍯汯C

湯牭慬

瑥硴畲t

捯潲摩湡瑥c

慲扩瑲慲a

癡汵敳
FragmentProcessorOutput
Fragment

Processor

Output

In O
p
enGL 2.X
p

Output of the fragment processor goes on to the fixed
function fragment operations and frame buffer
operationsusingbuilt
-
invariables
operations

using

built
in

variables

gl_FragColor –computed R, G, B, A for the fragment

gl_FragDepth –computed depth value for the fragment

杬䙲慧䑡瑡孮F
–
慲扩瑲慲a摡瑡灥p晲慧浥湴獴潲敤楮浵汴楰汥


_
䙲慧䑡瑡孮F

–
慲扩瑲慲a

摡瑡

灥p

晲慧浥湴

獴潲敤



浵汴楰汥

牥湤敲⁴慲来瑳
FtShdEl
F
ragmen
t

Sh
a
d
er:
E
xamp
l
e
// uniform qualified variables are changed at
t
void main
()
mos
t
// once per primitive by the application, and vec3
// declares a vector of three floating-point
numbers
uniformvec3 CoolestColor;
()
{
// get a color between coolest and hottest
colors, using
/
/ the mix
()
built-in function
uniformvec3 HottestColor;
// Temperature contains the now interpolated
// per-fragment value of temperature set by the
//vertexshader
()
vec3 color = mix(CoolestColor, HottestColor,
Temperature);
// make a vector of 4 floating-point numbers
by appending an
//

vertex

shader
varyingfloat Temperature;
// alpha of 1.0, and set this fragment’s color
gl_FragColor= vec4(color, 1.0);
}
FragmentProgramCapabilities
Fragment

Program

Capabilities

Pass the fra
g
ment shader out
p
ut to framebuffers for the
gp
following test

Scissor test/Alpha test/Depth test/Stencil test/Blending, etc.

Va汵敳慲a摥獴楮敤景fw物瑩湧楮瑯瑨tf牡浥扵b晥fifa汬扡捫

Va汵敳

慲a

摥獴楮敤

景f

睲楴楮w

楮瑯

瑨t

晲慭f

扵b晥f



慬a

扡捫

敮搠瑥獴猠⡳瑥湣楬Ⱐ摥灴栠整挮⤠灡獳
䍬iftitthttbffid

Cl
amp
i
ng or
f
orma
t
convers
i
on
t
o
th
e
t
arge
t

b
u
ff
er
i
s
d
one
automatically outside of the fragment shader
vertices
V
ertex
Shader
Fragment
Shader
vertices
primitives
Transform
And Lighting
Clipping
Primitive
Assembly
And
Rasterization
Texture
Stages
Fragment
Testing
GLSLfOGL3X/4X
GLSL

f
or
O
pen
GL

3
.
X/4
.
X

Twoprofilesforshaderlanguages

Two

profiles

for

shader

languages

Compatibility (1.X/2.X)

Core (3.X/4.X)

䵡楮捨慮来c

䵡楮

捨慮来c

Reduction of built-in states
No transformation matrix,
Nolighting

No

lighting
,

No built-in attributes for vertex/colors/normals, etc

Change of type qualifiers
Additilblt

Additi
ona
l
programma
bl
e s
t
ages

Geometry/Tessellation shader

Much more …
The features for compatibility profile are listed in GLSL Spec 4.2.
OGL3XTQlifi
O
pen
GL

3
.
X
:
T
ype
Q
ua
lifi
ers

in

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

out

forfunctionparameterscopiedoutofafunctionbutnotcopiedin

for

function

parameters

copied

out

of

a

function
,
but

not

copied

in

Can be combined with auxiliary storage qualifiers centroid/sample/patch
Vertex
Shade
r
Fragment
Shade
r
attribute(in) 
varying(out) varying(in)out
vertices
Transform
Clipping
Primitive
A
ssembl
y
Texture
Fra
g
men
t
primitives
And Lighting
Clipping
y
And
Rasterization
Stages
g
Testing
The complete list of GLSL data types functions are in Section 4.3 of GLSL Spec 4.2.