iPhone 3D Programming : Vector Beautification with C++

10/10/2010 2:58:56 PM
Recall the vertex structure in HelloArrow:
struct Vertex {
float Position[2];
float Color[4];

If we kept using vanilla C arrays like this throughout this book, life would become very tedious! What we really want is something like this:

struct Vertex {
vec2 Position;
vec4 Color;

This is where the power of C++ operator overloading and class templates really shines. It makes it possible (in fact, it makes it easy) to write a small class library that makes much of your application code look like it’s written in a vector-based language. In fact, that’s what we’ve done for the samples in this book. Our entire library consists of only three header files and no .cpp files:


Defines a suite of 2D, 3D, and 4D vector types that can be either float-based or integer-based. Has no dependencies on any other header.


Defines classes for 2×2, 3×3, and 4×4 matrices. Depends only on Vector.hpp.


Defines a class for quaternions and provides several methods for interpolation and construction. Depends on Matrix.hpp.

These files are listed in their entirety in the appendix, but to give you a taste of how the library is structured, Example 1 shows portions of Vector.hpp.

Example 1. Vector.hpp
#pragma once
#include <cmath>

template <typename T>
struct Vector2 {
Vector2() {}
Vector2(T x, T y) : x(x), y(y) {}
T x;
T y;

template <typename T>
struct Vector3 {
Vector3() {}
Vector3(T x, T y, T z) : x(x), y(y), z(z) {}
void Normalize()
float length = std::sqrt(x * x + y * y + z * z);
x /= length;
y /= length;
z /= length;
Vector3 Normalized() const
Vector3 v = *this;
return v;
Vector3 Cross(const Vector3& v) const
return Vector3(y * v.z - z * v.y,
z * v.x - x * v.z,
x * v.y - y * v.x);
T Dot(const Vector3& v) const
return x * v.x + y * v.y + z * v.z;
Vector3 operator-() const
return Vector3(-x, -y, -z);
bool operator==(const Vector3& v) const
return x == v.x && y == v.y && z == v.z;
T x;
T y;
T z;

template <typename T>
struct Vector4 {

typedef Vector2<int> ivec2;
typedef Vector3<int> ivec3;
typedef Vector4<int> ivec4;

typedef Vector2<float> vec2;
typedef Vector3<float> vec3;
typedef Vector4<float> vec4;

Note how we parameterized each vector type using C++ templates. This allows the same logic to be used for both float-based vectors and integer-based vectors.

Even though a 2D vector has much in common with a 3D vector, we chose not to share logic between them. This could’ve been achieved by adding a second template argument for dimensionality, as in the following:

template <typename T, int Dimension>
struct Vector {
T components[Dimension];

When designing a vector library, it’s important to strike the right balance between generality and readability. Since there’s relatively little logic in each vector class and since we rarely need to iterate over vector components, defining separate classes seems like a reasonable way to go. It’s also easier for readers to understand the meaning of, say, Position.y than Position[1].

Since a good bit of application code will be making frequent use of these types, the bottom of Example 2-5 defines some abbreviated names using typedefs. Lowercase names such as vec2 and ivec4 break the naming convention we’ve established for types, but they adopt a look and feel similar to native types in the language itself.

The vec2/ivec2 style names in our C++ vector library are directly pilfered from keywords in GLSL. Take care not to confuse this book’s C++ listings with shader listings.

Warning: In GLSL shaders, types such as vec2 and mat4 are built into the language itself. Our C++ vector library merely mimics them.
  •  jQuery 1.3 : An image carousel
  •  jQuery 1.3 : Headline rotator
  •  Silverlight : Print a Document
  •  Silverlight : Capture a Webcam
  •  Silverlight : Make Your Application Run out of the Browser
  •  Silverlight : Put Content into a 3D Perspective
  •  Silverlight : Response to Timer Events on the UI Thread
  •  Silverlight : Build a Download and Playback Progress Bar
  •  Silverlight : Play a Video
  •  C# 4.0 : Add a Static Constructor and Initialization
  •  C# 4.0 : Add a Constructor
  •  .NET Compact Framework : Font Selection
  •  .NET Compact Framework : Drawing Text
  •  Programming the Service Bus
  •  WCF Services : Generics
  •  WCF Services : Delegates and Data Contracts
  •  WCF Services : Enumerations
  •  WCF Services : Versioning
  •  WCF Services : Data Contract - Equivalence
  •  WCF Services : Data Contract - Hierarchy
    Top 10
    Microsoft XNA Game Studio 3.0 : Displaying Images - Using Resources in a Game (part 3) - Sprite Drawing with SpriteBatch
    The .NET Security Architecture
    Exploring Sample Virtualized SharePoint 2010 Architecture
    IIS 7.0 : Hosting ASP.NET Applications
    CSS for Mobile Browsers : Where to Insert the CSS
    Advanced ASP.NET : Output Caching
    Role-Based Security Explained
    Mobile Application Security : Windows Mobile Security - Development and Security Testing (part 1)
    iPhone Application Development : Customizing Interface Appearance
    Installing SharePoint 2010 Using PowerShell
    Most View
    Algorithms for Compiler Design: A HANDLE OF A RIGHT SENTENTIAL FORM
    Silverlight : Capture a Webcam
    Creating a Development Provisioning Profile on iPhone
    Programming with SQL Azure : Record Navigation in WCF Data Services
    Mobile Application Security : BlackBerry Security - Introduction to Platform
    Adobe InDesign CS5 : Importing Graphic Objects (part 1) - Understanding Adobe Bridge
    Windows Server 2008 R2 monitoring and troubleshooting : Data Collector Sets
    Transact-SQL in SQL Server 2008 : Insert over DML
    IIS 7.0 : Implementing Access Control - Authentication (part 1)
    Windows System Programming : File Pointers & Getting the File Size
    SharePoint 2010 : Workflow Modeling and Development Tools (part 1) - Microsoft Visio 2010 & SharePoint Designer 2010
    Web Security Testing : Changing Sessions to Evade Restrictions & Impersonating Another User
    Becoming an Excel Programmer : Start and Stop
    The best social game apps for iOS Device (Part 2) - SteamScope, Blockwick, Pinball Arcade
    SQL Server 2008 : Using ADO.NET Data Services
    .NET security : Isolated Storage Explained
    SharePoint 2010 : Beyond Built-In SharePoint PowerShell Cmdlets
    Server-Side Browser Detection and Content Delivery : Mobile Detection (part 1) - HTTP
    WCF Services : Data Contract - Equivalence
    Deploying a Native SharePoint 2010 Search Service Application