src/vector.h
author Radek Brich <radek.brich@devl.cz>
Sat, 17 Nov 2007 17:20:36 +0100
branchpyrit
changeset 4 c73bc405ee7a
parent 0 3547b885df7e
child 12 f4fcabf05785
permissions -rw-r--r--
multi-threaded rendering via pthreads added README

/*
 * C++ RayTracer
 * file: vector.h
 *
 * Radek Brich, 2006
 */

#ifndef VECTOR_H
#define VECTOR_H

#include <math.h>
#include <iostream>

using namespace std;

class Vector3
{
public:
	// data
	union {
		struct {
			float x, y, z;
		};
		struct {
			float r, g, b;
		};
		float cell[3];
	};

	// constructors
	Vector3(): x(0.0f), y(0.0f), z(0.0f) {};
	Vector3(float ax, float ay, float az): x(ax), y(ay), z(az) {};

	// index operator
	float &operator[](int index)	{ return cell[index]; };

	// normalize
	Vector3 normalize()
	{
		float f = 1.0f / mag();
		x *= f;
		y *= f;
		z *= f;
		return *this;
	}

	// get normalized copy
	Vector3 unit()
	{
		Vector3 u(*this);
		return u.normalize();;
	}

	// square magnitude, magnitude
	float mag2()	{ return x * x + y * y + z * z; }
	float mag()	{ return sqrtf(mag2()); }

	// negative
	Vector3 operator-()	{ return Vector3(-x, -y, -z); }

	// accumulate
	Vector3 operator+=(const Vector3 &v)
	{
		x += v.x;
		y += v.y;
		z += v.z;
		return *this;
	};

	// sum
	friend Vector3 operator+(const Vector3 &a, const Vector3 &b)
	{
		return Vector3(a.x + b.x, a.y + b.y, a.z + b.z);
	};

	// difference
	friend Vector3 operator-(const Vector3 &a, const Vector3 &b)
	{
		return Vector3(a.x - b.x, a.y - b.y, a.z - b.z);
	};

	// dot product
	friend float dot(const Vector3 &a, const Vector3 &b)
	{
		return a.x * b.x + a.y * b.y + a.z * b.z;
	};

	// cross product
	friend Vector3 cross(const Vector3 &a, const Vector3 &b)
	{
		return Vector3(a.y * b.z - a.z * b.y,
			a.z * b.x - a.x * b.z,
			a.x * b.y - a.y * b.x);
	};

	// product of vector and scalar
	Vector3 operator*(const float &f)
	{
		return Vector3(f * x, f * y, f * z);
	}

	friend Vector3 operator*(const float &f, Vector3 &v)
	{
		return v * f;
	};

	// cell by cell product (only usable for colours)
	friend Vector3 operator*(const Vector3 &a,  const Vector3 &b)
	{
		return Vector3(a.x * b.x, a.y * b.y, a.z * b.z);
	};

	// print
	friend ostream & operator<<(ostream &st, const Vector3 &v)
	{
		return st << "(" << v.x << ", " << v.y  << ", " << v.z << ")";
	}
};

typedef Vector3 Colour;

#endif