3D Math Primer for Graphics and Game Development
Second Edition
Fletcher Dunn
Ian Parberry
A K Peters/CRC Press Taylor & Francis Group
6000 Broken Sound Parkway NW, Suite 300 Boca Raton, FL 33487-2742
© 2011 by Taylor and Francis Group, LLC
A K Peters/CRC Press is an imprint of Taylor & Francis Group, an Informa business No claim to original U.S. Government works
International Standard Book Number-13: 978-1-4398-6981-9 (eBook - PDF)
This book contains information obtained from authentic and highly regarded sources. Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright holders of all material reproduced in this publication and apologize to copyright holders if permission to publish in this form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and recording, or in any information storage or retrieval system, without written permission from the publishers.
For permission to photocopy or use material electronically from this work, please access www.copyright.com (http://www.copyright.com/) or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-750-8400. CCC is a not-for-profit organization that provides licenses and registration for a variety of users. For organizations that have been granted a photocopy license by the CCC, a separate system of payment has been arranged.
Trademark Notice: Product or corporate names may be trademarks or registered trademarks, and are used only for identification and explanation without intent to infringe.
Visit the Taylor & Francis Web site at http://www.taylorandfrancis.com and the A K Peters Web site at http://www.akpeters.com
To A’me
—F.D.
To Maggie
in the hope that she continues her interest in math
—I. P.
Contents
Acknowledgments xiii
Introduction xv
1 Cartesian Coordinate Systems 1
1.1 1D Mathematics . . . . 2
1.2 2D Cartesian Space . . . . 5
1.3 3D Cartesian Space . . . . 12
1.4 Odds and Ends . . . . 19
1.5 Exercises . . . . 27
2 Vectors 31 2.1 Mathematical Definition of Vector, and Other Boring Stuff 32 2.2 Geometric Definition of Vector . . . . 34
2.3 Specifying Vectors with Cartesian Coordinates . . . . . 36
2.4 Vectors versus Points . . . . 39
2.5 Negating a Vector . . . . 43
2.6 Vector Multiplication by a Scalar . . . . 45
2.7 Vector Addition and Subtraction . . . . 47
2.8 Vector Magnitude (Length) . . . . 51
2.9 Unit Vectors . . . . 53
2.10 The Distance Formula . . . . 55
2.11 Vector Dot Product . . . . 56
2.12 Vector Cross Product . . . . 66
2.13 Linear Algebra Identities . . . . 70
2.14 Exercises . . . . 71
3 Multiple Coordinate Spaces 79 3.1 Why Bother with Multiple Coordinate Spaces? . . . . . 80
3.2 Some Useful Coordinate Spaces . . . . 81
3.3 Basis Vectors and Coordinate Space Transformations . . 86
3.4 Nested Coordinate Spaces . . . . 106
vii
viii
Contents
3.5 In Defense of Upright Space . . . . 108
3.6 Exercises . . . . 109
4 Introduction to Matrices 113 4.1 Mathematical Definition of Matrix . . . . 113
4.2 Geometric Interpretation of Matrix . . . . 124
4.3 The Bigger Picture of Linear Algebra . . . . 130
4.4 Exercises . . . . 132
5 Matrices and Linear Transformations 137 5.1 Rotation . . . . 138
5.2 Scale . . . . 144
5.3 Orthographic Projection . . . . 148
5.4 Reflection . . . . 151
5.5 Shearing . . . . 152
5.6 Combining Transformations . . . . 153
5.7 Classes of Transformations . . . . 154
5.8 Exercises . . . . 159
6 More on Matrices 161 6.1 Determinant of a Matrix . . . . 161
6.2 Inverse of a Matrix . . . . 168
6.3 Orthogonal Matrices . . . . 171
6.4 4 × 4 Homogeneous Matrices . . . . 176
6.5 4 × 4 Matrices and Perspective Projection . . . . 183
6.6 Exercises . . . . 189
7 Polar Coordinate Systems 191 7.1 2D Polar Space . . . . 191
7.2 Why Would Anybody Use Polar Coordinates? . . . . 201
7.3 3D Polar Space . . . . 203
7.4 Using Polar Coordinates to Specify Vectors . . . . 213
7.5 Exercises . . . . 214
8 Rotation in Three Dimensions 217 8.1 What Exactly is “Orientation”? . . . . 218
8.2 Matrix Form . . . . 220
8.3 Euler Angles . . . . 229
8.4 Axis-Angle and Exponential Map Representations . . . . 244
8.5 Quaternions . . . . 246
8.6 Comparison of Methods . . . . 273
8.7 Converting between Representations . . . . 275
8.8 Exercises . . . . 291
Contents
ix9 Geometric Primitives 295
9.1 Representation Techniques . . . . 295
9.2 Lines and Rays . . . . 297
9.3 Spheres and Circles . . . . 303
9.4 Bounding Boxes . . . . 304
9.5 Planes . . . . 311
9.6 Triangles . . . . 317
9.7 Polygons . . . . 332
9.8 Exercises . . . . 339
10 Mathematical Topics from 3D Graphics 343 10.1 How Graphics Works . . . . 345
10.2 Viewing in 3D . . . . 362
10.3 Coordinate Spaces . . . . 369
10.4 Polygon Meshes . . . . 381
10.5 Texture Mapping . . . . 393
10.6 The Standard Local Lighting Model . . . . 396
10.7 Light Sources . . . . 414
10.8 Skeletal Animation . . . . 424
10.9 Bump Mapping . . . . 431
10.10 The Real-Time Graphics Pipeline . . . . 438
10.11 Some HLSL Examples . . . . 457
10.12 Further Reading . . . . 475
10.13 Exercises . . . . 476
11 Mechanics 1: Linear Kinematics and Calculus 479 11.1 Overview and Other Expectation-Reducing Remarks . . 479
11.2 Basic Quantities and Units . . . . 483
11.3 Average Velocity . . . . 486
11.4 Instantaneous Velocity and the Derivative . . . . 490
11.5 Acceleration . . . . 513
11.6 Motion under Constant Acceleration . . . . 516
11.7 The Integral . . . . 530
11.8 Uniform Circular Motion . . . . 542
11.9 Exercises . . . . 549
12 Mechanics 2: Linear and Rotational Dynamics 553 12.1 Newton’s Three Laws . . . . 554
12.2 Some Simple Force Laws . . . . 562
12.3 Momentum . . . . 581
12.4 Impulsive Forces and Collisions . . . . 590
12.5 Rotational Dynamics . . . . 603
12.6 Real-Time Rigid Body Simulators . . . . 621
x
Contents
12.7 Suggested Reading . . . . 639
12.8 Exercises . . . . 640
13 Curves in 3D 645 13.1 Parametric Polynomial Curves . . . . 646
13.2 Polynomial Interpolation . . . . 653
13.3 Hermite Curves . . . . 665
13.4 B´ezier Curves . . . . 670
13.5 Subdivision . . . . 685
13.6 Splines . . . . 690
13.7 Hermite and B´ezier Splines . . . . 694
13.8 Continuity . . . . 697
13.9 Automatic Tangent Control . . . . 702
13.10 Exercises . . . . 711
14 Afterword 715 14.1 What Next? . . . . 715
14.2 Exercises . . . . 715
A Geometric Tests 717 A.1 Closest Point on 2D Implicit Line . . . . 717
A.2 Closest Point on a Parametric Ray . . . . 718
A.3 Closest Point on a Plane . . . . 719
A.4 Closest Point on a Circle or Sphere . . . . 719
A.5 Closest Point in an AABB . . . . 720
A.6 Intersection Tests . . . . 720
A.7 Intersection of Two Implicit Lines in 2D . . . . 721
A.8 Intersection of Two Rays in 3D . . . . 722
A.9 Intersection of a Ray and Plane . . . . 724
A.10 Intersection of an AABB and Plane . . . . 725
A.11 Intersection of Three Planes . . . . 726
A.12 Intersection of Ray and a Circle or Sphere . . . . 727
A.13 Intersection of Two Circles or Spheres . . . . 729
A.14 Intersection of a Sphere and AABB . . . . 731
A.15 Intersection of a Sphere and a Plane . . . . 732
A.16 Intersection of a Ray and a Triangle . . . . 734
A.17 Intersection of Two AABBs . . . . 737
A.18 Intersection of a Ray and an AABB . . . . 740
B Answers to the Exercises 745 B.1 Chapter 1 . . . . 745
B.2 Chapter 2 . . . . 746
B.3 Chapter 3 . . . . 758
Contents
xiB.4 Chapter 4 . . . . 759
B.5 Chapter 5 . . . . 763
B.6 Chapter 6 . . . . 765
B.7 Chapter 7 . . . . 767
B.8 Chapter 8 . . . . 772
B.9 Chapter 9 . . . . 774
B.10 Chapter 10 . . . . 779
B.11 Chapter 11 . . . . 781
B.12 Chapter 12 . . . . 784
B.13 Chapter 13 . . . . 792
B.14 Chapter 14 . . . . 799
Bibliography 801
Index 807
So much time, and so little to do!
Strike that, reverse it.
— Willy Wonka
Acknowledgments
Fletcher would like to thank his wife, A’me, who endured the absolute eternity that it took to produce this book, and his general tendency to generate lots of interesting ideas for large-scale projects that are initiated and then dropped a quarter of the way through. (No more gigantic projects for at least two or three weeks, I promise!)
Ian would like to thank his wife and children for not whining too loudly, and Fletcher for putting up with his procrastination. He would also like to thank Douglas Adams for the herring sandwich scoop, the bowl of petu- nias, and countless other references to the Hitchhiker’s Guide to the Galaxy trilogy that you will find in this book.
Mike Pratcher gets a very huge thanks for his detailed and knowledgable critique, and for writing a very large portion of the exercises. Matt Carter made the robot and kitchen and agreed to numerous requests to pose the robot one way or another. Thanks to Glenn Gamble for the dead sheep.
Eric Huang created the cover illustration and all other 2D artwork that required any artistic talent whatsoever. (The authors made the rest.) Pavel Krajcevski provided helpful criticism.
Gratitude is merely the secret hope of further favors.
— Francois de La Rochefoucauld (1613–1680)
Always look and smell your best.
— Riley Dunn (1945–)
xiii
Introduction
First things first, but not necessarily in that order.
— Doctor Who from Meglos (1980)
Who Should Read This Book
This book is about 3D math, the geometry and algebra of 3D space. It is designed to teach you how to describe objects and their positions, ori- entations, and trajectories in 3D using mathematics. This is not a book about computer graphics, simulation, or even computational geometry, al- though if you plan on studying those subjects, you will definitely need the information here.
This is not just a book for video game programmers. We do assume that a majority of our readers are learning for the purpose of programming video games, but we expect a wider audience and we have designed the book with a diverse audience in mind. If you’re a programmer or interested in learning how to make video games, welcome aboard! If you meet neither of these criteria, there’s still plenty for you here. We have made every effort to make the book useful to designers and technical artists. Although there are several code snippets in the book, they are (hopefully) easy to read even for nonprogrammers. Most important, even though it is always necessary to understand the surrounding concepts to make sense of the code, the reverse is never true. We use code samples to illustrate how ideas can be implemented on a computer, not to explain the ideas themselves.
The title of this book says it is for “game development,” but a great deal of the material that we cover is applicable outside of video games.
Practically anyone who wants to simulate, render, or understand a three- dimensional world will find this book useful. While we do try to provide motivating examples from the world of video game development, since that is our area of expertise and also our primary target audience, you won’t be left out if the last game you completed was Space Quest.
1If your interests
1Well, you may be left out of a few jokes, like that one. Sorry.
xv
xvi
Introduction
lie in more “grown up” things than video games, rest assured that this book is not filled with specific examples from video games about head-shots or severed limbs or how to get the blood spurt to look just right.
Why You Should Read This Book
This book has many unique features, including its topic, approach, authors, and writing style.
Unique topic. This book fills a gap that has been left by other books on graphics, linear algebra, simulation, and programming. It’s an introductory book, meaning we have focused our efforts on providing thorough coverage on fundamental 3D concepts—topics that are normally glossed over in a few quick pages or relegated to an appendix in other books (because, af- ter all, you already know all this stuff). We have found that these very topics are often the sticking points for beginners! In a way, this book is the mirror image of gluing together books on graphics, physics, and curves.
Whereas that mythical conglomeration would begin with a brief overview of the mathematical fundamentals, followed by in-depth coverage of the appli- cation area, we start with a thorough coverage of the math fundamentals, and then give compact, high-level overviews of the application areas.
This book does try to provide a graceful on-ramp for beginners, but that doesn’t mean we’ll be stuck in the slow lane forever. There is plenty of material here that is traditionally considered “advanced” and taught in upper-level or graduate classes. In reality, these topics are specialized more than they are difficult, and they have recently become important prerequisites that need to be taught earlier, which is part of what has driven the demand for a book like this.
Unique approach. All authors think that they strike the perfect balance
between being pedantic and being chatty in order to best reach their au-
dience, and we are no exception. We recognize, however, that the people
who disagree with this glowing self-assessment will mostly find this book
too informal (see the index entry for “stickler alert”). We have focused on
perspicuous explanations and intuition, and sometimes we have done this
at the expense of rigor. Our aim is to simplify, but not to oversimplify. We
lead readers to the goal through a path that avoids the trolls and dragons,
so why begin the journey by pointing them all out before we’ve even said
what our destination is or why we’re going there? However, since we know
readers will be crossing the field on their own eventually, after we reach our
goal we will turn around to point out where the dangers lie. But we may
sometimes need to leave certain troll-slaying to another source, especially if
Introduction
xviiwe expect that your usual path won’t take you near the danger. Those who intend to be on that land frequently should consult with a local for more intimate knowledge. This is not to say that we think rigor is unimportant;
we just think it’s easier to get rigor after intuition about the big picture has been established, rather than front-loading every discussion with defi- nitions and axioms needed to handle the edge cases. Frankly, nowadays a reader can pursue concise and formal presentations free on wikipedia.org or Wolfram MathWorld (mathworld.wolfram.com), so we don’t think any book offers much worth paying for by dwelling excessively on definitions, axioms, proofs, and edge cases, especially for introductory material targeted primarily to engineers.
Unique authors. Our combined experience brings together academic au- thority with in-the-trenches practical advice. Fletcher Dunn has 15 years of professional game programming experience, with around a dozen titles under his belt on a variety of gaming platforms. He worked at Terminal Reality in Dallas, where as principal programmer he was one of the archi- tects of the Infernal engine and lead programmer on BloodRayne. He was a technical director for The Walt Disney Company at Wideload Games in Chicago and the lead programmer for Disney Guilty Party, IGN’s E3 2010 Family Game of the Year. He now works for Valve Software in Bellevue, Washington. But his biggest claim to fame by far is as the namesake of Corporal Dunn from Call of Duty: Modern Warfare 2.
Dr. Ian Parberry has more than a quarter century of experience in re- search and teaching in academia. This is his sixth book, his third on game programming. He is currently a tenured full professor in the Department of Computer Science & Engineering at the University of North Texas. He is nationally known as one of the pioneers of game programming in higher ed- ucation, and has been teaching game programming classes at the University of North Texas continuously since 1993.
Unique writing style. We hope you will enjoy reading this math book (say what?) for two reasons. Most important, we want you to learn from this book, and learning something you are interested in is fun. Secondarily, we want you to enjoy reading this book in the same way that you enjoy reading a work of literature. We have no delusions that we’re in the same class as Mark Twain, or that this book is destined to become a classic like, say, The Hitchhikers Guide to the Galaxy. But one can always have aspirations.
Honestly, we are just silly people. At the same time, no writing style should stand in the way of the first priority: clear communication of mathematical knowledge about video games.
22Which is why we’ve put most of the jokes and useless trivia in footnotes like this.
Somehow, we felt like we could get away with more that way.
xviii
Introduction
What You Should Know before Reading This Book
We have tried to make the book accessible to as wide an audience as pos- sible; no book, however, can go back all the way to first principles. We expect from the reader the following basic mathematical skills:
• Manipulating algebraic expressions, fractions, and basic algebraic laws such as the associative and distributive laws and the quadratic equa- tion.
• Understanding what variables are, what a function is, how to graph a function, and so on.
• Some very basic 2D Euclidian geometry, such as what a point is, what a line is, what it means for lines to be parallel and perpendicular, and so forth. Some basic formulas for area and circumference are used in a few places. It’s OK if you have temporarily forgotten those—you will hopefully recognize them when you see them.
• Some prior exposure to trigonometry is best. We give a brief review of trigonometry in the front of this book, but it is not presented with the same level of paced explanation found most elsewhere in this book.
• Readers with some prior exposure to calculus will have an advan- tage, but we have restricted our use of calculus in this book to very basic principles, which we will (attempt to) teach in Chapter 11 for those without this training. Only the most high-level concepts and fundamental laws are needed.
Some programming knowledge is helpful, but not required. In several places, we give brief code snippets to show how the ideas being discussed get translated into code. (Also certain procedures are just easier to explain in code.) These snippets are extremely basic, well commented, and require only the most rudimentary understanding of C language syntax (which has been copied to several other languages). Most technical artists or level designers should be able to interpret these snippets with ease.
Overview
• Chapter 1 gets warmed up with some groundwork that it is needed in
the rest of the book and which you probably already know. It reviews
the Cartesian coordinate system in 2D and 3D and discusses how to
use the Cartesian coordinate system to locate points in space. Also
included is a very quick refresher on trigonometry and summation
notation.
Introduction
xix• Chapter 2 introduces vectors from a mathematical and geometric per- spective and investigates the important relationship between points and vectors. It also discusses a number of vector operations, how to do them, what it means geometrically to do them, and situations for which you might find them useful.
• Chapter 3 discusses examples of coordinate spaces and how they are nested in a hierarchy. It also introduces the central concepts of basis vectors and coordinate-space transformations.
• Chapter 4 introduces matrices from a mathematical and geometric perspective and shows how matrices are a compact notation for the math behind linear transformations.
• Chapter 5 surveys different types of linear transformations and their corresponding matrices in detail. It also discusses various ways to classify transformations.
• Chapter 6 covers a few more interesting and useful properties of matri- ces, such as affine transforms and perspective projection, and explains the purpose and workings of four-dimensional vectors and matrices within a three-dimensional world.
• Chapter 7 discusses how to use polar coordinates in 2D and 3D, why it is useful to do so, and how to convert between polar and Cartesian representations.
• Chapter 8 discusses different techniques for representing orientation and angular displacement in 3D: Euler angles, rotation matrices, ex- ponential maps, and quaternions. For each method, it explains how the method works and presents the advantages and disadvantages of the method and when its use is recommended. It also shows how to convert between different representations.
• Chapter 9 surveys a number of commonly used geometric primitives and discusses how to represent and manipulate them mathematically.
• Chapter 10 is a whirlwind lesson on graphics, touching on a few se-
lected theoretical as well as modern practical issues. First, it presents
a high-level overview of “how graphics works,” leading up to the ren-
dering equation. The chapter then walks through a few theoretical
topics of a mathematical nature. Next it discusses two contemporary
topics that are often sources of mathematical difficulty and should
be of particular interest to the reader: skeletal animation and bump
mapping. Finally, the chapter presents an overview of the real-time
graphics pipeline, demonstrating how the theories from the first half
xx
Introduction
of the chapter are implemented in the context of current rendering hardware.
• Chapter 11 crams two rather large topics into one chapter. It in- terleaves the highest-level topics from first-semester calculus with a discussion of rigid body kinematics—how to describe and analyze the motion of a rigid body without necessarily understanding its cause or being concerned with orientation or rotation.
• Chapter 12 continues the discussion of rigid body mechanics. It starts with a condensed explanation of classical mechanics, including New- ton’s laws of motion and basic concepts such as inertia, mass, force, and momentum. It reviews a few basic force laws, such as grav- ity, springs, and friction. The chapter also considers the rotational analogs of all of the linear ideas discussed up to this point. Due attention is paid to the important topic of collisions. The chapter ends with a discussion of issues that arise when using a computer to simulate rigid bodies.
• Chapter 13 explains parametric curves in 3D. The first half of the chapter explains how a relatively short curve is represented in some common, important forms: monomial, B´ezier, and Hermite. The second half is concerned with fitting together these shorter pieces into a longer curve, called a spline. In understanding each system, the chapter considers what controls the system presents to a designer of curves, how to take a description of a curve made by a designer and recreate the curve, and how these controls can be used to construct a curve with specific properties.
• Chapter 14 inspires the reader to pursue greatness in video games.
• Appendix A is an assortment of useful tests that can be performed on geometric primitives. We intend it to be a helpful reference, but it can also make for interesting browsing.
• Appendix B has all the answers.
3Find a Bug in This Book?
We calculated the odds that we could write an 800+ page math book free of mistakes. The result was a negative number, which we know can’t be right, but is probably pretty close. If you find a bug in this book, please
3To the exercises, that is.
Introduction
xxivisit gamemath.com. Most likely, the error is already listed in the errata, in which case you have our profound apologies. Otherwise, send us an email, and you will have (in addition to our profound thanks) everlasting fame via credit in the errata for being the first to find the mistake.
Careful. We don’t want to learn from this.
— Bill Watterson (1958–) from Calvin and Hobbes
Chapter 1
Cartesian Coordinate Systems
Before turning to those moral and mental aspects of the matter which present the greatest difficulties, let the inquirer begin by mastering more elementary problems.
— Sherlock Holmes from A Study in Scarlett (1887)
3D math is all about measuring locations, distances, and angles precisely and mathematically in 3D space. The most frequently used framework to perform such calculations using a computer is called the Cartesian coordi- nate system. Cartesian mathematics was invented by (and is named after) a brilliant French philosopher, physicist, physiologist, and mathematician named Ren´e Descartes, who lived from 1596 to 1650. Ren´e Descartes is famous not just for inventing Cartesian mathematics, which at the time was a stunning unification of algebra and geometry. He is also well-known for making a pretty good stab of answering the question “How do I know something is true?”—a question that has kept generations of philosophers happily employed and does not necessarily involve dead sheep (which will perhaps disturbingly be a central feature of the next section), unless you really want it to. Descartes rejected the answers proposed by the Ancient Greeks, which are ethos (roughly, “because I told you so”), pathos (“be- cause it would be nice”), and logos (“because it makes sense”), and set about figuring it out for himself with a pencil and paper.
This chapter is divided into four main sections.
• Section 1.1 reviews some basic principles of number systems and the first law of computer graphics.
• Section 1.2 introduces 2D Cartesian mathematics, the mathematics of flat surfaces. It shows how to describe a 2D cartesian coordinate space and how to locate points using that space.
• Section 1.3 extends these ideas into three dimensions. It explains left- and right-handed coordinate spaces and establishes some conventions used in this book.
1
2
1. Cartesian Coordinate Systems
• Section 1.4 concludes the chapter by quickly reviewing assorted pre- requisites.
1.1 1D Mathematics
You’re reading this book because you want to know about 3D mathematics, so you’re probably wondering why we’re bothering to talk about 1D math.
Well, there are a couple of issues about number systems and counting that we would like to clear up before we get to 3D.
Figure 1.1 One dead sheep
The natural numbers, often called the counting numbers, were invented millennia ago, probably to keep track of dead sheep. The concept of “one sheep” came easily (see Figure 1.1), then “two sheep,” “three sheep,” but people very quickly became convinced that this was too much work, and gave up counting at some point that they invariably called “many sheep.”
Different cultures gave up at different points, depending on their threshold of boredom. Eventually, civilization expanded to the point where we could afford to have people sitting around thinking about numbers instead of doing more survival-oriented tasks such as killing sheep and eating them.
These savvy thinkers immortalized the concept of zero (no sheep), and although they didn’t get around to naming all of the natural numbers, they figured out various systems whereby they could name them if they really wanted to using digits such as 1, 2, etc. (or if you were Roman, M, X, I, etc.). Thus, mathematics was born.
The habit of lining sheep up in a row so that they can be easily counted leads to the concept of a number line, that is, a line with the numbers marked off at regular intervals, as in Figure 1.2. This line can in principle go on for as long as we wish, but to avoid boredom we have stopped at five sheep and used an arrowhead to let you know that the line can continue.
Clearer thinkers can visualize it going off to infinity, but historical purveyors of dead sheep probably gave this concept little thought outside of their dreams and fevered imaginings.
Figure 1.2.A number line for the natural numbers
1.1. 1D Mathematics
3Figure 1.3.A number line for integers. (Note the ghost sheep for negative numbers.)
At some point in history, it was probably realized that sometimes, par- ticularly fast talkers could sell sheep that they didn’t actually own, thus simultaneously inventing the important concepts of debt and negative num- bers. Having sold this putative sheep, the fast talker would in fact own
“negative one” sheep, leading to the discovery of the integers, which consist of the natural numbers and their negative counterparts. The corresponding number line for integers is shown in Figure 1.3.
The concept of poverty probably predated that of debt, leading to a growing number of people who could afford to purchase only half a dead sheep, or perhaps only a quarter. This led to a burgeoning use of fractional numbers consisting of one integer divided by another, such as 2/3 or 111/27.
Mathematicians called these rational numbers, and they fit in the number line in the obvious places between the integers. At some point, people became lazy and invented decimal notation, writing “3.1415” instead of the longer and more tedious 31415/10000, for example.
After a while it was noticed that some numbers that appear to turn up in everyday life were not expressible as rational numbers. The classic example is the ratio of the circumference of a circle to its diameter, usually denoted π (the Greek letter pi, pronounced “pie”). These are the so-called real numbers, which include the rational numbers and numbers such as π that would, if expressed in decimal notation, require an infinite number of decimal places. The mathematics of real numbers is regarded by many to be the most important area of mathematics—indeed, it is the basis of most forms of engineering, so it can be credited with creating much of modern civilization. The cool thing about real numbers is that although rational numbers are countable (that is, can be placed into one-to-one correspon- dence with the natural numbers), the real numbers are uncountable. The study of natural numbers and integers is called discrete mathematics, and the study of real numbers is called continuous mathematics.
The truth is, however, that real numbers are nothing more than a polite
fiction. They are a relatively harmless delusion, as any reputable physicist
will tell you. The universe seems to be not only discrete, but also finite.
4
1. Cartesian Coordinate Systems
If there are a finite amount of discrete things in the universe, as currently appears to be the case, then it follows that we can only count to a certain fixed number, and thereafter we run out of things to count on—not only do we run out of dead sheep, but toasters, mechanics, and telephone sanitizers, too. It follows that we can describe the universe using only discrete mathe- matics, and only requiring the use of a finite subset of the natural numbers at that (large, yes, but finite). Somewhere, someplace there may be an alien civilization with a level of technology exceeding ours who have never heard of continuous mathematics, the fundamental theorem of calculus, or even the concept of infinity; even if we persist, they will firmly but politely insist on having no truck with π, being perfectly happy to build toasters, bridges, skyscrapers, mass transit, and starships using 3.14159 (or perhaps 3.1415926535897932384626433832795 if they are fastidious) instead.
So why do we use continuous mathematics? Because it is a useful tool that lets us do engineering. But the real world is, despite the cognitive dissonance involved in using the term “real,” discrete. How does that affect you, the designer of a 3D computer-generated virtual reality? The computer is, by its very nature, discrete and finite, and you are more likely to run into the consequences of the discreteness and finiteness during its creation than you are likely to in the real world. C++ gives you a variety of different forms of number that you can use for counting or measuring in your virtual world.
These are the short, the int, the float and the double, which can be described as follows (assuming current PC technology). The short is a 16- bit integer that can store 65,536 different values, which means that “many sheep” for a 16-bit computer is 65,537. This sounds like a lot of sheep, but it isn’t adequate for measuring distances inside any reasonable kind of virtual reality that take people more than a few minutes to explore. The int is a 32-bit integer that can store up to 4,294,967,296 different values, which is probably enough for your purposes. The float is a 32-bit value that can store a subset of the rationals (slightly fewer than 4,294,967,296 of them, the details not being important here). The double is similar, using 64 bits instead of 32.
The bottom line in choosing to count and measure in your virtual world
using ints, floats, or doubles is not, as some misguided people would have
it, a matter of choosing between discrete shorts and ints versus continuous
floats and doubles; it is more a matter of precision. They are all discrete
in the end. Older books on computer graphics will advise you to use integers
because floating-point hardware is slower than integer hardware, but this
is no longer the case. In fact, the introduction of dedicated floating point
vector processors has made floating-point arithmetic faster than integer in
many common cases. So which should you choose? At this point, it is
probably best to introduce you to the first law of computer graphics and
leave you to think about it.
1.2. 2D Cartesian Space
5The First Law of Computer Graphics If it looks right, it is right.
We will be doing a lot of trigonometry in this book. Trigonometry involves real numbers such as π, and real-valued functions such as sine and cosine (which we’ll get to later). Real numbers are a convenient fiction, so we will continue to use them. How do you know this is true? Because, Descartes notwithstanding, we told you so, because it would be nice, and because it makes sense.
1.2 2D Cartesian Space
You probably have used 2D Cartesian coordinate systems even if you have never heard the term “Cartesian” before. “Cartesian” is mostly just a fancy word for “rectangular.” If you have ever looked at the floor plans of a house, used a street map, seen a football
1game, or played chess, you have some exposure to 2D Cartesian coordinate spaces.
This section introduces 2D Cartesian mathematics, the mathematics of flat surfaces. It is divided into three main subsections.
• Section 1.2.1 provides a gentle introduction to the concept of 2D Cartesian space by imagining a fictional city called Cartesia.
• Section 1.2.2 generalizes this concept to arbitrary or abstract 2D Cartesian spaces. The main concepts introduced are
◦ the origin
◦ the x- and y-axes
◦ orienting the axes in 2D
• Section 1.2.3 describes how to specify the location of a point in the 2D plane using Cartesian (x, y) coordinates.
1This sentence works no matter which sport you think we are referring to with the word “football.” Well, OK, it works a little better with American football because of the clearly marked yard lines.
6
1. Cartesian Coordinate Systems
Figure 1.4.Map of the hypothetical city of Cartesia
1.2.1 An Example: The Hypothetical City of Cartesia
Let’s imagine a fictional city named Cartesia. When the Cartesia city planners were laying out the streets, they were very particular, as illustrated in the map of Cartesia in Figure 1.4.
As you can see from the map, Center Street runs east-west through the middle of town. All other east-west streets (parallel to Center Street) are named based on whether they are north or south of Center Street, and how far they are from Center Street. Examples of streets that run east-west are North 3rd Street and South 15th Street.
The other streets in Cartesia run north-south. Division Street runs
north-south through the middle of town. All other north-south streets
(parallel to Division Street) are named based on whether they are east or
1.2. 2D Cartesian Space
7west of Division Street, and how far they are from Division Street. So we have streets such as East 5th Street and West 22nd Street.
The naming convention used by the city planners of Cartesia may not be creative, but it certainly is practical. Even without looking at the map, it is easy to find the donut shop at North 4th and West 2nd. It’s also easy to determine how far you will have to drive when traveling from one place to another. For example, to go from that donut shop at North 4th and West 2nd, to the police station at South 3rd and Division, you would travel seven blocks south and two blocks east.
1.2.2 Arbitrary 2D Coordinate Spaces
Before Cartesia was built, there was nothing but a large flat area of land.
The city planners arbitrarily decided where the center of town would be, which direction to make the roads run, how far apart to space the roads, and so forth. Much like the Cartesia city planners laid down the city streets, we can establish a 2D Cartesian coordinate system anywhere we want—on a piece of paper, a chessboard, a chalkboard, a slab of concrete, or a football field.
Figure 1.5 shows a diagram of a 2D Cartesian coordinate system.
As illustrated in Figure 1.5, a 2D Cartesian coordinate space is defined by two pieces of information:
• Every 2D Cartesian coordinate space has a special location, called the origin, which is the “center” of the coordinate system. The origin is analogous to the center of the city in Cartesia.
Figure 1.5
A 2D Cartesian coordinate space
8
1. Cartesian Coordinate Systems
• Every 2D Cartesian coordinate space has two straight lines that pass through the origin. Each line is known as an axis and extends in- finitely in two opposite directions. The two axes are perpendicular to each other. (Actually, they don’t have to be, but most of the co- ordinate systems we will look at will have perpendicular axes.) The two axes are analogous to Center and Division streets in Cartesia.
The grid lines in the diagram are analogous to the other streets in Cartesia.
At this point it is important to highlight a few significant differences between Cartesia and an abstract mathematical 2D space:
• The city of Cartesia has official city limits. Land outside of the city limits is not considered part of Cartesia. A 2D coordinate space, however, extends infinitely. Even though we usually concern ourselves with only a small area within the plane defined by the coordinate space, in theory this plane is boundless. Also, the roads in Cartesia go only a certain distance (perhaps to the city limits) and then they stop. In contrast, our axes and grid lines extend potentially infinitely in two directions.
• In Cartesia, the roads have thickness. In contrast, lines in an abstract coordinate space have location and (possibly infinite) length, but no real thickness.
• In Cartesia, you can drive only on the roads. In an abstract coordinate space, every point in the plane of the coordinate space is part of the coordinate space, not just the “roads.” The grid lines are drawn only for reference.
In Figure 1.5, the horizontal axis is called the x-axis, with positive x pointing to the right, and the vertical axis is the y-axis, with positive y pointing up. This is the customary orientation for the axes in a diagram.
Note that “horizontal” and “vertical” are terms that are inappropriate for many 2D spaces that arise in practice. For example, imagine the coordinate space on top of a desk. Both axes are “horizontal,” and neither axis is really
“vertical.”
The city planners of Cartesia could have made Center Street run north-
south instead of east-west. Or they could have oriented it at a completely
arbitrary angle. For example, Long Island, New York, is reminiscent of
Cartesia, where for convenience the “streets” (1st Street, 2nd Street etc.)
run across the island, and the “avenues” (1st Avenue, 2nd Avenue, etc.)
run along its long axis. The geographic orientation of the long axis of the
island is an arbitrary result of nature. In the same way, we are free to orient
our axes in any way that is convenient to us. We must also decide for each
1.2. 2D Cartesian Space
9axis which direction we consider to be positive. For example, when working with images on a computer screen, it is customary to use the coordinate system shown in Figure 1.6. Notice that the origin is in the upper left-hand corner, +x points to the right, and +y points down rather than up.
Figure 1.6
Screen coordinate space
Unfortunately, when Cartesia was being laid out, the only mapmak- ers were in the neighboring town of Dyslexia. The minor-level functionary who sent the contract out to bid ne- glected take into account that the dyslectic mapmaker was equally likely to draw his maps with north pointing up, down, left, or right. Although he always drew the east-west line at right angles to the north-south line, he often got east and west backwards. When his boss realized that the job had gone to the lowest bidder, who happened to live in Dyslexia, many hours were spent in committee meetings trying to figure out what to do. The paperwork had been done, the purchase order had been is-
sued, and bureaucracies being what they are, it would be too expensive and time-consuming to cancel the order. Still, nobody had any idea what the mapmaker would deliver. A committee was hastily formed.
The committee fairly quickly decided that there were only eight possi- ble orientations that the mapmaker could deliver, shown in Figure 1.7. In
Figure 1.7.Possible map axis orientations in 2D
10
1. Cartesian Coordinate Systems
the best of all possible worlds, he would deliver a map oriented as shown in the top-left rectangle, with north pointing to the top of the page and east to the right, which is what people usually expect. A subcom- mittee formed for the task decided to name this the normal orientation.
After the meeting had lasted a few hours and tempers were beginning to fray, it was decided that the other three variants shown in the top row of Figure 1.7 were probably acceptable too, because they could be transformed to the normal orientation by placing a pin in the center of the page and rotating the map around the pin. (You can do this, too, by placing this book flat on a table and turning it.) Many hours were wasted by tired functionaries putting pins into various places in the maps shown in the second row of Figure 1.7, but no matter how fast they twirled them, they couldn’t seem to transform them to the normal orientation. It wasn’t until everybody important had given up and gone home that a tired intern, assigned to clean up the used coffee cups, noticed that the maps in the second row can be transformed into the normal orientation by holding them up against a light and viewing them from the back. (You can do this, too, by holding Figure 1.7 up to the light and viewing it from the back—you’ll have to turn it, too, of course.) The writing was backwards too, but it was decided that if Leonardo da Vinci (1452–1519) could handle backwards writing in 15th century, then the citizens of Cartesia, though by no means his intellectual equivalent (probably due to daytime TV), could probably handle it in the 21st century.
In summary, no matter what orientation we choose for the x- and y- axes, we can always rotate the coordinate space around so that +x points to our right and +y points up. For our example of screen-space coordinates, imagine turning the coordinate system upside down and looking at the screen from behind the monitor. In any case, these rotations do not distort the original shape of the coordinate system (even though we may be looking at it upside down or reversed). So in one particular sense, all 2D coordinate systems are “equal.” In Section 1.3.3, we discover the surprising fact that this is not the case in 3D.
1.2.3 Specifying Locations in 2D Using Cartesian Coordinates
A coordinate space is a framework for specifying location precisely. A gentleman of Cartesia could, if he wished to tell his lady love where to meet him for dinner, for example, consult the map in Figure 1.4 and say,
“Meet you at the corner of East 2nd Street and North 4th Street.” Notice
that he specifies two coordinates, one in the horizontal dimension (East 2nd
Street, listed along the top of the map in Figure 1.4) and one in the vertical
dimension (North 4th Street, listed along the left of the map). If he wished
1.2. 2D Cartesian Space
11to be concise he could abbreviate the “East 2nd Street” to “2” and the
“North 4th Street” to “4” and say to his lady love, somewhat cryptically,
“Meet you at (2, 4).”
The ordered pair (2, 4) is an example of what are called Cartesian coor- dinates. In 2D, two numbers are used to specify a location. (The fact that we use two numbers to describe the location of a point is the reason it’s called two-dimensional space. In 3D, we will use three numbers.) The first coordinate (the 2 in our example (2, 4)) is called the x-coordinate, and the second coordinate (the 4 in our example (2, 4)) is called the y-coordinate.
Figure 1.8
How to locate a point using 2D Cartesian coordinates
Analogous to the street names in Cartesia, each of the two coordinates specifies which side of the origin the point is on and how far away the point is from the origin in that direction. More precisely, each coordinate is the signed distance (that is, positive in one direc- tion and negative in the other) to one of the axes, measured along a line par- allel to the other axis. Essentially, we use positive coordinates for east and north streets and negative coordinates for south and west streets. As shown in Figure 1.8, the x-coordinate desig- nates the signed distance from the point to the y-axis, measured along a line parallel to the x-axis. Likewise, the y-coordinate designates the signed dis-
tance from the point to the x-axis, measured along a line parallel to the y-axis.
Figure 1.9 shows several points and their Cartesian coordinates. Notice that the points to the left of the y-axis have negative x values, and those to the right of the y-axis have positive x values. Likewise, points with positive y are located above the x-axis, and points with negative y are below the x-axis. Also notice that any point can be specified, not just the points at grid line intersections. You should study this figure until you are sure that you understand the pattern.
Let’s take a closer look at the grid lines usually shown in a diagram.
Notice that a vertical grid line is composed of points that all have the same x-coordinate. In other words, a vertical grid line (actually any vertical line) marks a line of constant x. Likewise, a horizontal grid line marks a line of constant y; all the points on that line have the same y coordinate.
We’ll come back to this idea in a bit when we discuss polar coordinate
spaces.
12
1. Cartesian Coordinate Systems
Figure 1.9.Example points labeled with 2D Cartesian coordinates
1.3 3D Cartesian Space
The previous sections have explained how the Cartesian coordinate system works in 2D. Now it’s time to leave the flat 2D world and think about 3D space.
It might seem at first that 3D space is only “50% more complicated”
than 2D. After all, it’s just one more dimension, and we already had two.
Unfortunately, this is not the case. For a variety of reasons, 3D space is more than incrementally more difficult than 2D space for humans to visualize and describe. (One possible reason for this difficulty could be that our physical world is 3D, whereas illustrations in books and on computer screens are 2D.) It is frequently the case that a problem that is “easy” to solve in 2D is much more difficult or even undefined in 3D. Still, many concepts in 2D do extend directly into 3D, and we frequently use 2D to establish an understanding of a problem and develop a solution, and then extend that solution into 3D.
This section extends 2D Cartesian math into 3D. It is divided into four major subsections.
• Section 1.3.1 begins the extension of 2D into 3D by adding a third
axis. The main concepts introduced are
1.3. 3D Cartesian Space
13◦ the z-axis
◦ the xy, xz, and yz planes
• Section 1.3.2 describes how to specify the location of a point in the 3D plane using Cartesian (x, y, z) coordinates.
• Section 1.3.3 introduces the concepts of left-handed and right-handed 3D coordinate spaces. The main concepts introduced are
◦ the hand rule, an informal definition for left-handed and right- handed coordinate spaces
◦ differences in rotation in left-handed and right-handed coordi- nate spaces
◦ how to convert between the two
◦ neither is better than the other, only different
• Section 1.3.4 describes some conventions used in this book.
1.3.1 Extra Dimension, Extra Axis
In 3D, we require three axes to establish a coordinate system. The first two axes are called the x-axis and y-axis, just as in 2D. (However, it is not accurate to say that these are the same as the 2D axes; more on this later.) We call the third axis (predictably) the z-axis. Usually, we set things up so that all axes are mutually perpendicular, that is, each one is perpendicular to the others. Figure 1.10 shows an example of a 3D coordinate space.
Figure 1.10
A 3D Cartesian coordinate space
As discussed in Section 1.2.2, it is customary in 2D for +x to point to
the right and +y to point up. (Or sometimes +y may point down, but
14
1. Cartesian Coordinate Systems
in either case, the x-axis is horizontal and the y-axis is vertical.) These conventions in 2D are fairly standardized. In 3D, however, the conven- tions for arrangement of the axes in diagrams and the assignment of the axes onto physical dimensions (left, right, up, down, forward, back) are not very standardized. Different authors and fields of study have dif- ferent conventions. Section 1.3.4 discusses the conventions used in this book.
As mentioned earlier, it is not entirely appropriate to say that the x-axis and y-axis in 3D are the “same” as the x-axis and y-axis in 2D. In 3D, any pair of axes defines a plane that contains the two axes and is perpendicular to the third axis. For example, the plane containing the x- and y-axes is the xy plane, which is perpendicular to the z-axis. Likewise, the xz plane is perpendicular to the y-axis, and the yz plane is perpendicular to the x-axis.
We can consider any of these planes a 2D Cartesian coordinate space in its own right. For example, if we assign +x, +y, and +z to point right, up, and forward, respectively, then the 2D coordinate space of the “ground” is the xz plane, as shown in Figure 1.10.
1.3.2 Specifying Locations in 3D
In 3D, points are specified using three numbers, x, y, and z, which give the signed distance to the yz, xz, and xy planes, respectively. This distance is measured along a line parallel to the axis. For example, the x-value is the signed distance to the yz plane, measured along a line parallel to the x-axis. Don’t let this precise definition of how points in 3D are located confuse you. It is a straightforward extension of the process for 2D, as shown in Figure 1.11.
Figure 1.11
Locating points in 3D
1.3. 3D Cartesian Space
151.3.3 Left-handed versus Right-handed Coordinate Spaces
As we discussed in Section 1.2.2, all 2D coordinate systems are “equal” in the sense that for any two 2D coordinate spaces A and B, we can rotate coordinate space A such that +x and +y point in the same direction as they do in coordinate space B. (We are assuming perpendicular axes.) Let’s examine this idea in more detail.
Figure 1.5 shows the “standard” 2D coordinate space. Notice that the difference between this coordinate space and “screen” coordinate space shown Figure 1.6 is that the y-axis points in opposite directions. How- ever, imagine rotating Figure 1.6 clockwise 180 degrees so that +y points up and +x points to the left. Now rotate it by “turning the page” and viewing the diagram from behind. Notice that now the axes are oriented in the “standard” directions like in Figure 1.5. No matter how many times we flip an axis, we can always find a way to rotate things back into the standard orientation.
Let’s see how this idea extends into 3D. Examine Figure 1.10 once more.
We stated earlier that +z points into the page. Does it have to be this way?
What if we made +z point out of the page? This is certainly allowed, so let’s flip the z-axis.
Now, can we rotate the coordinate system around such that things line up with the original coordinate system? As it turns out, we cannot. We can rotate things to line up two axes at a time, but the third axes always points in the wrong direction! (If you have trouble visualizing this, don’t worry. In just a moment we will illustrate this principle in more concrete terms.)
All 3D coordinate spaces are not equal, in the sense that some pairs of coordinate systems cannot be rotated to line up with each other. There are exactly two distinct types of 3D coordinate spaces: left-handed coordinate spaces and right-handed coordinate spaces. If two coordinate spaces have the same handedness, then they can be rotated such that the axes are aligned. If they are of opposite handedness, then this is not possible.
What exactly do “left-handed” and “right-handed” mean? The most intuitive way to identify the handedness of a particular coordinate system is to use, well, your hands! With your left hand, make an ‘L’ with your thumb and index finger.
2Your thumb should be pointing to your right, and your index finger should be pointing up. Now extend your third finger
3so it points directly forward. You have just formed a left-handed coordinate system. Your thumb, index finger, and third finger point in the +x, +y, and +z directions, respectively. This is shown in Figure 1.12.
2You may have to put the book down.
3This may require some dexterity. The authors advise that you not do this in public without first practicing privately, to avoid offending innocent bystanders.
16
1. Cartesian Coordinate Systems
Figure 1.12
Left-handed coordinate space
Now perform the same experiment with your right hand. Notice that your index finger still points up, and your third finger points forward. How- ever, with your right hand, your thumb will point to the left. This is a right-handed coordinate system. Again, your thumb, index finger, and third finger point in the +x, +y, and +z directions, respectively. A right- handed coordinate system is shown in Figure 1.13.
Figure 1.13
Right-handed coordinate space
Try as you might, you cannot rotate your hands into a position such that all three fingers simultaneously point the same direction on both hands.
(Bending your fingers is not allowed.)
Left-handed and right-handed coordinate systems also differ in the defi-
nition of “positive rotation.” Let’s say we a have line in space and we need
to rotate about this line by a specified angle. We call this line an axis of
rotation, but don’t think that the word axis implies that we’re talking only
about one of the cardinal axes (the x-, y-, or z-axis). An axis of rotation
can be arbitrarily oriented. Now, if you tell me to “rotate 30
oabout the
1.3. 3D Cartesian Space
17Left-hand rule Right-hand rule
Figure 1.14.The left-hand rule and right-hand rule define which direction is considered
“positive” rotation.
axis,” how do I know which way to rotate? We need to agree between us that one direction of rotation is the positive direction, and the other di- rection is the negative direction. The standard way to tell which is which in a left-handed coordinate system is called the left-hand rule. First, we must define which way our axis “points.” Of course, the axis of rotation is theoretically infinite in length, but we still consider it having a positive and negative end, just like the normal cardinal axes that define our coordinate space. The left-hand rule works like this: put your left hand in the “thumbs up” position, with your thumb pointing towards the positive end of the axis of rotation. Positive rotation about the axis of rotation is in the direction that your fingers are curled. There’s a corresponding rule for right-handed coordinate spaces; both of these rules are illustrated in Figure 1.14.
As you can see, in a left-handed coordinate system, positive rotation rotates clockwise when viewed from the positive end of the axis, and in a right-handed coordinate system, positive rotation is counterclockwise. Ta- ble 1.1 shows what happens when we apply this general rule to the specific case of the cardinal axes.
Any left-handed coordinate system can be transformed into a right-
handed coordinate system, or vice versa. The simplest way to do this is
by swapping the positive and negative ends of one axis. Notice that if we
18
1. Cartesian Coordinate Systems
When looking towards the origin from. . .
Positive rotation Negative rotation
Left-handed: Clockwise Left-handed: Counterclockwise Right-handed: Counterclockwise Right-handed: Clockwise +x +y → +z → −y → −z → +y +y → −z → −y → +z → +y +y +z → +x → −z → −x → +z +z → −x → −z → +x → +z +z +x → +y → −x → −y → +x +x → −y → −x → +y → +x Table 1.1.Rotation about the cardinal axes in left- and right-handed coordinate systems
flip two axes, it is the same as rotating the coordinate space 180
oabout the third axis, which does not change the handedness of the coordinate space. Another way to toggle the handedness of a coordinate system is to exchange two axes.
Both left-handed and right-handed coordinate systems are perfectly valid, and despite what you might read in other books, neither is “better”
than the other. People in various fields of study certainly have preferences for one or the other, depending on their backgrounds. For example, some newer computer graphics literature uses left-handed coordinate systems, whereas traditional graphics texts and more math-oriented linear algebra people tend to prefer right-handed coordinate systems. Of course, these are gross generalizations, so always check to see what coordinate system is being used. The bottom line, however, is that in many cases it’s just a matter of a negative sign in the z-coordinate. So, appealing to the first law of computer graphics in Section 1.1, if you apply a tool, technique, or resource from another book, web page, or article and it doesn’t look right, try flipping the sign on the z-axis.
1.3.4 Some Important Conventions Used in This Book
When designing a 3D virtual world, several design decisions have to be made beforehand, such as left-handed or right-handed coordinate system, which direction is +y, and so forth. The map makers from Dyslexia had to choose from among eight different ways to assign the axes in 2D (see Figure 1.7). In 3D, we have a total of 48 different combinations to choose from; 24 of these combinations are left-handed, and 24 are right-handed.
(Exercise 3 asks you to list all of them.)
Different situations can call for different conventions, in the sense that certain tasks can be easier if you adopt the right conventions. Usually, however, it is not a major deal as long as you establish the conventions early in your design process and stick to them. (In fact, the choice is most likely thrust upon you by the engine or framework you are using, because very few people start from scratch these days.) All of the basic principles discussed in this book are applicable regardless of the conventions used.
For the most part, all of the equations and techniques given are applicable
1.4. Odds and Ends
19regardless of convention, as well.
4However, in some cases there are some slight, but critical, differences in application dealing with left-handed versus right-handed coordinate spaces. When those differences arise, we will point them out.
We use a left-handed coordinate system in this book. The +x, +y, and +z directions point right, up, and forward, respectively, as shown in Figure 1.15. In situations where “right” and “forward” are not appropriate terms (for example, when we discuss the world coordinate space), we assign +x to “east” and +z to “north.”
Figure 1.15
The left-handed coordinate system conventions used in this book
1.4 Odds and Ends
In this book, we spend a lot of time focusing on some crucial material that is often relegated to a terse presentation tucked away in an appendix in the books that consider this material a prerequisite. We, too, must assume a nonzero level of mathematical knowledge from the reader, or else every book would get no further than a review of first principles, and so we also have our terse presentation of some prerequisites. In this section we present a few bits of mathematical knowledge with which most readers are probably familiar, but might need a quick refresher.
4This is due to a fascinating and surprising symmetry in nature. You might say that nature doesn’t know if we are using left- or right-handed coordinates. There’s a really interesting discussion in The Feynman Lectures on Physics about how it is impossible without very advanced physics to describe the concepts of “left” or “right” to someone without referencing some object you both have seen.
20
1. Cartesian Coordinate Systems
1.4.1 Summation and Product Notation
Summation notation is a shorthand way to write the sum of a list of things.
It’s sort of like a mathematical for loop. Let’s look at an example:
Summation notation
X
6i=1
a
i= a
1+ a
2+ a
3+ a
4+ a
5+ a
6.
The variable i is known as the index variable. The expressions above and below the summation symbol tell us how many times to execute our “loop”
and what values to use for i during each iteration. In this case, i will count from 1 to 6. To “execute” our loop, we iterate the index through all the values specified by the control conditions. For each iteration, we evaluate the expression on the right-hand side of the summation notation (substituting the appropriate value for the index variable), and add this to our sum.
Summation notation is also known as sigma notation because that cool- looking symbol that looks like an E is the capital version of the Greek letter sigma.
A similar notation is used when we are taking the product of a series of values, only we use the symbol Π, which is the capital version of the letter π:
Product notation
n
Y
i=1
a
i= a
1× a
2× · · · × a
n−1× a
n.
1.4.2 Interval Notation
Several times in this book, we refer to a subset of the real number line using interval notation. The notation [a, b] means, “the portion of the number line from a to b.” Or, more formally, we could read [a, b] as “all numbers x such that a ≤ x ≤ b.” Notice that this is a closed interval, meaning that the endpoints a and b are included in the interval. An open interval is one in which the endpoints are excluded. It is denoted using parentheses instead of square brackets: (a, b). This interval contains all x such that a < x < b.
Sometimes a closed interval is called inclusive and an open interval called exclusive.
Occasionally, we encounter half-open intervals, which include one end- point but exclude the other. These are denoted with a lopsided
5notation such as [a, b) or (a, b], with the square bracket being placed next to the endpoint that is included. By convention, if an endpoint is infinite, we con- sider that end to be open. For example, the set of all nonnegative numbers is [0, ∞).
5And confusing to the delimiter matching feature of your text editor.
1.4. Odds and Ends
21Notice that the notation (x, y) could refer to an open interval or a 2D point. Likewise, [x, y] could be a closed interval or a 2D vector (discussed in the next chapter). The context will always make clear which is the case.
1.4.3 Angles, Degrees, and Radians
An angle measures an amount of rotation in the plane. Variables repre- senting angles are often assigned the Greek letter θ.
6The most important units of measure used to specify angles are degrees (
o) and radians (rad).
Humans usually measure angles using degrees. One degree measures 1/360th of a revolution, so 360
orepresents a complete revolution.
7Math- ematicians, however, prefer to measure angles in radians, which is a unit of measure based on the properties of a circle. When we specify the angle between two rays in radians, we are actually measuring the length of the intercepted arc of a unit circle (a circle centered at the origin with radius 1), as shown in Figure 1.16.
Figure 1.16
A radian measures arc length on a unit circle
6One prerequisite that we do not assume in this book is familiarity with the Greek alphabet. The symbol θ is the lowercase theta, pronounced “THAY-tuh.”
7The number 360 is a relatively arbitrary choice, which may have had its origin in primitive calendars, such as the Persian calendar, which divided the year into 360 days.
This error was never corrected to 365 because the number 360 is so darn convenient. The number 360 has a whopping 22 divisors (not counting itself and 1): 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 18, 20, 24, 30, 36, 40, 45, 60, 72, 90, 120, and 180. This means 360 can be divided evenly in a large number of cases without needing fractions, which was apparently a good thing to early civilizations. As early as 1750 BCE the Babylonians had devised a sexagesimal (base 60) number system. The number 360 is also large enough so that precision to the nearest whole degree is sufficient in many circumstances.