Chapter01

22
Psrt I Mathematical Prerequisites Video games attempt to simulate a virtual world; however, computers, by their very nature, crunch numbers. Thus the problem of how to convey a world to a computer arises. The answer is to describe our worlds, and the interactions therein, completely mathematically. Consequently, mathemat- ics plays a fundamental role in video game development. In this prerequisites part, we introduce the mathematical tools that will be used throughout this book. The emphasis is on vectors, coordinate sys- tems, matrices, and transformations, as these tools are used in just about every sample program of this book. In addition to the mathematical expla- nations, a survey and demonstration of the relevant classes and functions from the D3DX math library are provided. Note that the topics covered here are only those essential to under- standing the rest of this book; it is by no means a comprehensive treatment of video game mathematics, as entire books are devoted to this topic. For readers desiring a more complete reference to video game mathematics, we recommend [Verth04] and |.Lengyel02|. Chapter 1, "Vector Algebra" Vectors are, perhaps, the most fundamental mathematical objects used in computer games. We use vectors to represent positions, displacements, directions, velocities, and forces, for example. In this chapter, we study vec- tors and the operations used to manipulate them. 1

Transcript of Chapter01

Page 1: Chapter01

Psrt I Mathematical Prerequisites

Video games attempt to simulate a v i r t u a l wor ld ; however, computers, by their ve ry nature, crunch numbers. Thus the problem of how to convey a w o r l d to a computer arises. The answer is to describe our worlds, and the interactions therein, completely mathematically. Consequently, mathematics plays a fundamental role in video game development.

In this prerequisites part, we introduce the mathematical tools that w i l l be used throughout this book. The emphasis is on vectors, coordinate systems, matrices, and transformations, as these tools are used in just about every sample program of this book. In addition to the mathematical explanations, a survey and demonstration of the relevant classes and functions from the D3DX math l ibrary are provided.

Note that the topics covered here are only those essential to understanding the rest of this book; it is by no means a comprehensive treatment of video game mathematics, as entire books are devoted to this topic. For readers desiring a more complete reference to video game mathematics, we recommend [Verth04] and |.Lengyel02|.

C h a p t e r 1, " V e c t o r A l g e b r a "

Vectors are, perhaps, the most fundamental mathematical objects used in computer games. We use vectors to represent positions, displacements, directions, velocities, and forces, for example. In this chapter, we study vectors and the operations used to manipulate them.

1

Page 2: Chapter01

Pari I: Mathematical Prerequisites

C h a p t e r 2 , " M a t r i x A l g e b r a "

Matrices provide an efficient and compact way of representing transformations. In this chapter, we become familiar w i t h matrices and the operations defined on them.

C h a p t e r 3 , " T r a n s f o r m a t i o n s "

This chapter examines three fundamental geometric transformations: scaling, rotation, and translation. We use these transformations to manipulate 3D objects in space. In addition, we explain change of coordinate transformations, which are used to transform coordinates representing geometry from one coordinate system into another.

Page 3: Chapter01

Chapter 1 Vector Algebra

Vectors play a crucial role in computer graphics, collision detection, and physical simulation, all of which are common components in modern video games. Our approach here is informal and practical; for a book dedicated to 3D game/graphics math, we recommend [Verth04] , We emphasize the importance of vectors by noting that they are used in just about every demo program in this book.

Objectives: • To learn how vectors are represented geometrically and numerically. • To discover the operations defined on vectors and their geometric

applications. • To become familiar w i t h the D 3 D X l ibrary 's vector math functions and

classes.

1.1 Vectors A vector refers to a quantity that possesses both magnitude and direction. Quantities that possess both magnitude and direction are called vector-valued quantities. Examples of vector-valued quantities are forces (a force is applied in a particular direction w i t h a certain strength — magnitude), displacements (the net direction and distance a particle moved), and velocities (speed and direction). Thus , vectors are used to represent forces, displacements, and velocities. We also use vectors to specify pure directions, such as the direction the player is looking in a 3D game, the direction a polygon is facing, the direction in which a ray of l ight travels, or the direct ion in wThich a ray of l ight reflects off a surface.

A f irst step in characterizing a vector mathematically is geometrically: We graphically specify a vector by a directed line segment (see Figure 1.1), where the length denotes the magnitude of the vector and the aim denotes the direction of the vector. We note that the location in which we draw a vector is immaterial because changing the location does not change the

3

Page 4: Chapter01

4 Part I: Mathematical Prerequisites

magnitude or direction (the two properties a vector possesses). That is, we say t w o vectors are equal if and only if they have the same length and they point in the same direction. Thus , the vectors u and v drawn in Figure 1.1a are actually equal because they have the same length and point in the same direction. In fact, because location is unimportant for vectors, we can always translate a vector without changing its meaning (since a translation changes neither length nor direction). Observe that we could translate u such that it completely overlaps w i t h v (and conversely), thereby making them indistinguishable — hence their equality. As a physical example, the vectors u and v in Figure L i b both t e l l the ants at two different points, A and B , to move n or th ten meters from their current location. Again we have that u = v. The vectors themselves are independent of position; they s i m ply instruct the ants how to move from where they are. In this example, they tel l the ants to move n or th (direction) ten meters (length).

Figure 1.1: (a) Vectors drawn on a 2D plane, (b) Vectors instructing ants to move ten meters north.

1.1.1 Vectors and Coordinate Systems We could now define useful geometric operations on vectors, which can then be used to solve problems involving vector-valued quantities. H o w ever, since the computer cannot work w i t h vectors geometrically, we need to f ind a way of specifying vectors numerically instead. So what we do is introduce a 3D coordinate system in space, and translate all the vectors so that their tails coincide w i t h the or ig in (Figure 1.2). Then we can identify a vector by specifying the coordinates of its head, and wr i t e v = (x, y, z) as shown in Figure 1.3. Now we can represent a vector w i t h three f loats in a computer program.

X

Page 5: Chapter01

Chapter 1: Vector Algebra 5

Figure 1.2: We translate v so that its tail coincides with the origin of the coordinate system. When a vectors tail coincides with the origin, we say that it is in standard position.

Figure 1.3: A vector specified by coordinates relative to a coordinate system.

Consider Figure 1.4, which shows a vector v and two frames in space. (Note that we use the terms frame, frame of reference, space, and coordinate system to mean the same thing in this book.) We can translate v so that it, is in standard position in either of the two frames. Observe, however, that the coordinates of the vector v relative to frame A are different, from the coordinates of the vector v relative to frame B. In other words, the same vector has a different coordinate representation for distinct frames.

Frame A

v = (x'.y')

Figure 1:4: The same vector v has different coordinates when described relative to different frames.

Frame B

The idea is analogous to, say, temperature. Water boils at 100° Celsius or 212° Fahrenheit. The physical temperature of boil ing water is the same no matter the scale (i.e., we can't lower the boil ing point by picking a different scale), but we assign a different scalar number to the temperature based on the scale we use. Similarly, for a vector, its direction and magnitude, which are embedded in the directed line segment, does not change; only the coordinates of it change based on the frame of reference we use to describe i t . This is important because it means whenever we identi fy a vector by

Page 6: Chapter01

6 Part I: Mathematical Prerequisites

coordinates, those coordinates are relative to some frame of reference. Often in 3D computer graphics we w i l l uti l ize more than one frame of reference and, therefore, w i l l need to keep track of which frame the coordinates of a vector are described relative to; additionally, we w i l l need to know how to convert vector coordinates f rom one frame to another.

Note: We see that both vectors and points can be described by coordinates (x, y, z) relative to a frame. However, they are not the same; a point represents a location in 3-space. whereas a vector represents a magnitude and direction. Points are discussed further in § 1 . 5 .

1.1.2 Left-Handed Versus Right-Handed Coordinate Systems Direct3D uses a so-called left-handed coordinate system. If you take your left hand and aim your fingers down the positive -r-axis, and then cur l your fingers toward the positive y-axis, your thumb points roughly in the direct ion of the positive z-axis. Figure 1.5 i l lustrates the differences between a left-handed and right-handed coordinate system.

Figure 1.5: On the left we have a left-handed coordinate system. Observe that the positive z-axis goes into the page. On the right we have a right-handed coordinate system. Observe that the positive z-axis comes out of the page.

Observe that for the right-handed coordinate system, if you take your r ight hand and aim your fingers down the positive x-axis, and then cur l your f i n gers toward the positive y-axis, your thumb points roughly in the direction of the positive z-axis.

1.1.3 Basic Vector Operations We now define equality, addition, scalar mult ipl icat ion, and subtraction on vectors using the coordinate representation. • Two vectors are equal if and only if their corresponding components are

equal. L e t u = (us,uy,uz) and v=(vx,vy,vz). Then u = v if and only if ux = vx, Uy = vy, and uz=vz.

• We add vectors componentwise; as such, it only makes sense to add vectors of the same dimension. L e t u = (ux,uy,uz) and v= (vx,vy,v z ) . Then u + v = {ux +vx,u +vy,uz +vz).

Page 7: Chapter01

Chapter 1: Vector Algebra 7

• We can mult ip ly a scalar (i.e., a real number) and a vector, and the result is a vector. Let k be a scalar, and let u = (uJ,uy,uz), then

ku = (kux,kuv,ku2). This is called scalar mult ipl ication. • We define subtraction in terms of vector addition and scalar

mult ipl icat ion. That is, u— v = u + (— l - v ) = u + (—v)= {ux-vx,uy-vy,uz-vz\

E x a m p l e 1.1

Let u = (1,2,3), v = ( l ,2 ,3 ) , w = ( 3 , 0 - 2 ) , and k = 2. Then ,

• u + w= (1,2, 3) + (3, 0, - 2) = (4 ,2 ,1 ) ; • u = v; • u - v = u + ( - v ) = ( l , 2 , 3 ) + ( - l , - 2 , - 3 ) = (0,0,0) = 0 ; • & w = 2 ( 3 , 0 , - 2 ) = ( 6 , 0 , - 4 ) .

T h e difference in the t h i r d line i l lustrates a special vector, called the zero-vector, which has zeros for all of its components and is denoted by 0.

E x a m p l e 1.2

We'l l i l lustrate this example w i t h 2D vectors to make the drawings simpler. The ideas are the same as in 3D ; we just w o r k w i t h one less component in 2D. • L e t v= (2,1). H o w do v and - l / 2 v compare geometrically? We note

- l / 2 v = ( - l , - 1 / 2 ) . Graphing both v and - l / 2 v (Figure 1.6a), we notice that — l / 2 v is in the direction directly opposite of v and its length is 1/2 that of v. Thus , geometrically, negating a vector can be thought of as " f l ipp ing" its direction, and scalar mult ipl icat ion can be thought of as scaling the length of the vector.

• L e t u = (2,1/2) and v = (1,2). Then v + u = (3,5/2). Figure 1.6b shows what vector addition means geometrically: We parallel translate u so that its tail coincides w i t h the head of v. Then, the sum is the vector originating at the tai l of v and ending at the head of u. (We get the same result if we keep u fixed and translate v so that its tai l coincides w i t h the head of u. In this case, u + v would be the vector originating at the tai l of u and ending at the head of the translated v.) Observe also that our rules of vector addition agree w i t h what we would intui t ive ly expect to happen physically when we add forces together to produce a net force: If we add two forces (vectors) in the same direction, we get another stronger force (longer vector) in that direction. If we add two forces (vectors) in opposition to each other, then we get a weaker net force (shorter vector) . Figure 1.7 i l lustrates these ideas.

• L e t u = (2,1/2) and v = ( 1 , 2 ) . Then v- u = ( -1 ,3 /2 ) . Figure 1.6c shows what vector subtraction means geometrically. Essentially, the difference v u gives us a vector aimed from the head of u to the head of v. If we instead interpret u and v as points, then v - u gives us a

Page 8: Chapter01

Part I: Mathematical Prerequisites

vector aimed f rom the point u to the point v; this interpretat ion is important as we w i l l often want the vector aimed f rom one point to another. Observe also that the length of v - u is the distance f rom u to v, when th ink ing of u and v as points.

-l/2v = (-1,-1/2) (a) (b) (c)

Figure 1,6; (a) The geometric interpretation of scalar multiplication, (b) The geometric interpretation of vector addition, (c) The geometric interpretation of vector subtraction.

Figure 1.7: Forces applied to a ball. The forces are combined using vector addition to get a net force.

Length and Unit Vectors Geometrically, the magnitude of a vector is the length of the directed l ine segment. We denote the magnitude of a vector by double vert ical bars (e.g., jjuj| denotes the magnitude of u ) . Now, given a vector v = (x, y, z), we w i sh to compute its magnitude algebraically. The magnitude of a 3D vector can be computed by applying the Pythagorean theorem twice ; see Figure 1.8.

+Y

u = (x, y, z)

/ X

Figure 1.8: The 3D length of a vector can be computed by applying the Pythagorean theorem twice.

Page 9: Chapter01

Chapter 1: Vector Algebra 9

First , we look at the triangle in the xz-plme w i t h sides x, z, and hypotenuse a. From the Pythagorean theorem, we have a = -\'x2 + z2. Now look at the triangle w i t h sides a,y, and hypotenuse ||u||. From the Pythagorean theorem again, we arrive at the fol lowing magnitude formula:

[|u||= V72 +a2 =^+(yJx^r+z2"Y = V * 2 + y 2 +z2 (1.1)

For some applications, we do not care about the length of a vector because we want to use the vector to represent a pure direction. For such direction-only vectors, we want the length of the vector to be exactly one. When we make a vector unit length, we say that we are normalizing the vector. We can normalize a vector by dividing each of its components by its magnitude:

||u|[ lju[| [!uj! i|ui[/

To ver i fy that this formula is correct, we can compute the length of u:

I t f l lNJ I . -^ l + 1 ^ 1 + 1 ^ 1 = V f ! ± i ± £ i = s = 1

J ml

So u is indeed a uni t vector.

E x a m p l e 1.3

Normalize the vector v = ( - 1 ,3 ,4 ) . We have ||v|| = V ( - 1 ) 2 + 3 2 + 4 2 = V26. Thus ,

„ v ( 1 3 4 |]v|| \ V26 V26 V 2 6 ;

To ver i fy that ||v|| is indeed a unit vector, we compute its length:

26) VV26 J \V26J ^26 26 26

1.3 The Dot Product The dot product is a f orm of vector multipl ication that results in a scalar value; for this reason, it is sometimes referred to as the scalar product. Let u = (ux,uy,uz) and \ = {vx,vy,vz); then the dot product is defined as follows:

U • V= UxVx+UyVy +U2VZ (1.3)

Page 10: Chapter01

Part I: Mathematical Prerequisites

In words, the dot product is the sum of the products of the corresponding components.

The dot product definition does not present an obvious geometric meaning. Using the law of cosines, we can find the relationship,

u-v=||u||||v||cos0 (1.4)

where 6 is the angle between the vectors u and v such that 0<()<.~r (see Figure 1.9). So, Equation 1.4 says that the dot product between two vectors is the cosine of the angle between t h e m scaled by the vectors ' magnitudes. In particular, if both u and v are unit vectors, then u - v i s the cosine of the angle between them (i.e., u • v = cos 0).

Equation 1.4 provides us w i t h some useful geometric properties of the dot product: • If u • v = 0, then u l v (i.e., the vectors are orthogonal). • If u • v > 0, then the angle 6 between the two vectors is less than 90°

(i.e., the vectors make an acute angle). • If u • v < 0, then the angle 0 between the two vectors is greater than 90°

(i.e., the vectors make an obtuse angle).

Note: The word "orthogonal" can be used as a synonym for "perpendicular."

Figure 1.9: On the left, the angle 6 between u and v is an acute angle. On the right, the angle 6 between u and v is an obtuse angle. When we refer to the angle between two vectors, we always mean the smallest angle, that is, the angle 0 such thatO<fJ<jr.

E x a m p l e 1.4

L e t u = (1,2, 3) and v = ( - 4 , 0 , - 1 ) . Find the angle between u and v. First we make the fol lowing computations:

(a) (b)

u - v = ( l , 2, 3 M - 4 , 0, - l ) = - 4 - 3 = - 7

|u||=^/l 2 + 2 2 + 3 2 = V l 4

|v|| = V ( — 4 ) 2 + 0 2 + ( — l ) 2 = V T 7

Page 11: Chapter01

Chapter 1: Vector Algebra 11

Now, applying Equation 1.4 and solving for theta, we get:

cos# = u • V - 7

Nil V u V r z

6= cos V T 4 V I 7

= 117°

E x a m p l e 1.5

Consider Figure 1.10. Given v and the unit vector n, f ind a formula for p using the dot product.

Figure 1.10: The orthogonal projection of v on n.

First , observe from the figure that there exists a scalar k such that p=/ ,n : moreover; since we assumed ||n||= 1, we have ||p||= ||&nj= |&|||n||= \k\. (Note that k may be negative if and only if p and 11 aim in opposite directions.) Using trigonometry, we have that k — fvPcos 0; therefore, p = fen = ([|v||cosf?)n. However, because n is a unit vector, we can say

this in another way:

p = (|'v|| cos d)n = (||v|| • 1 cos ()) n = (||v[[S|n||cos f?)n = ( v n ) n

In particular, this shows k = vn, and this i l lustrates the geometric in ter pretation of v • n when n is a unit vector. We call p the orthogonal projection of v on n, and it is commonly denoted by

p=projn(v)

If we interpret v as a force, p can be thought of as the port ion of the force v that acts in the direction n. Likewise, the vector w = v - p is the port ion of the force v that acts orthogonal to the direction n. Observe that v = p + w, which is to say we have decomposed the vector v into the sum of two orthogonal vectors p and w.

k

Page 12: Chapter01

12 Part I: Mathematical Prerequisites

If n is not of unit length, we can always normalize it f irst to make it unit length. Replacing n by the unit vector gives us the more general project ion formula:

, ' r \ ( n ) n ( v ' n )

n

1.4 The Cross Product The second form of mult ipl icat ion vector math defines is the cross product. Unl ike the dot product, which evaluates to a scalar, the cross product evaluates to another vector; moreover, the cross product is only defined for 3D vectors (in particular, there is no 2D cross product). Taking the cross product of two 3D vectors u and v yields another vector, w that is mutual ly orthogonal to u and v. By that we mean w is orthogonal to u. and w is orthogonal to v (see Figure 1.11). If u=(u„ uy, uz) a n d \ = { v „ vy, vz), then the cross product is computed l ike so:

w= uXv=(uyvz -uzvy,uzvx -uxvz,uxvy -uyvx) (1.5)

Figure 1.11: The cross product of two 3D vectors, u and v, yields another vector, w, that is mutually orthogonal to u and v. If you take your left hand and aim the fingers in the direction of the first vector u, and then curl your fingers toward v along an angle 0 <6 <n, then your thumb roughly points in the direction of w=uxw; this is called the left-hand-thumb rule.

E x a m p l e 1.6

Let u = (2 ,1 , 3) and v = (2, 0, 0). Compute w= u x v and z = v x u, and then verify that w is orthogonal to u and that w is orthogonal to v. Apply ing Equation 1.5 we have,

W = U X V = (2 ,1 , 3 ) x ( 2 , 0, 0) = ( l - 0 - 3 - 0 , 3 - 2 - 2 - 0 , 2 - 0 - l - 2 )

= ( 0 , 6 , - 2 )

and

Z = V X u

= ( 2 , 0 , 0 ) x ( 2 , l , 3 )

= ( 0 - 3 - 0 4 , Q - 2 - 2 - 3 , 2 - 1 - 0 - 2 )

= ( 0 , - 6 , 2 )

Page 13: Chapter01

Chapter 1: Vector Algebra 13

This result makes one th ing clear, generally speaking: u x v ^ v x u . There fore, we say that the cross product is anti-commutative. In fact, it can be shown that u x v = — v x u. You can determine the vector returned by the cross product by the left-hand-thumb rule. If you curve the fingers of your left hand from the direction of the f irst vector toward the second vector (always take the path w i t h the smallest angle), your thumb points in the direction of the returned vector, as shown in Figure 1.11.

To show that w is orthogonal to u and that w is orthogonal to v, we recall from §1.3 that if u • v= 0, then uJ_v (i.e., the vectors are orthogonal). Because

wu = (0, 6 , - 2 ) - ( 2 , 1 , 3 ) = 0-2 + 6 - l + ( - 2 ) - 3 = 0

and

w v = (0, 6 , - 2 ) - ( 2 , 0 , 0 ) = 0 - 2 + 6 -0 + ( - 2 ) - 0 = 0

we conclude that w is orthogonal to u and that w is orthogonal to v.

1.5 Points So far we have been discussing vectors, which do not describe positions. However, we w i l l also need to specify positions in our 3D programs; for example, the position of 3D geometry and the position of the 3D v i r tua l camera. Relative to a coordinate system, we can use a vector in standard position (see Figure 1.12) to represent a 3D position in space; we call this a position vector. In this case, the location of the t ip of the vector is the characterist ic of interest, not the direction or magnitude. We w i l l use the terms "posit ion vector" and "po in t " interchangeably since a position vector is enough to identify a point.

+ Y

(x, y, z)

+x

Figure 1.12: The position vector, which extends trom the origin to the point, fully describes the location of the point relative to the coordinate system.

One side effect of using vectors to represent points, especially in code, is that we can do vector operations that do not make sense for points; for instance, geometrically, what should the sum of two points mean? On the other hand, some operations can be extended to points. For example, we define the difference of two points q - p to be the vector from p to q. Also, we define a point p plus a vector v to be the point q obtained by displacing p

Page 14: Chapter01

14 Part I: Mathematical Prerequisites

by the vector v. Conveniently, because we are using vectors to represent points relative to a coordinate system, no extra work needs to be done for the point operations just discussed as the vector algebra framework already takes care of them (see Figure 1.13).

Figure 1.13: (a) The difference q - p between two points is defined as the vector from p to q. (b) A point p plus the vector v is defined to be the point q obtained by displacing p by the vector v.

Note: Actually there is a geometrically meaningful way to define a special sum of points, called an affine combination, which is like a weighted average of points. However, we do not use this concept in this book.

1.6 D3DX Vectors I n this section, we spend some t ime becoming familiar w i t h the D3DXVECT0R3 class, which is the class we often use to store the coordinates of both points and vectors in code relative to some coordinate system. I ts class definition

typedef struct D3DXVECTOR3 : public D3DVECTOR { public;

D3DXVECT0R3O { } ; D3DXVECTOR3C CONST FLOAT * ); D3DXVECT0R3( CONST 030VECT0R& ); O3DXVECT0R3( CONST 03DXFL0AT16 * ); D3DXVECT0R3( FLOAT x, FLOAT y, FLOAT z );

// casting operator FLOAT* ( ) ; operator CONST FLOAT* () const;

// assignment operators D3DXVECT0R3& operator += Q3DXVECT0R3& operator -= D30XVECTOR3& operator *= D3DXVECTOR3& operator /=

( CONST D30XVECT0R3& ); ( CONST D3DXVECT0R3& ); ( FLOAT'); ( FLOAT .);

// unary operators D3DXVECT0R3 operator + () const;

Page 15: Chapter01

Chapter 1: Vector Algebra 15

D3DXVECTOR3 operator - () const;

//binary operators : 03DXVECT0R3 operator + (CONST D3DXVICT0R3&) const; D3DXVECTOR3 operator - ( CONST 03DXVECT0R3& ) const; D30XVECTOR3 operator *( PLOAT ) const; D30XVECTOR3 operator / ( FLOAT ) const;

fr iend D3DXVECTQR3 operator * {FLOAT, CONST struct D3DXVECT0R3& );

: BOOL operator:^ { CONST D3DPECT0R3&:J const; BOOL operator != ( CONST D3DXV£CTOR3Bi) const;

} O3DXVECT0R3, *LPD3OXVECT0R3; ^

Note that D3DXVECT0R3 inherits its coordinate data from D3DVECT0R, which is defined as:

typedef struct J33DVECT0R j f l o a t x; f l o a t y; f l o a t z; . .

} D3DVECTQR;

Also observe that the D3DXVECT0R3 overloads the arithmetic operators to do vector addition, subtraction, and scalar mult ipl ication.

In addition to the above class, the D 3 D X l ibrary includes the fol lowing useful vector-related functions:

• FLOAT D3DXVec3Length( // Returns ijv|j CONST D3DXVECT0R3 *pV); // Input v

• FLOAT D3DXVec3LengthSq( // Returns Pvf CONST D3DXVECT0R3 *pV); // Input v

• FLOAT D3DXVec3Dot{ // Returns v, • v, CONST D3DXVECT0R3 *pVl, // Input v, CONST D3DXVECTOR3 *pV2); // Input v2

• D3DXVECT0R3 *D3DXVec3Cross( D3DXVECT0R3 *pOut, // Returns v, x v, CONST D3DXVECT0R3 *pVl, // Input \l

CONST D3DXVECT0R3 *pV2); // Input v?

• D3DXVECT0R3 *WINAPI D3DXVec3Normalize{ D3DXVECTOR3 *pOut, // Returns v / ||vf CONST D3DXVECT0R3 *pV, // Input v

Page 16: Chapter01

Part I: Mathematical Prerequisites

Note: Remember to link the d3dx10.lib (or d3dx10d.lib for debug builds) library file with your application to use any D3DX code; moreover, you will also need to #include <d3dx!0.h>.

The fol lowing short code provides some examples on how to use the D3DXVECT0R3 class and four of the five functions l isted above.

#include <d3dxl0.h> ^include <iostream> using namespace std;

/',' Overload the " « " operators so that we can use cout to // output D3DXVECTOR3 objects.

ostreamii o p e r d t o r « ( o s t r e a m & os, D3DXVECTOR3& v)

{

OS « "(" « v,x « ", " « v.y « ", " « v.z « ")"; return os;

i

in t main() {

// Using constructor, D3DXVECT0R3(FLOAT x, FLOAT y, FLOAT z); D3DXVECT0R3 u(1.0f, 2.Of, 3.Of);

// Using constructor, D3DXVECTOR3(CONST FLOAT *); float x[3] = {-2.Of, l.Of, -3.Of}; D3DXVECT0R3 v{x);

// Using constructor,\03DXVECT0R3() { } ; / D3DXVECTOR3 a, b, c , : d , e ;

// Vector addition: D3DXVECT0R3 operator + a = u + v..;

// Vector subtraction: D3DXVECTOR3 operator -b = u - v;

// Scalar m u l t i p l i c a t i o n : D3DXVE;eT0R3 operator * c = u *:10;

// I N I I . f l o a t L = D3DXVec3Length(&u);

// d - u / | |u|| D3DXVec3Norma1ize(&d, &u):;

// s = u dot v

f l o a t s=D3DXVec3Dot(&u, &v);

// e = u x v D3DXVec3Cross(&e, &u, ,&v)j

Page 17: Chapter01

Chapter 1: Vector Algebra 17

cout « "u cout « "v cout « "a cout « "b cout « "c cout « "d cout « "e cout « "L cout « "s

u + u -u * u / I u X V i i " i i

V V 10

« u « endl; « v « endl; « a « endl; « b « endl; « c « endl; « cl « endl; « e « endl; « L « endl; « s « end!;

return 0;

: = c i , 2. 3> - <-2, 1. -3>

v! = <-i, 3, 0> u = <3. ±, f»> IB - <10, 20, 31> n . i i i - <p.?c?26i. n.hw/.z, m mv,'M^ v\ - <-?, -9. 5>

I I - 3.7-1166 - -9

Figure 1.14: Output for the above program.

While we 're on the subject of work ing w i t h vectors on a computer, we should be aware of the fol lowing. When comparing floating-point numbers, care must be taken due to floating-point imprecision. Two floating-point numbers that we expect to be equal may differ slightly. For example, mathematically, we'd expect a normalized vector to have a length of 1, but in a computer program, the length w i l l only be approximately 1. Moreover, mathematically, V = 1 for any real number^), but when we only have a numerical approximation for 1, we see that the approximation raised to the pth power increases the error ; thus, numerical error also accumulates. The fol lowing short program illustrates these ideas:

l include <iostream> linclude <d3dxt0.h>; using namespace std;

int main() {

cout,precision(8);

D3DXVECT0R3 u(1.0f, l.Of, l .Of) ; D3DX¥ec3Normalize(&u, &u);

f loat LU = D3DXVec3Length(&u);

// Mathematically, the length should be 1. Is it numerically?

Page 18: Chapter01

Part I: Mathematical Prerequisites

cout « LU « endl; i f ( LU == l.Of )

cout « "Length 1" « endl; else

cout « "Length not 1" « endl;

// Raising 1 to any power should s t i l l be 1. Is i t ? f loat powLU = powffLU, 1.0e6f); cout « "LU^ClO e) - " « powLU « endl;

}

m c \W';-oows\systerr32\cn'd.exe " ' ' t *' I

Figure 1.15: Output for the above program.

To compensate for floating-point imprecision, we test if two floating-point numbers are approximately equal. We do this by defining an EPSILON constant, which is a very small value we use as a "buffer." We say two values are approximately equal if their distance is less than EPSILON. In other words, EPSILON gives us some tolerance for floating-point imprecision. The fol lowing function il lustrates how EPSILON can be used to test if two floating-point values are equal:

const f l o a t EPSILON = O.OOtf; bool Equals(float Ihs, f l o a t rhs)

// Is the distance between Ihs and rhs less than EPSILON? return f a b s ( l h S - rhs} < EPSILON ? true : false; } ."

Summary • Vectors are used to model physical quantities that possess both

magnitude and direction. Geometrically, we represent a vector w i t h a directed line segment. A vector is in standard position when it is translated parallel to itself so that its tail coincides w i t h the or ig in of the coordinate system. A vector in standard position can be described numerically by specifying the coordinates of its head relative to a coordinate system.

• If u = (w x , uy, uz) a n d \ = { v x , vv, vz), then we have the fol lowing vector operations:

Addit ion: u + v = (ux +vx,uv +vy,u2 +vz)

Subtraction: u— v=(ur — v.,, u,,—v... u—v.)

Scalar mult ipl icat ion: ku = (kux, kuy, ku.)

Page 19: Chapter01

Chapter 1: Vector Algebra 19

Length : ||u|| = y x 2 +}'2 + z2

Normalization: u = 11

U Dot product: u • v = !ju||vSJcosf9 = w , ^ +uyvy + uzvz

Cross product: u xv = (uyvz — uzvy, u,vx — uxvz, uxvy — uyvx)

• The D3DXVECT0R3 class is used to describe a 3D vector in code. This class contains three f 1 oat data members for representing the x-, y-, and z-coordinates of a vector relative to some coordinate system. The D3DXVECT0R3 class overloads the arithmetic operators to do vector addition, subtraction, and scalar mult ipl icat ion. Moreover, the D 3 D X l ibrary provides the fol lowing useful functions for computing the length of a vector, the squared length of a vector, the dot product of two vectors, the cross product of two vectors, and normalizing a vector:

FLOAT D3DXVec3Length(CONST D3DXVECT0R3 *pV); FLOAT D3DXVec3LengthSq(CONST 03DXVECT0R3 *pV); FLOAT D3DXVec3Dot(CONST D3DXVECT0R3 *pVl, CONST D3DXVECT0R3 *pV2); D3DXVECTQR3* D3DXVec3Cross(D3DXVECT0R3 *pOut,

CONST D3DXVECTOR3 *pVl, CONST D3DXVECTOR3 *pV2); D3DXVECT0R3* WINAPI 03DXVec3Norinal i ze(03DXVECTOR3 *pOut,

CONST D3DXVECT0R3 *pV);

1.8 Exercises 1. L e t u = (1,2) and v = ( 3 , - 4 ) . Perform the fol lowing computations and

draw the vectors relative to a 2D coordinate system:

a. u + v

b. u - v

c. 2 u + l / 2 v

d. - 2 u + v 2. L e t u = (— 1, 3,2) and v = (3, - 4 ,1) . Perform the fol lowing

computations:

a. u + v

b. u - v

c . 3 u + 2 v

d. - 2 u + v

3. This exercise shows that vector algebra shares many of the nice properties of real numbers (this is not an exhaustive l ist ) . Assume u = (ux, uy,uz),v= (vx,vy,vz), and w=(wx,wy,w.). Also assume that c

and k are scalars. Prove the fol lowing vector properties:

a. u + v = v + u (Commutative property of addition)

b. u + (v + w) = (u + v) + w (Associative property of addition)

Page 20: Chapter01

Part I: Mathematical Prerequisites

c. (ck)u = c(ku) (Associative property of scalar multipl ication)

d. k(u + v) = ku+kv (Distr ibut ive property 1)

e. u(k + c) = ku + cu (Distr ibut ive property 2) Hint: Just use the definition of the vector operations and the properties of real numbers. For example,

(ck)u = (ck)(ux,uy,uz)

= ((ck)ux, (ck)uv, (ck)uz)

— (dkux ), dkUy ), C(kuz ))

= C(kUX,kUy,kUz)

— c{k\x)

4. Solve the equation 2((1,2, 3) - x) - ( - 2 , 0 ,4) = - 2 ( 1 , 2 , 3) for x .

5. L e t u = ( - 1 , 3,2) and v = ( 3 , - 4 ,1) . Normalize u and v.

6. Let k be a scalar and let u = (ux, uv, uz). Prove that ]|/eu|| = | ||u[|.

7. Is the angle between u and v orthogonal, acute, or obtuse? a. u = ( l , l , l ) , v = (2, 3 ,4)

b. u = ( l , 1, 0 ) , v = ( - 2 , 2 , 0)

c. u = ( - 1 , - 1 , - 1 ) , v = ( 3 , 1 , 0)

8. L e t u = (—1, 3,2) and v = (3, — 4,1) . Find the angle 6 between u and v.

9. Letu = (ux,uy,uz), v=(v x,vy,v z ) , and w=(wx,wy,wz). Also l e t c andfe

be scalars. Prove the fol lowing dot properties:

a. u • v — v u

b. u • (v + w ) = u • v + u • w

c. k(u -v) = (ku)-v= u-(kv)

d. v • v = |v||2

e. ()• v = 0

Hint: Just use the definition, for example, v v = vxvx+vyvy+vzv2

= V2X+VJ+V2

Z

Page 21: Chapter01

Chapter 1: Vector Algebra 21

10. Use the law of cosines (c2 = a2 +b2 =2abcos6, where a, b, and c are the lengths of the sides of a triangle and 0 is the angle between sides a and b) to show:

uxvx+uvi\, +uzvz = ||u|j||v||cosf9.

Hint: Consider Figure 1.9 and set c2 = Sju - vj|, a2 = ||u||", and b2 - jjv|J2,

and use the dot product properties from the previous exercise.

11. Let n = ( - 2 , 1 ) . Decompose the vector g = (0, - 9.8) into the sum of two orthogonal vectors, one parallel to n and the other orthogonal to n. Also, draw the vectors relative to a 2D coordinate system.

12. Let u = ( - 2 , 1 , 4 ) and v = ( 3 , - 4 , 1 ) . Find w= u x v, and show w u = 0 and w • v = 0.

13. L e t the fol lowing points define a triangle relative to some coordinate system: A = (0, 0, 0), B = ( 0 , 1 , 3), and C = ( 5 , 1 , 0). Find a vector orthogonal to this triangle.

Hint: Find two vectors on two of the triangle's edges and use the cross product.

14. Prove that ||u x v|| = ||u||jvjjsin0. Hint: Start w i t h |ju||||v||sin0 and use the

tr igonometric identity cos 2 0 + s i n 2 6 > = l = > s i n # = V l - c o s 2 0 ; then apply Equation 1.4.

15. Prove that ||u x v|| gives the area of the parallelogram spanned by u and v (see Figure 1.16).

Figure 1.16: Parallelogram spanned by two 3D vectors u and v: the parallelogram has base "vji and height h.

16. Give an example of 3D vectors u. v. and w such that u x (v x \v) * (u x v) x w. This shows the cross product is generally not associative. Hint: Consider combinations of the simple vectors i = (1, 0, 0), j = ( 0 , 1 , 0), and k = (0, 0,1).

17. Prove that the cross product of two nonzero parallel vectors results in the nu l l vector; that is, u xfeu = 0. Hint: Just use the cross product definition.

Page 22: Chapter01

Part I: Mathematical Prerequisites

18. The D 3 D X l ibrary also provides the D3DXVECT0R2 and D3DXVECT0R4 classes for w o r k i n g w i t h 2D and 4D vectors. We w i l l later use 2D vectors to describe 2D points on texture maps. The purpose of 4D vectors w i l l make more sense after reading the next chapter when we discuss homogeneous coordinates. Rewrite the program in §1.6 twice , once using 2D vectors (D3DXVECT0R2) and a second t ime using 4D vectors (D3DXVECT0R4). Note that there is no 2D cross product function, so you can skip that. (Hint: Search the index for these keywords in the DirectX S D K documentation: D3DXVECT0R2, D3DXVECT0R4, D3DXVec2, and D3DXVec4.)