Opengl 4.0 Shading Language Cookbook
Total Page:16
File Type:pdf, Size:1020Kb
OpenGL 4.0 Shading Language Cookbook Over 60 highly focused, practical recipes to maximize your use of the OpenGL Shading Language David Wolff BIRMINGHAM - MUMBAI OpenGL 4.0 Shading Language Cookbook Copyright © 2011 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: July 2011 Production Reference: 1180711 Published by Packt Publishing Ltd. 32 Lincoln Road Olton Birmingham, B27 6PA, UK. ISBN 978-1-849514-76-7 www.packtpub.com Cover Image by Fillipo ([email protected]) Credits Author Project Coordinator David Wolff Srimoyee Ghoshal Reviewers Proofreader Martin Christen Bernadette Watkins Nicolas Delalondre Indexer Markus Pabst Hemangini Bari Brandon Whitley Graphics Acquisition Editor Nilesh Mohite Usha Iyer Valentina J. D’silva Development Editor Production Coordinators Chris Rodrigues Kruthika Bangera Technical Editors Adline Swetha Jesuthas Kavita Iyer Cover Work Azharuddin Sheikh Kruthika Bangera Copy Editor Neha Shetty About the Author David Wolff is an associate professor in the Computer Science and Computer Engineering Department at Pacific Lutheran University (PLU). He received his PhD in Physics from Oregon State University. He has a passion for computer graphics and the intersection between art and science. He has been teaching computer graphics to undergraduates at PLU for over 10 years, using OpenGL. Special thanks to Brandon Whitley for interesting discussions and helpful insights during the writing of this book. His help has been incredibly valuable. Thanks also to all of the reviewers and editors for their help. I'd also like to thank my parents for a lifetime of support, love and encouragement. About the Reviewers Martin Christen graduated with a Computer Science degree. Today, he is a senior research associate at the Institute of Geomatics Engineering of the University of Applied Sciences Northwestern (FHNW) Switzerland. He is the lead developer of the open source virtual globe engine (http://www.openwebglobe.org). Previously, he was software developer in the fields of 3D geoinformation and in 3D computer game development. His main research interests are GPU-programming, parallel computing, terrain-rendering, and 3D graphics engine architecture. Nicolas Delalondre has been working on 3D computer graphics software for more than ten years mainly in OpenGL on desktop and mobile devices. Currently, he is a freelance developer at Digital Mind and an associate at Rhino Terrain where he develops geomodeling and meshing algorithms. Before joining Rhino Terrain, Nicolas was a 3D software engineer at Bionatics, a French startup, developing OpenGL engine and algorithms for geographic information system (GIS). Prior to working with Bionatics, he worked for INRIA (French research institute in computer science) in the radiosity field. Nicolas has a Master's degree in Computer Science from EFREI, France. Markus Pabst has been working with OpenGL since 2002. He works in the digital mapping industry and has worked with the desktop and embedded versions of OpenGL. Since 2007, he has been leading a team of software engineers developing an embedded OpenGL-based cockpit display system for the Airbus A400M aircraft certified against DO- 178B Level C standard. In 2005, he began teaching OpenGL at the German University of Applied Sciences Ravensburg-Weingarten. Markus received his university degree in Multimedia Technologies from the Technical University of Ilmenau, in 2002. In the summer, you may find Markus on a sailing boat in southern Germany. Brandon Whitley worked for four years as a graphics programmer for Zipper Interactive, a Sony Computer Entertainment Worldwide Studio. He earned his Masters degree in Computer Science from Georgia Institute of Technology. While obtaining his undergraduate degree at Pacific Lutheran University, he was inspired by the author of this book to pursue a career in computer graphics. Brandon is currently a graphics programmer at Bungie, creators of the Halo series. I would like to thank my wife, Katie, and my son, Parker, for their love and support. www.PacktPub.com Support files, eBooks, discount offers and more You might want to visit www.PacktPub.com for support files and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. Why subscribe? f Fully searchable across every book published by Packt f Copy and paste, print and bookmark content f On demand and accessible via web browser Free access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access. Table of Contents Preface 1 Chapter 1: Getting Started with GLSL 4.0 5 Introduction 6 Using the GLEW Library to access the latest OpenGL functionality 8 Using the GLM library for mathematics 10 Determining the GLSL and OpenGL version 13 Compiling a shader 15 Linking a shader program 18 Sending data to a shader using per-vertex attributes and vertex buffer objects 22 Getting a list of active vertex input attributes and indices 29 Sending data to a shader using uniform variables 31 Getting a list of active uniform variables 35 Using uniform blocks and uniform buffer objects 37 Building a C++ shader program class 43 Chapter 2: The Basics of GLSL Shaders 47 Introduction 47 Implementing diffuse, per-vertex shading with a single point light source 50 Implementing per-vertex ambient, diffuse, and specular (ADS) shading 55 Using functions in shaders 62 Implementing two-sided shading 65 Implementing flat shading 69 Using subroutines to select shader functionality 71 Discarding fragments to create a perforated look 76 Chapter 3: Lighting, Shading Effects, and Optimizations 81 Introduction 81 Shading with multiple positional lights 82 Shading with a directional light source 84 Using per-fragment shading for improved realism 88 Table of Contents Using the halfway vector for improved performance 91 Simulating a spotlight 94 Creating a cartoon shading effect 97 Simulating fog 100 Chapter 4: Using Textures 105 Introduction 105 Applying a 2D texture 106 Applying multiple textures 111 Using alpha maps to discard pixels 114 Using normal maps 116 Simulating reflection with cube maps 123 Simulating refraction with cube maps 130 Image-based lighting 135 Applying a projected texture 138 Rendering to a texture 143 Chapter 5: Image Processing and Screen Space Techniques 149 Introduction 149 Applying an edge detection filter 150 Applying a Gaussian blur filter 157 Creating a "bloom" effect 164 Using gamma correction to improve image quality 170 Using multisample anti-aliasing 173 Using deferred shading 179 Chapter 6: Using Geometry and Tessellation Shaders 187 Introduction 187 Point sprites with the geometry shader 192 Drawing a wireframe on top of a shaded mesh 198 Drawing silhouette lines using the geometry shader 205 Tessellating a curve 214 Tessellating a 2D quad 220 Tessellating a 3D surface 225 Tessellating based on depth 230 Chapter 7: Shadows 235 Introduction 235 Rendering shadows with shadow maps 236 Anti-aliasing shadow edges with PCF 247 Creating soft shadow edges with random sampling 251 Improving realism with prebaked ambient occlusion 258 ii Table of Contents Chapter 8: Using Noise in Shaders 263 Introduction 263 Creating a noise texture using libnoise 265 Creating a seamless noise texture 269 Creating a cloud-like effect 272 Creating a wood grain effect 275 Creating a disintegration effect 279 Creating a paint-spatter effect 281 Creating a night-vision effect 284 Chapter 9: Animation and Particles 289 Introduction 289 Animating a surface with vertex displacement 290 Creating a particle fountain 293 Creating a particle system using transform feedback 299 Creating a particle system using instanced particles 308 Simulating fire with particles 312 Simulating smoke with particles 314 Index 317 iii Preface The OpenGL Shading Language (GLSL) Version 4.0 brings unprecedented power and flexibility to programmers interested in creating modern, interactive, graphical programs. It allows us to harness the power of modern Graphics Processing Units (GPUs) in a straightforward way by providing a simple, yet powerful, language and API. The OpenGL 4.0 Shading Language Cookbook will provide easy-to-follow examples that start by walking you through the theory and background behind each technique. It then goes on to provide and explain the GLSL and OpenGL code needed to implement them. Beginning through to advanced techniques are presented, including topics such as texturing, screen- space techniques, lighting, shading, tessellation shaders, geometry shaders, and shadows.