1 // original post to the D newsgroup:
2 // http://www.digitalmars.com/pnews/read.php?server=news.digitalmars.com&group=D&artnum=10554&header
3 // Test to manipulate 3D vectors, in D!
4 // by Sean L Palmer (seanpalmer@directvinternet.com)
5 // This code is released without any warranty. Use at your own risk.
6 import core.stdc.stdio;
7 import std.math : sqrt;
9 template VecTemplate(tfloat, int dim:3)
17 // sets the vector to the value of the given array
18 void set(tfloat[dim] r) { d[] = r[]; }
19 // comparison (a == b, a != b)
20 bool opEquals(Vector b) { for (int i=0; i<dim; ++i) if (d[i] != b.d[i]) return
23 Vector opNeg() { Vector r; for (int i=0; i<dim; ++i) r.d[i] = -d[i]; return
26 Vector opCom() { Vector r; for (int i=0; i<dim; ++i) r.d[i] = d[(i+1)%dim];
27 d[0] = -d[0]; return r; }
29 Vector opAdd(Vector b) { Vector r; r.d[] = d[] + b.d[]; return r; }
31 Vector opAddAssign(Vector b) { d[] += b.d[]; return r; }
33 Vector opSub(Vector b) { Vector r; r.d[] = d[] - b.d[]; return r; }
34 // multiply by scalar (a * 2.0)
35 Vector opMul(tfloat b) { Vector r; for (int i=0; i<dim; ++i) r.d[i] = d[i]
37 // divide by scalar (a / b)
38 Vector opDiv(tfloat b) { return *this * (1/b); }
39 // dot product (a * b)
40 tfloat opMul(Vector b) { tfloat r=0; for (int i=0; i<dim; ++i) r += d[i];
42 // outer product (a ^ b)
43 //Vector opXor(Vector b) { Vector r; for (int i=0; i<dim; ++i) r += d[i]; return r; }
46 void set(tfloat[dim] r) { for (int i=0; i<dim; ++i) d[i] = r[i]; }
47 // comparison (a == b, a != b)
48 const bool opEquals(ref const Vector b) { for (int i=0; i<dim; ++i) if (d[i] != b.d[i]) return
51 Vector opNeg() { Vector r; for (int i=0; i<dim; ++i) r.d[i] = -d[i]; return
54 Vector opCom() { Vector r; for (int i=0; i<dim; ++i) r.d[i] = d[(i+1)%dim];
55 d[0] = -d[0]; return r; }
57 Vector opAdd(Vector b) { Vector r; for (int i=0; i<dim; ++i) r.d[i] = d[i] +
60 Vector opAddAssign(Vector b) { for (int i=0; i<dim; ++i) d[i] += b.d[i]; return
63 Vector opSub(Vector b) { Vector r; for (int i=0; i<dim; ++i) r.d[i] = d[i] -
65 // multiply by scalar (a * 2.0)
66 Vector opMul(tfloat b) { Vector r; for (int i=0; i<dim; ++i) r.d[i] = d[i] *
68 // divide by scalar (a / b)
69 Vector opDiv(tfloat b) { return this * (1/b); }
70 // dot product (a * b)
71 tfloat opMul(Vector b) { tfloat r=0; for (int i=0; i<dim; ++i) r += d[i];
73 // outer product (a ^ b)
74 //Vector opXor(Vector b) { Vector r; for (int i=0; i<dim; ++i) r += d[i]; return r; }
76 void print() { for (int i=0; i<dim; ++i) printf("%f ", d[i]);
91 alias VecTemplate!(float, 3) VcT;
93 float[3] up = [ 0, 1, 0 ];
95 int main(char[][] args)
98 with (VcT) // try this, I dare ya!! crashes DMD 0.51
105 printf("b * c = %f\n",b * c);
106 printf("abs(a) = %f\n",VcT.abs(a));
107 printf("sqr(a) = %f\n",VcT.sqr(a));