GLSL Basics Slides by : Wei-Wen Feng.

Slides:



Advertisements
Similar presentations
GLSL Basics Discussion Lecture for CS 418 Spring 2015 TA: Zhicheng Yan, Sushma S Kini, Mary Pietrowicz.
Advertisements

Informationsteknologi Wednesday, December 12, 2007Computer Graphics - Class 171 Today’s class OpenGL Shading Language.
MAT 594CM S10Fundamentals of Spatial ComputingAngus Forbes Week 4 : GLSL Shaders Topics: Shader programs, vertex & fragment shaders, passing data into.
MAT 594CM S10Fundamentals of Spatial ComputingAngus Forbes Week 5 : GLSL Shaders Topics: Shader syntax, passing textures into shaders, per-pixel lighting,
GLSL I May 28, 2007 (Adapted from Ed Angel’s lecture slides)
GLSL I Ed Angel Professor of Computer Science, Electrical and Computer Engineering, and Media Arts Director, Arts Technology Center University of New Mexico.
Cg: C for Graphics Jon Moon Based on slides by Eugene Lee.
The programmable pipeline Lecture 10 Slide Courtesy to Dr. Suresh Venkatasubramanian.
Mohan Sridharan Based on slides created by Edward Angel GLSL I 1 CS4395: Computer Graphics.
GAM532 DPS932 – Week 1 Rendering Pipeline and Shaders.
GPU Programming Robert Hero Quick Overview (The Old Way) Graphics cards process Triangles Graphics cards process Triangles Quads.
Programmable Pipelines. Objectives Introduce programmable pipelines ­Vertex shaders ­Fragment shaders Introduce shading languages ­Needed to describe.
An Introduction to the OpenGL Shading Language Benj Lipchak Rob Simpson Bill Licea-Kane.
CS 418: Interactive Computer Graphics Introduction to WebGL: HelloTriangle.html Eric Shaffer.
OpenGL Shading Language (Advanced Computer Graphics) Ernest Tatum.
Programmable Pipelines. 2 Objectives Introduce programmable pipelines ­Vertex shaders ­Fragment shaders Introduce shading languages ­Needed to describe.
CS 450: COMPUTER GRAPHICS PORTRAIT OF AN OPENGL PROGRAM SPRING 2015 DR. MICHAEL J. REALE.
Real-Time High Quality Rendering CSE 291 [Winter 2015], Lecture 4 Brief Intro to Programmable Shaders
Lecture by: Martin Deschamps CSE 4431
Shader Basics Chap. 2 of Orange Book. 2 Contents Why write shaders OpenGL programmable processors Language overview System overview.
OpenGL Shading Language Jian Huang CS594, Spring 2005.
GPU Shading and Rendering: OpenGL Shading Language Marc Olano UMBC.
GRAPHICS PIPELINE & SHADERS SET09115 Intro to Graphics Programming.
Programmable Pipelines Ed Angel Professor of Computer Science, Electrical and Computer Engineering, and Media Arts Director, Arts Technology Center University.
OpenGL Shader Language Vertex and Fragment Shading Programs.
Wilf Comp Shaders. Wilf Comp 4002 Shaders Shaders are programs that you can download onto the card Can be used.
Shaders in OpenGL Marshall Hahn. Introduction to Shaders in OpenGL In this talk, the basics of OpenGL Shading Language will be covered. This includes.
Shading in OpenGL Ed Angel Professor Emeritus of Computer Science University of New Mexico 1 E. Angel and D. Shreiner: Interactive Computer Graphics 6E.
OpenGL Shading Language (GLSL)
CSE 381 – Advanced Game Programming GLSL. Rendering Revisited.
OpenGL Shading Language (GLSL)
Vertex Buffer Objects and Shader Attributes. For Further Reading Angel 7 th Ed: –Most parts of Chapter 2. Beginning WebGL: –Chapter 1: vertex Buffer Objects,
Week 3 Lecture 4: Part 2: GLSL I Based on Interactive Computer Graphics (Angel) - Chapter 9.
 Learn some important functions and process in OpenGL ES  Draw some triangles on the screen  Do some transformation on each triangle in each frame.
What are shaders? In the field of computer graphics, a shader is a computer program that runs on the graphics processing unit(GPU) and is used to do shading.
OpenGL Shading Language
OpenGL Shading Language (GLSL)
Programming with OpenGL Part 3: Shaders Ed Angel Professor of Emeritus of Computer Science University of New Mexico 1 E. Angel and D. Shreiner: Interactive.
OpenGl Shaders Lighthouse3d.com.
GLSL I.  Fixed vs. Programmable  HW fixed function pipeline ▪ Faster ▪ Limited  New programmable hardware ▪ Many effects become possible. ▪ Global.
An Introduction to the Cg Shading Language Marco Leon Brandeis University Computer Science Department.
GLSL Review Monday, Nov OpenGL pipeline Command Stream Vertex Processing Geometry processing Rasterization Fragment processing Fragment Ops/Blending.
COMP 175 | COMPUTER GRAPHICS Remco Chang1/XX13 – GLSL Lecture 13: OpenGL Shading Language (GLSL) COMP 175: Computer Graphics April 12, 2016.
CS 480/680 Computer Graphics Programming with Open GL Part 2: Complete Programs Dr. Frederick C Harris, Jr. Fall 2011.
COMP3421 The programmable pipeline and Shaders. TODO.
Shaders, part 2 alexandri zavodny.
Shader.
Programmable Pipelines
Chapter 6 GPU, Shaders, and Shading Languages
Objectives Simple Shaders Programming shaders with GLSL
GLSL I Ed Angel Professor of Computer Science, Electrical and Computer Engineering, and Media Arts Director, Arts Technology Center University of New Mexico.
Day 05 Shader Basics.
Chapter VI OpenGL ES and Shader
Introduction to Computer Graphics with WebGL
Introduction to Shaders
Introduction to Computer Graphics with WebGL
Introduction to Computer Graphics with WebGL
Shader Basics Chap. 2 of Orange Book.
ICG 2018 Fall Homework1 Guidance
Programming with OpenGL Part 2: Complete Programs
Programming with OpenGL Part 3: Shaders
Programming with OpenGL Part 2: Complete Programs
Mickaël Sereno Shaders Mickaël Sereno 25/04/2019 Mickaël Sereno -
CIS 441/541: Introduction to Computer Graphics Lecture 15: shaders
CS 480/680 Computer Graphics GLSL Overview.
Language Definitions Chap. 3 of Orange Book.
Computer Graphics Shading in OpenGL
Shading in OpenGL Ed Angel Professor Emeritus of Computer Science
Introduction to Computer Graphics with WebGL
CS 480/680 Fall 2011 Dr. Frederick C Harris, Jr. Computer Graphics
Presentation transcript:

GLSL Basics Slides by : Wei-Wen Feng

Shader Concept Application Screen Transform Rasterize Shading OpenGL Fixed Graphics Pipeline : Application Screen Vertex Pos Normal Camera View Light Pixels Color Transform Rasterize Shading

Shader Concept Application Screen Vertex Shader Rasterize Programmable Shader : Application Screen Vertex Pos Normal Camera View Light Pixel Color Vertex Shader Rasterize Fragment Shader User Program Control !

Shader Concept Vertex Shader Vertex Shader Rasterize Application Execute on “Every” vertex. Write your program to replace OpenGL fixed-function You can transform vertex position, compute per-vertex attributes (Ex : color ). Vertex Pos Normal Camera Light Vertex Pos Vertex Color Vertex Shader Rasterize Application

Shader Concept Fragment Shader ( Pixel Shader ) Fragment Shader Execute for each “Fragment” “Fragments” are pixels from a triangle after rasterize. Output final color on Screen. Vertex Fragment Rasterize Fragment Shader Interpolate Pos, Color Pixel Color

Shader Concept Application Vertex Shader Rasterize Fragment Shader Process Vertex Vertex Shader Interpolate Attrib. Rasterize Fragment Shader Process Fragment Screen Pixels

Shader Programming C-like syntax for programming. More difficult to program than usual C/C++ No “printf” type debug. You only see “Colors”. Respect rules for input/output and data access. Think in parallel. Same code will apply to all vertices/fragments.

GLEW Include “glew.h” instead of “gl.h” glewInit()//not necessary for xcode Call it right after you setup GL context. Or it will crash on you. After that, you can call extension APIs as usual. #include <GL/glew.h> #include <GL/glut.h> ... glutInit(&argc, argv); glutCreateWindow(“Test"); GLenum err = glewInit();

Hello-Shader // Vertex Shader void main() { gl_Position = gl_ModelViewProjectionMatrix*gl_Vertex; } // Fragment Shader void main() { gl_FragColor = vec4(1, 0, 0, 1); }

Setup Shader Programming Basic flow : Write your shader code in a text editor. Make shader setup in OpenGL code. Load / build shader source code from file. Apply shader program to your rendering pipeline.

Setup Shader Shader Vertex shader Shader Object Fragment shader Create a shader Create object Set source code Compile code Shader Object glCreateShader glShaderSource glCompileShader Shader Code

Setup Shader glCreateShader(GLenum Type ) Create a shader container for use. Return the handle ( ID ) to a new shader. Type : GL_VERTEX_SHADER GL_FRAGMENT_SHADER Shader Object glCreateShader glShaderSource glCompileShader

Setup Shader Shader Object glCreateShader glShaderSource glShaderSource(int shaderobject, int numOfStrings, const char **strings, int *lenOfStrings) Specify source code for a shader. What I usually do : Edit and save shader code to text file. Load the text file and store them in char array Call glShaderSource and pass in strings loaded from file. Don’t try to specify a vertex shader code to a fragment shader object. Shader Object glCreateShader glShaderSource glCompileShader

Setup Shader glCompileShader(int shaderobject ) Compile the source code in shader object before you can use it. Be sure to check for compiling error. Use glGetShaderInfoLog to get compiler errors for shader. If you use a faulty shader, OpenGL might reset to fixed pipeline, or ….crash. Shader Object glCreateShader glShaderSource glCompileShader

Setup Program Shader Program A container holds multiple shaders. OpenGL will execute your “program” on graphics card. You don’t need to have both “VS” and “FS” in program. Fixed pipeline will be used in place of missing shader. Shader Program glCreateProgram glAttachShader glLinkProgram glUseProgram

Setup Program glCreateProgram(int program) Create a container and return its ID. glAttachShader(int program, int shader) Add your shader objects to program. More than one shaders can be added. glCreateProgram glAttachShader glLinkProgram Shader Program glUseProgram //Shader1 : main() { // do transform } //Shader2 : HelpFunc() { // do something } //Shader3 : main() { // do lighting } Attach Shader1 & Shader2 OK Attach Shader1 & Shader3  Error !

Setup Program glLinkProgram(int program) Shader Program Link shader objects in a program. Like your C/C++ compiler ! You can change source code later, program recompile automatically. glUseProgram(int program) Apply this program in your rendering. You can create/link multiple programs and switch them. Ex : Shader Program glCreateProgram glAttachShader glLinkProgram glUseProgram

GetErrors glGetError, gluErrorString Check for OpenGL error, and get Error message. glGetShaderInfoLog, glGetProgramInfoLog Check if shader compile correctly. You can’t run a C/C++ program with compile error. So does shader. We put together some help functions in skeleton code. printShaderInfoLog  shader compile msg printProgramInfoLog  shader program link msg printOpenGLError  OpenGL error Use them, they can save you lots of time !

Source Code vtx_shader = glCreateShader(GL_VERTEX_SHADER); vs = textFileRead("vs_basic.vert"); const char * vv = vs; glShaderSource(vtx_shader, 1, &vv,NULL); glCompileShader(vtx_shader); printShaderInfoLog(vtx_shader) // check compile msg shader_program = glCreateProgram(); glAttachShader(shader_program,vtx_shader); glLinkProgram(shader_program); printProgramInfoLog(shader_program); // check link msg glUseProgram(shader_program);

Basic Data Type GLSL is like C, but with more vector/matrix data types built-in. vec2, vec3, vec4 : float vector data ivec for “int” vector. mat2, mat3, mat4 : float matrix data Each vertex/fragment shader must have an entry point “void main()”, just like C !. void main() { mat4 M; vec3 t; t = vec3(0,0,1); }

Accessing Vector However, don’t try to break its logic : void main() { mat4 M; vec3 t; t = vec3(0,0,1); t[0] = 3; // Now t = (3,0,1) t.x = 1; // t = (1,0,1) t.yz = vec2(1,2); // t = (1,1,2) t.zx = vec2(3,0); // t = (0,1,3) } Swizzling operator let you access particular parts of vec (x,y,z,w) = (r,g,b,a) = (s,t,p,q) V.x = V.r = V.s = V[0] Access parts of a vec V.xy = vec2(4,2) Can do it in any order : V.zx = vec2(3,0) Or repeat the elements V.xyz = U.xxx However, don’t try to break its logic : V.xzz = vec3(1,2,3); // Err!

Control Flow C-like expression for program control if (bool expression) ... else for (int i=0 ;i<n ;i++) loop do…while (bool expression) These conditional branch is much more expensive than in CPU.  Don’t overuse it, especially in fragment shader.

Function C-like function declaration void func_name(in vec3 pin, out vec3 pout) However, no C-like reference to get return values. void func_name(vec3& out)  No available Qualifiers for function parameters : in : for input out : for return values inout : for both input & return values By default, they are input parameters.

Useful Functions normalize(v) : unitize a vector dot(u,v) : dot product ftransform() : return transformed vertex positions ( Vertex shader only ! ) reflect(v,n) : get reflected direction ( useful for specular ! ) I skip texture access for now. We will discuss it next time.

Variable Types : Attribute attribute vec4 velocity; void main() { gl_Position = gl_Vertex + velocity*0.1; } Application glVertex, glNormal UserAttrib. Binding Attribute variable : Change at each vertex ( Position, Color, etc ) Define your own attributes in OpenGL. Useful default binding : gl_Vertex  glVertex gl_Normal glNormal gl_Color glColor gl_Vertex, gl_Normal Attribute Variable Vertex Shader

Variable Types : Uniform attribute vec4 velocity; uniform float time; void main() { mat4 m = gl_ModelViewProjectionMatrix; gl_Position = m*gl_Vertex + velocity*time; } Application ModelView Projection User Variable Binding Uniform variable : Information that is constant for an object You can set it for both vertex/fragment shader Useful default variable: gl_ModelViewProjectionMatrix gl_NormalMatrix  Transform normal Default Variables User Uniform Variables Vertex Shader Fragment Shader

Variable Types : Varying Varying variable : Passing data from Vertex shader to Fragment shader. Data that will be interpolated during rasterization. Vertex Shader Set values for varying var. gl_TexCoord[x] gl_FrontColor gl_BackColor Fragment Shader Get interpolation varying var.

Variable Types : Varying A Simple Gouraud Shading Vertex Shader Fragment Shader Compute vtx_color Get interpolated vtx_color gl_FragColor // Vertex Shader Program varying vec4 vtx_color; //to fragment shader void main() { gl_Position = gl_Vertex; vtx_color = dot(gl_Normal,LightDir); } // Fragment Shader Program varying vec4 vtx_color; // from vertex shader void main() { gl_FragColor = vtx_color; //output vtx_color }

Setting Variables OpenGL already set up some default variables for you. Uniform : gl_LightSource, gl_***Matrix, etc Attributes : gl_Vertex, gl_Normal, etc. You may want to define your own variables Attributes : tangent, binormal direction Uniform : animation time

Setting Uniform int glGetUniformLocation(int prog, int Name) Return Location(ID) to a uniform variable Prog : shader program Name : variable name in shader code int glUniform (int loc, float value) Set value for Uniform var. in shader //OpenGL code LocA = glGetUniformLocation(prog,”time”); glUniform1f(LocA,1.0f); LocB = glGetUniformLocation(prog,”vel”); glUniform3f(LocB, 0.0, 1.0, 0.5); //Shader code uniform float time; uniform vec3 vel; void main { gl_Position = vel*time; }

Setting Attributes int glGetAttribLocation(prog, int name) Return Location(ID) to a attribute variable Prog : Shader program, Name : Attribute name in shader int glVertexAttrib Similar to other calls like glColor, glNormal. //OpenGL code Loc = glGetAttribLocation(prog,”scale”); glBegin(GL_TRIANGLES); for (int i=0;i<3;i++) { glVertexAttrib1f(Loc,Scale[i]); glVertex3fv(Pos[i]); } glEnd(); //Shader code attribute float scale; void main { gl_Position = gl_Vertex*scale; }

Coding for GPU Think in parallel when writing shader code The same program run on every vertices/fragments. GPU is not like CPU, don’t abuse “if..then..else”. Coding & Debugging : Always make sure shader is compiled correctly. Make use of default variables like gl_Vertex, gl_Normal, gl_XXMatrix to save your time. Check variables in question  Output it as color.

Coding for GPU Common Mistakes : Nothing change when you modify shader code ? Maybe OpenGL already go back to fixed pipeline. Which means something wrong in your shader code Use wrong names in OpenGL to refer Shader variables. That variable has no values. Mismatch vector length gl_Normal : vec3 gl_Vertex : vec4

Useful resources http://zach.in.tu- clausthal.de/teaching/cg_literatur/glsl_tutorial/ http://www.ics.uci.edu/~gopi/CS211B/opengl_prog ramming_guide_8th_edition.pdf http://web.cse.ohio- state.edu/~whmin/courses/cse5542-2013- spring/13-GLSL.pdf