This is a member function of my Vec3D class that I often find very useful.
It constructs a coordinate system from a single 3D vector.
The code is adapted from the book “Physically Based Rendering”.
// v1, v2 and v3 are result vectors
// v1 becomes parallel to this (a Vec3D)
public void getCoordinateSystemFromThis(Vec3D v1, Vec3D v2, Vec3D v3) {
Vec3D v = normalizeCopy();
if (Math.abs(v.x) > Math.abs(v.y)) {
double invLen = 1.0 / Math.sqrt(v.x * v.x + v.z * v.z);
v2.set(-v.z * invLen, 0.0, v.x * invLen);
} else {
double invLen = 1.0 / Math.sqrt(v.y * v.y + v.z * v.z);
v2.set(0.0, v.z * invLen, -v.y * invLen);
}
v3.set(v.crossProductCopy(v2));
v1.set(v);
}