• Keine Ergebnisse gefunden

Einf ¨uhrung Computergraphik (SS 2021)

N/A
N/A
Protected

Academic year: 2021

Aktie "Einf ¨uhrung Computergraphik (SS 2021)"

Copied!
379
0
0

Wird geladen.... (Jetzt Volltext ansehen)

Volltext

(1)

Einf ¨uhrung Computergraphik (SS 2021)

Martin Held

FB Computerwissenschaften Universit ¨at Salzburg A-5020 Salzburg, Austria

held@cs.sbg.ac.at

25. Juni 2021

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

(2)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Personalia

Instructor: M. Held.

Email: held@cs.sbg.ac.at

Base-URL: https://www.cosy.sbg.ac.at/~held.

Office: Universit ¨at Salzburg, Computerwissenschaften, Rm. 1.20, Jakob-Haringer Str. 2, 5020 Salzburg-Itzling.

Phone number (office): (0662) 8044-6304.

Phone number (secr.): (0662) 8044-6328.

(3)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Formalia

URL of course: Base-URL/teaching/einfuehrung graphik/cg.html. Lecture times (VO): Friday 1130–1300.

Lecture times (PS): Friday 1030–1115. Venue: Online via eduMEET:

https://edumeet.geant.org/held_sbg_lectures. I recommend to use Google’s “Chrome” browser.

c

(4)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Electronic Slides and Online Material

In addition to these slides, you are encouraged to consult the WWW home-page of this lecture:

https://www.cosy.sbg.ac.at/~held/teaching/einfuehrung_graphik/cg.html.

In particular, this WWW page contains links to online manuals, slides, and code.

(5)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

A Few Words of Warning

I hope that these slides will serve as a practice-minded introduction to various aspects of computer graphics. I would like to warn you explicitly not to regard these slides as the sole source of information on the topics of my course. It may and will happen that I’ll use the lecture for talking about subtle details that need not be covered in these slides! That is, by making these slides available to you I do not intend to encourage you to attend the lecture on an irregular basis.

c

(6)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Acknowledgments

Several students contributed to the genesis of these slides, by assembling reports on graphics projects, producing electronic transcripts of my own lectures, and by writing LATEX code and generating computer-based figures:

Richard Bauer, Stephan Czermak, Gerd Dauenhauer, Mohamed Elkattahf, Christian Gasperi, Martin Hargassner, Claudia Horner, Christian Koidl, Florian Krisch, Claudio Landerer, Lothar Mausz, Kathrin Meisl, Oskar Schobesberger, Roland Schorn, Rolf Sint, Alex Stumpfl, Oliver Suter, Florian Treml, Christian Z ¨odl, and Gerhard Zwingenberger; Matthias Ausweger, G ¨unther Gschwendtner, Herwig H ¨ofle, Balthasar Laireiter, Bernhard Salzlechner, and Gerald Wiesbauer; and Markus Amersdorfer, Martin Angerer, Matthias Ausweger, Richard Bauer, Fritz Bischof, Ronald Blaschke, Michael Brachtl, Markus Chalupar, Walter Chalupar, Werner Dietl, Johann Edtmayr, Gregor Haberl, Dorly Har- ringer, Sandor Herramhof, Martin Hinterseer, Hermann Huber, Gyasi Johnson, Wolfgang Klier, August Mayer, Albert Meixner, Christof Meer- wald, Michael Neubacher, Michael Noisternig, Christoph Oberauer, Christoph Obermair, Peter Palfrader, Marc Posch, Christopher Retten- bacher, Herwig Rittsteiger, Gerhard Scharfetter, Josef Schmidbauer, Ingrid Schneider, Harald Schweiger, Stefan Sodar, Gerald Stieglbauer, Marc Strapetz, Johanna Temmel, Christopher Vogl, Werner Weiser, Gerald Wiesbauer, Franz Wilhelmst ¨otter.

I would like to express my thankfulness for their help with these slides. My apologies go to all those who should be on this list and who I omitted by mistake.

This revision and extension was carried out by myself, and I am responsible for all errors.

Salzburg, February 2021 Martin Held

(7)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Legal Fine Print and Disclaimer

To the best of our knowledge, these slides do not violate or infringe upon somebody else’s copyrights. If copyrighted material appears in these slides then it was considered to be available in a non-profit manner and as an educational tool for teaching at an academic institution, within the limits of the “fair use” policy. For copyrighted material we strive to give references to the copyright holders (if known).

Of course, any trademarks mentioned in these slides are properties of their respective owners.

Please note that these slides are copyrighted. The copyright holder(s) grant you the right to download and print it for your personal use. Any other use, including non-profit instructional use and re-distribution in electronic or printed form of significant portions of it, beyond the limits of “fair use”, requires the explicit permission of the copyright holder(s). All rights reserved.

These slides are made available without warrant of any kind, either express or implied, including but not limited to the implied warranties of merchantability and fitness for a particular purpose. In no event shall the copyright holder(s) and/or their respective employers be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, arising out of or in connection with the use of information provided in these slides.

c

(8)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Recommended Textbooks I

E. Angel, D. Shreiner.

Interactive Computer Graphics: A Top-Down Approach With Shader-Based WebGL.

Addison-Wesley, 7th edition, 2015; ISBN 978-0133574845.

https://www.cs.unm.edu/~angel/BOOK/INTERACTIVE_COMPUTER_GRAPHICS/

SEVENTH_EDITION/. S. Guha.

Computer Graphics Through OpenGL: From Theory to Experiments.

CRC Press, 3rd edition, Jan 2019; ISBN 978-1138612648.

J. Kessenich, G. Sellers, and D. Shreiner.

The OpenGL Programming Guide.

Addison-Wesley, 9th edition, 2016; 978-0134495491.

http://www.opengl-redbook.com/

G. Sellers, R.S. Wright, and N. Haemel.

OpenGL SuperBible.

Addison-Wesley, 7th edition, 2015; ISBN 978-0672337475.

http://www.openglsuperbible.com/

(9)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Recommended Textbooks II

T. Akenine-M ¨oller, E. Haines, N. Hoffman, A. Pesce, M. Iwanicki, and S. Hillaire.

Real-Time Rendering.

CRC Press, 4th edition, 2018; ISBN 9781138627000.

http://www.realtimerendering.com W. Engel.

GPU Pro 360 Guide to Rendering.

CRC Press, 1st edition, July 2018; ISBN 9780815365501.

W. Engel.

GPU Pro 360 Guide to Geometry Manipulation.

CRC Press, 1st edition, July 2018; ISBN 9781138568242.

M. Pharr, W. Jakob, and G. Humphreys.

Physically Based Rendering.

Morgan Kaufmann, 3rd edition, 2016; ISBN 978-0-12-800645-0.

https://www.pbrt.org/,http://www.pbr-book.org/. S. Marschner, P. Shirley.

Fundamentals of Computer Graphics.

A K Peters/CRC Press, 4th edition, Dec 2015; ISBN 978-1482229394.

c

(10)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Recommended Textbooks III

D.D. Hearn and M.P. Baker and W. Carithers.

Computer Graphics with OpenGL.

Pearson, 4th edition, 2014; ISBN 978-1-292-02425-7.

P. Shirley.

Ray Tracingmini series. 2016.

https://github.com/petershirley/raytracinginoneweekend/releases. https://github.com/petershirley/raytracingthenextweek/releases. https:

//github.com/petershirley/raytracingtherestofyourlife/releases.

(11)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Table of Content

1 Introduction

2 OpenGL

3 Representation and Modeling

4 Raster Graphics

5 Basic Rendering Techniques

6 Ray Tracing

c

(12)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

1 Introduction

A First Step into Computer Graphics Basics

(13)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

What is Computer Graphics?

The term “computer graphics” was coined by William Fetter in 1960 to describe the work he was pursuing at Boeing.

. . .a consciously managed and documented technology directed toward communicating information accurately and descriptively.”

William A. Fetter, “Computer Graphics” (1960).

Computer graphics is generally regarded as the creation, storage and manipulation of objects for the purpose of generating images of those objects.

. . .the use of computers to produce pictorial images. The images pro- duced can be printed documents or animated motion pictures, but the term computer graphics refers particularly to images displayed on a video display screen, or display monitor. ”

Encyclopedia Britannica.

Why Computer Graphics?

Humans enjoy visual information.

Visual information is easy to comprehend.

Visual information is difficult to generate manually.

c

(14)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Photorealism

What is a realistic image? What does it mean for a picture, whether painted, photographed, or computer-generated, to be “realistic”?

Answer is subject to much scholarly debate!

Photorealism

Hall&Greenberg (1983):

“Our goal in realistic image synthesis is to generate an image that evokes from the visual perception system a response indistinguishable from that evoked by the actual environment.”

Physical properties of objects have to be taken into account!

The term “photorealism” is normally used to refer to a picture that captures many of the effects of light interacting with real physical objects.

It is an attempt to synthesize the field of light intensities that would be focused on the film plane of a camera aimed at the objects depicted.

(15)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Photorealism

There exist applications, however, where perfection is not such a mandatory feature. For instance, flight simulators need a fairly believable output, but need not to be perfect in every detail. The dominant challenge here is real-time interactive control.

A more realistic picture is not necessarily a more desirable or useful one. E.g., to convey information: A picture that is free of the complications of shadows and reflections may well be more successful than a tour de force of photorealism!

In molecular modeling, the realistic depictions are not of “real” atoms, but rather of stylized ball-and-stick and volumetric models that permit special effects, such as animated vibrating bands and color change representing reactions.

In many applications reality is intentionally altered for esthetic effect or to fulfill a na¨ıve viewer’s expectation.

c

(16)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Visualization

Defined as the art to produce images of objects that could not (or hardly) be seen otherwise. E.g., since they are too small, too abstract, too slow or too fast, or simply invisible for some other reason.

Typical examples include weather forecast charts in meteorology, hearts, brains and bones of living creatures in medicine, temperature distributions on brakes, the growth of plants over years, geological changes like volcano eruptions or continental movements.

(17)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Applications of Computer Graphics

Entertainment: Games, Commercials, Movies (Tron, Toy Story, Jurassic Park, Ants, A Bug’s Life, Star Wars, Toy Story 2, Titanic, Gladiator, Troja,. . .), Virtual Reality.

Computer-Aided Design (CAD, CAM):

One of the earliest applications.

Car parts, Boeing 777, submarine design.

City models, architectural walk-throughs.

Control of robots and manufacturing cells.

Education and Training: Simulated environment, Virtual Reality, Augmented Reality.

Flight simulation, pilot training.

Maintenance and assembly training.

Military training (digitized battlefields, mission rehearsal).

Telemedicine

3D models of heart, brain, skeleton, etc.

Haptic interface.

Minimal non-invasive surgery.

c

(18)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Applications of Computer Graphics: Augmented Reality

The term “augmented reality” was coined around 1990 by Thomas Caudell and David Mizell at Boeing.

[Image credit: The Boeing Company.]

Sample augmented reality in today’s consumer products: Head-up displays in cars.

(19)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Applications of Computer Graphics

Scientific Visualization and Data Analysis:

Molecular graphics (protein structures)

Geographic information systems (maps, topographic maps).

Turbulence, temperature, stress, etc.

Weather models.

Business Visualization: Data mining, visualization of massive commercial data.

Graphical User Interfaces (GUI).

c

(20)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

History of Computer Graphics: 1950s, 1960s, and 1970s

early 1950s US military used an interactive CRT graphics called SAGE.

1959 Computer drawing system DAC-1 by IBM and GM.

1961 Sketchpad developed by Ivan Sutherland at MIT.

1963 Douglas Englebart used a mouse as an input device.

1965 Jack Bresenham introduced his line-drawing algorithm.

1966 First computer-controlled head-mounted display (HMD) designed by Ivan Sutherland.

1971 Henri Gouraud developed Gouraud shading.

1972 2D raster display for PC workstations at Xerox.

1973 First SIGGRAPH Conference. Roughly 600 attendees.

1974 Ed Catmull introduced texture mapping (andz-buffering).

1974 Phong Bui-Tong developed Phong shading.

1975 Benoit Mandelbrot published the paper “A Theory of Fractal Sets”.

1977 Nintendo entered the graphics market.

(21)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

History of Computer Graphics: 1980s

1980 “Bol Libre” (by Loren Carpentar) shown at SIGGRAPH.

1980 Ray tracing developed by Turner Whitted.

1982 “Tron” produced by Disney; Perlin noise.

1982 Silicon Graphics founded by Jim Clark. Sun Microsystems, Autodesk, and Adobe Systems founded.

1982 AutoCAD developed by John Walker and Dan Drake.

1984 Radiosity method developed at Cornell University by Ben Battaile, Cindy Goral, Don Greenberg, Ken Torrance.

1985 Adobe System introduced Postscript.

1986 Pixar founded.

1988 Pat Hanrahan implemented and released Renderman.

c

(22)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

History of Computer Graphics: 1990s

1990 Autodesk introduced 3D Studio.

1991 “Terminator 2” was released.

1991 JPEG and MPEG standards were introduced.

1992 SGI specified OpenGL.

1992 Wavelets were used for radiosity.

1994 Industrial Light and Magic won an Academy Award for Technical Achievement for its special-effects work on “Jurassic Park”.

1994 Sun Microsystems introduced Java.

1995 Pixar released “Toy Story”.

1997 SIGGRAPH’97 had more than 48 000 attendees.

1997 “Titanic” released.

1997 Ken Perlin won an Academy Award for Technical Achievement for

“Perlin noise”.

1998 “Ants” and “A Bug’s Life” released.

(23)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

History of Computer Graphics: 2000 and Beyond

2001 Microsoft’s “Xbox console” (based on NVIDIA graphics) makes its debut.

2003 Graphics cards (NVIDIA, ATI, Matrox,. . .) become widely available.

2004 “Half Life 2” released; graphics cards for mobile phones and PDAs.

2004 OpenGL Shading Language formally included into OpenGL 2.0.

2005 “StarWars Episode III”.

2007 CUDA (Compute Unified Device Architecture) released by NVIDIA.

2008 OpenCL (Open Computing Language) specified by the Khronos Group.

2010 GPUs with native 64bit floating-point precision and support for massively-parallel computing become widely available.

2014 OpenGL 4.5 released.

2015 Vulkan introduced as “next generation OpenGL” at GDC 2015.

2016 Vulkan 1.0 released.

2017 OpenGL 4.6 released.

2020 Hardware-accelerated ray tracing on NVIDIA/AMD GPUs.

20?? Real-time radiosity rendering? Photo-realistic consumer graphics?

Realistically rendered humans?

c

(24)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Foundations of Computer Graphics

Computer Science:

algorithms, data structures, programming, software engineering, architecture, artificial intelligence, 3D modeling.

Mathematics:

linear algebra, analytical geometry, complex analysis, numerical analysis, differential geometry, topology, 3D modeling.

Physics:

optics, fluid dynamics, energy, kinematics and dynamics.

Psychology:

human light and color perception.

Biology:

human body, behavioral and cognitive systems, nervous system.

Art:

realism, esthetics.

(25)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

3D Graphics System: Software Components

A system for 3D graphics consists of three major (software) parts:

the modeler, the renderer,

image handling and display.

Image Handling

Image handling is often only a device driver to make the computed image visible for the user on a screen or on a hard copy device.

It can also be an image processing system to improve the quality of images or to alter or transform them before displaying.

c

(26)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Modeling System

Geometry-based modeling:

Lines, polygons, polyhedra, Free-form curves and surfaces, Quadtrees, octrees, bounding volumes, Physics-based modeling:

Kinematics and dynamics (contact detection, contact resolution, force calculation, natural gait),

Fluid dynamics (e.g., for modeling water and waves), Gas, smoke, fire,

Deformable objects (e.g., clothes, cords), Haptics (e.g., touch sensors).

Cognitive-based modeling:

Domain knowledge, learning.

Interaction with real world.

Wide-spread simple modelers CAD systems,

3D editors,

object description languages.

(27)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Rendering System

The output of the modeler is used as input to therendering system.

Rendering is the process of reducing the 3D information of the scene to a 2D representation, the image.

A camera definition is necessary to project the 3D scene onto the desired image plane.

Conventional rendering is very simple: visibility determination and simple shading are performed.

In a more realistic image synthesis system the rendering consists of several parts:

Visibility determination, Shading,

Texturing, Anti-aliasing.

c

(28)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Rendering System

Shading: It is the main part of every rendering system.

Shadows must be determined.

The intensity and color of light leaving an object, given the incoming light distribution and the surface properties, must be computed.

Texturing: It achieves surface details which, in reality, are caused by varying optical properties of the object.

Such variations are often stored in texture maps for fast access.

Texture mapping is the process of determining the transformation from a texture map onto the surface of an object and then onto the screen.

Anti-aliasing: It tries to correct all errors that occur by aliasing.

Aliasing can be caused during various steps in the image generation process.

Aliasing is, more or less, usually due to a discretization of a continuum.

(29)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

3D Graphics System: Hardware Components

1 Input devices (keyboard, mouse, joystick, data glove, eye tracker,. . .)

2 Processor (CPU)

3 CPU memory

4 Graphics Processing Unit (GPU)

5 GPU memory

6 Frame buffer

7 Output devices (monitor, printer,. . .)

CPU GPU Frame

buffer . . . -

- -

-

CPU memory

GPU memory

- -

?

-

- - -

. . .

?

c

(30)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Frame Buffer

A common graphics technique is to use aframe bufferorrefresh buffer.

In its simplest meaning, a frame buffer is simply the video memory that holds the pixels from which the video display (frame) is refreshed.

The frame buffer can be manipulated by the rendering algorithm, and its contents can be moved to the screen when desired.

Double bufferingis a technique whereby the graphics system displays one finished buffer while the hardware renders the next frame into a second buffer.

Without double buffering, the process of drawing is visible as it progresses.

Double buffering generally produces flicker-free rendering for simple animations.

Triple bufferingmakes use of one front buffer and two back buffers, thus enabling the graphics hardware and the rendering algorithm to progress on their own speeds.

Quadruple bufferingmeans the use of double buffering for stereoscopic images.

(31)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Graphics Processing Unit

By today’s definition, a “graphics processing unit” (GPU) is a graphics output device that manipulates the frame buffer and provides accelerated 2D or 3D graphics.

The frame buffer is usually stored in the memory chips on the GPU.

Modern GPUs provide much more thanz-buffer memory! (E.g., a stencil buffer for computing shadows and reflections has become common.)

Modern GPUs also offer a (comparatively cheap) hardware for massively parallel computations, at a floating-point precision of 64 bits.

c

(32)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Device-Independent Graphics Primitives

Since graphics output devices are many and diverse, it is imperative to achieve device independence.

Thus, it is generally preferred to work in world coordinates rather than device coordinates.

Typical graphics commands will be similar to the following commands:

DrawLine(x1,y1,x2,y2);

DrawCircle(x1,y1,r);

DrawPolygon(PointArray);

DrawText(x1,y1,”A Message”);

wherex1,y1,x2,y2,rare specified in world coordinates.

Graphics primitives haveattributes, such as style, thickness and color for a line, or font, size and color for a text.

(33)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Application Programmer’s Interface (API)

Graphic APIs provide the programmer with procedures for handling menus, windows and, of course, graphics.

Well-known APIs for 3D graphics:

OpenGL, WebGL, Direct3D, Java3D, Vulkan.

Vulkan offers a better CPU/GPU balance (than OpenGL) and parallel processing, but it is considerably more low-level than OpenGL.

Vulkan can be expected to replace OpenGL on standard consumer GPUs within the next few years.

In this course we will use OpenGL for practical work.

c

(34)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

A Note on Direct3D and Java3D

Direct3D:

Advantages:

More high-level functionality;

Better control of resources.

Disadvantages:

Only supported by MS Windows machines;

Lack of backwards compatibility of newer versions.

Fahrenheit was an attempt by Microsoft and SGI to unify OpenGL and Direct3D in the 1990s, but it got cancelled.

Java3D:

Advantages:

Based on true object-oriented approach.

Ties natively into Java.

Open-source code since 2004.

Disadvantages:

Runs atop of Java OpenGL (JOGL); delay in use of new GPU features.

Reputation and use has been badly hit by a pause in development during 2003 and 2004.

(35)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

2 OpenGL

Introduction to OpenGL Basic OpenGL

Coordinates and Transformations Event-Handling and Callbacks Textures

Loading 3D Models

c

(36)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

What is OpenGL?

OpenGL stands for “Open Graphics Library”.

Designed by Silicon Graphics Inc. (SGI) in 1991.

Initial design in 1982 (“IRIS GL”).

For many years, development of OpenGL had been coordinated by an Architectural Review Board (ARB).

In 2006, the ARB and the Khronos Board of Directors voted to transfer control of the OpenGL API standard to the non-profit technology consortiumKhronos Group.

As of February 2021, the following companies were promoter members of the Khronos Group: AMD, Apple, ARM, Epic Games, Google, HUAWEI, IKEA, Imagination Technologies Group, Intel, Nvidia, Qualcomm, Samsung, Sony, Valve, VeriSilicon.

The Khronos Group now controls the adaption/extension of OpenGL to reflect new hardware and software advances,

“. . .to bring advanced 3D graphics to all hardware platforms and operating systems — from supercomputers to jet fighters to cell phones.”

Official website:https://www.opengl.org/.

(37)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

What is OpenGL?

OpenGL is a high-performance system interface to graphics hardware.

It is the most widely used library for high-end platform-independent computer graphics; de-facto industry standard.

It runs on different operating systems (including Unix/Linux, Windows, MacOS) without requiring changes to the source code.

Platform-specific features can be implemented via extensions.

OpenGL is a C Library of several hundreds of distinct functions.

OpenGL is not object-oriented.

Several (commercial) versions of an OpenGL library have been implemented.

OpenGL functionality is also provided by Mesa,http://www.mesa3d.org, which is free. Mesa 20.x implements the OpenGL 4.6 API. (OpenGL 3.3 and Mesa 10.x would be perfectly fine for this course, though!)

c

(38)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

What is OpenGL?

OpenGL takes advantage of graphics hardware where it exists; whether or not hardware acceleration is used depends on the availability of suitable drivers.

OpenGL does not come with any windowing functionality; it has to rely on additional libraries (such as GLFW).

It ties into standard C/C++; various other language bindings exist, too. In particular, OpenGL can be used from within

C, C++, Java, Python, Fortran, Ada.

OpenGL supports polygon rendering, texture mapping, anti-aliasing,

shader-level operations.

OpenGL does not provide or (directly) support high-level graphics like ray tracing,

radiosity calculations, volume rendering.

(39)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

OpenGL 3.x/4.x versus OpenGL 2.x

Note that OpenGL 1.x and 2.x differ substantially from OpenGL 3.x and OpenGL 4.x:

Modern OpenGL is entirely shader-based.

Modern OpenGL no longer relies on tons of state variables.

Be careful. . .

. . .when studying tutorials in the Web! A surprisingly large number of tutorials still teach old-style “legacy” OpenGL.

Hint: It is old-style OpenGL if you see statements likeglBeginorglColor4f. No GLU anymore

OpenGL 3.0 deprecated the entire Graphics Library Utilities (GLU) of “legacy”

OpenGL 1.x/2.x. It was removed in OpenGL 3.1. This means that GLU will fail to work in OpenGL 3.x/4.x contexts.

Similarly, GLUT commands likeglutSolidSphere()do no longer work.

c

(40)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

OpenGL Tutorials

Sample Tutorials https://open.gl/:

Requires a GPU compatible with OpenGL 3.2, CMake; uses GLFW for context and window creation and GLEW for access to newer OpenGL functions.

http://www.opengl-tutorial.org:

Requires a GPU compatible with OpenGL 3.3. Similar tohttps://open.gl/. Learn OpenGL,https://learnopengl.com/:

Similar tohttp://www.opengl-tutorial.org. http://ogldev.org/:

Tutorials that require a GPU compatible with OpenGL 3.3.

(41)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

OpenGL Libraries

OpenGL proper does not provide any windowing functionality! That is, it does not support opening a window or getting input from the mouse or a keyboard.

Quote taken from the OpenGL 3.1 Specification (chapter 2, first paragraph):

OpenGL is concerned only with rendering into a frame buffer (and reading values stored in that frame buffer). There is no support for other peripherals sometimes associated with graphics hardware, such as mice and keyboards.

Programmers must rely on other mechanisms to obtain user input.

Thus, a link to the underlying windowing system (GLX for X windows, WGL for Windows, AGL for Macintosh) and an add-on library (e.g., GLFW) is required!

c

(42)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

OpenGL Libraries: GLFW

GLFWis a light-weight multi-platform library for OpenGL.

It supports Windows (XP and later), OS X (10.7 Lion and later) and Unix-like operating systems that run the X Window System.

Its commands start with the prefixglfw. E.g.,glfwInit().

It can create and manage windows as well as handle standard input (via keyboard, mouse or joystick).

It can control multiple monitors and enumerate video modes.

In addition to portability, its single biggest advantage is its simplicity.

Its biggest disadvantage is its lack of menus and buttons.

Xlib, Xtk Frame Buffer GLX

GL Program

Application OpenGL

GLEW GLFW

(43)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

OpenGL Libraries: GLEW

The OpenGL Extension Wrangler Library (GLEW) is a cross-platform library that provides efficient run-time mechanisms for determining which OpenGL

extensions are supported on the target platform.

That is, it makes it easy to access OpenGL extensions that are available on a particular system.

GLEW commands start with the prefixglew. Easy to use: Includeglew.hand runglewInit().

Xlib, Xtk Frame Buffer GLX

GL Program

Application OpenGL

GLEW GLFW

c

(44)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Compiling and Linking an OpenGL Program

The source code for an OpenGL program has to contain the following directives for including OpenGL header files:

If GLEW is used:

# i n c l u d e < GL / g l e w . h >

If GLFW is used:

# i n c l u d e < G L F W / g l f w 3 . h >

Note: When compiling and linking an OpenGL program, the OpenGL header files and libraries have to be available for inclusion. This means, e.g., using the-lgl loader flags, and possibly,-Lflags for the X libraries.

Better alternative: Resort to cmake!

See the sample files onhttps:

//www.cosy.sbg.ac.at/~held/teaching/einfuehrung_graphik/cg.html.

(45)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Basic OpenGL Program Structure

# i n c l u d e < H e a d e r s O p e n G L >

int m a i n () {

C r e a t e W i n d o w ( title , width , h e i g h t ) ; C r e a t e O p e n G L C o n t e x t ( s e t t i n g s ) ;

w h i l e ( w i n d o w I s O p e n ) { / * e v e n t p r o c e s s i n g & d r a w i n g * /

w h i l e ( e v e n t == G e t N e x t E v e n t () )

H a n d l e E v e n t ( e v e n t ) ; / * e . g . , h a n d l e m o u s e * /

U p d a t e S c e n e () ; / * e . g . , m o v e o b j e c t s * /

R e n d e r S c e n e () ; / * g e n e r a t e n e x t i m a g e * /

D i s p l a y G r a p h i c s () ; / * e . g . , s w a p b u f f e r s * /

} }

Every real-time graphics application will have a program flow that boils down to this structure, no matter whether it uses OpenGL or some other library.

c

(46)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Creating an OpenGL Window and Context

We use GLFW to create an OpenGL display window.

It comes as no surprise that you need to load the header file and initialize GLFW.

# include< G L F W / g l f w 3 . h >

/ * i n i t i a l i z a t i o n o f G L F W * /

g l f w S e t E r r o r C a l l b a c k ( e r r o r C a l l b a c k ) ; if ( g l f w I n i t () != G L F W _ T R U E ) {

f p r i n t f ( stderr , " C a n n o t i n i t i a l i z e G L F W \ n ") ; e x i t ( E X I T _ F A I L U R E ) ;

} ...

/ * t e r m i n a t i o n o f G L F W * /

g l f w T e r m i n a t e () ; GLFW error callback function:

s t a t i c v o i d e r r o r C a l l b a c k (int err , c o n s t c h a r* l o g T e x t ) {

f p r i n t f ( stderr , " G L F W err % d : % s \ n ", err , l o g T e x t ) ; }

(47)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Creating an OpenGL Window and Context

TheglfwWindowHint()function is used to set some GLFW options.

g l f w W i n d o w H i n t ( G L F W _ C O N T E X T _ V E R S I O N _ M A J O R , 3) ; g l f w W i n d o w H i n t ( G L F W _ C O N T E X T _ V E R S I O N _ M I N O R , 3) ;

g l f w W i n d o w H i n t ( G L F W _ O P E N G L _ F O R W A R D _ C O M P A T , G L _ T R U E ) ; g l f w W i n d o w H i n t ( G L F W _ R E S I Z A B L E , G L _ F A L S E ) ;

Window creation:

c o n s t G L u i n t W I D T H = 800 , H E I G H T = 6 0 0 ;

G L F W w i n d o w * m y W i n d o w = g l f w C r e a t e W i n d o w ( WIDTH , HEIGHT ,

" OGL D e m o ", NULL , N U L L ) ; if ( m y W i n d o w == N U L L ) {

f p r i n t f ( stderr , " C a n n o t o p e n G L F W w i n d o w \ n ") ; e x i t ( E X I T _ F A I L U R E ) ;

}

The first two parameters specify the width and height of the drawing area.

The fourth parameter tells GLFW to use the monitor in windowed mode, and the last parameter would allow to share resources with an existing OpenGL context.

Roughly, a context stores all of the state data associated with an instance of OpenGL. A process can create multiple OpenGL contexts, and each context can represent a separate drawing area, e.g., a window in a graphics application.

c

(48)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Creating an OpenGL Window and Context

For fullscreen mode:

G L F W w i n d o w * m y W i n d o w = g l f w C r e a t e W i n d o w ( WIDTH , HEIGHT ,

" OGL D e m o ",

g l f w G e t P r i m a r y M o n i t o r () , N U L L ) ; Making an OpenGL context active:

g l f w M a k e C o n t e x t C u r r e n t ( m y W i n d o w ) ;

(49)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Creating an OpenGL Window and Context: Event-Handling Loop

This should be enough to get an OpenGL window mapped to your screen:

/ * e v e n t - h a n d l i n g a n d r e n d e r i n g l o o p * /

w h i l e (! g l f w W i n d o w S h o u l d C l o s e ( m y W i n d o w ) ) {

/ * p o l l e v e n t s * /

g l f w P o l l E v e n t s () ;

/ * S w a p b u f f e r s * /

g l f w S w a p B u f f e r s ( m y W i n d o w ) ;

/ * c l o s e w i n d o w u p o n h i t t i n g t h e e s c a p e k e y * /

if ( g l f w G e t K e y ( m y W i n d o w , G L F W _ K E Y _ E S C A P E ) ==

G L F W _ P R E S S )

g l f w S e t W i n d o w S h o u l d C l o s e ( m y W i n d o w , G L _ T R U E ) ; }

The event-handling loop always needs to callglfwSwapBuffers()and glfwPollEvents().

You can ignore events that you do not want to handle. (We’ll learn more on event handling later. . .)

Do not forget to handle the escape key (or some other key) to return to the desktop if using the fullscreen mode.

c

(50)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Creating an OpenGL Window and Context

One technical issue remains: At runtime a graphics application needs to check which functionality is supported by a GPU, as specified in the driver provided by the vendor of the GPU, and needs to link to them.

This is tedious and is best handled by resorting to GLEW:

# include< GL / g l e w . h >

/ * i n i t i a l i z a t i o n o f G L E W * /

g l e w E x p e r i m e n t a l = G L _ T R U E ; G L e n u m g l e w S t a t u s = g l e w I n i t () ; if ( g l e w S t a t u s != G L E W _ O K ) {

f p r i n t f ( stderr , " E r r o r : % s \ n ",

g l e w G e t E r r o r S t r i n g ( g l e w S t a t u s ) ) ; e x i t ( E X I T _ F A I L U R E ) ;

}

Make sure to includeglew.hprior to other OpenGL-related headers!

SettingglewExperimentalforces GLEW to use a “modern” OpenGL method for checking whether a function is available.

Seewindow.cconhttps:

//www.cosy.sbg.ac.at/~held/teaching/einfuehrung_graphik/cg.html.

(51)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Vertex Buffer Object

Classical bottleneck in pre-OpenGL 3.1: Whenever a vertex is specified in a pre-OpenGL 3.1 application, by means ofglVertex, its coordinates need to be sent to the GPU.

Goal: Increase performance by using the GPU rather than the CPU and by decreasing the amount of data that is exchanged between CPU and GPU.

Basic idea:

We pack the vertex and attribute data into arrays.

A vertex array is transferred to the GPU and stored in the GPU memory.

Array data that is in the GPU memory can be rendered via a simple call to a callback function:glDrawArrays()

This leads to vertex array objects and vertex buffer objects.

No object-oriented “object”

OpenGL is fairly liberal in its use of the word “object”! That is, an OpenGL “object” is not to be understood as an object in the object-oriented programming meaning.

Rather, OpenGL objects tend to be simple arrays of data for which we get a handle (i.e., an identifier) to interact with.

c

(52)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Vertex Buffer Object

OpenGL expects vertices to be stored in arrays.

f l o a t vtx [] = {

0.0 f , 0.0 f , / * x - a n d y - c o o r d s o f 1 s t v e r t e x * /

0.5 f , 0.5 f , / * x - a n d y - c o o r d s o f 2 n d v e r t e x * /

0.5 f , -0.5 f / * x - a n d y - c o o r d s o f 3 r d v e r t e x * /

};

A Vertex Buffer Object (VBO) is an array of data, typically floats.

E.g., it may hold data like world coordinates, color, texture coordinates and, possibly, application-specific data.

It will reside in the high-speed memory of the GPU.

G L u i n t m y V B O ;

g l G e n B u f f e r s (1 , & m y V B O ) ;

g l B i n d B u f f e r ( G L _ A R R A Y _ B U F F E R , m y V B O ) ;

Since GPU memory is managed by OpenGL, you get a positive number as a reference to it.

TheglBindBuffer()function turns a VBO into the active buffer.

(53)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Vertex Buffer Object

Once an VBO is active, we can copy the vertex data to it.

g l B u f f e r D a t a ( G L _ A R R A Y _ B U F F E R , s i z e o f( vtx ) , vtx , G L _ S T A T I C _ D R A W ) ;

Depending on the intended type of use, the last argument ofglBufferData() determines the kind of GPU memory (relative to writing and drawing speed) in which the data is stored:

GL STATIC DRAW: Generated once, no changes, drawn many times.

GL DYNAMIC DRAW: Changed a few times, drawn many times.

GL STREAM DRAW: Changed and drawn many times.

We can store more than just the 2D or 3D coordinates of points in a VBO. E.g., store 2D texture coordinates or 3D normals.

Hence, it is likely that most of the VBOs will consist of arrays of two and three floats.

c

(54)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Vertex Array Object

A Vertex Array Object (VAO) is used to tell OpenGL how the VBO is arranged.

E.g., it might be divided into variables of two floats each.

That is, a VAO is not the actual object storing the data, but a descriptor of the data.

G L u i n t m y V A O ;

g l G e n V e r t e x A r r a y s (1 , & m y V A O ) ; g l B i n d V e r t e x A r r a y ( m y V A O ) ;

Once a VAO has been bound, every call toglVertexAttribPointer()will cause the attributes associated with a VBO to be stored in that VAO.

Warning

Only attribute bindings performed after binding a VAO refer to it! Thus, make sure to bind an VAO at the start of your code!

(55)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Shader Programs

GPU-based rendering is envoked through so-calledshader programs.

An application sends data to the GPU, and the GPU does all the rendering.

Starting with OpenGL 3.1, OpenGL is entirely shader-based:

The state model is replaced by a data-flow model.

Several pre-OpenGL 3.1 functions are deprecated, and backwards compatibility is not required. (At least not in Core Mode.)

No default shaders — but each application has to provide at least a vertex and a fragment shader.

Vertex Shader:

Processes input vertices (e.g., of triangles) individually.

Influences the attributes of a vertex, e.g., position, color, and texture coordinates.

Performs the perspective transformation.

Fragment Shader:

Calculates individual fragment colors.

E.g., it might sample a texture or simply output a color.

It may also be used for lighting and for creating advanced effects like bump-mapping effects.

More shaders (e.g., Tesselation and Geometry Shaders) added with OpenGL 4.1.

c

(56)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Shader Programs: Execution Pipeline

vertex shader geometry shader shape assembly

rasterization fragment shader tests and blending vertex data

(arrays)

tesselation shaders

culling, clipping

The geometry shader is optional. It can discard, modify or pass through primitives, or even generate new ones. E.g., it could generate squares out of input vertex data.

In the shape assembly, the GPU formsprimitives(e.g., triangles, line segments) out of the vertices. Up to this stage, all operations are carried out on the vertices.

Rasterization converts the primitives into pixel-sizedfragments.

(57)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

OpenGL Shading Language

Shaders are written in the OpenGL Shading Language (GLSL).

The GLSL is C/C++-like with overloaded operators.

New data types (e.g., matrices, vectors) and C++-like constructors.

E.g.,vec3 myVec=vec3(1.0,0.0,1.0).

Similar in use to NVIDIA’s Cg and Microsoft’s HLSL.

GLSL code is sent to the shaders as source code.

New OpenGL functions added to compile and link that code and to exchange information with the shaders.

Shaders can be written inside the C/C++code, or can be stored in files and loaded.

We will only discuss vertex shader and fragment shader very briefly.

c

(58)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

OpenGL Shading Language: Sample Vertex Shader

Since the triangle in our sample is already given by 2D vertices, a vertex shader can be fairly simple.

/ * d e f i n e t h e v e r t e x s h a d e r * /

c o n s t c h a r* v e r t e x S h a d e r S o u r c e = G L S L ( in v e c 2 p o s i t i o n ;

v o i d m a i n () {

g l _ P o s i t i o n = v e c 4 ( p o s i t i o n , 0.0 f , 1.0 f ) ; }

) ;

/ * c o m p i l e t h e v e r t e x s h a d e r * /

G L u i n t v e r t e x S h a d e r = g l C r e a t e S h a d e r ( G L _ V E R T E X _ S H A D E R ) ; g l S h a d e r S o u r c e ( v e r t e x S h a d e r , 1 , & v e r t e x S h a d e r S o u r c e ,

N U L L ) ;

g l C o m p i l e S h a d e r ( v e r t e x S h a d e r ) ;

Since we deal with homogeneous coordinates, the last argument of gl Position()will, in general, be 1.0. . ..

(59)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

OpenGL Shading Language: Sample Vertex Shader

Warning

No error will be reported byglGetError()if a shader fails to compile!

Hence, make sure to check explicitly!

/ * c h e c k w h e t h e r t h e v e r t e x s h a d e r h a s c o m p i l e d * /

G L i n t s t a t u s ;

g l G e t S h a d e r i v ( v e r t e x S h a d e r , G L _ C O M P I L E _ S T A T U S , & s t a t u s ) ; if ( s t a t u s != G L _ T R U E ) {

f p r i n t f ( stderr , " V e r t e x s h a d e r did not c o m p i l e \ n ") ; c h a r v e r t e x C o m p i l e r L o g [ 5 1 2 ] ;

g l G e t S h a d e r I n f o L o g ( v e r t e x S h a d e r , 512 , NULL , v e r t e x C o m p i l e r L o g ) ; f p r i n t f ( stderr , " % s ", v e r t e x C o m p i l e r L o g ) ; e x i t ( E X I T _ F A I L U R E ) ;

}

c

(60)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

OpenGL Shading Language: Sample Fragment Shader

For simplicity, we’ll draw the triangle entirely red and get the following simple fragment shader.

/ * d e f i n e a n d c o m p i l e t h e f r a g m e n t s h a d e r : * /

/ * w e ’ l l g e t a r e d t r i a n g l e * /

c o n s t c h a r* f r a g m e n t S h a d e r S o u r c e = G L S L ( out v e c 4 o u t C o l o r ;

v o i d m a i n () {

o u t C o l o r = v e c 4 ( 1 . 0 f , 0.0 f , 0.0 f , 1.0 f ) ; }

) ;

G L u i n t f r a g m e n t S h a d e r = g l C r e a t e S h a d e r (

G L _ F R A G M E N T _ S H A D E R ) ; g l S h a d e r S o u r c e ( f r a g m e n t S h a d e r , 1 , & f r a g m e n t S h a d e r S o u r c e ,

N U L L ) ;

g l C o m p i l e S h a d e r ( f r a g m e n t S h a d e r ) ;

(61)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Creating a Shader Program

We form a shader program by linking the vertex and fragment shader into one unit.

G L u i n t s h a d e r P r o g r a m = g l C r e a t e P r o g r a m () ; g l A t t a c h S h a d e r ( s h a d e r P r o g r a m , v e r t e x S h a d e r ) ; g l A t t a c h S h a d e r ( s h a d e r P r o g r a m , f r a g m e n t S h a d e r ) ;

g l B i n d F r a g D a t a L o c a t i o n ( s h a d e r P r o g r a m , 0 , " o u t C o l o r ") ; g l L i n k P r o g r a m ( s h a d e r P r o g r a m ) ;

To make the shader program active, we use the following statement:

g l U s e P r o g r a m ( s h a d e r P r o g r a m ) ;

c

(62)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Creating a Shader Program

Again, no error checking is done by OpenGL! Hence, make sure to check whether linking the shader program worked.

b o o l c h e c k S h a d e r P r o g r a m L i n k S t a t u s ( G L u i n t p r o g r a m I D ) {

G L i n t s t a t u s ;

g l G e t P r o g r a m i v ( p r o g r a m I D , G L _ L I N K _ S T A T U S , & s t a t u s ) ; if( s t a t u s == G L _ F A L S E ) {

G L i n t l e n g t h ;

g l G e t P r o g r a m i v ( p r o g r a m I D , G L _ I N F O _ L O G _ L E N G T H ,

& l e n g t h ) ;

G L c h a r * log = new c h a r[ l e n g t h + 1];

g l G e t P r o g r a m I n f o L o g ( p r o g r a m I D , length , & length ,

& log [ 0 ] ) ; f p r i n t f ( stderr , " % s ", log ) ; r e t u r n f a l s e ;

}

r e t u r n t r u e ; }

(63)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Specifying the Vertex Atributes

We obtain a reference to the position input in the vertex shader — in our example this will be 0 — and then useglVertexAttribPointer()to specify how the input data is organized:

c o n s t c h a r* a t t r N a m e = " p o s i t i o n ";

G L i n t p o s A t t r i b = g l G e t A t t r i b L o c a t i o n ( s h a d e r P r o g r a m , a t t r N a m e ) ; if ( p o s A t t r i b == -1) {

f p r i n t f ( stderr , " E r r o r for a t t r i b % s \ n ", a t t r N a m e ) ; e x i t ( E X I T _ F A I L U R E ) ;

}

g l E n a b l e V e r t e x A t t r i b A r r a y ( p o s A t t r i b ) ;

g l V e r t e x A t t r i b P o i n t e r ( p o s A t t r i b , 2 , G L _ F L O A T , G L _ F A L S E , 2*s i z e o f(f l o a t) , 0) ;

The arguments ofglVertexAttribPointer()are as follows:

1 Reference to the input.

2 Number of values for that input, i.e., components otvec.

3 Type of each component.

4 Normalization to [-1.0,1.0] requested?

5 Stride: How many bytes are between every position attribute in the array?

6 Offset: Byte offset for the first component of the first attribute.

c

(64)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Drawing the Sample Triangle

Finally, we set the background to black and draw the triangle.

/ * s e t t h e w i n d o w b a c k g r o u n d t o b l a c k * /

g l C l e a r C o l o r ( 0 . 0 f , 0.0 f , 0.0 f , 1.0 f ) ; g l C l e a r ( G L _ C O L O R _ B U F F E R _ B I T ) ;

/ * d r a w t h e t r i a n g l e * /

g l D r a w A r r a y s ( G L _ T R I A N G L E S , 0 , 3) ;

The callglClearColor(0.0,0.0,1.0,0.0)would set the background color to “no red, no green, maximum blue”. (The fourth parameter pertains to blending, and can be ignored for the moment.)

Each argument is a floating-point value in the range[0,1], specifying the amount of red, green and blue.

The arguments ofglDrawArrays()are as follows:

1 Type of primitives to be rendered.

2 How many vertices shall be skipped at the beginning.

3 Number of vertices. (Not the number of primitives!)

(65)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Cleaning Up in the End

Do not forget to release all resources in the end:

g l D e l e t e P r o g r a m ( s h a d e r P r o g r a m ) ; g l D e l e t e S h a d e r ( f r a g m e n t S h a d e r ) ; g l D e l e t e S h a d e r ( v e r t e x S h a d e r ) ; g l D e l e t e B u f f e r s (1 , & m y V B O ) ; g l D e l e t e V e r t e x A r r a y s (1 , & m y V A O ) ; Seedrawing.cconhttps:

//www.cosy.sbg.ac.at/~held/teaching/einfuehrung_graphik/cg.html.

c

(66)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Drawing a Colorful Triangle

We will now modify the sample code to draw a colorful triangle, by assigning the RGB values for red, green and blue to the vertices; seecolored tri.ccon https:

//www.cosy.sbg.ac.at/~held/teaching/einfuehrung_graphik/cg.html:

f l o a t vtx [] = {

0.0 f , 0.0 f , 1.0 f , 0.0 f , 0.0 f , / * c o o r d s , r e d * /

0.5 f , 0.5 f , 0.0 f , 1.0 f , 0.0 f , / * c o o r d s , g r e e n * /

0.5 f , -0.5 f , 0.0 f , 0.0 f , 1.0 f / * c o o r d s , b l u e * /

};

Modified vertex shader:

c o n s t c h a r* v e r t e x S h a d e r S o u r c e = G L S L ( in v e c 2 p o s i t i o n ;

in v e c 3 c o l o r V t x I n ; out v e c 3 c o l o r V t x O u t ; v o i d m a i n () {

c o l o r V t x O u t = c o l o r V t x I n ;

g l _ P o s i t i o n = v e c 4 ( p o s i t i o n , 0.0 , 1 . 0 ) ; }

) ;

(67)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Drawing a Colorful Triangle

Modified fragment shader:

c o n s t c h a r* f r a g m e n t S h a d e r S o u r c e = G L S L ( in v e c 3 c o l o r V t x O u t ;

out v e c 4 o u t C o l o r ; v o i d m a i n () {

o u t C o l o r = v e c 4 ( c o l o r V t x O u t , 1.0 f ) ; }

) ;

Modified bindings:

G L i n t p o s A t t r i b = g l G e t A t t r i b L o c a t i o n ( s h a d e r P r o g r a m ,

" p o s i t i o n ") ; g l E n a b l e V e r t e x A t t r i b A r r a y ( p o s A t t r i b ) ;

g l V e r t e x A t t r i b P o i n t e r ( p o s A t t r i b , 2 , G L _ F L O A T , G L _ F A L S E , 5*s i z e o f(f l o a t) , 0) ;

G L i n t c o l A t t r i b = g l G e t A t t r i b L o c a t i o n ( s h a d e r P r o g r a m ,

" c o l o r V t x I n ") ; g l E n a b l e V e r t e x A t t r i b A r r a y ( c o l A t t r i b ) ;

g l V e r t e x A t t r i b P o i n t e r ( c o l A t t r i b , 3 , G L _ F L O A T , G L _ F A L S E , 5*s i z e o f(f l o a t) , (v o i d*) (2*s i z e o f(f l o a t) ) ) ;

c

(68)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Index Buffer Object

Typically, geometric objects will reuse vertices. E.g., the two triangles of a rectangle share two vertices, and it is a waste of precious GPU memory to store them twice.

Index Buffer Objects (IBOs) are applied for re-using vertex data:

We model a rectangle formed by five vertices and four triangles:

f l o a t vtx [] = {

-0.5 f , -0.5 f , 1.0 f , 0.0 f , 0.0 f , / * l o w e r - l e f t c o r n e r * /

0.5 f , -0.5 f , 0.0 f , 1.0 f , 0.0 f , / * l o w e r - r i g h t c o r n e r * /

0.5 f , 0.5 f , 0.0 f , 0.0 f , 1.0 f , / * u p p e r - r i g h t c o r n e r * /

-0.5 f , 0.5 f , 1.0 f , 1.0 f , 1.0 f , / * u p p e r - l e f t c o r n e r * /

0.0 f , 0.0 f , 0.0 f , 0.0 f , 0.0 f / * c e n t e r * /

};

G L u i n t idx [] = { 0 , 1 , 4 , 1 , 2 , 4 , 2 , 3 , 4 , 3 , 0 , 4 };

(69)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

Index Buffer Object

Creation of an IBO:

/ * g e n e r a t e o n e I n d e x B u f f e r O b j e c t * /

G L u i n t m y I B O ;

g l G e n B u f f e r s (1 , & m y I B O ) ;

g l B i n d B u f f e r ( G L _ E L E M E N T _ A R R A Y _ B U F F E R , m y I B O ) ;

/ * c o p y t h e e l e m e n t d a t a t o i t * /

g l B u f f e r D a t a ( G L _ E L E M E N T _ A R R A Y _ B U F F E R , s i z e o f( idx ) , idx , G L _ S T A T I C _ D R A W ) ;

For drawing we useglDrawElements()rather thanglDrawArrays()in the rendering loop:

g l D r a w E l e m e n t s ( G L _ T R I A N G L E S , 12 , G L _ U N S I G N E D _ I N T , 0) ; The arguments ofglDrawElements()are as follows:

1 Type of primitives to be rendered.

2 Number of element indices. (Not the number of triangles!)

3 Type of element indices.

4 Offset.

Seecolored quad.cconhttps:

//www.cosy.sbg.ac.at/~held/teaching/einfuehrung_graphik/cg.html.

Note that the square appears to be a quad in the graphics window: distortion!

c

(70)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

OpenGL Naming Conventions

All OpenGL functions have the prefixgl, followed by one or more capitalized words to denote the function. E.g.,glBindBuffer().

GLEW and GLFW use the same scheme for naming their functions.

Recall that OpenGL is C-based and, thus, does not have function overloading.

As consequence, suffixes after the main part of a function name are used for prodiving information on the specific number and type of arguments that a function accepts. E.g.:

glUniform2f()indicates that this function takes two parameters (in addition to its standard arguments) which are of typeGLfloat.

glUniform2fv()indicates that these two floats are passed as a one-dimensional array rather than two individual parameters.

All OpenGL constants begin withGLand use underscores to separate words.

E.g.,GL STATIC DRAW.

(71)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

OpenGL Data Types

Data Type Min. Prec. Description Suffix

GLbyte 8 bits signed integer b

GLubyte 8 bits unsigned integer ub

GLshort 16 bits signed integer s

GLushort 16 bits unsigned integer us

GLsizei 32 bits integer size i

GLint 32 bits signed integer i

GLuint 32 bits unsigned integer ui

GLenum 32 bits enumeration type ui

GLfloat 32 bits floating-point value f

GLclampf 32 bits floating-point value clamped to[0.0,1.0] f

GLdouble 64 bits floating-point value d

GLclampd 64 bits floating-point value clamped to[0.0,1.0] d An OpenGL implementation must use at least the minimum number of bits specified. It may use more bits than the minimum number required to represent a GL type.

An OpenGL data type may but need not match the “corresponding” C data type in a specific implementation.

Thus, use the OpenGL types to assure portability!

c

(72)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

OpenGL Graphical Primitives

OpenGL Primitive Description Min. #(vertices)

GL_POINTS 1

GL_LINES 2

GL_LINE_STRIP 2

GL_LINE_LOOP 2

GL_TRIANGLES 3

GL_TRIANGLE_STRIP 3

GL_TRIANGLE_FAN 3

Make sure to pay close attention to how vertices are grouped for the strips and fans.

0 1

2 3

4 5

0

1 2

3 4 5

(73)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

OpenGL Coordinate Systems

The units of the coordinates of a vertex depend on the application; those coordinates are calledworld coordinates.

A standard right-handed coordinate system is assumed for the world coordinates:

the positivex-axis is to your right, the positivey-axis is up and the positivez-axis points out of the screen towards you.

Internally, OpenGL will convert tocamera coordinatesand later towindow coordinates.

OpenGL’s camera is placed at the origin pointing in the negativez-direction of the world coordinate system.

The camera cannot be moved. Rather, one has to apply an inverse transformation to the scene to be rendered.

OpenGL supports the definition of aviewing volume: Only (those portions of) objects that are inside this 3D region will be drawn (“clipping”).

c

(74)

Computational Geometry and Applications Lab UNIVERSIT ¨AT SALZBURG

OpenGL Coordinate Transformation Pipeline

Modeling Transformation

Viewing Transformation

Projection Transformation

Perspective Division

Viewport Transformation OCS

DCS

WCS VCS

NDCS

CCS

CCS

The coordinates of a 3D pointpundergo several transformations until eventually a pixel on the screen corresponding to its 2D equivalentp0is set.

This sequence of transformations is encoded in theOpenGL transformation pipeline: from object coordinate system (OCS) to world coordinate system (WCS), viewing coordinate system (VCS), clipping coordinate system (CCS), normalized device coordinate system (NDCS), and finally to device coordinate system (DCS).

p0=Mproj·Mview·Mmodel·p

Referenzen

ÄHNLICHE DOKUMENTE

Es sei ∆ ein abgeschlossenes Dreieck in H , so dass eine Seite in der reellen

[r]

Zeigen Sie unter Verwendung von Blatt 7, Aufgabe 3, dass f auf ganz U holomorph ist.. b) Es sei G ein zur reellen Achse symmetrisch gelegenes

Die Funktionen f und g seinen in einer Umgebung des

Aufgabe 1. Zeigen Sie am Beispiel der Funktion cos z, dass das Maximumprinzip nicht f¨ ur unbeschr¨ ankte Gebiete gilt.. Aufgabe 4. Damit ist aber auch g konstant und f ein Polynom

Beweisen Sie, dass eine Laurent-Reihe in ihrem Konvergenzgebiet gliedweise differenziert werden darf.

Bestimmen Sie f¨ ur die folgenden Funktionen die Art der Singularit¨ at im Punkt

· um einen beliebigen Entwick- lungspunkt z 0 ∈ C in eine Potenzreihe und bestimmen Sie den Konvergenzradius. Was f¨ allt auf, wenn Sie den Konvergenzkreis mit dem Definitionsgebiet