35,99 €
Animation is one of the most important parts of any game. Modern animation systems work directly with track-driven animation and provide support for advanced techniques such as inverse kinematics (IK), blend trees, and dual quaternion skinning.
This book will walk you through everything you need to get an optimized, production-ready animation system up and running, and contains all the code required to build the animation system. You’ll start by learning the basic principles, and then delve into the core topics of animation programming by building a curve-based skinned animation system. You’ll implement different skinning techniques and explore advanced animation topics such as IK, animation blending, dual quaternion skinning, and crowd rendering. The animation system you will build following this book can be easily integrated into your next game development project. The book is intended to be read from start to finish, although each chapter is self-contained and can be read independently as well.
By the end of this book, you’ll have implemented a modern animation system and got to grips with optimization concepts and advanced animation techniques.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 412
Veröffentlichungsjahr: 2020
Learn modern animation techniques from theory to implementation with C++ and OpenGL
Gabor Szauer
BIRMINGHAM—MUMBAI
Copyright © 2020 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 or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.
Commissioning Editor: Pavan Ramchandani
Acquisition Editor: Ashwin Nair
Senior Editor: Hayden Edwards
Content Development Editor: Akhil Nair, Aamir Ahmed
Technical Editor: Deepesh Patel
Copy Editor: Safis Editing
Project Coordinator: Kinjal Bari
Proofreader: Safis Editing
Indexer: Pratik Shirodkar
Production Designer: Jyoti Chauhan
First published: June 2020
Production reference: 1110620
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80020-808-7
www.packt.com
Packt.com
Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
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 packt.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.packt.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.
Gabor Szauer has been making games since 2010. He graduated from Full Sail University in 2010 with a bachelor's degree in game development. Gabor maintains an active Twitter presence, @gszauer, and maintains a programming-oriented game development blog: gabormakesgames.com. Gabor's previously published books are Game Physics Programming Cookbook and Lua Quick Start Guide, both published by Packt.
Pedro Sousa is your typical software engineer by day, but at night he goes by the name SketchPunk as he develops various open source projects – basically whatever tickles his fancy at any given moment. Being self-taught in many areas of software development and having a pure love of art has given him a good amount of success in his career since he's able to balance writing good software with splashing a beautiful coat of paint over it.
In the last 3 years, Pedro has spent a great deal of time developing a game engine from scratch and, along the way, creating YouTube tutorials of all the nuts and bolts so that others can learn and follow in his footsteps. He has a strong belief that knowledge should be free and shared with all who want to learn.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Modern game animation is a bit of a black art. There are not many resources available that detail how to build a track-driven animation system, or advanced topics such as dual quaternion skinning. That is the void this book aims to fill. The goal of this book is to shed some light on the black art of animation programming and make the topic approachable for everyone.
This book takes a "theory to implementation" approach, where you will learn the theory of each topic discussed first. Once you understand the theory, you will implement it to get hands-on experience.
This book makes it a point to focus on the concepts and implementation details of animation programming, not the language or graphics API being used. By focusing on these fundamental concepts, you will be able to implement an animation system regardless of language or graphics API.
This book is for programmers who want to learn how to build a modern animation system. The only requirement for following along with this book is some familiarity with C++. Other than that, everything is covered, from how to open a new window, to creating an OpenGL context, rendering an animated model, and advanced animation techniques.
Chapter 1, Creating a Game Window, explains how to create a new visual studio project, create a Win32 window, set up an OpenGL 3.3 render context, and enable vsynch. The code samples for this book are compiled against OpenGL 3.3. All the OpenGL code is compatible with the latest version of OpenGL and OpenGL 4.6.
Chapter 2, Implementing Vectors, covers vector math for game animation programming.
Chapter 3, Implementing Matrices, discusses matrix math for game animation programming.
Chapter 4, Implementing Quaternions, explains how to use quaternion math for game animation programming.
Chapter 5, Implementing Transforms, explains how to combine position, rotation, and scale into a transform object. These transform objects can be arranged in a hierarchy.
Chapter 6, Building an Abstract Renderer, shows you how to create an abstraction layer on top of OpenGL 3.3. The rest of this book will use this abstraction for rendering. By using an abstraction, we can focus on the core concepts of animation programming instead of the API being used to implement it. The abstraction layer targets OpenGL 3.3, but the code is valid with OpenGL 4.6 as well.
Chapter 7, Understanding the glTF File Format, introduces the glTF file format. glTF is a standard open file format that is supported by most 3D content creation tools. Being able to load a common format will let you load animation authored in almost any creation tool.
Chapter 8 Creating Curves, Frames, and Tracks, covers how to interpolate curves and how cruces can be used to animate transforms stored in a hierarchy.
Chapter 9, Implementing Animation Clips, explains how to implement animation clips. Animation clips modify a transform hierarchy over time.
Chapter 10, Mesh Skinning, covers how to deform a mesh so that it matches the pose generated by sampling an animation clip.
Chapter 11, Optimizing the Animation Pipeline, shows you how to optimize parts of the animation pipeline to make it faster and more production-ready.
Chapter 12, Blending between Animations, explains how to blend two animated poses together. This technique can be used to switch between two animations smoothly, without any visual popping.
Chapter 13, Implementing Inverse Kinematics, covers how to use inverse kinematics to make animations interact with the environment. For example, you'll learn how to make an animated character's foot not penetrate the ground on uneven terrain.
Chapter 14, Using Dual Quaternions for Skinning, covers dual quaternion math for game animation. Dual quaternions can be used to avoid pinching at animated joints.
Chapter 15, Rendering Instanced Crowds, shows how to encode animation data to a texture and move pose generation into a vertex shader. You will use this technique to render a large crowd using instancing.
To get the most out of this book, some experience with C++ is expected. You don’t have to be a hardened C++ master, but you should be able to debug simple C++ problems. Having some experience with OpenGL is a plus, but not required. No advanced C++ features are used. The provided code compiles against C++ 11 or the most recent version.
The code in this book is written against OpenGL 3.3 Core. The OpenGL code presented in this book is forward compatible; the highest compatible version of OpenGL at the time of publishing is 4.6. In Chapter 6, Building an Abstract Renderer, you will implement a thin abstraction layer on top of OpenGL. Throughout the rest of the book, you will be coding against this abstraction layer, rather than OpenGL directly.
The code presented should compile and run on just about any laptop running Windows 10 or a more recent version. The only hardware requirement to follow along with this book is access to a computer that can run Visual Studio 2019 or a more recent version.
The minimum hardware requirements for Visual Studio 2019 are:
Windows 10, version 1703 or higher1.8 Ghz or a faster processor2GB of RAMThese requirements can be found online at: https://docs.microsoft.com/en-us/visualstudio/releases/2019/system-requirements
Download the example code files
You can download the example code files for this book from your account at http://www.packt.com. If you purchased this book elsewhere, you can visit http://www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at http://www.packt.com.Select the SUPPORT tab.Click on Code Downloads & Errata.Enter the name of the book in the Search box and follow the on-screen instructions.Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for WindowsZipeg/iZip / UnRarX for Mac7-Zip/PeaZip for LinuxThe code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Game-Animation-Programming. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example; "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."
A block of code is set as follows:
public:
Pose();
Pose(const Pose& p);
Pose& operator=(const Pose& p);
Pose(unsigned int numJoints);
Any command-line input or output is written as follows:
# cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample
/etc/asterisk/cdr_mysql.conf
Bold: Indicates a new term, an important word, or words that you see on the screen, for example, in menus or dialog boxes, also appear in the text like this. For example: "Select System info from the Administration panel."
Note
Warnings or important notes appear like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Get in touch with the author: The best way to get in touch with Gabor, the book's author, is on Twitter: @gszauer.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit, http://www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
In this chapter, you will learn the basics of vector math. Much of what you will code throughout the rest of this book relies on having a strong understanding of vectors. Vectors will be used to represent displacement and direction.
By the end of this chapter, you will have implemented a robust vector library and will be able to perform a variety of vector operations, including component-wise and non-component-wise operations.
We will cover the following topics in this chapter:
Introducing vectorsCreating a vectorUnderstanding component-wise operationsUnderstanding non-component-wise operationsInterpolating vectorsComparing vectorsExploring more vectorsImportant information:
In this chapter, you will learn how to implement vectors in an intuitive, visual way that relies on code more than math formulas. If you are interested in math formulas or want some interactive examples to try out, go to https://gabormakesgames.com/vectors.html.
What is a vector? A vector is an n-tuple of numbers. It represents a displacement measured as a magnitude and a direction. Each element of a vector is usually expressed as a subscript, such as (V0, V1, V2, … VN). In the context of games, vectors usually have two, three, or four components.
For example, a three-dimensional vector measures displacement on three unique axes: x, y, and z. Elements of vectors are often subscripted with the axis they represent, rather than an index. (VX, VY, VZ) and (V0, V1, V2) are used interchangeably.
When visualizing vectors, they are often drawn as arrows. The position of the base of an arrow does not matter because vectors measure displacement, not a position. The end of the arrow follows the displacement of the arrow on each axis.
For example, all of the arrows in the following figure represent the same vector:
Figure 2.1: Vector (2, 5) drawn in multiple locations
Each arrow has the same length and points in the same direction, regardless of where it is positioned. In the next section, you will start to implement the vector structure that will be used throughout the rest of this book.
Vectors will be implemented as structures, not classes. The vector struct will contain an anonymous union that allows the vector's components to be accessed as an array or as individual elements.
To declare the vec3 structure and the function headers, create a new file, vec3.h. Declare the new vec3 structure in this file. The vec3 struct needs three constructors—a default constructor, one that takes each component as an element, and one that takes a pointer to a float array:
#ifndef _H_VEC3_
#define _H_VEC3_
struct vec3 {
union {
struct {
float x;
float y;
float z;
};
float v[3];
};
inline vec3() : x(0.0f), y(0.0f), z(0.0f) { }
inline vec3(float _x, float _y, float _z) :
x(_x), y(_y), z(_z) { }
inline vec3(float *fv) :
x(fv[0]), y(fv[1]), z(fv[2]) { }
};
#endif
The anonymous union in the vec3 struct allows data to be accessed using .x, .y, and .z notation, or as a contiguous array using .v. Before moving on to implementing functions that work on the vec3 struct, you need to consider comparing floating point numbers and whether or not to use an epsilon value.
Comparing floating point numbers is difficult. Instead of comparing two floating point numbers directly, you need to compare them using an epsilon. An epsilon is an arbitrarily small positive number that is the minimum difference two numbers need to have to be considered different numbers. Declare an epsilon constant in vec3.h:
#define VEC3_EPSILON 0.000001f
Important note:
You can learn more about floating point comparison at https://bitbashing.io/comparing-floats.html
With the vec3 structure created and the vec3 epsilon defined, you are ready to start implementing some common vector operations. In the next section, you're going to start by learning and implementing several component-wise operations.
Several vector operations are just component-wise operations. A component-wise operation is one that you perform on each component of a vector or on like components of two vectors. Like components are components that have the same subscript. The component-wise operations that you will implement are as follows:
Vector additionVector subtractionVector scalingMultiplying vectorsDot productLet's look at each of these in more detail.
Adding two vectors together yields a third vector, which has the combined displacement of both input vectors. Vector addition is a component-wise operation; to perform it, you need to add like components.
To visualize the addition of two vectors, draw the base of the second vector at the tip of the first vector. Next, draw an arrow from the base of the first vector to the tip of the second vector. This arrow represents the vector that is the result of the addition:
Figure 2.2: Vector addition
To implement vector addition in code, add like components of the input vectors. Create a new file, vec3.cpp. This is where you will define functions related to the vec3 struct. Don't forget to include vec3.h. Overload the + operator to perform vector addition. Don't forget to add the function signature to vec3.h:
vec3 operator+(const vec3 &l, const vec3 &r) {
return vec3(l.x + r.x, l.y + r.y, l.z + r.z);
}
When thinking about vector addition, remember that a vector represents a displacement. When adding two vectors, the result is the combined displacement of both input vectors.
As with adding vectors, subtracting vectors is also a component-wise operation. You can think of subtracting vectors as adding the negative of the second vector to the first vector. When visualized as an arrow, subtraction points from the tip of the second vector to the tip of the first one.
To visually subtract vectors, place both vectors so they share the same origin. Draw a vector from the tip of the second arrow to the tip of the first one. The resulting arrow is the subtraction result vector:
Figure 2.3: Vector subtraction
To implement vector subtraction, subtract like components. Implement the subtraction function by overloading the - operator in vec3.cpp. Don't forget to add the function declaration to vec3.h:
vec3 operator-(const vec3 &l, const vec3 &r) {
return vec3(l.x - r.x, l.y - r.y, l.z - r.z);
}
The steps and logic are very similar to vector addition. It might help to think of vector subtraction as adding a negative vector.
When a vector is scaled, it only changes in magnitude, not direction. As with addition and subtraction, scaling is a component-wise operation. Unlike addition and subtraction, a vector is scaled by a scalar, not another vector.
Visually, a scaled vector points in the same direction as the original vector, but it has a different length. The following figure shows two vectors: (2, 1) and (2, 4). Both vectors share the same direction, but the magnitude of the second vector is longer:
Figure 2.4: Vector scaling
To implement vector scaling, multiply every component of the vector by the given scalar value.
Implement the scale function by overloading the * operator in vec3.cpp. Don't forget to add the function declaration to vec3.h:
vec3 operator*(const vec3 &v, float f) {
return vec3(v.x * f, v.y * f, v.z * f);
}
Negating a vector can be done by scaling the vector by -1. When negating a vector, the vector maintains its magnitude but changes its direction.
Vector multiplication can be considered a