Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
OpenGL 4.0 Shading Language Cookbook
OpenGL 4.0 Shading Language Cookbook

OpenGL 4.0 Shading Language Cookbook: With over 60 recipes, this Cookbook will teach you both the elementary and finer points of the OpenGL Shading Language, and get you familiar with the specific features of GLSL 4.0. A totally practical, hands-on guide.

eBook
zł59.99 zł177.99
Paperback
zł221.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

OpenGL 4.0 Shading Language Cookbook

Chapter 2. The Basics of GLSL Shaders

In this chapter, we will cover:

  • Implementing diffuse, per-vertex shading with a single point light source

  • Implementing per-vertex ambient, diffuse, and, specular (ADS) shading

  • Using functions in shaders

  • Implementing two sided shading

  • Implementing flat shading

  • Using subroutines to select shader functionality

  • Discarding fragments to create a perforated look

Introduction


Shaders were first introduced into OpenGL in version 2.0, introducing programmability into the formerly fixed-function OpenGL pipeline. Shaders give us the power to implement alternative rendering algorithms and a greater degree of flexibility in the implementation of those techniques. With shaders, we can run custom code directly on the GPU, providing us with the opportunity to leverage the high degree of parallelism available with modern GPUs.

Shaders are implemented using the OpenGL Shading Language (GLSL). The GLSL is syntactically similar to C, which should make it easier for experienced OpenGL programmers to learn. Due to the nature of this text, I won't present a thorough introduction to GLSL here. Instead, if you're new to GLSL, reading through these recipes should help you to learn the language by example. If you are already comfortable with GLSL, but don't have experience with version 4.0, you'll see how to implement these techniques utilizing the newer API. However...

Implementing diffuse, per-vertex shading with a single point light source


One of the simplest shading techniques is to assume that the surface exhibits purely diffuse reflection. That is to say that the surface is one that appears to scatter light in all directions equally, regardless of direction. Incoming light strikes the surface and penetrates slightly before being re-radiated in all directions. Of course, the incoming light interacts with the surface before it is scattered, causing some wavelengths to be fully or partially absorbed and others to be scattered. A typical example of a diffuse surface is a surface that has been painted with a matte paint. The surface has a dull look with no shine at all.

The following image shows a torus rendered with diffuse shading.

The mathematical model for diffuse reflection involves two vectors: the direction from the surface point to the light source (s), and the normal vector at the surface point (n). The vectors are represented in the following diagram...

Implementing per-vertex ambient, diffuse, and specular (ADS) shading


The OpenGL fixed function pipeline implemented a default shading technique which is very similar to the one presented here. It models the light-surface interaction as a combination of three components: ambient, diffuse, and specular. The ambient component is intended to model light that has been reflected so many times that it appears to be emanating uniformly from all directions. The diffuse component was discussed in the previous recipe, and represents omnidirectional reflection. The specular component models the shininess of the surface and represents reflection around a preferred direction. Combining these three components together can model a nice (but limited) variety of surface types. This shading model is also sometimes called the Phong reflection model (or Phong shading model), after Bui Tuong Phong.

An example of a torus rendered with the ADS shading model is shown in the following screenshot:

The ADS model is...

Using functions in shaders


The GLSL supports functions that are syntactically similar to C functions. However, the calling conventions are somewhat different. In this example, we'll revisit the ADS shader using functions to help provide abstractions for the major steps.

Getting ready

As with previous recipes, provide the vertex position at attribute location 0 and the vertex normal at attribute location 1. Uniform variables for all of the ADS coefficients should be set from the OpenGL side, as well as the light position and the standard matrices.

How to do it...

To implement ADS shading using functions, use the following code:

  1. Use the following vertex shader:

    #version 400
    
    layout (location = 0) in vec3 VertexPosition;
    layout (location = 1) in vec3 VertexNormal;
    
    out vec3 LightIntensity;
    
    struct LightInfo {
        vec4 Position; // Light position in eye coords.
        vec3 La;       // Ambient light intensity
        vec3 Ld;       // Diffuse light intensity
        vec3 Ls;       // Specular light intensity...

Implementing two-sided shading


When rendering a mesh that is completely closed, the back faces of polygons are hidden. However, if a mesh contains holes, it might be the case that the back faces would become visible. In this case, the polygons may be shaded incorrectly due to the fact that the normal vector is pointing in the wrong direction. To properly shade those back faces, one needs to invert the normal vector and compute the lighting equations based on the inverted normal.

The following image shows a teapot with the lid removed. On the left, the ADS lighting model is used. On the right, the ADS model is augmented with the two-sided rendering technique discussed in this recipe.

In this recipe, we'll look at an example that uses the ADS model discussed in the previous recipes, augmented with the ability to correctly shade back faces.

Getting ready

The vertex position should be provided in attribute location 0 and the vertex normal in attribute location 1. As in previous examples, the lighting...

Implementing flat shading


Per-vertex shading involves computation of the shading model at each vertex and associating the result (a color) with that vertex. The colors are then interpolated across the face of the polygon to produce a smooth shading effect. This is also referred to as Gouraud shading . In earlier versions of OpenGL, this per-vertex shading with color interpolation was the default shading technique.

It is sometimes desirable to use a single color for each polygon so that there is no variation of color across the face of the polygon, causing each polygon to have a flat appearance. This can be useful in situations where the shape of the object warrants such a technique, perhaps because the faces really are intended to look flat, or to help visualize the locations of the polygons in a complex mesh. Using a single color for each polygon is commonly called flat shading .

The images below show a mesh rendered with the ADS shading model. On the left, Gouraud shading is used. On the...

Using subroutines to select shader functionality


In GLSL, a subroutine is a mechanism for binding a function call to one of a set of possible function definitions based on the value of a variable. In many ways it is similar to function pointers in C. A uniform variable serves as the pointer and is used to invoke the function. The value of this variable can be set from the OpenGL side, thereby binding it to one of a few possible definitions. The subroutine's function definitions need not have the same name, but must have the same number and type of parameters and the same return type.

Subroutines therefore provide a way to select alternate implementations at runtime without swapping shader programs and/or recompiling, or using if statements along with a uniform variable. For example, a single shader could be written to provide several shading algorithms intended for use on different objects within the scene. When rendering the scene, rather than swapping shader programs (or using a conditional...

Discarding fragments to create a perforated look


Fragment shaders can make use of the discard keyword to "throw away" fragments. Use of this keyword causes the fragment shader to stop execution, without writing anything (including depth) to the output buffer. This provides a way to create holes in polygons without using blending. In fact, since fragments are completely discarded, there is no dependence on the order in which objects are drawn, saving us the trouble of doing any depth sorting that might have been necessary if blending was used.

In this recipe, we'll draw a teapot, and use the discard keyword to remove fragments selectively based on texture coordinates. The result will look like the following image:

Getting ready

The vertex position, normal, and texture coordinates must be provided to the vertex shader from the OpenGL application. The position should be provided at location 0, the normal at location 1, and the texture coordinates at location 2. As in previous examples, the lighting...

Left arrow icon Right arrow icon

Key benefits

  • A full set of recipes demonstrating simple and advanced techniques for producing high-quality, real-time 3D graphics using GLSL 4.0
  • How to use the OpenGL Shading Language to implement lighting and shading techniques
  • Use the new features of GLSL 4.0 including tessellation and geometry shaders
  • How to use textures in GLSL as part of a wide variety of techniques from basic texture mapping to deferred shading
  • Simple, easy-to-follow examples with GLSL source code, as well as a basic description of the theory behind each technique

Description

The OpenGL Shading Language (GLSL) is a programming language used for customizing parts of the OpenGL graphics pipeline that were formerly fixed-function, and are executed directly on the GPU. It provides programmers with unprecedented flexibility for implementing effects and optimizations utilizing the power of modern GPUs. With version 4.0, the language has been further refined to provide programmers with greater flexibility, and additional features have been added such as an entirely new stage called the tessellation shader. The OpenGL Shading Language 4.0 Cookbook provides easy-to-follow examples that first walk you through the theory and background behind each technique then go on to provide and explain the GLSL and OpenGL code needed to implement it. Beginning level through to advanced techniques are presented including topics such as texturing, screen-space techniques, lighting, shading, tessellation shaders, geometry shaders, and shadows. The OpenGL Shading Language 4.0 Cookbook is a practical guide that takes you from the basics of programming with GLSL 4.0 and OpenGL 4.0, through basic lighting and shading techniques, to more advanced techniques and effects. It presents techniques for producing basic lighting and shading effects; examples that demonstrate how to make use of textures for a wide variety of effects and as part of other techniques; examples of screen-space techniques, shadowing, tessellation and geometry shaders, noise, and animation. The OpenGL Shading Language 4.0 Cookbook provides examples of modern shading techniques that can be used as a starting point for programmers to expand upon to produce modern, interactive, 3D computer graphics applications.

Who is this book for?

If you are an OpenGL programmer looking to use the modern features of GLSL 4.0 to create real-time, three-dimensional graphics, then this book is for you. Familiarity with OpenGL programming, along with the typical 3D coordinate systems, projections, and transformations is assumed. It can also be useful for experienced GLSL programmers who are looking to implement the techniques that are presented here.

What you will learn

  • Compile, install, and communicate with shader programs
  • Use new features of GLSL 4.0 such as subroutines and uniform blocks
  • Implement basic lighting and shading techniques such as diffuse and specular shading, per-fragment shading, and spotlights
  • Apply single or multiple textures
  • Use textures as environment maps for simulating reflection or refraction
  • Implement screen-space techniques such as gamma correction, blur filters, and deferred shading
  • Implement geometry and tessellation shaders
  • Learn shadowing techniques including shadow mapping and screen space ambient occlusion
  • Use noise in shaders
  • Use shaders for animation

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 26, 2011
Length: 340 pages
Edition : 1st
Language : English
ISBN-13 : 9781849514774
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jul 26, 2011
Length: 340 pages
Edition : 1st
Language : English
ISBN-13 : 9781849514774
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just zł20 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just zł20 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 641.97
OpenGL 4.0 Shading Language Cookbook
zł221.99
WebGL Beginner's Guide
zł197.99
OpenGL Development Cookbook
zł221.99
Total 641.97 Stars icon
Banner background image

Table of Contents

9 Chapters
Getting Started with GLSL 4.0 Chevron down icon Chevron up icon
The Basics of GLSL Shaders Chevron down icon Chevron up icon
Lighting, Shading Effects, and Optimizations Chevron down icon Chevron up icon
Using Textures Chevron down icon Chevron up icon
Image Processing and Screen Space Techniques Chevron down icon Chevron up icon
Using Geometry and Tessellation Shaders Chevron down icon Chevron up icon
Shadows Chevron down icon Chevron up icon
Using Noise in Shaders Chevron down icon Chevron up icon
Animation and Particles Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4
(10 Ratings)
5 star 50%
4 star 40%
3 star 10%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Marilee Dec 31, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a good book for people familiar with OpenGL but less familiar with the modern versions of OpenGL. This book is particularly useful for OSX users, as OSX requires either the OpenGL 2.1 Compatibility mode or a modern OpenGL 4.1 Core mode. The "Core" version removes a lot of deprecated but useful functions. On the other hand, Linux and Windows programmers tend to have the OpenGL compatibility profile (which allows you to mix and match legacy functions with new ones). I found the examples were well thought out. The chapters build on each other, but each project is useful in its own right, and nicely demonstrates how the chapter's topic can be used in a practical manner. I found this book a great follow-on to Philip Rideout's classic (but slightly dated) iPhone 3D book. Both demonstrate the tools of the trade with artistic and useful examples.
Amazon Verified review Amazon
JamesBedford Jan 09, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Really awesome book and incredibly good value. Makes a change to a lot of the really long OpenGL books because you can find the OpenGL nugget you're interested in learning about or using and read the section on that.My only problem with this book is that the formatting for the Table of Contents could be a LOT better for the Kindle version. Whilst all the hyperlinks will take you directly to wherever you need to go, because this book has a set format for each chapter, the sub-sections for each chapter are repeated over and over again which makes it hard to see what the actual chapter is about. For example,Title1ABC2ABC3ABCIt's hard to see the numbers for all the letters!
Amazon Verified review Amazon
Paul T. Miller Oct 01, 2011
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book covers OpenGL Shading Language Core profile 4 and modern OpenGL usage. It does assume some familiarity with OpenGL and C++, which helps to cut down on a lot of introductory boilerplate. It's best to start reading from the beginning, as examples and recipes build on information from previous chapters and Wolff doesn't waste space repeating the same stuff over and over, which I really appreciated.All of the examples use the newer OpenGL APIs, and there is some basic background information on how to use them. I found this useful for people like me who have been using the fixed-function API for so long. The examples also use OpenGL Mathematics (GLM), an Open Source toolkit for working with OpenGL-style vectors and matrices. I had been unaware of this toolkit, and I'll most likely be switching to it for my next project. Wolff's style is short and to the point and keeps things moving along.The meat of the book are the recipes, covering a wide range of shading topics, including emulating the OpenGL 2.0 fixed function pipeline, image processing, soft shadows, synthetic texture generation, and particle systems. There is a lot of information here and it is well written, though it assumes the reader is not a complete novice. Be warned, this is NOT a book for beginners.I had a couple of minor issues with the book. Most of the examples use C++ and the STL but in a few cases Wolff falls back to using malloc/free for temporary buffers. All of the recipes are based on using geometry, and even in the image processing section it is assumed we'll be processing a 3D scene. It would be nice to have some examples focused entirely on doing 2D image processing of images directly.Those points are very minor though and in all I thought the book was exactly what I needed to bring my skills up to the most recent OpenGL and GLSL standards.
Amazon Verified review Amazon
Sol_HSA Nov 25, 2011
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I got a request from PACKT to review an OpenGL book they've published. It looked like a fun thing to do, so I said okay.First off, this book is perfect for people who already know their way around OpenGL, but may not be too deep into shaders yet, and/or have some legacy bits in their engines.The book does walk you through setting up a shader based application, and explains what kinds of support libraries you're going to need (always managing to pick the "other" lib than the ones I've used - they like glew more than glee, for instance - but the libs they picked still work as advertised, so I'm not saying they're bad choises. Oddly, there's no mention of SDL or SFML though), but knowing how OpenGL generally works as well as how the math generally works is taken for granted.On the positive side you won't have to browse through hundred pages of basic matrix and vector math, or compilation basics, which I feel is a good thing.After the basics the book gets to the fun stuff, explaining lighting, texture use, screen space trickery (like bloom and deferred shading), geometry shaders and tesselation, practical shadows (i.e, shadow mapping and PCT filters, but doesn't waste pages on anything "more advanced"), noise and some particle tricks.All in all I think it's a rather good resource for anyone who wants to upgrade their OpenGL knowledge to more "modern OpenGL", dropping all legacy stuff, but it doesn't mean you don't still have to get your hands on the orange book.
Amazon Verified review Amazon
TechGuyOnAmazon Jan 11, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I found David Wolff's book to be very helpful in learning the foundations of GLSL programming with OpenGL. There are some nice advance techniques covered in this book also. The coding style is good, and the available source code (located on github) was helpful.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.