Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Real-Time 3D Graphics with WebGL 2
Real-Time 3D Graphics with WebGL 2

Real-Time 3D Graphics with WebGL 2: Build interactive 3D applications with JavaScript and WebGL 2 (OpenGL ES 3.0) , Second Edition

Arrow left icon
Profile Icon Farhad Ghayour Profile Icon Diego Cantor
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8 (12 Ratings)
Paperback Oct 2018 500 pages 2nd Edition
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Farhad Ghayour Profile Icon Diego Cantor
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8 (12 Ratings)
Paperback Oct 2018 500 pages 2nd Edition
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Real-Time 3D Graphics with WebGL 2

Rendering

In the previous chapter, we covered the history of WebGL, along with its evolution. We discussed the fundamental elements in a 3D application and how to set up a WebGL context. In this chapter, we will investigate how geometric entities are defined in WebGL.

WebGL renders objects following a "divide and conquer" approach. Complex polygons are decomposed into triangles, lines, and point primitives. Then, each geometric primitive is processed in parallel by the GPU in order to create the final scene.

In this chapter, you will:

  • Understand how WebGL defines and processes geometric information
  • Discuss the relevant API methods that relate to geometry manipulation
  • Examine why and how to use JavaScript Object Notation (JSON) to define, store, and load complex geometries
  • Continue our analysis of WebGL as a state machine to describe the attributes that are relevant...

WebGL Rendering Pipeline

Although WebGL is often thought of as a comprehensive 3D API, it is, in reality, just a rasterization engine. It draws points, lines, and triangles based on the code you supply. Getting WebGL to do anything else requires you to provide code to use points, lines, and triangles to accomplish your task.

WebGL runs on the GPU on your computer. As such, you need to provide code that runs on that GPU. The code should be provided in the form of pairs of functions. Those two functions are known as the vertex shader and fragment shader, and they are each written in a very strictly-typed C/C++-like language called GLSL (GL Shader Language). Together, they are called a program.

GLSL

GLSL is an acronym for the official OpenGL Shading Language. GLSL is a C/C++-like, high-level programming language for several parts of the graphic card. With GLSL, you can code short...

Rendering in WebGL

WebGL handles geometry in a standard way, independent of the complexity and number of points that surfaces can have. There are two data types that are fundamental to represent the geometry of any 3D object: vertices and indices.

Vertices

Vertices are the points that define the corners of 3D objects. Each vertex is represented by three floating-point numbers that correspond to the x, y, and z coordinates of the vertex. Unlike its cousin, OpenGL, WebGL does not provide API methods to pass independent vertices to the rendering pipeline; therefore, all of our vertices need to be written in a JavaScript array, which can then be used to construct a WebGL vertex buffer.

...

Time for Action: Rendering a Square

Follow the given steps:

  1. Open the ch02_01_square.html file in a code editor (ideally one that supports syntax highlighting).
  1. Examine the structure of this file with the help of the following diagram:
  1. The web page contains the following:
  • The <script id="vertex-shader" type="x-shader/x-vertex"> script contains the vertex shader code.
  • The <script id="fragment-shader" type="x-shader/x-fragment"> script contains the fragment shader code. We won't pay attention to these two scripts as they will be the main point of study in the next chapter. For now, simply notice that we have a fragment shader and a vertex shader.
  • The next script on our web page, <script type="text/javascript">, contains all the JavaScript WebGL code that we will need. This script is divided into the...

Vertex Array Objects

Vertex array objects (VAOs) allow you to store all of the vertex/index binding information for a set of buffers in a single, easy to manage object. That is, the state of attributes, which buffers to use for each attribute, and how to pull data out from those buffers, is collected into a VAO. Although we can implement VAOs in WebGL 1 by using extensions, they are available by default in WebGL 2.

This is an important feature that should always be used, since it significantly reduces rendering times. When not using VAOs, all attributes data is in global WebGL state, which means that calling functions such as gl.vertexAttribPointer, gl.enableVertexAttribArray, and gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer) manipulates the global state. This leads to performance loss, because before any draw call, we would need to set up all vertex attributes and set the ELEMENT_ARRAY_BUFFER...

Time for Action: Rendering a Square Using a VAO

Let's refactor a previous example using VAOs:

  1. Open up ch02_01_square.html in your editor.
  2. First, we update our global variables:
// Global variables that are set and used
// across the application
let gl,
program,
squareVAO,
squareIndexBuffer,
indices;
  1. We've replaced squareVertexBuffer with squareVAO, as we no longer need to reference the vertex buffer directly.
  1. Next, we update the initBuffers functions as follows:
// Set up the buffers for the square
function initBuffers() {
/*
V0 V3
(-0.5, 0.5, 0) (0.5, 0.5, 0)
X---------------------X
| |
| |
| (0, 0) |
| |
| |
X---------------------X
V1 V2
(-0.5, -0.5, 0) (0.5, -0.5, 0)
*/
const vertices...

Time for Action: Rendering Modes

Let's revisit the signature of the drawElements function:

gl.drawElements(mode, count, type, offset)

The first parameter determines the type of primitives that we are rendering. In the following section, we will see the different rendering modes with examples.

Follow the given steps:

  1. Open the ch02_04_rendering-modes.html file in your browser. This example follows the same structure as in the previous section.
  2. Open ch02_04_rendering-modes.html in your editor and scroll down to the initBuffers function:
function initBuffers() {
const vertices = [
-0.5, -0.5, 0,
-0.25, 0.5, 0,
0.0, -0.5, 0,
0.25, 0.5, 0,
0.5, -0.5, 0
];

indices = [0, 1, 2, 0, 2, 3, 2, 3, 4];

// Create VAO
trapezoidVAO = gl.createVertexArray();

// Bind VAO
gl.bindVertexArray(trapezoidVAO);

const trapezoidVertexBuffer = gl.createBuffer();
gl.bindBuffer...

WebGL as a State Machine: Buffer Manipulation

When dealing with buffers for the getParameter, getBufferParameter, and isBuffer functions, new information about the state of the rendering pipeline becomes available to us.

Similar to Chapter 1, Getting Started, we will use getParameter(parameter), where parameter can have the following values:

  • ARRAY_BUFFER_BINDING: Retrieves a reference to the currently-bound VBO
  • ELEMENT_ARRAY_BUFFER_BINDING: Retrieves a reference to the currently-bound IBO

We can also query the size and the usage of the currently-bound VBO and IBO using getBufferParameter(type, parameter), where type can have the following values:

  • ARRAY_BUFFER: To refer to the currently-bound VBO
  • ELEMENT_ARRAY_BUFFER: To refer to the currently-bound IBO

And parameter can have the following values:

  • BUFFER_SIZE: Returns the size of the requested buffer
  • BUFFER_USAGE: Returns...

Time for Action: Querying the State of Buffers

Follow the given steps:

  1. Open the ch02_05_state-machine.html file in your browser. You should see the following:
  1. Open ch02_05_state-machine.html in your editor and scroll down to the initBuffers method:
function initBuffers() {
const vertices = [
1.5, 0, 0,
-1.5, 1, 0,
-1.5, 0.809017, 0.587785,
-1.5, 0.309017, 0.951057,
-1.5, -0.309017, 0.951057,
-1.5, -0.809017, 0.587785,
-1.5, -1, 0,
-1.5, -0.809017, -0.587785,
-1.5, -0.309017, -0.951057,
-1.5, 0.309017, -0.951057,
-1.5, 0.809017, -0.587785
];

indices = [
0, 1, 2,
0, 2, 3,
0, 3, 4,
0, 4, 5,
0, 5, 6,
0, 6, 7,
0, 7, 8,
0, 8, 9,
0, 9, 10,
0, 10, 1
];

// Create VAO
coneVAO = gl.createVertexArray();

// Bind VAO
gl.bindVertexArray(coneVAO);

const coneVertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER...

Advanced Geometry-Loading Techniques

So far, we’ve rendered very simple objects. Now, let's investigate how to load a geometry (vertices and indices) from a file instead of declaring the vertices and indices every time we call initBuffers. To do this, we will make asynchronous calls to the web server using AJAX. We will retrieve the file with our geometry from the web server and then use the built-in JSON parser to convert the context of our files into JavaScript objects. In our case, these objects will be the vertices and indices arrays.

Introduction to JavaScript Object Notation (JSON)

JSON stands for JavaScript Object Notation. It is a lightweight, text-based, open format used for data interchange. JSON is commonly...

Time for Action: Encoding and Decoding JSON

Most modern web browsers support native JSON encoding and decoding. Let's examine the methods available inside this object:

Method Description
JSON.stringify(object) We use JSON.stringify to convert JavaScript objects to JSON-formatted text.
JSON.parse(string) We use JSON.parse to convert text into JavaScript objects.

Let's learn how to encode and decode with the JSON notation by creating a simple model—a 3D line. Here, we will be focusing on how we do JSON encoding and decoding. Follow the given steps:

  1. In your browser, open the interactive JavaScript console. Use the following table for assistance:
Browser Shortcut keys (PC/Mac)
Firefox Ctrl + Shift + K/Command + Alt + K
Safari Ctrl + Shift + C/Command + Alt + C
Chrome Ctrl + Shift + J/Command + Alt + J
  1. Create a JSON object by typing the following...

Time for Action: Loading a Cone with AJAX

Follow the given steps:

  1. Make sure that your web server is running and access the ch02_07_ajax-cone.html file using your web server.
Web Server Address

You know that you are using the web server if the URL in the address bar starts with localhost/ or 127.0.0.1/ instead of file://.
  1. The folder containing the code for this chapter should look like this:
  1. Click on ch02_07_ajax-cone.html.
  2. The example will load in your browser and you will see something similar to this:
  1. Please review the load functions to better understand the use of AJAX and JSON in the application.
  2. How is the global model variable used? (Check the source code.)
  3. Check what happens when you change the color in the common/models/geometries/cone.json file and reload the page.
  4. Modify the coordinates of the cone in the common/models/geometries/cone.json file and reload the...

Architecture Updates

Let's cover some useful functions that we can refactor for use in later chapters:

  1. Open common/js/utils.js in your editor to see the following changes.
  2. We have added two additional methods, autoResizeCanvas and getShader, to utils.js that look very similar to the code we implemented earlier in this chapter:
'use strict';

// A set of utility functions for /common operations across our
// application
const utils = {

// Find and return a DOM element given an ID
getCanvas(id) {
// ...
},

// Given a canvas element, return the WebGL2 context
getGLContext(canvas) {
// ...
},

// Given a canvas element, expand it to the size of the window
// and ensure that it automatically resizes as the window changes
autoResizeCanvas(canvas) {
const expandFullScreen = () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight...

Summary

Let’s summarize what we’ve learned in this chapter:

  • The WebGL API itself is just a rasterizer and, conceptually, is fairly simple.
  • WebGL's rendering pipeline describes how the WebGL buffers are used and passed in the form of attributes to be processed by the vertex shader. The vertex shader parallelizes vertex processing in the GPU. Vertices define the surface of the geometry that is going to be rendered. Every element on this surface is known as a fragment. These fragments are processed by the fragment shader.
  • Fragment processing also occurs in parallel in the GPU. When all fragments have been processed, the framebuffer, a two-dimensional array, contains the image that is then displayed on your screen.
  • WebGL is actually a pretty simple API. Its job is to execute two user-supplied functions, a vertex shader and fragment shader, and draw triangles, lines...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Create visually stunning, high-performance 3D applications for the web with WebGL 2
  • A complete course on 3D computer graphics: rendering, 3D math, lighting, cameras, and more
  • Unlock a variety of new and advanced features offered in WebGL 2

Description

As highly interactive applications have become an increasingly important part of the user experience, WebGL is a unique and cutting-edge technology that brings hardware-accelerated 3D graphics to the web. Packed with 80+ examples, this book guides readers through the landscape of real-time computer graphics using WebGL 2. Each chapter covers foundational concepts in 3D graphics programming with various implementations. Topics are always associated with exercises for a hands-on approach to learning. This book presents a clear roadmap to learning real-time 3D computer graphics with WebGL 2. Each chapter starts with a summary of the learning goals for the chapter, followed by a detailed description of each topic. The book offers example-rich, up-to-date introductions to a wide range of essential 3D computer graphics topics, including rendering, colors, textures, transformations, framebuffers, lights, surfaces, blending, geometry construction, advanced techniques, and more. With each chapter, you will "level up" your 3D graphics programming skills. This book will become your trustworthy companion in developing highly interactive 3D web applications with WebGL and JavaScript.

Who is this book for?

This book is intended for developers who are interested in building highly interactive 3D applications for the web. A basic understanding of JavaScript is necessary; no prior computer graphics or WebGL knowledge is required.

What you will learn

  • Understand the rendering pipeline provided in WebGL
  • Build and render 3D objects with WebGL
  • Develop lights using shaders, 3D math, and the physics of light reflection
  • Create a camera and use it to navigate a 3D scene
  • Use texturing, lighting, and shading techniques to render realistic 3D scenes
  • Implement object selection and interaction in a 3D scene
  • Cover advanced techniques for creating immersive and compelling scenes
  • Learn new and advanced features offered in WebGL 2

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 31, 2018
Length: 500 pages
Edition : 2nd
Language : English
ISBN-13 : 9781788629690
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Oct 31, 2018
Length: 500 pages
Edition : 2nd
Language : English
ISBN-13 : 9781788629690
Languages :
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 $5 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 $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 155.97
OpenGL 4 Shading Language Cookbook
$48.99
Real-Time 3D Graphics with WebGL 2
$48.99
Learn Three.js
$57.99
Total $ 155.97 Stars icon
Banner background image

Table of Contents

13 Chapters
Getting Started Chevron down icon Chevron up icon
Rendering Chevron down icon Chevron up icon
Lights Chevron down icon Chevron up icon
Cameras Chevron down icon Chevron up icon
Animations Chevron down icon Chevron up icon
Colors, Depth Testing, and Alpha Blending Chevron down icon Chevron up icon
Textures Chevron down icon Chevron up icon
Picking Chevron down icon Chevron up icon
Putting It All Together Chevron down icon Chevron up icon
Advanced Techniques Chevron down icon Chevron up icon
WebGL 2 Highlights Chevron down icon Chevron up icon
Journey Ahead Chevron down icon Chevron up icon
Other Books You May Enjoy 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.8
(12 Ratings)
5 star 83.3%
4 star 8.3%
3 star 8.3%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Joseph Nov 12, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
A very good introduction to the world of graphics thru WebGL 2. What I like most is that each chapter is packed with hands-on examples which in my opinion is the best way to learn. This book teaches the fundamentals of 3D graphics like perspective, lighting and textures in the context of WebGL so it's great for people who are just getting started with both of those things. The "car showroom" example is a particularly awesome one!
Amazon Verified review Amazon
Amazon Customer Nov 18, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book allowed me to embrace a concept that will truley reshape the way we use the web!
Amazon Verified review Amazon
Love Amazon Nov 13, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great read and help to the animation help I needed!
Amazon Verified review Amazon
Why Nov 13, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very informative and easy to read.I've been wanting to learn 3D graphics programming for a long time and I started here. This book is an excellent guide through the complexities. It provides a deep dive into 3D programming. My favorite aspect was the double click into building a 3D model. The author really takes a design thinking approach to learning a new skill.One thing I would change is to have more modest car choices when building the 3D model such as a Pagani.I learned, I laughed, I cried, I bled. It was a journey to remember.Couldn't get npm install to work
Amazon Verified review Amazon
Raj Feb 11, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Just as with most all tech books, there are errors, but references are provided. The major project theme is about creating an auto showroom. You will need a web server, suggestions for downloading one is provided.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.