SlideShare a Scribd company logo
3d Programming I
Dr Anton Gerdelan
gerdela@scss.tcd.ie
3d Programming
ā—
3d programming is very difficult
ā—
3d programming is very time consuming
3d Programming
ā—
Practical knowledge of the latest, low-level
graphics APIs is very valuable (CV)
ā—
Good grasp of basic concepts in this semester
ā—
Caveat - You must keep API knowledge up-to-
date or it becomes redundant
Essential Checklist
āœ”
always have a pencil and paper
āœ”
solve your problem before you start coding
āœ”
know how to compile and link against libraries
āœ”
know how to use memory, pointers, addresses
āœ”
understand the hardware pipeline
āœ”
make a 3d maths cheat sheet
āœ”
do debugging (visual and programmatic)
āœ”
print the Quick Reference Card for OpenGL
āœ”
start assignments ASAP
Quick Background
ā—
What is a vertex?
ā—
Modern graphics hardware is able to draw:
– triangles
– points
– lines (unofficially deprecated)
ā—
How do we define these?
ā—
What is a normal?
Computer Graphics - Lecture 01 - 3D Programming I
Computer Graphics - Lecture 01 - 3D Programming I
Computer Graphics - Lecture 01 - 3D Programming I
Computer Graphics - Lecture 01 - 3D Programming I
OpenGL
ā—
Open Grapics Library - originally the IrisGL by SGI
ā—
Managed by Khronos Group
{lots of big hw and sw companies}
ā—
Vector graphics
ā—
Only the spec. is sort-of open
ā—
Various implementations, lots of platforms
ā—
C API + driver + GLSL shaders
ā—
All the APIs do the same jobs on hardware, but present
different interfaces
OpenGL Caveats
ā—
OpenGL has a very clunky old-fashioned C interface that
will definitely confuse
ā—
OpenGL has been modernised but there is a lot of left-
over ā€œcruftā€ that you shouldn't use
ā—
Print the Quick Reference Card and double-check
everything that you use.
http://www.opengl.org/sdk/docs/
ā—
The naming conventions are very confusing
ā—
OpenGL is currently being completely re-written to
address these problems
ā—
I'll try to help steer around these issues - use the
discussion boards if unsure!
OpenGL Global State Machine
ā—
The OpenGL interface uses an architecture called a
ā€œglobal state machineā€
ā—
Instead of doing this sort of thing:
Mesh myMesh;
myMesh.setData (some_array);
opengl.drawMesh (myMesh);
ā—
in a G.S.M. we do this sort of thing [pseudo-code]:
unsigned int mesh_handle;
glGenMesh (&mesh_handle); // okay so far, just C style
glBindMesh (mesh_handle); // my mesh is now ā€œtheā€ mesh
// affects most recently ā€œboundā€ mesh
glMeshData (some_array);
ā—
How this might cause a problem later?
OpenGL Global State Machine
ā—
Operations affect the currently ā€œboundā€ object
ā—
Be very careful. Write long functions.
ā—
Can sometimes ā€œunbindā€ by binding to 0 (no object)
ā—
Operations ā€œenableā€ states like
blending/transparency
ā—
They affect all subsequently drawn things
ā—
Don't forget to ā€œdisableā€ things
ā—
Can get messy in larger programmes
ā—
Write long functions.
Graphics API Architecture
ā—
Set-up and rendering loop run
on CPU
ā—
Copy mesh data to buffers in
graphics hardware memory
ā—
Write shaders to draw on GPU
(graphics processing unit)
ā—
CPU command queues
drawing on GPU with this
shader, and that mesh data
ā—
CPU and GPU then run
asychronously
Before We Look at Code
ā—
OpenGL functions preceded
by ā€œgl...()ā€
ā—
OpenGL data types preceded
by ā€œGL...ā€
ā—
OpenGL constants preceeded
by ā€œGL_...ā€
ā—
Find each feature used in man
pages
http://www.opengl.org/sdk/d
ocs/man/
ā—
Parameters, related functions
Walk-Through ā€œHello Triangleā€
ā—
Upgrade graphics drivers to download latest OpenGL
libraries
ā—
GLEW or GL3W - extensions and newest GL.h
ā—
GLFW or FreeGLUT or SDL or Qt - OS window/context
Start GLFW (or FreeGLUT)
ā—
Start GLFW
ā—
We use GLFW to start an OpenGL context
ā—
Can use FreeGLUT, SDL, Qt, etc. Instead
ā—
Can also do manually, but ugly
Hint to Use a Specific OpenGL Version
ā—
Leave commented the first time, it will try to run latest v.
ā—
We can print this out to see what you have on the machine
ā—
Uncomment and specify to force a specific version (good,
safe practice)
ā—
CORE and FORWARD mean ā€œdon't allow any old, deprecated
stuffā€
ā—
Apple only has 3.2 and 4.1? core, forward implemented
Create a Window on the OS
ā—
GLFW/FreeGLUT etc. do this in a platform-
independent way
ā—
Tie OpenGL context to the window
ā—
Refer to GLFW docs for each function
Start GLEW (or GL3W)
ā—
Windows has a 1992? Microsoft gl.h in the system folder
ā—
Makes sure you are using the latest gl.h
ā—
Makes extensions available (experimental/new feature
plug-ins)
ā—
Ask OpenGL to print the version running (check in console)
ā—
3.2+ is fine for this course
Create Vertex Points
Create Vertex Buffer Object (VBO)
ā—
We copy our array of points from RAM to
graphics memory
ā—
Note ā€œbindingā€ idea
ā—
The vbo variable is just an unsigned integer that
GL will give an unique ID to
Create Vertex Array Object (VAO)
ā—
ā€œWhatā€ to draw
ā—
Meta-data with ā€œattributeā€ pointer that says
what data from a VBO to use for a shader input
variable
Vertex Shader and Fragment Shader Strings
ā—
ā€œHowā€ to draw (style)
ā—
Set vertex positions in range -1 to 1 on X,Y,Z
ā—
gl_Position is the built-in variable to use for final position
ā—
Colour in RGBA (red blue green alpha) range 0.0 to 1.0
ā—
Like C but more data types.
Compile and Link Shaders
ā—
Compile each shader
ā—
Attach to shader program (another bad naming convention)
ā—
Link the program
ā—
Should check compile and linking logs for errors
Drawing Loop
ā—
Clear drawing buffer {colour, depth}
ā—
ā€œUseā€ our shader program
ā—
ā€œBindā€ our VAO
ā—
Draw triangles. Start at point 0. Use 3 points. How many triangles?
ā—
Swap buffers. Why?
Terminate
ā—
Makes sure window closes if your loop finishes first
ā—
Compile, link against GLEW and GLFW and OpenGL
ā—
VS Template on Blackboard
ā—
Makefiles for Linux/Mac/Windows
https://github.com/capnramses/antons_opengl_tutorials_book/
ā—
Don't get stuck on linking/projects - start fiddling now!
ā€œHello Triangleā€
ā—
Getting GL started is a
lot of work
ā—
ā€œIf you can draw 1
triangle, you can draw
1000000ā€
ā—
Go through some
tutorials
Pause and Review
ā—
What are the main components of a modern 3d
graphics programme?
ā—
Where do we store mesh data (vertex points)?
ā—
In what?
ā—
How do we define the format of the data?
ā—
What do we need to do before we tell OpenGL
to draw with glDrawArrays() etc.?
Things to Think About or Try
ā—
Can we change the colour of the triangle drawn?
ā—
How can we extend the triangle into a square?
ā—
Could we load mesh data from a file rather than
an array?
ā—
Shaders can be loaded from files. If you change
a shader in an external file, do you need to re-
compile?
ā—
How would you draw a second, separate shape?
3d Programming I
Part B
Graphics System Architecture
ā—
move data to graphics hardware before drawing
ā—
minimise use of the bus
Asynchronous Processing
ā—
Minimise CPU-GPU bus comm. Overhead
ā—
Maximise parallel processing to reduce overall GPU time
ā—
ā€œClientā€ gl commands queue up and wait to be run on GPU
ā—
Can glFlush() to say ā€œhurry up, I'm waitingā€ and glFinish() to
actually wait – don't normally need to use these
Closer Look at Shaders
GPU Parallelism
ā—
1 vertex = 1 shader = 1 core
ā—
1 fragment = 1 shader = 1 core
ā—
but drawing operations serialise
ā—
.: 1 big mesh draw is faster than many small draws
GPU Uniform Shader Cores
GeForce 605 48
Radeon HD 7350 80
GeForce GTX 580 512
Radeon HD 8750 768
GeForce GTX 690 1536
Radeon HD 8990 2304
ā—
minimum:
– vertex shader
– fragment shader
ā—
also have GPGPU
ā€œcomputeā€ shaders
now
ā—
note: Direct3D hw
pipeline is the same,
but different names
Difference Between Fragment and Pixels
ā—
Pixel = ā€œpicture elementā€
ā—
Fragment = pixel-sized area of a surface
ā—
Each triangle is divided into fragments on
rasterisation
ā—
All fragments are drawn, even the obscured ones*
ā—
If depth testing is enabled closer fragments are
drawn over farther-away fragments
ā—
.: Huge #s of redundant FS may be executed
Shader Language
OpenGL Version GLSL Version Tag
1.2 none none
2.0 1.10.59 #version 110
2.1 1.20.8 #version 120
3.0 1.30.10 #version 130
3.1 1.40.08 #version 140
3.2 1.50.11 #version 150
3.3 3.30.6 #version 330
4.0 4.00.9 #version 400
4.1 4.10.6 #version 410
4.2 4.20.6 #version 420
4.3 4.30.6 #version 430
4.4 ... #version 440
... ... ...
GLSL Operators and Data Types
ā—
Same operators as C
ā—
no pointers
ā—
bit-wise operators since v 1.30
data type detail common use
void same as C functions that do not
return a value
bool, int, float same as C
vec2, vec3, vec4 2d, 3d, 4d floating point points and direction vectors
mat2, mat3, mat4 2x2, 3x3, 4x4 f.p. matrices transforming points,
vectors
sampler2D 2d texture texture mapping
samplerCube 6-sided texture sky boxes
sampler2DShadow shadow projected texture
ivec3 etc. integer versions
File Naming Convention
ā—
Upgarde the template – load shader strings from text files
ā—
post-fix with
– .vert - vetex shader
– .frag - fragment shader
– .geom - geometry shader
– .comp - compute shader
– .tesc - tessellation control shader
– .tese - tessellation evaluation shader
ā—
allows you to use a tool like Glslang reference compiler to
check for [obvious] errors
Example Vertex Shader
#version 400
in vec3 vertex_position;
void main() {
gl_Position = vec4 (vertex_position, 1.0);
}
ā—
Macro to explicitly set GLSL version required. Can also use #defines
ā—
in keyword – variable from previous stage in pipeline.
Q. What is the stage before the vertex shader?
ā—
vec3 - 3d vector. Store positions, directions, or colours.
ā—
Every shader has a main() entry point as in C.
... contd.
Example Vertex Shader
#version 400
in vec3 vertex_position;
void main() {
gl_Position = vec4 (vertex_position, 1.0);
}
ā—
vec4 - has 4th component. gl_Position uses it to determine
perspective. Set by virtual cameras. For now leave at 1.0 - "don't
calculate any perspective".
ā—
Can also use out keyword to send variable to next stage.
Q. What is the next stage?
ā—
Every VS positions one vertex between -1:1,-1:1,-1:1.
Q. How does every vertex end up in a different position
then?
ā—
minimum:
– vertex shader
– fragment shader
ā—
also have GPGPU
ā€œcomputeā€ shaders
now
ā—
note: Direct3D hw
pipeline is the same,
but different names
Example Fragment Shader
#version 400
uniform vec4 inputColour;
out vec4 fragColour;
void main() {
fragColour = inputColour;
}
ā—
What important pipeline process happens first?
ā—
A uniform variable is a way to communicate to shaders from the main
application in C
ā—
For each fragment set a vec4 to RGBA (range 0.0 to 1.0)
Q. What is the next stage? Where does out go?
Q. What can the alpha channel do?
Uniforms
// do this once, after linking the shader p. not in the main loop
int inputColour_loc = glGetUniformLocation (my_shader_program, ā€œinputColourā€);
if (inputColour_loc < 0) {
fprintf (stderr, ā€œERROR inputColour variable not found. Invalid uniformnā€);
do something rash;
}
// do this whenever you want to change the colour used by this shader program
glUseProgram (my_shader_program);
glUniform4f (inputColour_loc, 0.5f, 0.5f, 1.0f, 1.0f);
ā—
Uniforms are 0 by default i.e. our colour=black
ā—
Unused uniforms are optimised out by shader compiler
ā—
Basic uniforms are specific and persistent to one shader programme
ā—
Uniforms are available to all shaders in programme
ā—
Uniforms are a constant value in all shaders
ā—
You can change a uniform once, every frame, or whenever you like
ā—
Keep uniform updates to a minimum (don't flood the bus)
Adding Error-Checking Functionality
ā—
After calling glCompileShader()
– Check GL_COMPILE_STATUS with glGetShaderiv()
– If failed, get the log from glGetShaderInfoLog() and print it!
ā—
After calling glLinkProgram()
– Check GL_LINK_STATUS with glGetProgramiv()
– Get the log from glGetProgramInfoLog() and print it!
ā—
Check out the man-pages to find out how to use these
functions.
ā—
Add this to your projects! It gives you basic error checking
with the line numbers.
Shadertoy
ā—
WebGL tool to experiment with shaders
on-the-fly
ā—
implement entirely in a fragment shader
https://www.shadertoy.com/
Example: Adding Vertex Colours
Data Layout Options
ā—
We could:
– Concatenate colour data onto the end of our points
buffer:
array = XYZXYZXYZRGBRGBRGB
– Interleave colours between points:
array = XYZRGBXYZRGBXYZRGB
– Just create a new array and new vertex buffer
object
array1 = XYZXYZXYZ array2 = RGBRGBRGB
Second Array
GLfloat points[] = {
0.0f, 0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
-0.5f, -0.5f, 0.0f
};
GLfloat colours[] = {
1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f
};
Second VBO
GLuint points_vbo = 0;
glGenBuffers (1, &points_vbo);
glBindBuffer (GL_ARRAY_BUFFER, points_vbo);
glBufferData (GL_ARRAY_BUFFER, sizeof (points),
points, GL_STATIC_DRAW);
GLuint colours_vbo = 0;
glGenBuffers (1, &colours_vbo);
glBindBuffer (GL_ARRAY_BUFFER, colours_vbo);
glBufferData (GL_ARRAY_BUFFER, sizeof (colours),
colours, GL_STATIC_DRAW);
Tell the VAO where to get 2nd
variable
GLuint vao;
glGenVertexArrays (1, &vao);
glBindVertexArray (vao);
glEnableVertexAttribArray (0);
glBindBuffer (GL_ARRAY_BUFFER, points_vbo);
glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray (1);
glBindBuffer (GL_ARRAY_BUFFER, colours_vbo);
glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 0, NULL);
Second shader input
variable
Still a vec3
Change these 2
variables if interleaved
or concatenated in
one VBO
Modify Vertex Shader
#version 400
layout (location=0) in vec3 vp; // point
layout (location=1) in vec3 vc; // colour
out vec3 fcolour;
void main () {
fcolour = point; // ā€œpass-throughā€ output
gl_Position = vec4 (vp, 1.0);
}
Q. Why does the colour input have to start in the vertex
shader?
Modify the Fragment Shader
#version 400
in vec3 fcolour;
out vec4 frag_colour;
void main () {
frag_colour = vec4 (fcolour, 1.0);
}
Q. There are more fragments than vertices. What values will
fcolour have in each fragment?
Interpolation
Drawing Modes
ā—
Points can be scaled
ā—
Lines are deprecated
but still sort-of work
ā—
How would you
change your triangles
to an edges
wireframe?
Winding Order and Back-Face Culling
ā—
Easy optimisation – don't waste time drawing the
back face or inside-facing parts of a mesh
ā—
How do we define the ā€œfrontā€ and ā€œbackā€
ā—
= order that points are given
ā—
Clock-wise order or Counter clock-wise
glEnable (GL_CULL_FACE); // cull face
glCullFace (GL_BACK); // cull back face
glFrontFace (GL_CW); // usually front is CCW

More Related Content

PPTX
Projection In Computer Graphics
PDF
Abalanche - Unity Shader Graph #1: Shader & PBR Materials
PPTX
Applications of computer graphics
PPT
Computer graphics iv unit
PPTX
History of Computer Graphics
PPTX
Raster Scan Graphics, Line Drawing Algorithm and Circle Drawing Algorithm
PPTX
Introduction to computer graphics
PPT
GRPHICS06 - Shading
Projection In Computer Graphics
Abalanche - Unity Shader Graph #1: Shader & PBR Materials
Applications of computer graphics
Computer graphics iv unit
History of Computer Graphics
Raster Scan Graphics, Line Drawing Algorithm and Circle Drawing Algorithm
Introduction to computer graphics
GRPHICS06 - Shading

What's hot (20)

PPTX
3D transformation in computer graphics
PPTX
illumination model in Computer Graphics by irru pychukar
PPTX
Computer graphics - bresenham line drawing algorithm
PPTX
Hidden surface removal
PPTX
Graphics_3D viewing
PDF
Brdf기반 ģ‚¬ģ „ģ •ģ˜ ģŠ¤ķ‚Ø ģ…°ģ“ė”
PPTX
3 d display-methods-in-computer-graphics(For DIU)
PPT
Quadric surfaces
PPTX
Concept of basic illumination model
PPT
Computer animation
PPTX
Window to Viewport Transformation in Computer Graphics with.pptx
PPT
Texture mapping
PPTX
Texture mapping in_opengl
PPTX
BRESENHAM’S LINE DRAWING ALGORITHM
PPT
Visible surface detection in computer graphic
PDF
Computer graphics - colour crt and flat-panel displays
PDF
Skia & Freetype - Android 2D Graphics Essentials
PPT
Window to viewport transformation
PPTX
Flat panel display
PPT
Polygon filling
3D transformation in computer graphics
illumination model in Computer Graphics by irru pychukar
Computer graphics - bresenham line drawing algorithm
Hidden surface removal
Graphics_3D viewing
Brdf기반 ģ‚¬ģ „ģ •ģ˜ ģŠ¤ķ‚Ø ģ…°ģ“ė”
3 d display-methods-in-computer-graphics(For DIU)
Quadric surfaces
Concept of basic illumination model
Computer animation
Window to Viewport Transformation in Computer Graphics with.pptx
Texture mapping
Texture mapping in_opengl
BRESENHAM’S LINE DRAWING ALGORITHM
Visible surface detection in computer graphic
Computer graphics - colour crt and flat-panel displays
Skia & Freetype - Android 2D Graphics Essentials
Window to viewport transformation
Flat panel display
Polygon filling
Ad

Similar to Computer Graphics - Lecture 01 - 3D Programming I (20)

PDF
lectureAll-OpenGL-complete-Guide-Tutorial.pdf
PDF
Open gl
PPT
PPTX
Opengl lec 3
PPTX
OpenGL Fixed Function to Shaders - Porting a fixed function application to ā€œm...
Ā 
PDF
GL Shading Language Document by OpenGL.pdf
PPT
Advanced Graphics Workshop - GFX2011
PPT
CS 354 Programmable Shading
PPTX
OpenGL basics
PDF
Opengl basics
PPT
CS 354 Viewing Stuff
PDF
Introduction of openGL
PPTX
Opengl presentation
PPT
september11.ppt
PPT
Introduction to OpenGL modern OpenGL program
PPTX
3 CG_U1_P2_PPT_3 OpenGL.pptx
PDF
Android open gl2_droidcon_2014
PPTX
UNIT 1 OPENGL_UPDATED .pptx
PDF
Open gl basics
lectureAll-OpenGL-complete-Guide-Tutorial.pdf
Open gl
Opengl lec 3
OpenGL Fixed Function to Shaders - Porting a fixed function application to ā€œm...
Ā 
GL Shading Language Document by OpenGL.pdf
Advanced Graphics Workshop - GFX2011
CS 354 Programmable Shading
OpenGL basics
Opengl basics
CS 354 Viewing Stuff
Introduction of openGL
Opengl presentation
september11.ppt
Introduction to OpenGL modern OpenGL program
3 CG_U1_P2_PPT_3 OpenGL.pptx
Android open gl2_droidcon_2014
UNIT 1 OPENGL_UPDATED .pptx
Open gl basics
Ad

Recently uploaded (20)

PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
PDF
English Language Teaching from Post-.pdf
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
PSYCHOLOGY IN EDUCATION.pdf ( nice pdf ...)
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
BƀI Tįŗ¬P Bį»” TRỢ 4 KỸ NĂNG TIįŗ¾NG ANH 9 GLOBAL SUCCESS - Cįŗ¢ NĂM - BƁM SƁT FORM Đ...
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Insiders guide to clinical Medicine.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Ā 
PPTX
Pharma ospi slides which help in ospi learning
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
PDF
01-Introduction-to-Information-Management.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
O5-L3 Freight Transport Ops (International) V1.pdf
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
English Language Teaching from Post-.pdf
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PSYCHOLOGY IN EDUCATION.pdf ( nice pdf ...)
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
BƀI Tįŗ¬P Bį»” TRỢ 4 KỸ NĂNG TIįŗ¾NG ANH 9 GLOBAL SUCCESS - Cįŗ¢ NĂM - BƁM SƁT FORM Đ...
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Insiders guide to clinical Medicine.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Ā 
Pharma ospi slides which help in ospi learning
Microbial disease of the cardiovascular and lymphatic systems
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
01-Introduction-to-Information-Management.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Renaissance Architecture: A Journey from Faith to Humanism
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx

Computer Graphics - Lecture 01 - 3D Programming I

  • 2. 3d Programming ā— 3d programming is very difficult ā— 3d programming is very time consuming
  • 3. 3d Programming ā— Practical knowledge of the latest, low-level graphics APIs is very valuable (CV) ā— Good grasp of basic concepts in this semester ā— Caveat - You must keep API knowledge up-to- date or it becomes redundant
  • 4. Essential Checklist āœ” always have a pencil and paper āœ” solve your problem before you start coding āœ” know how to compile and link against libraries āœ” know how to use memory, pointers, addresses āœ” understand the hardware pipeline āœ” make a 3d maths cheat sheet āœ” do debugging (visual and programmatic) āœ” print the Quick Reference Card for OpenGL āœ” start assignments ASAP
  • 5. Quick Background ā— What is a vertex? ā— Modern graphics hardware is able to draw: – triangles – points – lines (unofficially deprecated) ā— How do we define these? ā— What is a normal?
  • 10. OpenGL ā— Open Grapics Library - originally the IrisGL by SGI ā— Managed by Khronos Group {lots of big hw and sw companies} ā— Vector graphics ā— Only the spec. is sort-of open ā— Various implementations, lots of platforms ā— C API + driver + GLSL shaders ā— All the APIs do the same jobs on hardware, but present different interfaces
  • 11. OpenGL Caveats ā— OpenGL has a very clunky old-fashioned C interface that will definitely confuse ā— OpenGL has been modernised but there is a lot of left- over ā€œcruftā€ that you shouldn't use ā— Print the Quick Reference Card and double-check everything that you use. http://www.opengl.org/sdk/docs/ ā— The naming conventions are very confusing ā— OpenGL is currently being completely re-written to address these problems ā— I'll try to help steer around these issues - use the discussion boards if unsure!
  • 12. OpenGL Global State Machine ā— The OpenGL interface uses an architecture called a ā€œglobal state machineā€ ā— Instead of doing this sort of thing: Mesh myMesh; myMesh.setData (some_array); opengl.drawMesh (myMesh); ā— in a G.S.M. we do this sort of thing [pseudo-code]: unsigned int mesh_handle; glGenMesh (&mesh_handle); // okay so far, just C style glBindMesh (mesh_handle); // my mesh is now ā€œtheā€ mesh // affects most recently ā€œboundā€ mesh glMeshData (some_array); ā— How this might cause a problem later?
  • 13. OpenGL Global State Machine ā— Operations affect the currently ā€œboundā€ object ā— Be very careful. Write long functions. ā— Can sometimes ā€œunbindā€ by binding to 0 (no object) ā— Operations ā€œenableā€ states like blending/transparency ā— They affect all subsequently drawn things ā— Don't forget to ā€œdisableā€ things ā— Can get messy in larger programmes ā— Write long functions.
  • 14. Graphics API Architecture ā— Set-up and rendering loop run on CPU ā— Copy mesh data to buffers in graphics hardware memory ā— Write shaders to draw on GPU (graphics processing unit) ā— CPU command queues drawing on GPU with this shader, and that mesh data ā— CPU and GPU then run asychronously
  • 15. Before We Look at Code ā— OpenGL functions preceded by ā€œgl...()ā€ ā— OpenGL data types preceded by ā€œGL...ā€ ā— OpenGL constants preceeded by ā€œGL_...ā€ ā— Find each feature used in man pages http://www.opengl.org/sdk/d ocs/man/ ā— Parameters, related functions
  • 16. Walk-Through ā€œHello Triangleā€ ā— Upgrade graphics drivers to download latest OpenGL libraries ā— GLEW or GL3W - extensions and newest GL.h ā— GLFW or FreeGLUT or SDL or Qt - OS window/context
  • 17. Start GLFW (or FreeGLUT) ā— Start GLFW ā— We use GLFW to start an OpenGL context ā— Can use FreeGLUT, SDL, Qt, etc. Instead ā— Can also do manually, but ugly
  • 18. Hint to Use a Specific OpenGL Version ā— Leave commented the first time, it will try to run latest v. ā— We can print this out to see what you have on the machine ā— Uncomment and specify to force a specific version (good, safe practice) ā— CORE and FORWARD mean ā€œdon't allow any old, deprecated stuffā€ ā— Apple only has 3.2 and 4.1? core, forward implemented
  • 19. Create a Window on the OS ā— GLFW/FreeGLUT etc. do this in a platform- independent way ā— Tie OpenGL context to the window ā— Refer to GLFW docs for each function
  • 20. Start GLEW (or GL3W) ā— Windows has a 1992? Microsoft gl.h in the system folder ā— Makes sure you are using the latest gl.h ā— Makes extensions available (experimental/new feature plug-ins) ā— Ask OpenGL to print the version running (check in console) ā— 3.2+ is fine for this course
  • 22. Create Vertex Buffer Object (VBO) ā— We copy our array of points from RAM to graphics memory ā— Note ā€œbindingā€ idea ā— The vbo variable is just an unsigned integer that GL will give an unique ID to
  • 23. Create Vertex Array Object (VAO) ā— ā€œWhatā€ to draw ā— Meta-data with ā€œattributeā€ pointer that says what data from a VBO to use for a shader input variable
  • 24. Vertex Shader and Fragment Shader Strings ā— ā€œHowā€ to draw (style) ā— Set vertex positions in range -1 to 1 on X,Y,Z ā— gl_Position is the built-in variable to use for final position ā— Colour in RGBA (red blue green alpha) range 0.0 to 1.0 ā— Like C but more data types.
  • 25. Compile and Link Shaders ā— Compile each shader ā— Attach to shader program (another bad naming convention) ā— Link the program ā— Should check compile and linking logs for errors
  • 26. Drawing Loop ā— Clear drawing buffer {colour, depth} ā— ā€œUseā€ our shader program ā— ā€œBindā€ our VAO ā— Draw triangles. Start at point 0. Use 3 points. How many triangles? ā— Swap buffers. Why?
  • 27. Terminate ā— Makes sure window closes if your loop finishes first ā— Compile, link against GLEW and GLFW and OpenGL ā— VS Template on Blackboard ā— Makefiles for Linux/Mac/Windows https://github.com/capnramses/antons_opengl_tutorials_book/ ā— Don't get stuck on linking/projects - start fiddling now!
  • 28. ā€œHello Triangleā€ ā— Getting GL started is a lot of work ā— ā€œIf you can draw 1 triangle, you can draw 1000000ā€ ā— Go through some tutorials
  • 29. Pause and Review ā— What are the main components of a modern 3d graphics programme? ā— Where do we store mesh data (vertex points)? ā— In what? ā— How do we define the format of the data? ā— What do we need to do before we tell OpenGL to draw with glDrawArrays() etc.?
  • 30. Things to Think About or Try ā— Can we change the colour of the triangle drawn? ā— How can we extend the triangle into a square? ā— Could we load mesh data from a file rather than an array? ā— Shaders can be loaded from files. If you change a shader in an external file, do you need to re- compile? ā— How would you draw a second, separate shape?
  • 32. Graphics System Architecture ā— move data to graphics hardware before drawing ā— minimise use of the bus
  • 33. Asynchronous Processing ā— Minimise CPU-GPU bus comm. Overhead ā— Maximise parallel processing to reduce overall GPU time ā— ā€œClientā€ gl commands queue up and wait to be run on GPU ā— Can glFlush() to say ā€œhurry up, I'm waitingā€ and glFinish() to actually wait – don't normally need to use these
  • 34. Closer Look at Shaders
  • 35. GPU Parallelism ā— 1 vertex = 1 shader = 1 core ā— 1 fragment = 1 shader = 1 core ā— but drawing operations serialise ā— .: 1 big mesh draw is faster than many small draws GPU Uniform Shader Cores GeForce 605 48 Radeon HD 7350 80 GeForce GTX 580 512 Radeon HD 8750 768 GeForce GTX 690 1536 Radeon HD 8990 2304
  • 36. ā— minimum: – vertex shader – fragment shader ā— also have GPGPU ā€œcomputeā€ shaders now ā— note: Direct3D hw pipeline is the same, but different names
  • 37. Difference Between Fragment and Pixels ā— Pixel = ā€œpicture elementā€ ā— Fragment = pixel-sized area of a surface ā— Each triangle is divided into fragments on rasterisation ā— All fragments are drawn, even the obscured ones* ā— If depth testing is enabled closer fragments are drawn over farther-away fragments ā— .: Huge #s of redundant FS may be executed
  • 38. Shader Language OpenGL Version GLSL Version Tag 1.2 none none 2.0 1.10.59 #version 110 2.1 1.20.8 #version 120 3.0 1.30.10 #version 130 3.1 1.40.08 #version 140 3.2 1.50.11 #version 150 3.3 3.30.6 #version 330 4.0 4.00.9 #version 400 4.1 4.10.6 #version 410 4.2 4.20.6 #version 420 4.3 4.30.6 #version 430 4.4 ... #version 440 ... ... ...
  • 39. GLSL Operators and Data Types ā— Same operators as C ā— no pointers ā— bit-wise operators since v 1.30 data type detail common use void same as C functions that do not return a value bool, int, float same as C vec2, vec3, vec4 2d, 3d, 4d floating point points and direction vectors mat2, mat3, mat4 2x2, 3x3, 4x4 f.p. matrices transforming points, vectors sampler2D 2d texture texture mapping samplerCube 6-sided texture sky boxes sampler2DShadow shadow projected texture ivec3 etc. integer versions
  • 40. File Naming Convention ā— Upgarde the template – load shader strings from text files ā— post-fix with – .vert - vetex shader – .frag - fragment shader – .geom - geometry shader – .comp - compute shader – .tesc - tessellation control shader – .tese - tessellation evaluation shader ā— allows you to use a tool like Glslang reference compiler to check for [obvious] errors
  • 41. Example Vertex Shader #version 400 in vec3 vertex_position; void main() { gl_Position = vec4 (vertex_position, 1.0); } ā— Macro to explicitly set GLSL version required. Can also use #defines ā— in keyword – variable from previous stage in pipeline. Q. What is the stage before the vertex shader? ā— vec3 - 3d vector. Store positions, directions, or colours. ā— Every shader has a main() entry point as in C. ... contd.
  • 42. Example Vertex Shader #version 400 in vec3 vertex_position; void main() { gl_Position = vec4 (vertex_position, 1.0); } ā— vec4 - has 4th component. gl_Position uses it to determine perspective. Set by virtual cameras. For now leave at 1.0 - "don't calculate any perspective". ā— Can also use out keyword to send variable to next stage. Q. What is the next stage? ā— Every VS positions one vertex between -1:1,-1:1,-1:1. Q. How does every vertex end up in a different position then?
  • 43. ā— minimum: – vertex shader – fragment shader ā— also have GPGPU ā€œcomputeā€ shaders now ā— note: Direct3D hw pipeline is the same, but different names
  • 44. Example Fragment Shader #version 400 uniform vec4 inputColour; out vec4 fragColour; void main() { fragColour = inputColour; } ā— What important pipeline process happens first? ā— A uniform variable is a way to communicate to shaders from the main application in C ā— For each fragment set a vec4 to RGBA (range 0.0 to 1.0) Q. What is the next stage? Where does out go? Q. What can the alpha channel do?
  • 45. Uniforms // do this once, after linking the shader p. not in the main loop int inputColour_loc = glGetUniformLocation (my_shader_program, ā€œinputColourā€); if (inputColour_loc < 0) { fprintf (stderr, ā€œERROR inputColour variable not found. Invalid uniformnā€); do something rash; } // do this whenever you want to change the colour used by this shader program glUseProgram (my_shader_program); glUniform4f (inputColour_loc, 0.5f, 0.5f, 1.0f, 1.0f); ā— Uniforms are 0 by default i.e. our colour=black ā— Unused uniforms are optimised out by shader compiler ā— Basic uniforms are specific and persistent to one shader programme ā— Uniforms are available to all shaders in programme ā— Uniforms are a constant value in all shaders ā— You can change a uniform once, every frame, or whenever you like ā— Keep uniform updates to a minimum (don't flood the bus)
  • 46. Adding Error-Checking Functionality ā— After calling glCompileShader() – Check GL_COMPILE_STATUS with glGetShaderiv() – If failed, get the log from glGetShaderInfoLog() and print it! ā— After calling glLinkProgram() – Check GL_LINK_STATUS with glGetProgramiv() – Get the log from glGetProgramInfoLog() and print it! ā— Check out the man-pages to find out how to use these functions. ā— Add this to your projects! It gives you basic error checking with the line numbers.
  • 47. Shadertoy ā— WebGL tool to experiment with shaders on-the-fly ā— implement entirely in a fragment shader https://www.shadertoy.com/
  • 49. Data Layout Options ā— We could: – Concatenate colour data onto the end of our points buffer: array = XYZXYZXYZRGBRGBRGB – Interleave colours between points: array = XYZRGBXYZRGBXYZRGB – Just create a new array and new vertex buffer object array1 = XYZXYZXYZ array2 = RGBRGBRGB
  • 50. Second Array GLfloat points[] = { 0.0f, 0.5f, 0.0f, 0.5f, -0.5f, 0.0f, -0.5f, -0.5f, 0.0f }; GLfloat colours[] = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f };
  • 51. Second VBO GLuint points_vbo = 0; glGenBuffers (1, &points_vbo); glBindBuffer (GL_ARRAY_BUFFER, points_vbo); glBufferData (GL_ARRAY_BUFFER, sizeof (points), points, GL_STATIC_DRAW); GLuint colours_vbo = 0; glGenBuffers (1, &colours_vbo); glBindBuffer (GL_ARRAY_BUFFER, colours_vbo); glBufferData (GL_ARRAY_BUFFER, sizeof (colours), colours, GL_STATIC_DRAW);
  • 52. Tell the VAO where to get 2nd variable GLuint vao; glGenVertexArrays (1, &vao); glBindVertexArray (vao); glEnableVertexAttribArray (0); glBindBuffer (GL_ARRAY_BUFFER, points_vbo); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray (1); glBindBuffer (GL_ARRAY_BUFFER, colours_vbo); glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 0, NULL); Second shader input variable Still a vec3 Change these 2 variables if interleaved or concatenated in one VBO
  • 53. Modify Vertex Shader #version 400 layout (location=0) in vec3 vp; // point layout (location=1) in vec3 vc; // colour out vec3 fcolour; void main () { fcolour = point; // ā€œpass-throughā€ output gl_Position = vec4 (vp, 1.0); } Q. Why does the colour input have to start in the vertex shader?
  • 54. Modify the Fragment Shader #version 400 in vec3 fcolour; out vec4 frag_colour; void main () { frag_colour = vec4 (fcolour, 1.0); } Q. There are more fragments than vertices. What values will fcolour have in each fragment?
  • 56. Drawing Modes ā— Points can be scaled ā— Lines are deprecated but still sort-of work ā— How would you change your triangles to an edges wireframe?
  • 57. Winding Order and Back-Face Culling ā— Easy optimisation – don't waste time drawing the back face or inside-facing parts of a mesh ā— How do we define the ā€œfrontā€ and ā€œbackā€ ā— = order that points are given ā— Clock-wise order or Counter clock-wise glEnable (GL_CULL_FACE); // cull face glCullFace (GL_BACK); // cull back face glFrontFace (GL_CW); // usually front is CCW