Vectors and matrices in D
Andreas Zwinkau
beza1e1 at web.de
Thu Mar 15 09:21:19 PDT 2007
> I started implementing a little raytracer in D (raytracing is addictive, yeah ;)), and faced problems with vector/matrix math :(
Me too :)
I wanted to learn D and to write a raytracer for some time. Currently i have some time to do so. I got a little sidetracked into D templates by the vector implementation.
Every implementation (Artyom, helix, some C++ raytracers) i've seen so far uses a struct for the vectors. Why? Performance? Does Bill Baxter hint at this?
http://www.digitalmars.com/pnews/read.php?server=news.digitalmars.com&group=digitalmars.D&artnum=46958
I wrote a generic vector class. Maybe someone would like to comment on that? I it's just addition and subtraction so far, but the pattern is clear. Here comes my code:
import std.stdarg;
import std.string;
class Vector(T, int S) {
T[S] content;
this(...) {
for (int i = 0; i < _arguments.length; i++) {
content[i] = va_arg!(T)(_argptr);
}
}
T opIndex(int i) {
assert(i < content.length,
std.string.format("%d < %d !!!\n", i, content.length));
return content[i];
}
void opIndexAssign(T n, int i) {
content[i] = n;
}
Vector!(T,S) opAdd( Vector!(T,S) other ) {
Vector!(T,S) n = new Vector!(T,S)();
foreach(int i, T c; content) {
n[i] = c + other[i];
}
return n;
}
Vector!(T,S) opSub( Vector!(T,S) other ) {
Vector!(T,S) n = new Vector!(T,S)();
foreach(int i, T c; content) {
n[i] = c - other[i];
}
return n;
}
}
unittest {
Vector!(int, 2) a = new Vector!(int, 2)(1,3);
Vector!(int, 2) b = new Vector!(int, 2)(1,2);
// check addition
Vector!(int, 2) c = a + b;
assert(c[0] == 2);
assert(c[1] == 5);
// check subtraction
Vector!(int, 2) d = a - b;
assert(d[0] == 0);
assert(d[1] == 1);
}
alias Vector!(float,3) Vector3D;
alias Vector!(float,2) Vector2D;
unittest {
Vector3D x = new Vector3D(2,3,4);
Vector3D y = x + x;
assert(y[2] - 8 < 0.001);
}
More information about the Digitalmars-d-learn
mailing list