3d vector struct

Brenton bnrayner at hotmail.com
Mon Feb 3 12:10:57 PST 2014


Hi, I'm just getting to know D and so am hoping that someone more 
experienced with the language could review this 3d vector struct 
and my comments below.  I'm planning on building a little ray 
tracer in the next week or so :)

struct Vector3d {
	double x = 0, y = 0, z = 0;

	void normalize() {
		double scale = 1.0 / (x * x + y * y + z * z);
		x *= scale; y *= scale; z *= scale;
	}
	double dot(in Vector3d other) inout {
		return x * other.x + y * other.y + z * other.z;
	}
	Vector3d cross(in Vector3d other) inout {
		const Vector3d result = {
			y * other.z - z * other.y,
			z * other.x - x * other.z,
			x * other.y - y * other.x
		};
		return result;
	}
}

1) I initialize the vector to a null vector, not nans
2) The dot and cross are "inout" methods, i.e. available for 
mutable, const, and immutable objects.  There is no reason to 
declare "inout" methods as being "const".
3) The dot and cross methods take an input "in" argument.  This 
allows the compiler to choose between passing the parameter by 
const value or const reference.  I read somewhere that "in" and 
"scope" have not yet been implemented yet and that I should use 
"const ref" instead?
4) Is it advisable for the cross method to return by value?  In 
C++, I would declare this method as inline and in a header file.  
Can I trust D to inline away this inefficiency?  Perhaps I should 
pass in the result as a "ref" or "out" parameter (although I 
don't require the vector to be initialized here)?  Is there a 
more efficient way to do this?
5) I notice that a lot of other people online prefer using fixed 
arrays not structs for Vectors in D, why?
6) Any other comments or suggestions?


More information about the Digitalmars-d-learn mailing list