Introduction to the OpenGL Shading Language (GLSL)

Similar documents
The Basic Computer Graphics Pipeline, OpenGL-style. Introduction to the OpenGL Shading Language (GLSL)

The Transition from RenderMan to the OpenGL Shading Language (GLSL)

Introduction to Shaders for Visualization. The Basic Computer Graphics Pipeline

Using Shaders for Lighting

Programmable Graphics Hardware

12.2 Programmable Graphics Hardware

GLSL Introduction. Fu-Chung Huang. Thanks for materials from many other people

Supplement to Lecture 22

Using Shaders for Lighting

Shader Programs. Lecture 30 Subsections 2.8.2, Robb T. Koether. Hampden-Sydney College. Wed, Nov 16, 2011

GLSL Introduction. Fu-Chung Huang. Thanks for materials from many other people

Programmable GPUs. Real Time Graphics 11/13/2013. Nalu 2004 (NVIDIA Corporation) GeForce 6. Virtua Fighter 1995 (SEGA Corporation) NV1

The Graphics Pipeline and OpenGL III: OpenGL Shading Language (GLSL 1.10)!

GLSL Geometry Shaders

Programming with OpenGL Part 3: Shaders. Ed Angel Professor of Emeritus of Computer Science University of New Mexico

Sign up for crits! Announcments

Information Coding / Computer Graphics, ISY, LiTH GLSL. OpenGL Shading Language. Language with syntax similar to C

GLSL 1: Basics. J.Tumblin-Modified SLIDES from:

Lecture 5 Vertex and Fragment Shaders-1. CITS3003 Graphics & Animation

Stripes, Rings, and Dots!

Shader Programming. Daniel Wesslén, Stefan Seipel, Examples

Lecture 09: Shaders (Part 1)

A Tessellated Parametric Triangular Bézier Patch

Programming shaders & GPUs Christian Miller CS Fall 2011

The Graphics Pipeline and OpenGL III: OpenGL Shading Language (GLSL 1.10)!

CS4621/5621 Fall Basics of OpenGL/GLSL Textures Basics

CSE 167: Lecture #8: GLSL. Jürgen P. Schulze, Ph.D. University of California, San Diego Fall Quarter 2012

Lecture 17: Shading in OpenGL. CITS3003 Graphics & Animation

Programming with OpenGL Shaders I. Adapted From: Ed Angel Professor of Emeritus of Computer Science University of New Mexico

Today s Agenda. Basic design of a graphics system. Introduction to OpenGL

SHADER PROGRAMMING. Based on Jian Huang s lecture on Shader Programming

Some advantages come from the limited environment! No classes. Stranight ans simple code. Remarkably. Avoids most of the bad things with C/C++.

Shader Programming 1. Examples. Vertex displacement mapping. Daniel Wesslén 1. Post-processing, animated procedural textures

WebGL and GLSL Basics. CS559 Fall 2015 Lecture 10 October 6, 2015

OPENGL RENDERING PIPELINE

Shaders. Introduction. OpenGL Grows via Extensions. OpenGL Extensions. OpenGL 2.0 Added Shaders. Shaders Enable Many New Effects

Copyright Khronos Group 2012 Page 1. Teaching GL. Dave Shreiner Director, Graphics and GPU Computing, ARM 1 December 2012

GLSL v1.20. Scott MacHaffie Schrödinger, Inc.

Information Coding / Computer Graphics, ISY, LiTH GLSL. OpenGL Shading Language. Language with syntax similar to C

CSE 167: Introduction to Computer Graphics Lecture #13: GLSL. Jürgen P. Schulze, Ph.D. University of California, San Diego Fall Quarter 2015

Today. Rendering - III. Outline. Texturing: The 10,000m View. Texture Coordinates. Specifying Texture Coordinates in GL

GPU Programming EE Final Examination

Graphics Programming. Computer Graphics, VT 2016 Lecture 2, Chapter 2. Fredrik Nysjö Centre for Image analysis Uppsala University

Objectives Shading in OpenGL. Front and Back Faces. OpenGL shading. Introduce the OpenGL shading methods. Discuss polygonal shading

Bump Mapping. Mike Bailey. What is Bump-Mapping?

GPU Programming EE Final Examination

Objectives. Open GL Shading Language (GLSL)

WebGL and GLSL Basics. CS559 Fall 2016 Lecture 14 October

Today s Agenda. Shaders fundamentals. Programming with shader-based OpenGL

EDAF80 Introduction to Computer Graphics. Seminar 3. Shaders. Michael Doggett. Slides by Carl Johan Gribel,

Programming with OpenGL Shaders I. Adapted From: Ed Angel Professor of Emeritus of Computer Science University of New Mexico

2D graphics with WebGL

Introduction to Shaders.

An Overview GLUT GLSL GLEW

CMPS160 Shader-based OpenGL Programming. All slides originally from Prabath Gunawardane, et al. unless noted otherwise

Waves, Displacement, Reflections. Arun Rao CS 594

Programmable Graphics Hardware

Shaders. Slide credit to Prof. Zwicker

CS559 Computer Graphics Fall 2015

Bump Mapping. Mike Bailey. Oregon State University. What is Bump-Mapping?

GPU Programming EE Final Examination

Lighting and Shading II. Angel and Shreiner: Interactive Computer Graphics 7E Addison-Wesley 2015

C P S C 314 S H A D E R S, O P E N G L, & J S RENDERING PIPELINE. Mikhail Bessmeltsev

Best practices for effective OpenGL programming. Dan Omachi OpenGL Development Engineer

CSE 167: Introduction to Computer Graphics Lecture #7: GLSL. Jürgen P. Schulze, Ph.D. University of California, San Diego Spring Quarter 2016

CSE 4431/ M Advanced Topics in 3D Computer Graphics. TA: Margarita Vinnikov

Lab 9 - Metal and Glass

Lighting and Texturing

GPU Programming EE Midterm Examination

Accelerating the Hyperbolic Display of Complex 2D Scenes Using the GPU

Lecture 13: OpenGL Shading Language (GLSL)

Introduction to Computer Graphics. Hardware Acceleration Review

Technical Game Development II. Reference: Rost, OpenGL Shading Language, 2nd Ed., AW, 2006 The Orange Book Also take CS 4731 Computer Graphics

CS770/870 Spring 2017 Open GL Shader Language GLSL

CS770/870 Spring 2017 Open GL Shader Language GLSL

CS475/CS675 - Computer Graphics. OpenGL Drawing

Real-Time Rendering (Echtzeitgraphik) Michael Wimmer

Programmable shader. Hanyang University

CS 432 Interactive Computer Graphics

Stored Texture Shaders

Tuesday, 23 March OpenGL Shading Language

CS 4620 Midterm, October 23, 2018 SOLUTION

Programming Graphics Hardware

Lecture 11 Shaders and WebGL. October 8, 2015

Introduction to GLSL. Announcements. Agenda. Course Contents. Patrick Cozzi University of Pennsylvania CIS Fall 2012

INF3320 Computer Graphics and Discrete Geometry

GPU Programming EE Final Examination

CS4621/5621 Fall Computer Graphics Practicum Intro to OpenGL/GLSL

GLSL. OpenGL Shading Language. OpenGL 1.5 Logical Diagram. OpenGL 2.0 Logical Diagram

OUTLINE. Implementing Texturing What Can Go Wrong and How to Fix It Mipmapping Filtering Perspective Correction

OpenGL Programmable Shaders

CMPS160 Shader-based OpenGL Programming

Lets assume each object has a defined colour. Hence our illumination model is looks unrealistic.

Technical Game Development II. Reference: Rost, OpenGL Shading Language, 2nd Ed., AW, 2006 The Orange Book Also take CS 4731 Computer Graphics

LSU EE Homework 5 Solution Due: 27 November 2017

Shaders CSCI 4239/5239 Advanced Computer Graphics Spring 2014

Computergraphics Exercise 15/ Shading & Texturing

Pipeline Operations. CS 4620 Lecture Steve Marschner. Cornell CS4620 Spring 2018 Lecture 11

Preparing for Texture Access. Stored Texture Shaders. Accessing Texture Maps. Vertex Shader Texture Access

Vertex & Fragment shaders

Transcription:

1 Introduction to the OpenGL Shading Language (GLSL) This work is licensed under a Creative Commons Attribution-NonCommercial- NoDerivatives 4.0 International License Mike Bailey mjb@cs.oregonstate.edu IntroToShaders.pptx

The Basic Pipeline, OpenGL-style 2 Vertex, Normal, Color ModelViewMatrix, ProjectionMatrix, ModelViewProjectionMatrix MC WC EC EC Model Transform View Transform Per-vertex Lighting Projection Transform Rasterization Framebuffer Fragment Processing, Texturing, Per-fragment Lighting MC = Model Vertex Coordinates WC = World Vertex Coordinates EC = Eye Vertex Coordinates

The Basic Pipeline, Shader-style 3 gl_vertex, gl_normal, gl_color Per-vertex in variables gl_modelviewmatrix, gl_projectionmatrix, gl_modelviewprojectionmatrix Uniform Variables MC Model Transform WC View Transform EC Per-vertex Lighting EC Projection Transform gl_position, Per-vertex out variables Vertex Shader Rasterization Fragment Shader Framebuffer gl_fragcolor Fragment Processing, Texturing, Per-fragment Lighting Per-fragment in variables Uniform Variables MC = Model Vertex Coordinates WC = World Vertex Coordinates EC = Eye Vertex Coordinates

The Basic Pipeline, Shader-style 4 gl_vertex, gl_modelviewmatrix, gl_normal, gl_projectionmatrix, gl_color Per-vertex in variables gl_modelviewprojectionmatrix Uniform Variables Vertex Shader gl_position, Per-vertex out variables Rasterization Framebuffer gl_fragcolor Fragment Shader Per-fragment in variables Uniform Variables

GLSL Variable Types 5 attribute uniform out / in These are per-vertex in variables. They are assigned per-vertex and passed into the vertex shader, usually with the intent to interpolate them through the rasterizer. These are global values, assigned and left alone for a group of primitives. They are read-only accessible from all of your shaders. They cannot be written to from a shader. These are passed from one shader stage to the next shader stage. In our case, out variables come from the vertex shader, are interpolated in the rasterizer, and go in to the fragment shader. Attribute variables are in variables to the vertex shader.

GLSL Shaders Are Like C With Extensions for Graphics: 6 Types include int, ivec2, ivec3, ivec4 Types include float, vec2, vec3, vec4 Types include mat2, mat3, mat4 Types include bool, bvec2, bvec3, bvec4 Types include sampler to access textures Vector components are accessed with [index],.rgba,.xyzw, or.stpq You can ask for parallel SIMD operations (doesn t necessarily do it in hardware): vec4 a, b, c; a = b + c; Vector components can be swizzled ( c1.rgba = c2.abgr ) Type qualifiers: const, attribute, uniform, in, out Variables can have layout qualifiers (more on this later) Thediscard operator is used in fragment shaders to get rid of the current fragment

The discard Operator 7 if( random_number < 0.5 ) discard;

GLSL Shaders Are Missing Some C-isms: 8 No type casts -- use constructors instead: int i = int( x ); Only some amount of automatic promotion (don t rely on it!) No pointers No strings No enums Can only use 1-D arrays (no bounds checking) Warning: integer division is still integer division! float f = float( 2 / 4 ); // still gives 0. like C, C++, Python, Java

The Shaders View of the Basic Pipeline 9 A missing stage is OK. The output from one stage becomes the input of the next stage that is there. The last stage before the fragment shader feeds its output variables into the rasterizer. The interpolated values then go to the fragment shader We are just going to cover these two = Fixed Function = You-Programmable

A GLSL Vertex Shader Replaces These Operations: 10 Vertex transformations Normal transformations Normal unitization (normalization) Computing per-vertex lighting Taking per-vertex texture coordinates (s,t) and passing them through the rasterizer to the fragment shader

Built-in Vertex Shader Variables You Will Use a Lot: 11 vec4 gl_vertex vec3 gl_normal vec4 gl_color vec4 gl_multitexcoord0 mat4 gl_modelviewmatrix mat4 gl_projectionmatrix mat4 gl_modelviewprojectionmatrix mat4 gl_normalmatrix (this is the transpose of the inverse of the MV matrix) vec4 gl_position Note: while this all still works, OpenGL now prefers that you pass in all the above variables (except gl_position) as user-defined attribute variables. We ll talk about this later.

A GLSL Fragment Shader Replaces These Operations: 12 Color computation Texturing Handling of per-fragment lighting Color blending Discarding fragments Built-in Fragment Shader Variables You Will Use a Lot: vec4 gl_fragcolor Note: while this all still works, OpenGL now prefers that you pass information out of the Fragment Shader as out variables. We ll talk about this later.

My Own Variable Naming Convention 13 With 7 different places that GLSL variables can be written from, I decided to adopt a naming convention to help me recognize what programdefined variables came from what sources: Beginning letter(s) a u v tc te g f Means that the variable Is a per-vertex attribute from the application Is a uniform variable from the application Came from the vertex shader Came from the tessellation control shader Came from the tessellation evaluation shader Came from the geometry shader Came from the fragment shader This isn t part of official OpenGL it is my way of handling the confusion

The Minimal Vertex and Fragment Shader 14 Vertex shader: #version 330 compatibility void main( ) { } gl_position = gl_modelviewprojectionmatrix * gl_vertex; Fragment shader: #version 330 compatibility void main( ) { } gl_fragcolor = vec4(.5, 1., 0., 1. );

A Reminder (from the Getting Started notes) of what a Rasterizer does 15 NDC There is a piece of hardware called the Rasterizer. Its job is to interpolate a line or polygon, defined by vertices, into a collection of fragments. Think of it as filling in squares on graph paper. A fragment is a pixel-to-be. In computer graphics, pixel is defined as having its full RGBA already computed. A fragment does not yet but all of the information needed to compute the RGBA is there. SC Rasterization A fragment is turned into a pixel by the fragment processing operation. Rasterizers interpolate built-in variables, such as the (x,y) position where the pixel will live and the pixel s z-coordinate. They can also interpolate user-defined variables as well. Fragment Processing, Texturing, Per-fragment Lighting

A Little More Interesting 16 Vertex shader: #version 330 compatibility out vec3 vcolor; void main( ) { } vec4 pos = gl_vertex; vcolor = pos.xyz; // set rgb from xyz! gl_position = gl_modelviewprojectionmatrix * gl_vertex; Fragment shader: #version 330 compatibility in vec3 vcolor; void main( ) { } gl_fragcolor = vec4( vcolor, 1. );

Setting rgb From xyz, I 17 vcolor = gl_vertex.xyz;

What s Changed About This? 18 Vertex shader: #version 330 compatibility out vec3 vcolor; void main( ) { } vec4 pos = gl_modelviewmatrix * gl_vertex; vcolor = pos.xyz; // set rgb from xyz! gl_position = gl_modelviewprojectionmatrix * gl_vertex; Fragment shader: #version 330 compatibility in vec3 vcolor; void main( ) { } gl_fragcolor = vec4( vcolor, 1. );

What s Different About This? Set the color from the pre-transformed (MC) xyz: #version 330 compatibility out vec3 vcolor; 19 void main( ) { } vec4 pos = gl_vertex; vcolor = pos.xyz; // set rgb from xyz! gl_position = gl_modelviewprojectionmatrix * gl_vertex; Set the color from the post-transformed (WC/EC) xyz: #version 330 compatibility out vec3 vcolor; void main( ) { } vec4 pos = gl_modelviewmatrix * gl_vertex; vcolor = pos.xyz; // set rgb from xyz! why? who cares? gl_position = gl_modelviewprojectionmatrix * gl_vertex;

Setting rgb From xyz, II 20 vcolor = ( gl_modelviewmatrix * gl_vertex ).xyz;

Setting rgb From xyz 21 vcolor = gl_vertex.xyz; vcolor = ( gl_modelviewmatrix * gl_vertex ).xyz;

Per-fragment Lighting 22 Vertex shader: #version 330 compatibility out vec2 vst; out vec3 vn; out vec3 vl; out vec3 ve; // texture coords // normal vector // vector from point to light // vector from point to eye const vec3 LIGHTPOSITION = vec3( 5., 5., 0. ); void main( ) { } vst = gl_multitexcoord0.st; vec4 ECposition = gl_modelviewmatrix * gl_vertex; vn = normalize( gl_normalmatrix * gl_normal ); // normal vector vl = LIGHTPOSITION - ECposition.xyz; // vector from the point // to the light position ve = vec3( 0., 0., 0. ) - ECposition.xyz; // vector from the point // to the eye position gl_position = gl_modelviewprojectionmatrix * gl_vertex;

Fragment shader: #version 330 compatibility uniform float uka, ukd, uks; uniform vec3 ucolor; uniform vec3 uspecularcolor; uniform float ushininess; in vec2 vst; in vec3 vn; in vec3 vl; in vec3 ve; Per-fragment Lighting // coefficients of each type of lighting // object color // light color // specular exponent // texture cords // normal vector // vector from point to light // vector from point to eye 23 void main( ) { vec3 Normal = normalize(vn); vec3 Light = normalize(vl); vec3 Eye = normalize(ve); vec3 ambient = uka * ucolor; float d = max( dot(normal,light), 0. ); vec3 diffuse = ukd * d * ucolor; // only do diffuse if the light can see the point Computer } Graphics float s = 0.; if( dot(normal,light) > 0. ) { vec3 ref = normalize( reflect( -Light, Normal ) ); s = pow( max( dot(eye,ref),0. ), ushininess ); } vec3 specular = uks * s * uspecularcolor; gl_fragcolor = vec4( ambient + diffuse + specular, 1. ); // only do specular if the light can see the point

Per-fragment Lighting 24 Ambient Diffuse Specular All together now!

Attaching a Rectangular Pattern to an Object 25 Within the fragment shader:... vec3 mycolor = ucolor; if( { } us0-usize/2. <= vst.s && vst.s <= us0+usize/2. && ut0-usize/2. <= vst.t && vst.t <= ut0+usize/2. ) mycolor = vec3( 1., 0., 0. ); vec3 ambient = uka * mycolor;...

Attaching a Rectangular Pattern to an Object 26 Here s the cool part: It doesn t matter (up to the limits of 32-bit floating-point precision) how far you zoom in. You still get an exact crisp edge. This is an advantage of procedural (equation-based) textures, as opposed to texelbased textures. Zoomed way in

A C++ Class to Handle the Shaders 27 Setup: GLSLProgram *Pattern;... Pattern = new GLSLProgram( ); bool valid = Pattern->Create( "pattern.vert", "pattern.frag" ); if(! valid ) {... } This loads, compiles, and links the shader. If something went wrong, it prints error messages and returns a value of false.

A C++ Class to Handle the Shaders 28 Invoking this class in Display( ): float S0, T0; float Ds, Dt; float V0, V1, V2; float ColorR, ColorG, ColorB;... Pattern->Use( ); Pattern->SetUniformVariable( "us0", S0); Pattern->SetUniformVariable( "ut0", T0 ); Pattern->SetUniformVariable( "uds", Ds); Pattern->SetUniformVariable( "udt", Dt ); Pattern->SetUniformVariable( ucolor", ColorR, ColorG, ColorB ); glbegin( GL_TRIANGLES ); Pattern->SetAttributeVariable( "av0", V0 ); // don t need for Project #5 glvertex3f( x 0, y 0, z 0 ); Pattern->SetAttributeVariable( "av1", V1 ); // don t need for Project #5 glvertex3f( x 1, y 1, z 1 ); Pattern->SetAttributeVariable( "av2", V2 ); // don t need for Project #5 glvertex3f( x 2, y 2, z 2 ); glend( ); Pattern->Use( 0 ); // go back to fixed-function OpenGL

Setting Up Texturing in Your C/C++ Program 29 You do all the texture things you did before, but add this: Pattern->Use( ); This is the Texture Unit Number. It can be 0-15 (and often a lot higher depending on the graphics card). glactivetexture( GL_TEXTURE5 ); glbindtexture( GL_TEXTURE_2D, texname ); // 0, 1, 2, 3, 4, 5, Pattern->SetUniformVariable( utexunit", 5 );

2D Texturing 30 Vertex shader: #version 330 compatibility out vec2 vst; void main( ) { } vst = gl_multitexcoord0.st; gl_position = gl_modelviewprojectionmatrix * gl_vertex; Fragment shader: #version 330 compatibility in vec2 vst; uniform sampler utexunit; Pattern->SetUniformVariable( utexunit", 5 ); void main( ) { } vec3 newcolor = texture( utexunit, vst ).rgb; gl_fragcolor = vec4( newcolor, 1. );

2D Texturing 31

Hints on Running Shaders on Your Own System 32 You need a graphics system that is OpenGL 2.0 or later. Basically, if you got your graphics system in the last 5 years, you should be OK. If you don't have access to such a system, use the CGEL. (The most recent OpenGL level there is 4.6) Update your graphics drivers to the most recent level! If you are on Windows, you must do the GLEW setup. It looks like this in the sample code: GLenum err = glewinit( ); if( err!= GLEW_OK ) { fprintf( stderr, "glewinit Error\n" ); } else fprintf( stderr, "GLEW initialized OK\n" ); And, this must come after you've opened a window. (It is this way in the code, but I'm saying this because I know some of you went in and "simplified" the sample code by deleting everything you didn't think you needed.) You can use the GLSL C++ class you've been given only after GLEW has been setup. So, initialize your shader program: bool valid = Pattern->Create( "pattern.vert", "pattern.frag" ); after successfully initializing GLEW.

Guide to Where to Put Pieces of Your Shader Code, I 33 Declare the GLSLProgram above the main program (as a global): GLSLProgram *Pattern; At the end of InitGraphics( ), create the shader program and setup your shaders: Pattern = new GLSLProgram( ); bool valid = Pattern->Create( "proj05.vert", "proj05.frag" ); if(! valid ) {... } Use the Shader Program in Display( ): Pattern->Use( ); Pattern->SetUniformVariable(... Draw the object here Pattern->Use( 0 ); // return to fixed functionality

Guide to Where to Put Pieces of Your Shader Code, II 34 Tips on drawing the object: If you want to key off of s and t coordinates in your shaders, the object had better have s and t coordinates assigned to its vertices not all do! If you want to use surface normals in your shaders, the object had better have surface normals assigned to its vertices not all do! Be sure you explicitly assign all of your uniform variables no error messages occur if you forget to do this it just quietly screws up. The glutsolidteapot has been textured in patches, like a quilt cute, but weird The MjbSphere( ) function from the texturing project will give you a very good sphere