of 17/17
Computer Graphics Basic Maths for Graphics in C++ CO2409 Computer Graphics Week 4
• date post

19-Jan-2016
• Category

## Documents

• view

212
• download

0

Embed Size (px)

### Transcript of Computer Graphics Basic Maths for Graphics in C++ CO2409 Computer Graphics Week 4.

• Computer GraphicsBasic Maths for Graphics in C++CO2409 Computer GraphicsWeek 4

• Todays LectureNumbersNumeric FunctionsMath FunctionsVectors & Vector Operations

• Mathematics distinguishes between several types of number:Whole numbers (called the natural numbers)0,1,2, only positive numbers

Integers0,1,-1,2,-2,3,-3, +ve or -ve whole numbers

Real numbers0.02, -3.455, 124.0, 0.33333, any number written with a decimal point (possibly infinitely long)

As well as others

A number (in any form) is called a scalarNumbers.

• Numbers in C++Equivalent types of number in C++:int - integers (+ve or ve)unsigned int - whole numbers (+ve only)float or double - real numbers

Each type has finite storage, e.g. 4-bytes for intExact size depends on compiler

So they have limitations not present in maths:Maximum and minimum valuesE.g. typical int (4-bytes) has max/min of approximately 2 billionfloat cant represent all possible real numbersE.g. float cant hold 0.1, value may be 0.0999999977648258

• More Numbers in C++There are different sizes of these types:long int (or long) / short int (or short)More / less precision than int (maybe)unsigned versions of these toochar, unsigned charUsed for characters, but really a 1-byte integerdouble and long doubleHave more precision than float

Exact sizes of these also depend on compilerDont assume the size or accuracy of a type in C++Unless you use compiler-specific codePossible exception of char (1-byte)

• Guidelines for C++ Numbers Large values may be out of range for an intE.g. Astronomical distances

float / double rarely hold exactly the numbers you tell them to there is usually a small approximation errorExcept for a small range of integersSo never use == on floats or doublesUnless you can guarantee that the value will be an exact small integer (e.g. f == 0.0), this situation is rareRepeated float calculations can cause the error to magnifyThe approximation error will be greater for larger values

Normally int / float = 4 bytes, double = 8 bytesSome compilers/platforms use larger values now (int = 8 bytes)

• Number Conversions in C++C++ can automatically convert number typesBut doesnt always: 5 / 10 = 0, Correct: 5.0 / 10.0

The compiler usually issues a warning when it does perform a conversionE.g. int i = 9.0/10.0; // Warning likely (i = 0)Dont ignore warnings ensure it is what you want

float / double are always rounded down to intint DownInt = 3.7f; // DownInt = 3If you want to round to the nearest int:int NearInt = MyFloat + 0.5f;N.B. 0.5 is a double, 0.5f is a float

• Number Conversions in C++Casting is explicitly requesting a conversion

The modern C++ casting style is:float f = static_cast(MyInteger);The older style should be avoided in new code (less safe):float f = (float)MyInteger;

Casting will remove warnings about conversionsHowever, use of casting sometimes implies poorly designed codeEnsure that the casting is necessaryMaybe you just need to reconsider the variable types that you are using

• Basic Functions: Max & MinWe frequently need the maximum or minimum of a pair of numbersDont repeatedly write if statements in your code

Instead, the STL contains a max functionint maxSize = std::max( size1, size2 );This is a template function that works with any typeInclude the header file

You may see code examples with min/max in a macroA line using the keyword #defineAvoid this approach as it wont check your types

• Basic Functions: RemaindersFinding remainders is also commonE.g. the remainder of 15 after dividing by 6, is 3

Can use C operators or standard library functions:A % B = remainder of A / B where A and B are intfmodf( A, B ) is the same for floatfmod( A, B ) for double

E.g. 18 % 7 = 4, fmod( 5.4, 2.0 ) = 1.4

All C++ functions in this lecture are in

• Math Functions: Absolute ValueThe absolute value or modulus of a scalar, written |x|, is mathematically defined like this:

Simply removes any minus sign, e.g. |5| = 5, |-23| = 23Roughly speaking |x| means the size of xWe will see it used for vectors later with this meaning

Use abs / fabsf / fabs functions in C++:int i = abs( MyInteger );float f = fabsf( MyFloat ); // fabs for doubleUse modulus to find the distance between two valuesint Dist = abs( X2 X1 )Same result even if we swap X1 & X2

• Math Functions: xyxy is calculated with C++ function pow:y = pow( x, 4 ); // y = x4 (= x*x*x*x)y = pow( x, 0.5 ); // y = x (= x)y = pow( x, 0.333 ); // y = 3x (= x)Use pow for doubles, powf for floats

Dont always use pow:for x2 use x * xfor x3 use x * x * xfor x use sqrt( x ) More efficient for these simpler cases

• Math Functions: cos & sinGiven a right angled triangle:cos = AC / ABsin = BC / ABThere are many other properties of cos and sinE.g. Circle equations earlierIn the C library, angles (i.e. ) are measured in radians360 = 2 radians, so a = a * /180 radiansE.g. 90 degrees = 90 * /180 = / 2 radians (about 1.57)

So in C++: float f = cos( a * 3.14f/180.0f );Where a is an angle in degrees

• VectorsA vector can be a directed edge joining two pointsBut a vector can be defined without reference to pointsE.g. the velocity of an aircraft

Vectors are often used to represent a translation (movement) or a velocityThe length of vector v(x, y) is: Note the reuse of the modulus symbol (size of)This is the distance travelled for a translation, or the speed for a velocity

• NormalsA normal is any vector whose length is 1Sometimes, but not always, represented with a ^ symbol:

Any vector can be converted to a normal (normalised) by dividing the components by the length:

A normal can be seen as the direction of a vectorA vector can be broken up into normal and length, e.g.Movement = Normal (direction of movement) + distanceVelocity = Normal (direction of motion) + speedNormals and normalising are very common in graphics

• Dot ProductsA dot product is an operation on two vectors, giving a scalar resultThe dot product of the vectors v1(x1,y1) and v2(x2,y2) is:

Easily calculated

The dot product is also equal to:

Where is angle between the vectorsJust multiply together the lengths of the vectors and the angle between themA useful form when working with angles

• Dot ProductsDot products become important when the vectors are normalised : |v1| = |v2| = 1Using the formulas from last slide: v1 v2 = cos => = cos-1(v1 v2) => = cos-1(x1 x2 + y1 y2)

Allows us can calculate the angle between two vectors:Need the vector componentsAnd cos-1 (in C++ use function acos)Very useful in graphics (and games)