Tartalmi kivonat
Source: http://www.doksinet Computer Graphics (CS 4731) Lecture 1: Introduction to Computer Graphics Prof Emmanuel Agu Computer Science Dept. Worcester Polytechnic Institute (WPI) Source: http://www.doksinet What is Computer Graphics (CG)? Computer graphics: algorithms, mathematics, data structures . that computer uses to generate PRETTY PICTURES Techniques (e.g draw a line, polygon) evolved over years Built into programmable libraries Computer‐Generated! Not a picture! Source: http://www.doksinet Photorealistic Vs Real‐Time Graphics Not this Class This Class • Photo‐realistic: E.g ray tracing slow: may take days to render • Real Time graphics: Milliseconds to render (30 FPS) But lower image quality Source: http://www.doksinet Uses of Computer Graphics: Entertainment Entertainment: games Movies Courtesy: Super Mario Galaxy 2 Courtesy: Spiderman Source: http://www.doksinet Uses of Computer Graphics Image processing: alter images,
remove noise, super‐impose images Original Image Sobel Filter Source: http://www.doksinet Uses of Computer Graphics Monitor large systems or plants Simulators Courtesy: Dataviews.de Courtesy: Evans and Sutherland Source: http://www.doksinet Uses of Computer Graphics Computer‐aided design: Display math functions E.g matlab Courtesy: cadalog.com Source: http://www.doksinet Uses of Computer Graphics Scientific analysis and visualization: molecular biology, weather, matlab, Mandelbrot set Courtesy: Human Brain Project, Denmark Source: http://www.doksinet 2D Vs. 3D 2‐Dimensional (2D) Flat Objects no notion of distance from viewer Only (x,y) color values on screen • • 3‐Dimensional (3D) Objects have distances from viewer (x,y,z) values on screen This class covers both 2D & 3D! Also interaction: Clicking, dragging Source: http://www.doksinet About This Course Computer Graphics has many aspects
Computer Scientists create/program graphics tools (e.g Maya, photoshop) Artists use CG tools/packages to create pretty pictures Source: http://www.doksinet About This Course Most hobbyists follow artist path. Not much math! This Course: Computer Graphics for computer scientists!!! Teaches concepts, uses OpenGL as concrete example Course is NOT just about programming OpenGL a comprehensive course in OpenGL. (Only parts of OpenGL covered) about using packages like Maya, Photoshop Source: http://www.doksinet About This Course Class is concerned with: This course is a lot of work. Requires: How to build/program graphics tools Underlying mathematics Underlying data structures Underlying algorithms Lots of coding in C/C++ Shader programming Lots of math, linear algebra, matrices We shall combine: Programmer’s view: Program OpenGL APIs Under the hood: Learn OpenGL internals (graphics algorithms,
math, implementation) Source: http://www.doksinet Course Text Interactive Computer Graphics: A Top‐Down Approach with Shader‐based OpenGL by Angel and Shreiner (6th edition), 2012 Buy 6th edition . NOT 7th edition!!! Source: http://www.doksinet Syllabus Summary 2 Exams (50%), 4 Projects (50%) Projects: Develop OpenGL/GLSL code on any platform, must port to Zoolab machine May discuss projects but turn in individual projects Class website: http://web.cswpiedu/~emmanuel/courses/cs4731/A14/ Cheating: Immediate ‘F’ in the course Advice: Come to class Read the text Understand concepts before coding Source: http://www.doksinet Elements of 2D Graphics Polylines Text Filled regions Raster images (pictures) Source: http://www.doksinet Elements of 2D Graphics Polyline: connected sequence of straight lines Straight lines connect vertices (corners) blow-up vertex Source: http://www.doksinet
Polyline Attributes Color Thickness Stippling of edges (dash pattern) Source: http://www.doksinet Text Devices have: text mode graphics mode. Big Text Little Text Shadow Text Graphics mode: Text is drawn Text mode: Text not drawn uses character generator Rotated TextOutlined text Text attributes: Font, color, size, spacing, and orientation SMALLCAPS Source: http://www.doksinet Filled Regions Filled region: shape filled with some color or pattern Example: polygons B A C D Source: http://www.doksinet Raster Images Raster image (picture) consists of 2D matrix of small cells (pixels, for “picture elements”), in different colors or grayscale. Middle image: magnified showing pixels (squares) Source: http://www.doksinet Computer Graphics Tools Hardware tools Output devices: Video monitors, printers Input devices: Mouse/trackball, pen/drawing tablet, keyboard Graphics cards/accelerators (GPUs)
Software tools (low level) Operating system Editor Compiler Debugger Graphics Library (OpenGL) Source: http://www.doksinet Graphics Processing Unit (GPU) OpenGL implemented in hardware => FAST!! Programmable: as shaders Located either on PC motherboard (Intel) or Separate graphics card (Nvidia or ATI) GPU on PC motherboard GPU on separate PCI express card Source: http://www.doksinet Computer Graphics Libraries Functions to draw line, circle, image, etc Previously device‐dependent Different OS => different graphics library Tedious! Difficult to port (e.g move program Windows to Linux) Error Prone Now device‐independent libraries APIs: OpenGL, DirectX Working OpenGL program minimal changes to move from Windows to Linux, etc Source: http://www.doksinet OpenGL Basics OpenGL’s function is Rendering (or drawing) Rendering? – Convert geometric/mathematical object descriptions into images
OpenGL can render: 2D and 3D Geometric primitives (lines, dots, etc) Bitmap images (pictures, .bmp, jpg, etc) OpenGL Program OpenGL Source: http://www.doksinet GL Utility Toolkit (GLUT) OpenGL does NOT manage drawing window OpenGL Window system independent Concerned only with drawing (2D, 3D, images, etc) No window management (create, resize, etc), very portable GLUT: Minimal window management Interfaces with different windowing systems Easy porting between windowing systems. Fast prototyping GLUT OpenGL Source: http://www.doksinet GL Utility Toolkit (GLUT) No bells and whistles No sliders No dialog boxes No elaborate menus, etc To add bells and whistles, use system’s API or GLUI: X window system Apple: AGL Microsoft :WGL, etc GLUT (minimal) Slider Dialog box Source: http://www.doksinet OpenGL Basics Low‐level graphics rendering API Maximal portability
Display device independent (Monitor type, etc) Operating system independent (Unix, Windows, etc) Window system independent based (Windows, X, etc) OpenGL programs behave same on different devices, OS Source: http://www.doksinet Simplified OpenGL Pipeline Vertices go in, sequence of steps (vertex processor, clipper, rasterizer, fragment processor) image rendered This class: learn algorithms and order of these steps Vertex Shader Converts 3D to 2D Fragment (Pixel) Shader Source: http://www.doksinet OpenGL Programming Interface Programmer view of OpenGL? Application Programmer Interface (API) Writes OpenGL Application programs. Eg glDrawArrays(GL LINE LOOP, 0, N); glFlush( ); Source: http://www.doksinet Framebuffer Dedicated memory location: Draw in framebuffer => shows up on screen Located either on CPU (software) or GPU (hardware) x logical address y x scan controller geometric position y 0 at (639, 0) 639 0
pixel at address [x,y] frame buffer spot at (x,y) convert pixel 479 value to color display surface y at (639, 479) x Source: http://www.doksinet References Angel and Shreiner, Interactive Computer Graphics (6th edition), Chapter 1 Hill and Kelley, Computer Graphics using OpenGL (3rd edition), Chapter 1 Source: http://www.doksinet Computer Graphics (CS 4731) Lecture 2: Introduction to OpenGL/GLUT (Part 1) Prof Emmanuel Agu Computer Science Dept. Worcester Polytechnic Institute (WPI) Source: http://www.doksinet Recall: OpenGL/GLUT Basics OpenGL’s function – Rendering (2D, 3D drawings or images) OpenGL does not manage drawing window GLUT: minimal window management GLUT OpenGL Source: http://www.doksinet OpenGL/GLUT Installation OpenGL: Specific version (e.g 43)already on your graphics card Just need to check your graphics card, OpenGL version GLUT: software that needs to be installed already installed in zoolab machines GLUT:
install it! OpenGL: already on graphics card Source: http://www.doksinet glInfo: Finding out about your Graphics Card Software tool to find out OpenGL version and extensions your graphics card supports This class? Need graphics card that supports OpenGL 4.3 or later Source: http://www.doksinet OpenGL Extension Wrangler Library (GLEW) OpenGL extensions: allows individual card manufacturers to implement new features Example: If card manufacturer maker implements new cool features after OpenGL version 4.5 released, make available as extension to OpenGL 4.5 GLEW: easy access to OpenGL extensions available on a particular graphics card We install GLEW as well. Access to extensions on zoolab cards Source: http://www.doksinet Windows Installation of GLUT, GLEW Install Visual Studio (e.g 2010) Download freeglut 32‐bit (GLUT implementation) http://freeglut.sourceforgenet/ Download 32‐bit GLEW Check graphics card
http://glew.sourceforgenet/ Install GLUT, GLEW Unzip => .lib, h, dll files E.g download freeglut 281, files: freeglut.dll glut.h freeglut.lib Source: http://www.doksinet Windows Installation of GLUT, GLEW E.g download freeglut 281, files: freeglut.dll glut.h freeglut.lib Check graphics card Install GLUT, GLEW Install files: Put .dll files (for GLUT and GLEW) in C:windowssystem Put .h files in c:Visual Studioinclude directory Put .lib files in c:Visual Studiolib directory Note: If you have multiple versions of Visual Studio, use include directory of the highest Visual Studio version E.g if you have Visual Studio 2008 + Visual Studio 2010 Use include, lib directories of Visual Studio 2010 Source: http://www.doksinet OpenGL Program? Usually has 3 files: Main .cpp file: containing your main function Does initialization, generates/loads geometry to be drawn 2 shader files: Vertex
shader: functions to manipulate (e.g move) vertices Fragment shader: functions to manipulate pixels/fragments (e.g change color) .cpp program (contains main( ) ) Image Source: http://www.doksinet Getting Started: Writing .cpp In Visual studio Create empty project 2. Create blank console application (C program) 3. Include glewh and gluth at top of your program 1. Create VS Solution #include <glew.h> #include <GL/glut.h> GLUT, GLEW includes Note: GL/ is sub‐directory of compiler include/ directory OpenGL drawing functions in gl.h glut.h contains GLUT functions, also includes glh Source: http://www.doksinet Getting Started: More #includes Most OpenGL applications use standard C library (e.g printf), so #include <glew.h> #include <GL/glut.h> #include <stdlib.h> #include <stdio.h> Source: http://www.doksinet OpenGL/GLUT Program Structure Open window (GLUT) Configure display mode, window position/size
Register input callback functions (GLUT) GLUT, GLEW includes Render, resize, input: keyboard, mouse, etc My initialization Set background color, clear color, etc Generate points to be drawn Initialize shader stuff Create GLUT Window Initialize GLEW Register GLUT callbacks glutMainLoop( ) Register callback fns My Inialializations Inialialize GLEW Waits here infinitely till event GLUT main loop Source: http://www.doksinet GLUT: Opening a window GLUT used to create and open window glutInit(&argc, argv); Initializes GLUT glutInitDisplayMode(GLUT SINGLE | GLUT RGB); sets display mode (e.g single framebuffer with RGB colors) glutInitWindowSize(640,480); sets window size (Width x Height) in pixels glutInitPosition(100,150); sets location of upper left corner of window glutCreateWindow(“my first attempt”); open window with title “my first attempt” Then also initialize GLEW
glewInit( ); Source: http://www.doksinet OpenGL Skeleton void main(int argc, char* argv){ // First initialize toolkit, set display mode and create window glutInit(&argc, argv); // initialize toolkit glutInitDisplayMode(GLUT SINGLE | GLUT RGB); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 150); glutCreateWindow(“my first attempt”); glewInit( ); 150 // then register callback functions, // do my initialization // . wait in glutMainLoop for events } 100 my first attempt 480 640 Source: http://www.doksinet Sequential Vs Event‐driven OpenGL programs are event‐driven Sequential program Start at main( ) Perform actions 1, 2, 3. N End Event‐driven program Start at main( ) Initialize Wait in infinite loop Wait till defined event occurs Event occurs => Take defined actions What is World’s most famous event‐driven program? Source: http://www.doksinet OpenGL: Event‐driven Program only
responds to events Do nothing until event occurs Example Events: mouse clicks, keyboard stroke window resize Programmer defines: Events that program should respond to Actions to be taken when event occurs System (Windows): Receives event, maintains event queue Left mouse click Keyboard ‘h’ key takes programmer‐defined actions Source: http://www.doksinet OpenGL: Event‐driven How in OpenGL? Programmer registers callback functions (event handler) Callback function called when event occurs Example: Programmer 1. 2. Declare function myMouse, to be called on mouse click Register it: glutMouseFunc(myMouse); When OS receives mouse click, calls callback function myMouse Mouse click Event myMouse Callback function Source: http://www.doksinet GLUT Callback Functions Register callbacks for all events your program will react to No registered callback = no action Example: if no registered
keyboard callback function, hitting keyboard keys generates NO RESPONSE!! Source: http://www.doksinet GLUT Callback Functions GLUT Callback functions in skeleton glutDisplayFunc(myDisplay): Image to be drawn initially glutReshapeFunc(myReshape): called when window is reshaped glutMouseFunc(myMouse): called when mouse button is pressed glutKeyboardFunc(mykeyboard): called when keyboard is pressed or released glutMainLoop( ): program draws initial picture (by calling myDisplay function once) Enters infinite loop till event Source: http://www.doksinet OpenGL Skeleton void main(int argc, char* argv){ // First initialize toolkit, set display mode and create window glutInit(&argc, argv); // initialize toolkit glutInitDisplayMode(GLUT SINGLE | GLUT RGB); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 150); glutCreateWindow(“my first attempt”); glewInit( ); // now register callback functions glutDisplayFunc(myDisplay); --Next
how to draw in myDisplay glutReshapeFunc(myReshape); glutMouseFunc(myMouse); glutKeyboardFunc(myKeyboard); myInit( ); glutMainLoop( ); } Source: http://www.doksinet Example: Draw in function myDisplay Task: Draw red triangle on white background Rendering steps: 1. 2. 3. 4. 5. Generate triangle corners (3 vertices) Store 3 vertices into an array Create GPU buffer for vertices Move 3 vertices from CPU to GPU buffer Draw 3 points from array on GPU using glDrawArray Source: http://www.doksinet Example: Retained Mode Graphics Rendering steps: 1. 2. 3. 4. 5. 1. Generate triangle corners (3 vertices) Store 3 vertices into an array Create GPU buffer for vertices Move array of 3 vertices from CPU to GPU buffer Draw 3 points from array on GPU using glDrawArray Simplified Execution model: Generate 3 triangle corners 4. Move array of 3 vertices from CPU to GPU buffer 3. Create GPU buffers for vertices 2. Store 3 vertices in array Application Program (on CPU) GPU
5. Draw points using glDrawArrays Rendered vertices Source: http://www.doksinet 1. Generate triangle corners (3 vertices) 2. Store 3 vertices into an array point2 points[3]; // generate 3 triangle vertices + store in array void generateGeometry( void ){ points[0] = point2( -0.5, -05 ); points[1] = point2( 0.0, 05 ); points[2] = point2( 0.5, -05 ); } x y (-0.5, -05) (0.0, 05) (0.5, -05) Source: http://www.doksinet Declare some Types for Points, vectors Useful to declare types point2 for (x,y) locations vec3 for (x,y,z) vector coordinates Put declarations in header file vec.h #include “vec.h” E.g Declares (x, y, z) coordinates of a vector vec3 vector1; Can also do typedefs typedef (x, y) coordinates of a point typedef vec2 point2; Note: You will be given file Angel.h, which includes vech Source: http://www.doksinet OpenGL Skeleton: Where are we? void main(int argc, char* argv){ glutInit(&argc, argv); // initialize toolkit
glutInitDisplayMode(GLUT SINGLE | GLUT RGB); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 150); glutCreateWindow(“my first attempt”); glewInit( ); // now register callback functions glutDisplayFunc(myDisplay); glutReshapeFunc(myReshape); glutMouseFunc(myMouse); glutKeyboardFunc(myKeyboard); glewInit( ); generateGeometry( ); glutMainLoop( ); } // generate 3 triangle vertices + store in array void generateGeometry( void ){ points[0] = point2( -0.5, -05 ); points[1] = point2( 0.0, 05 ); points[2] = point2( 0.5, -05 ); } Source: http://www.doksinet 3. Create GPU Buffer for Vertices Rendering from GPU memory significantly faster. Move data there Fast GPU (off‐screen) memory for data called Vertex Buffer Objects (VBO) Array of VBOs (called Vertex Array Object (VAO)) usually created Example use: vertex positions in VBO 1, color info in VBO 2, etc VBO So, first create the vertex array object VAO GLuint vao; glGenVertexArrays( 1, &vao );
glBindVertexArray( vao ); VBO VBO // create VAO // make VAO active Source: http://www.doksinet 3. Create GPU Buffer for Vertices Next, create a buffer object in two steps 1. Create VBO and give it name (unique ID number) GLuint buffer; glGenBuffers(1, &buffer); // create one buffer object Number of Buffer Objects to return 2. Make created VBO currently active one glBindBuffer(GL ARRAY BUFFER, buffer); Data is array of values Source: http://www.doksinet 4. Move points GPU memory 3. Move points generated earlier to VBO glBufferData(GL ARRAY BUFFER, buffer, sizeof(points), points, GL STATIC DRAW ); //data is array Data to be transferred to GPU memory (generated earlier) GL STATIC DRAW: buffer object data will not be changed. Specified once by application and used many times to draw GL DYNAMIC DRAW: buffer object data will be changed. Specified repeatedly and used many times to draw Source: http://www.doksinet Put it Together: 3. Create GPU Buffer for
Vertices 4. Move points GPU memory void initGPUBuffers( void ) { // Create a vertex array object GLuint vao; glGenVertexArrays( 1, &vao ); glBindVertexArray( vao ); VBO VAO VBO VBO // Create and initialize a buffer object GLuint buffer; glGenBuffers( 1, &buffer ); glBindBuffer( GL ARRAY BUFFER, buffer ); glBufferData( GL ARRAY BUFFER, sizeof(points), points, GL STATIC DRAW ); } Source: http://www.doksinet OpenGL Skeleton: Where are we? void main(int argc, char* argv){ glutInit(&argc, argv); // initialize toolkit glutInitDisplayMode(GLUT SINGLE | GLUT RGB); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 150); glutCreateWindow(“my first attempt”); glewInit( ); // now register callback functions glutDisplayFunc(myDisplay); glutReshapeFunc(myReshape); glutMouseFunc(myMouse); glutKeyboardFunc(myKeyboard); glewInit( ); generateGeometry( ); initGPUBuffers( ); void initGPUBuffers( void ) { // Create a vertex array object GLuint vao; glGenVertexArrays( 1,
&vao ); glBindVertexArray( vao ); // Create and initialize a buffer object GLuint buffer; glGenBuffers( 1, &buffer ); glBindBuffer( GL ARRAY BUFFER, buffer ); glBufferData( GL ARRAY BUFFER, sizeof(points), points, GL STATIC DRAW ); glutMainLoop( ); } } Source: http://www.doksinet 5. Draw points (from VBO) glDrawArrays(GL POINTS, 0, N); Render buffered data as points Starting index Number of points to be rendered Display function using glDrawArrays: void mydisplay(void){ glClear(GL COLOR BUFFER BIT); // clear screen glDrawArrays(GL LINE LOOP, 0, 3); // draw the points glFlush( ); // force rendering to show } Source: http://www.doksinet References Angel and Shreiner, Interactive Computer Graphics, 6th edition, Chapter 2 Hill and Kelley, Computer Graphics using OpenGL, 3rd edition, Chapter 2 Source: http://www.doksinet Computer Graphics (CS 4731) Lecture 3: Introduction to OpenGL/GLUT (Part 2) Prof Emmanuel Agu Computer Science Dept. Worcester
Polytechnic Institute (WPI) Source: http://www.doksinet Recall: OpenGL/GLUT Basics OpenGL: Specific version (e.g 43)already on your graphics card Just need to check your graphics card, OpenGL version GLUT: software that needs to be installed already installed in zoolab machines GLUT: install it! OpenGL: already on graphics card Source: http://www.doksinet Recall: OpenGL Skeleton void main(int argc, char* argv){ // First initialize toolkit, set display mode and create window glutInit(&argc, argv); // initialize toolkit glutInitDisplayMode(GLUT SINGLE | GLUT RGB); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 150); glutCreateWindow(“my first attempt”); glewInit( ); 150 // then register callback functions, // do my initialization // . wait in glutMainLoop for events } 100 my first attempt 480 640 Source: http://www.doksinet Recall: Drawing 3 dots Rendering steps: 1. 2. 3. 4. 5. 1. Generate triangle corners (3 vertices)
Store 3 vertices into an array Create GPU buffer for vertices Move array of 3 vertices from CPU to GPU buffer Draw 3 points from array on GPU using glDrawArray Simplified Execution model: Generate 3 triangle corners 4. Move array of 3 vertices from CPU to GPU buffer 3. Create GPU buffers for vertices 2. Store 3 vertices in array Application Program (on CPU) GPU 5. Draw points using glDrawArrays Rendered vertices Source: http://www.doksinet Recall: OpenGL Skeleton: Where are we? void main(int argc, char* argv){ glutInit(&argc, argv); // initialize toolkit glutInitDisplayMode(GLUT SINGLE | GLUT RGB); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 150); glutCreateWindow(“my first attempt”); glewInit( ); // now register callback functions glutDisplayFunc(myDisplay); glutReshapeFunc(myReshape); glutMouseFunc(myMouse); glutKeyboardFunc(myKeyboard); glewInit( ); generateGeometry( ); glutMainLoop( ); } (-0.5, -05) (0.0, 05) (0.5, -05) // generate 3 triangle
vertices + store in array void generateGeometry( void ){ points[0] = point2( -0.5, -05 ); points[1] = point2( 0.0, 05 ); points[2] = point2( 0.5, -05 ); } Source: http://www.doksinet Recall: OpenGL Skeleton: Where are we? void main(int argc, char* argv){ glutInit(&argc, argv); // initialize toolkit glutInitDisplayMode(GLUT SINGLE | GLUT RGB); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 150); glutCreateWindow(“my first attempt”); glewInit( ); // now register callback functions glutDisplayFunc(myDisplay); glutReshapeFunc(myReshape); glutMouseFunc(myMouse); glutKeyboardFunc(myKeyboard); glewInit( ); generateGeometry( ); initGPUBuffers( ); VAO VBO VBO void initGPUBuffers( void ) { // Create a vertex array object GLuint vao; glGenVertexArrays( 1, &vao ); glBindVertexArray( vao ); // Create and initialize a buffer object GLuint buffer; glGenBuffers( 1, &buffer ); glBindBuffer( GL ARRAY BUFFER, buffer ); glBufferData( GL ARRAY BUFFER, sizeof(points),
points, GL STATIC DRAW ); glutMainLoop( ); } VBO } Source: http://www.doksinet Recall: OpenGL Program? OpenGL program has 3 files: Main .cpp file: generates picture (eg 3 dots) 3 dots need to pass through 2 shader files: Vertex shader: functions to manipulate vertices Fragment shader: functions to manipulate pixels/fragments (e.g change color) How to pass 3 dots from main program to vertex shader? .cpp program (contains main( ) ) Image Source: http://www.doksinet OpenGL Program: Shader Setup OpenGL programs now have 3 parts: Main OpenGL program (.cpp file), vertex shader (eg vshader1glsl), and fragment shader (e.g fshader1glsl) in same Windows directory In main program, need to link names of vertex, fragment shader initShader( ) is homegrown shader initialization function. More later GLuint = program; GLuint program = InitShader( "vshader1.glsl", fshader1glsl"); glUseProgram(program); Main Program Vertex
shader Fragment Shader initShader( ) Homegrown, connects main Program to shader files More on this later!! Source: http://www.doksinet Vertex Attributes Want to make 3 dots (vertices) accessible as variable vPosition in vertex shader First declare vPosition in vertex shader, get its address .cpp program (contains main( ) ) in vec4 vPosition Compiler puts all variables declared in shader into a table Need to find location of vPosition in table of variables Variable Variable 1 Location of vPosition vPosition Variable N GLuint loc = glGetAttribLocation( program, "vPosition" ); Source: http://www.doksinet Vertex Attributes Want to make 3 dots (vertices) accessible as variable vPosition in vertex shader First declare vPosition in vertex shader, get its address .cpp program (contains main( ) ) in vec4 vPosition Get location of vertex attribute vPosition GLuint loc = glGetAttribLocation( program, "vPosition" );
glEnableVertexAttribArray( loc ); glVertexAttribPointer( loc, 2, GL FLOAT, GL FALSE, 0, BUFFER OFFSET(0) ); Enable vertex array attribute at location of vPosition Specify vertex array attribute at location of vPosition Source: http://www.doksinet glVertexAttribPointer Data now in VBO on GPU, but need to specify meta format (using glVertexAttribPointer) Vertices are packed as array of values E.g 3 dots stored in array on VBO Vertices stored in array x y x y x y x y x y -0.5 -0.5 x y dot 1 vertex 1 vertex 2 . 0.0VBO 0.5 0.5 -0.5 y x y x dot 2 dot 3 Padding between Consecutive vertices glVertexAttribPointer( loc, 2, GL FLOAT, GL FALSE, 0,BUFFER OFFSET(0) ); Location of vPosition in table of variables 2 (x,y) floats per vertex Data starts at offset from start of array Data not normalized to 0-1 range Source: http://www.doksinet Put it Together: Shader Set up void shaderSetup( void ) { // Load shaders and use the resulting shader program program
= InitShader( "vshader1.glsl", "fshader1glsl" ); glUseProgram( program ); // Initialize vertex position attribute from vertex shader GLuint loc = glGetAttribLocation( program, "vPosition" ); glEnableVertexAttribArray( loc ); glVertexAttribPointer( loc, 2, GL FLOAT, GL FALSE, 0, BUFFER OFFSET(0) ); // sets white as color used to clear screen glClearColor( 1.0, 10, 10, 10 ); } Source: http://www.doksinet OpenGL Skeleton: Where are we? void main(int argc, char* argv){ glutInit(&argc, argv); // initialize toolkit glutInitDisplayMode(GLUT SINGLE | GLUT RGB); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 150); glutCreateWindow(“my first attempt”); glewInit( ); // now register callback functions glutDisplayFunc(myDisplay); void shaderSetup( void ) glutReshapeFunc(myReshape); { // Load shaders and use the resulting shader program glutMouseFunc(myMouse); program = InitShader( "vshader1.glsl", "fshader1glsl" );
glutKeyboardFunc(myKeyboard); glUseProgram( program ); // Initialize vertex position attribute from vertex shader GLuint loc = glGetAttribLocation( program, "vPosition" ); glEnableVertexAttribArray( loc ); glVertexAttribPointer( loc, 2, GL FLOAT, GL FALSE, 0, BUFFER OFFSET(0) ); glewInit( ); generateGeometry( ); initGPUBuffers( ); void shaderSetup( ); glutMainLoop( ); } // sets white as color used to clear screen glClearColor( 1.0, 10, 10, 10 ); } Source: http://www.doksinet Vertex Shader We write a simple “pass‐through” shader (does nothing) Simply sets output vertex position = input position gl Position is built in variable (already declared) in vec4 vPosition void main( ) { gl Position = vPosition; } output vertex position input vertex position Source: http://www.doksinet Execution Model 1. Vertex data Moved to GPU (glBufferData) GPU Graphics Hardware (not programmable) Application Program (on CPU) Figures out which Pixels on screen Colored
to draw dots Vertex Vertex Shader Vertex Shader Shader 2. glDrawArrays 3. Vertex shader invoked on each vertex on GPU Rendered Vertices Source: http://www.doksinet Fragment Shader We write a simple fragment shader (sets color to red) gl FragColor is built in variable (already declared) void main( ) { gl FragColor = vec(1.0, 00, 00, 10); } Set each drawn fragment color to red Source: http://www.doksinet Execution Model OpenGL Program Application Graphics Hardware (not programmable) Figures out pixels to to be olored to draw 2 dots 1. Fragments corresponding to Rendered vertices Fragment Fragment Shader Fragment Shader Shader 2. Fragment shader invoked on each fragment on GPU Frame Buffer 3.Rendered Fragment Color Source: http://www.doksinet Recall: OpenGL Skeleton void main(int argc, char* argv){ // First initialize toolkit, set display mode and create window glutInit(&argc, argv); // initialize toolkit glutInitDisplayMode(GLUT SINGLE | GLUT RGB);
glutInitWindowSize(640, 480); glutInitWindowPosition(100, 150); glutCreateWindow(“my first attempt”); glewInit( ); // now register callback functions glutDisplayFunc(myDisplay); --Next how to draw in myDisplay glutReshapeFunc(myReshape); glutMouseFunc(myMouse); glutKeyboardFunc(myKeyboard); myInit( ); glutMainLoop( ); } Source: http://www.doksinet Recall: Draw points (from VBO) glDrawArrays(GL POINTS, 0, N); Render buffered data as points Starting index Number of points to be rendered Display function using glDrawArrays: void mydisplay(void){ glClear(GL COLOR BUFFER BIT); // clear screen glDrawArrays(GL LINE LOOP, 0, 3); // draw the points glFlush( ); // force rendering to show } Source: http://www.doksinet Other possible arguments to glDrawArrays instead of GL LINE LOOP? glDrawArrays(GL POINTS, .) glDrawArrays((GL LINES, ) – draws dots – Connect vertex pairs to draw lines Source: http://www.doksinet glDrawArrays( ) Parameters glDrawArrays(GL LINE
STRIP,.) glDrawArrays(GL POLYGON,) – polylines glDrawArrays(GL LINE LOOP) – Close loop of polylines (Like GL LINE STRIP but closed) – convex filled polygon Source: http://www.doksinet glDrawArrays( ) Parameters Triangles: Connect 3 vertices GL TRIANGLES, GL TRIANGLE STRIP, GL TRIANGLE FAN Quad: Connect 4 vertices GL QUADS, GL QUAD STRIP Source: http://www.doksinet Triangulation Generally OpenGL breaks polygons down into triangles which are then rendered. Example d glDrawArrays(GL POLYGON,.) – convex filled polygon c b a Source: http://www.doksinet Previously: Generated 3 Points to be Drawn Stored points in array points[ ], moved to GPU, draw using glDrawArray 0.0, 05 point2 points[NumPoints]; points[0] = point2( -0.5, -05 ); points[1] = point2( 0.0, 05 ); points[2] = point2( 0.5, -05 ); -0.5, -05 0.5, -05 Once drawing steps are set up, can generate more complex sequence of points algorithmically, drawing steps don’t
change Next: example of more algorithm to generate more complex point sequences Source: http://www.doksinet Sierpinski Gasket Program Any sequence of points put into array points[ ] will be drawn Can generate interesting sequence of points Put in array points[ ], draw!! Sierpinski Gasket: Popular fractal Source: http://www.doksinet Sierpinski Gasket Start with initial triangle with corners (x1, y1, 0), (x2, y2, 0) and (x3, y3, 0) 1. 2. 3. 4. 5. 6. Pick initial point p = (x, y, 0) at random inside a triangle Select on of 3 vertices at random Find q, halfway between p and randomly selected vertex Draw dot at q Replace p with q Return to step 2 Source: http://www.doksinet Actual Sierpinski Code #include “vec.h” // include point types and operations #include <stdlib.h> // includes random number generator void Sierpinksi( ) { const int NumPoints = 5000; vec2 points[NumPoints]; // Specifiy the vertices for a triangle vec2 vertices[3] = { vec2( -1.0,
-10 ), vec2( 00, 10 ), vec2( 10, -10 ) }; Source: http://www.doksinet Actual Sierpinski Code // An arbitrary initial point inside the triangle points[0] = point2(0.25, 050); // compute and store N-1 new points for ( int i = 1; i < NumPoints; ++i ) { int j = rand() % 3; // pick a vertex at random // Compute the point halfway between the selected vertex // and the previous point points[i] = ( points[i - 1] + vertices[j] ) / 2.0; } Source: http://www.doksinet References Angel and Shreiner, Interactive Computer Graphics, 6th edition, Chapter 2 Hill and Kelley, Computer Graphics using OpenGL, 3rd edition, Chapter 2 Source: http://www.doksinet Computer Graphics (4731) Lecture 4: 2D Graphics Systems (Drawing Polylines, tiling, & Aspect Ratio) Prof Emmanuel Agu Computer Science Dept. Worcester Polytechnic Institute (WPI) Source: http://www.doksinet Screen Coordinate System •Screen: 2D coordinate system (WxH) •2D Regular Cartesian Grid •Origin (0,0): lower
left corner (OpenGL convention) y •Horizontal axis – x •Vertical axis – y •Pixel positions: grid intersections x (0,0) (2,2) Source: http://www.doksinet Screen Coordinate System (0,0) is lower left corner of OpenGL Window. NOT lower left corner of entire desktop OpenGL’s (0,0) Source: http://www.doksinet Defining a Viewport Can draw to any rectangle (sub‐area of screen) Viewport: Area of screen we want to draw to To define viewport glViewport(left, bottom, width, height) or glViewport(V.L, VB, VR – VL, VT – VB) or glViewport(180, 260, (410 – 180), (480 – 260) ) V.T 480 V.B 260 V.L V.R 180 410 Source: http://www.doksinet Recall: OpenGL Skeleton void main(int argc, char* argv){ // First initialize toolkit, set display mode and create window glutInit(&argc, argv); // initialize toolkit glutInitDisplayMode(GLUT SINGLE | GLUT RGB); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 150); glutCreateWindow(“my first
attempt”); glewInit( ); // now register callback functions glutDisplayFunc(myDisplay); glutReshapeFunc(myReshape); glutMouseFunc(myMouse); glutKeyboardFunc(myKeyboard); myInit( ); glutMainLoop( ); } void mydisplay(void){ glClear(GL COLOR BUFFER BIT); glDrawArrays(GL LINE LOOP, 0, 3); glFlush( ); } Note: default viewport is entire created window Source: http://www.doksinet Example: Changing Viewport How to change viewport to: Bottom left corner at (100,80) Width changes to 700, height changes to 300?? void main(int argc, char* argv){ // First initialize toolkit, set display mode and create window glutInit(&argc, argv); // initialize toolkit glutInitDisplayMode(GLUT SINGLE | GLUT RGB); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 150); glutCreateWindow(“my first attempt”); glewInit( ); // now register callback functions glutDisplayFunc(myDisplay); glutReshapeFunc(myReshape); glutMouseFunc(myMouse); glutKeyboardFunc(myKeyboard); myInit( ); glutMainLoop( ); }
void mydisplay(void){ glClear(GL COLOR BUFFER BIT); glViewport(100,80,700,300); glDrawArrays(GL LINE LOOP, 0, 3); glFlush( ); } Note: Set desired viewport, then draw Source: http://www.doksinet Tiling: Changing Viewport in a Loop Problem: Want to tile Triangle file on screen Solution: change viewport in loop, draw tiles One world triangle Multiple tiled viewports Source: http://www.doksinet Tiling Triangle Code Snippet Set viewport, draw into tile in a loop Code snippet: float w, h; w = width / 6; h = height / 6; for (int k=0; k<6; k++) { for (int m=0; m<6; m++) { glViewport(k * w, m h, w, h); glDrawArrays(GL LINE LOOP, 0, NumPoints); } } Source: http://www.doksinet Example: Tiling, Changing Viewport void main(int argc, char* argv){ // First initialize toolkit, set display mode and create window glutInit(&argc, argv); // initialize toolkit glutInitDisplayMode(GLUT SINGLE | GLUT RGB); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 150);
glutCreateWindow(“my first attempt”); void mydisplay(void){ glewInit( ); glClear(GL COLOR BUFFER BIT); float w, h; // now register callback functions glutDisplayFunc(myDisplay); glutReshapeFunc(myReshape); glutMouseFunc(myMouse); glutKeyboardFunc(myKeyboard); w = width / 6; h = height / 6; for (int k=0; k<6; k++) { for (int m=0; m<6; m++) { glViewport(k * w, m h, w, h); glDrawArrays(GL LINE LOOP, 0, NumPoints); } } glFlush( ); myInit( ); glutMainLoop( ); } } Source: http://www.doksinet World Coordinate System • Problems with drawing in screen coordinates: • (x,y) dimensions in pixels: one mapping, inflexible • Not application specific, difficult to use • World coordinate: application‐specific • E.g: Same screen area Change input drawing (x,y) range Change World window (mapping) V.T V.B V.L 100 pixels = 30 miles V.R V.T V.B V.L V.R 100 pixels = 0.25 miles Source: http://www.doksinet Using Window Coordinates Would like to: Specify set
source boundaries (extents) of original drawing in world coordinates (miles, meters, etc) Display target region in screen coordinates (pixels) Programming steps: Define world window (original drawing extents) 2. Define viewport (drawing extents on screen) 3. Map drawings within window to viewport 1. Mapping called Window‐to‐viewport mapping! Source: http://www.doksinet World Coordinate System • World Window: region of source drawing to be rendered • Rectangle specified by world window is drawn to screen • Defined by (left, right, bottom, top) or (W.L, WR, WB, WT) W.T W.B W.L W.R Source: http://www.doksinet Defining World Window mat4 ortho = Ortho2D(left, right, bottom, top) Or mat4 ortho = Ortho2D(W.L, WR, WB, WT) Ortho2D generates 4x4 matrix that scales input drawing Note: Ortho2D in header file mat.h W.T W.B W.L W.R Source: http://www.doksinet Drawing After setting world window (using ortho2D) and viewport (using
glviewport), Draw as usual with glDrawArrays Source: http://www.doksinet Apply ortho( ) matrix in Vertex Shader One more detail: Need to pass ortho matrix to shader Multiply each vertex by ortho matrix to scale input drawing Need to connect ortho matrix to proj variable in shader mat4 ortho = Ortho2D( W.L, WR, WB, WT ); Call Ortho2D in Main .cpp file uniform mat4 Proj; in vec4 vPosition; void main( ){ gl Position = Proj * vPosition; } In vertex shader, multiply each vertex with proj matrix Source: http://www.doksinet Apply ortho( ) matrix in Vertex Shader 1. Include mat.h from book website (ortho2D declared in math ) #include "mat.h" 2. Connect ortho matrix to proj variable in shader mat4 ortho = Ortho2D( W.L, WR, WB, WT ); Call Ortho2D in Main .cpp file ProjLoc = glGetUniformLocation( program, "Proj" ); glUniformMatrix4fv( ProjLoc, 1, GL TRUE, ortho ); uniform mat4 Proj; in vec4 vPosition; void main( ){ gl Position = Proj *
vPosition; } In shader, multiply each vertex with proj matrix Source: http://www.doksinet Drawing Polyline Files May read in list of vertices defining a drawing Problem: want to draw single dino.dat on screen Note: size of input drawing may vary 440 640 Source: http://www.doksinet Drawing Polyline Files Problem: want to draw single dino.dat on screen Code snippet: // set world window (left, right, bottom, top) ortho = Ortho2D(0, 640.0, 0, 4400); // now set viewport (left, bottom, width, height) glViewport(0, 0, 64, 44); // Draw polyline fine drawPolylineFile(dino.dat); 440 Question: What if I wanted to draw the bottom quadrant of polyline? 640 Source: http://www.doksinet Tiling using W‐to‐V Mapping Problem: Want to tile polyline file on screen Solution: W‐to‐V in loop, adjacent tiled viewports One world Window Multiple tiled viewports Source: http://www.doksinet Tiling Polyline Files Problem: want to tile dino.dat in 5x5 across
screen Code snippet: // set world window ortho = Ortho2D(0, 640.0, 0, 4400); for(int i=0;i < 5;i++) { for(int j = 0;j < 5; j++) { // . now set viewport in a loop glViewport(i * 64, j 44; 64, 44); drawPolylineFile(dino.dat); } } Source: http://www.doksinet Maintaining Aspect Ratios Aspect ratio R = Width/Height What if window and viewport have different aspect ratios? Two possible cases: Case a: viewport too wide Case b: viewport too tall Source: http://www.doksinet What if Window and Viewport have different Aspect Ratios? R = window aspect ratio, W x H = viewport dimensions Two possible cases: Case A (R > W/H): map window to tall viewport? Viewport Aspect ratio R H Window W/R ortho = Ortho2D(left, right, bottom, top ); R = (right – left)/(top – bottom); If(R > W/H) glViewport(0, 0, W, W/R); W Source: http://www.doksinet What if Window and Viewport have different Aspect Ratios? Case B (R < W/H): map window to wide
viewport? W Aspect ratio R Aspect ratio R HR Window HR Viewport ortho = Ortho2D(left, right, bottom, top ); R = (right – left)/(top – bottom); If(R < W/H) glViewport(0, 0, H*R, H); H Source: http://www.doksinet reshape( ) function that maintains aspect ratio // Ortho2D(left, right, bottom, top )is done previously, // probably in your draw function // function assumes variables left, right, top and bottom // are declared and updated globally void myReshape(double W, double H ){ R = (right – left)/(top – bottom); if(R > W/H) glViewport(0, 0, W, W/R); else if(R < W/H) glViewport(0, 0, H*R, H); else glViewport(0, 0, W, H); // equal aspect ratios } Source: http://www.doksinet References Angel and Shreiner, Interactive Computer Graphics, 6th edition, Chapter 9 Hill and Kelley, Computer Graphics using OpenGL, 3rd edition, Appendix 4 Source: http://www.doksinet Computer Graphics 4731 Lecture 5: Fractals Prof Emmanuel Agu Computer Science Dept.
Worcester Polytechnic Institute (WPI) Source: http://www.doksinet What are Fractals? Mathematical expressions to generate pretty pictures Evaluate math functions to create drawings approach infinity ‐> converge to image Utilizes recursion on computers Popularized by Benoit Mandelbrot (Yale university) Dimensional: Line is 1‐dimensional Plane is 2‐dimensional Defined in terms of self‐similarity Source: http://www.doksinet Fractals: Self‐similarity See similar sub‐images within image as we zoom in Example: surface roughness or profile same as we zoom in Types: Exactly self‐similar Statistically self‐similar Source: http://www.doksinet Examples of Fractals Clouds Grass Fire Modeling mountains (terrain) Coastline Branches of a tree Surface of a sponge Cracks in the pavement Designing antennae (www.fractennacom) Source: http://www.doksinet Example: Mandelbrot Set
Source: http://www.doksinet Example: Mandelbrot Set Source: http://www.doksinet Example: Fractal Terrain Courtesy: Mountain 3D Fractal Terrain software Source: http://www.doksinet Example: Fractal Terrain Source: http://www.doksinet Example: Fractal Art Courtesy: Internet Fractal Art Contest Source: http://www.doksinet Application: Fractal Art Courtesy: Internet Fractal Art Contest Source: http://www.doksinet Recall: Sierpinski Gasket Program Popular fractal Source: http://www.doksinet Koch Curves Discovered in 1904 by Helge von Koch Start with straight line of length 1 Recursively: Divide line into 3 equal parts Replace middle section with triangular bump, sides of length 1/3 New length = 4/3 Source: http://www.doksinet Koch Curves Can form Koch snowflake by joining three Koch curves S3, S4, S5, Source: http://www.doksinet Koch Snowflakes Pseudocode, to draw Kn: If (n equals 0) draw straight line Else{ Draw Kn-1 Turn left 60°
Draw Kn-1 Turn right 120° Draw Kn-1 Turn left 60° } Draw Kn-1 Source: http://www.doksinet L‐Systems: Lindenmayer Systems Express complex curves as simple set of string‐production rules Example rules: ‘F’: go forward a distance 1 in current direction ‘+’: turn right through angle A degrees ‘‐’: turn left through angle A degrees Using these rules, can express koch curve as: “F‐F++F‐F” Angle A = 60 degrees Source: http://www.doksinet L‐Systems: Koch Curves Rule for Koch curves is F ‐> F‐F++F‐F Means each iteration replaces every ‘F’ occurrence with “F‐F++F‐F” So, if initial string (called the atom) is ‘F’, then S1 =“F‐F++F‐F” S2 =“F‐F++F‐F‐ F‐F++F‐F++ F‐F++F‐F‐ F‐F++F‐F” S3 = . Gets very large quickly Source: http://www.doksinet Hilbert Curve Discovered by German Scientist, David Hilbert in late 1900s Space filling curve Drawn
by connecting centers of 4 sub‐squares, make up larger square. Iteration 0: 3 segments connect 4 centers in upside‐down U Iteration 0 Source: http://www.doksinet Hilbert Curve: Iteration 1 Each of 4 squares divided into 4 more squares U shape shrunk to half its original size, copied into 4 sectors In top left, simply copied, top right: it's flipped vertically In the bottom left, rotated 90 degrees clockwise, Bottom right, rotated 90 degrees counter‐clockwise. 4 pieces connected with 3 segments, each of which is same size as the shrunken pieces of the U shape (in red) Source: http://www.doksinet Hilbert Curve: Iteration 2 Each of the 16 squares from iteration 1 divided into 4 squares Shape from iteration 1 shrunk and copied. 3 connecting segments (shown in red) are added to complete the curve. Implementation? Recursion is your friend!! Source: http://www.doksinet Gingerbread Man Each new point q is formed from
previous point p using the equation For 640 x 480 display area, use M = 40 L = 3 A good starting point is (115, 121) Source: http://www.doksinet Iterated Function Systems (IFS) Recursively call a function Does result converge to an image? What image? IFS’s converge to an image Examples: The Fern The Mandelbrot set Source: http://www.doksinet The Fern Use either f1, f2, f3 or f4 with probabilities .01, 07,07,85 to generate next point Function f1 (previous point) Start at initial point (0,0). Draw dot at (0,0) .01 .07 Function f2 (previous point) .07 (0,0) Function f3 (previous point) .85 Function f4 (previous point) {Ref: Peitgen: Science of Fractals, p.221 ff} {Barnsley & Sloan, "A Better way to Compress Images" BYTE, Jan 1988, p.215} Source: http://www.doksinet The Fern Each new point (new.x,newy) is formed from the prior point (oldx,oldy) using the rule: new.x := a[index] * old.x + c[index] * old.y + tx[index]; new.y
:= b[index] * old.x + d[index] * old.y + ty[index]; Function f1 .01 a[1]:= 0.0; b[1] := 00; c[1] := 00; d[1] := 016; tx[1] := 0.0; ty[1] := 00; (ie values for function f1) a[2]:= 0.2; b[2] := 023; c[2] :=‐026; d[2] := 022; tx[2] := 0.0; ty[2] := 16; (values for function f2) a[3]:= ‐0.15; b[3] := 026; c[3] := 028; d[3] := 024; tx[3] := 0.0; ty[3] := 044; (values for function f3) a[4]:= 0.85; b[4] := ‐004; c[4] := 004; d[4] := 085; tx[4] := 0.0; ty[4] := 16; (values for function f4) .07 Function f2 .07 (0,0) Function f3 .85 Function f4 Source: http://www.doksinet Mandelbrot Set Based on iteration theory Function of interest: f ( z ) (s) 2 c Sequence of values (or orbit): d1 ( s ) 2 c d 2 (( s ) 2 c) 2 c d 3 ((( s ) 2 c) 2 c) 2 c d 4 ((((s ) 2 c) 2 c) 2 c) 2 c Source: http://www.doksinet Mandelbrot Set Orbit depends on s and c Basic question,: For given s and c, does function
stay finite? (within Mandelbrot set) explode to infinity? (outside Mandelbrot set) Definition: if |d| < 1, orbit is finite else inifinite Examples orbits: s = 0, c = ‐1, orbit = 0,‐1,0,‐1,0,‐1,0,‐1,.finite s = 0, c = 1, orbit = 0,1,2,5,26,677 explodes Source: http://www.doksinet Mandelbrot Set Mandelbrot set: use complex numbers for c and s Always set s = 0 Choose c as a complex number For example: s = 0, c = 0.2 + 05i Hence, orbit: 0, c, c2+ c, (c2+ c)2 + c, Definition: Mandelbrot set includes all finite orbit c Source: http://www.doksinet Mandelbrot Set Some complex number math: i * i 1 Example: Im Argand diagram 2i * 3i 6 Re Modulus of a complex number, z = ai + b: z a2 b2 Squaring a complex number: ( x yi) 2 ( x 2 y 2 ) (2 xy )i Source: http://www.doksinet Mandelbrot Set Examples: Calculate first 3 terms with s=2, c=‐1, terms are
22 1 3 32 1 8 82 1 63 with s = 0, c = ‐2+i 0 (2 i ) 2 i (2 i ) 2 (2 i ) 1 3i 1 3i 2 (2 i) 10 5i ( x yi ) 2 ( x 2 y 2 ) (2 xy )i Source: http://www.doksinet Mandelbrot Set Fixed points: Some complex numbers converge to certain values after x iterations. Example: s = 0, c = ‐0.2 + 05i converges to –0249227 + 0.333677i after 80 iterations Experiment: square –0.249227 + 0333677i and add ‐0.2 + 05i Mandelbrot set depends on the fact the convergence of certain complex numbers Source: http://www.doksinet Mandelbrot Set Routine Math theory says calculate terms to infinity Cannot iterate forever: our program will hang! Instead iterate 100 times Math theorem: if no term has exceeded 2 after 100 iterations, never will! Routine returns: 100, if modulus doesn’t exceed 2 after 100 iterations Number of
times iterated before modulus exceeds 2, or s, c Mandelbrot function Number < 100 ( first term > 2) Number = 100 (did not explode) Source: http://www.doksinet Mandelbrot dwell( ) function ( x yi ) 2 ( x 2 y 2 ) (2 xy )i ( x yi ) 2 (c X cY i ) [( x 2 y 2 ) c X ] (2 xy cY )i int dwell(double cx, double cy) { // return true dwell or Num, whichever is smaller #define Num 100 // increase this for better pics double tmp, dx = cx, dy = cy, fsq = cx*cx + cycy; for(int count = 0;count <= Num && fsq <= 4; count++) { tmp = dx; // save old real part [( x 2 y 2 ) c X ] dx = dx*dx – dydy + cx; // new real part dy = 2.0 * tmp dy + cy; // new imag. Part (2 xy cY )i fsq = dx*dx + dydy; } return count; // number of iterations used } Source: http://www.doksinet Mandelbrot Set Map real part to x‐axis Map imaginary part to y‐axis Decide range of complex numbers to investigate. Eg: X in
range [‐2.25: 075], Y in range [‐15: 15] Range of complex Numbers ( c ) Representation of -1.5 + i (-1.5, 1) X in range [-2.25: 075], Y in range [-1.5: 15] Call ortho2D to set range of values to explore Source: http://www.doksinet Mandelbrot Set Set world window (ortho2D) (range of complex numbers to investigate) X in range [‐2.25: 075], Y in range [‐15: 15] Set viewport (glviewport). Eg: ortho2D Viewport = [V.L, VR, VB, VT]= [60,380,80,240] glViewport Source: http://www.doksinet Mandelbrot Set So, for each pixel: For each point ( c ) in world window call your dwell( ) function Assign color <Red,Green,Blue> based on dwell( ) return value Choice of color determines how pretty Color assignment: Basic: In set (i.e dwell( ) = 100), color = black, else color = white Discrete: Ranges of return values map to same color E.g 0 – 20 iterations = color 1 20 – 40 iterations = color 2, etc. Continuous: Use
a function Source: http://www.doksinet FREE SOFTWARE Free fractal generating software Fractint FracZoom Astro Fractals Fractal Studio 3DFract Source: http://www.doksinet References Angel and Shreiner, Interactive Computer Graphics, 6th edition, Chapter 9 Hill and Kelley, Computer Graphics using OpenGL, 3rd edition, Appendix 4 Source: http://www.doksinet Adding Interaction So far, OpenGL programs just render images Can add user interaction Examples: User hits ‘h’ on keyboard ‐> Program draws house User clicks mouse left button ‐> Program draws table Source: http://www.doksinet Types of Input Devices String: produces string of characters e.g keyboard Locator: User points to position on display. Eg mouse Source: http://www.doksinet Types of Input Devices Valuator: generates number between 0 and 1.0 (proportional to how much it is turned) Pick: User selects location on screen (e.g
touch screen in restaurant, ATM) Source: http://www.doksinet GLUT: How keyboard Interaction Works Example: User hits ‘h’ on keyboard ‐> Program draws house 1. User hits ‘h’ key Keyboard handler Function ‘h’ key OS Programmer needs to write keyboard handler function Source: http://www.doksinet Using Keyboard Callback for Interaction void main(int argc, char* argv){ // First initialize toolkit, set display mode and create window glutInit(&argc, argv); // initialize toolkit glutInitDisplayMode(GLUT SINGLE | GLUT RGB); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 150); x,y location ASCII character glutCreateWindow(“my first attempt”); of mouse of pressed key glewInit( ); 2. Implement keyboard function // now register callback functions void myKeyboard(char key, int x, int y ) { // put keyboard stuff here glutDisplayFunc(myDisplay); . switch(key){ // check which key glutReshapeFunc(myReshape); case ‘f’: glutMouseFunc(myMouse); // do
stuff break; glutKeyboardFunc(myKeyboard); case ‘k’: // do other stuff break; myInit( ); glutMainLoop( ); } 1. Register keyboard Function } } Note: Backspace, delete, escape keys checked using their ASCII codes Source: http://www.doksinet Special Keys: Function, Arrow, etc glutSpecialFunc (specialKeyFcn); Void specialKeyFcn (Glint specialKey, GLint, xMouse, Glint yMouse) Example: if (specialKey == GLUT KEY F1)// F1 key pressed GLUT KEY F1, GLUT KEY F12, . for function keys GLUT KEY UP, GLUT KEY RIGHT, . for arrow keys keys GLUT KEY PAGE DOWN, GLUT KEY HOME, . for page up, home keys Complete list of special keys designated in glut.h Source: http://www.doksinet GLUT: How Mouse Interaction Works Example: User clicks on (x,y) location in drawing window ‐> Program draws a line 1. User clicks on (x,y) location Mouse handler Function OS Programmer needs to write keyboard handler function Source: http://www.doksinet Using Mouse Callback for
Interaction void main(int argc, char* argv){ // First initialize toolkit, set display mode and create window glutInit(&argc, argv); // initialize toolkit glutInitDisplayMode(GLUT SINGLE | GLUT RGB); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 150); glutCreateWindow(“my first attempt”); glewInit( ); 2. Implement mouse function // now register callback functions glutDisplayFunc(myDisplay); glutReshapeFunc(myReshape); glutMouseFunc(myMouse); glutKeyboardFunc(myKeyboard); myInit( ); glutMainLoop( ); } 1. Register keyboard Function void myMouse(int button, int state, int x, int y) { // put mouse stuff here } Source: http://www.doksinet Mouse Interaction Declare prototype Register callbacks: GLUT LEFT BUTTON, GLUT MIDDLE BUTTON, GLUT RIGHT BUTTON State returned values: glutMouseFunc(myMouse): mouse button pressed glutMotionFunc(myMovedMouse): mouse moves with button pressed glutPassiveMotionFunc(myMovedMouse): mouse
moves with no buttons pressed Button returned values: myMouse(int button, int state, int x, int y) myMovedMouse GLUT UP, GLUT DOWN GLUT (0,0) X,Y returned values: x,y coordinates of mouse location Convert GLUT (0,0) to GLUT (0,0)? How? OpenGL (0,0) Source: http://www.doksinet Mouse Interaction Example Example: draw (or select ) rectangle on screen Each mouse click generates separate events Store click points in global or static variable in mouse function void myMouse(int button, int state, int x, int y) { static GLintPoint corner[2]; static int numCorners = 0; // initial value is 0 if(button == GLUT LEFT BUTTON && state == GLUT DOWN) { corner[numCorners].x = x; corner[numCorners].y = screenHeight – y; //flip y coord numCorners++; Screenheight is height of drawing window Source: http://www.doksinet Mouse Interaction Example (continued) Corner[1] 4 3 if(numCorners == 2) 2 Corner[0] 1 { // draw rectangle or do whatever you planned to
do Point3 points[4] = corner[0].x, corner[0]y, //1 corner[1].x, corner[0]y, //2 corner[1].x, corner[1]y, //3 corner[0].x, corner[1]y); //4 glDrawArrays(GL QUADS, 0, 4); numCorners == 0; } else if(button == GLUT RIGHT BUTTON && state == GLUT DOWN) glClear(GL COLOR BUFFER BIT); // clear the window glFlush( ); } Source: http://www.doksinet Menus Adding menu that pops up on mouse click 1. Create menu using glutCreateMenu(myMenu); 2. Use glutAddMenuEntry adds entries to menu 3. Attach menu to mouse button (left, right, middle) using glutAttachMenu Source: http://www.doksinet Menus Example: Shows on menu Checked in mymenu glutCreateMenu(myMenu); glutAddMenuEntry(“Clear Screen”, 1); glutAddMenuEntry(“Exit”, 2); glutAttachMenu(GLUT RIGHT BUTTON); . void mymenu(int value){ if(value == 1){ glClear(GL COLOR BUFFER BIT); glFlush( ); } if (value == 2) exit(0); } Clear Screen 1 Exit 2 Source: http://www.doksinet GLUT Interaction using other input
devices Tablet functions (mouse cursor must be in display window) glutTabletButton (tabletFcn); . void tabletFcn(Glint tabletButton, Glint action, Glint xTablet, Glint yTablet) Spaceball functions Dial functions Picking functions: use your finger Menu functions: minimal pop‐up windows within your drawing window Reference: Hearn and Baker, 3rd edition (section 20‐6) Source: http://www.doksinet Computer Graphics (CS 4731) Lecture 6: Shader Setup & GLSL Introduction Prof Emmanuel Agu Computer Science Dept. Worcester Polytechnic Institute (WPI) Source: http://www.doksinet OpenGL function format function name Number of arguments glUniform3f(x,y,z) belongs to GL library x,y,z are floats glUniform3fv(p) Argument is array of values p is a pointer to array Source: http://www.doksinet Lack of Object Orientation OpenGL is not object oriented Multiple versions for each command glUniform3f glUniform2i glUniform3dv Source:
http://www.doksinet OpenGL Data Types C++ OpenGL Signed char GLByte Short GLShort Int GLInt Float GLFloat Double GLDouble Unsigned char GLubyte Unsigned short GLushort Unsigned int GLuint Example: Integer is 32‐bits on 32‐bit machine but 64‐bits on a 64‐bit machine Source: http://www.doksinet Recall: Single Buffering If display mode set to single framebuffers Any drawing into framebuffer is seen by user. How? glutInitDisplayMode(GLUT SINGLE | GLUT RGB); Single buffering with RGB colors Drawing may not be drawn to screen until call to glFlush( ) void mydisplay(void){ glClear(GL COLOR BUFFER BIT); // clear screen glDrawArrays(GL POINTS, 0, N); glFlush( ); Drawing sent to screen } Single Frame buffer Source: http://www.doksinet Double Buffering Set display mode to double buffering (create front and back framebuffers) glutInitDisplayMode(GLUT DOUBLE | GLUT RGB); Double buffering with RGB colors Front buffer
displayed on screen, back buffers not displayed Drawing into back buffers (not displayed) until swapped in using glutSwapBuffers( ) void mydisplay(void){ glClear(GL COLOR BUFFER BIT); // clear screen glDrawArrays(GL POINTS, 0, N); Back buffer drawing swapped glutSwapBuffers( ); in, becomes visible here } Back Front Double Frame buffer Source: http://www.doksinet Recall: OpenGL Skeleton void main(int argc, char* argv){ glutInit(&argc, argv); // initialize toolkit glutInitDisplayMode(GLUT SINGLE | GLUT RGB); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 150); glutCreateWindow(“my first attempt”); glewInit( ); // now register callback functions glutDisplayFunc(myDisplay); void shaderSetup( void ) glutReshapeFunc(myReshape); { // Load shaders and use the resulting shader program glutMouseFunc(myMouse); program = InitShader( "vshader1.glsl", "fshader1glsl" ); glutKeyboardFunc(myKeyboard); glUseProgram( program ); // Initialize vertex position
attribute from vertex shader GLuint loc = glGetAttribLocation( program, "vPosition" ); glEnableVertexAttribArray( loc ); glVertexAttribPointer( loc, 2, GL FLOAT, GL FALSE, 0, BUFFER OFFSET(0) ); glewInit( ); generateGeometry( ); initGPUBuffers( ); void shaderSetup( ); glutMainLoop( ); } // sets white as color used to clear screen glClearColor( 1.0, 10, 10, 10 ); } Source: http://www.doksinet Recall: OpenGL Program: Shader Setup initShader( ): our homegrown shader initialization Used in main program, connects and link vertex, fragment shaders Shader sources read in, compiled and linked Gluint = program; GLuint program = InitShader( "vshader1.glsl", "fshader1glsl" ); glUseProgram(program); example.cpp What’s inside initShader?? Next! Main Program Vertex shader Fragment Shader vshader1.glsl fshader1.glsl Source: http://www.doksinet Coupling Shaders to Application (initShader function) Create a program object Read shaders Add +
Compile shaders Link program (everything together) Link variables in application with variables in shaders 1. 2. 3. 4. 5. Vertex attributes Uniform variables Source: http://www.doksinet Step 1. Create Program Object Container for shaders Can contain multiple shaders, other GLSL functions GLuint myProgObj; myProgObj = glCreateProgram(); Main Program Create container called Program Object Source: http://www.doksinet Step 2: Read a Shader Shaders compiled and added to program object example.cpp Passed in as string Main Program Passed in as string Vertex shader Fragment Shader vshader1.glsl Fshader1.glsl Shader file code passed in as null‐terminated string using the function glShaderSource Shaders in files (vshader.glsl, fshaderglsl), write function readShaderSource to convert shader file to string Shader file name (e.g vshaderglsl) readShaderSource String of entire shader code Source: http://www.doksinet Shader Reader Code? #include
<stdio.h> static char* readShaderSource(const char shaderFile) { FILE* fp = fopen(shaderFile, "r"); if ( fp == NULL ) { return NULL; } fseek(fp, 0L, SEEK END); long size = ftell(fp); fseek(fp, 0L, SEEK SET); char* buf = new char[size + 1]; fread(buf, 1, size, fp); buf[size] = '