Lesson 6 of 15
Dot and Cross Products
Dot and Cross Products
Two fundamental vector operations power almost all lighting math in the ray tracer.
Dot Product
The dot product returns a scalar — the sum of component-wise products:
dot(a, b) = a.x*b.x + a.y*b.y + a.z*b.z
double dot(Tuple a, Tuple b) {
return a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w;
}
The dot product has a geometric meaning: dot(a, b) = |a| * |b| * cos(θ) where θ is the angle between them. For normalized vectors:
dot = 1→ same directiondot = 0→ perpendiculardot = -1→ opposite directions
Cross Product
The cross product returns a vector perpendicular to both inputs:
cross(a, b).x = a.y*b.z - a.z*b.y
cross(a, b).y = a.z*b.x - a.x*b.z
cross(a, b).z = a.x*b.y - a.y*b.x
Tuple cross(Tuple a, Tuple b) {
return Tuple(
a.y*b.z - a.z*b.y,
a.z*b.x - a.x*b.z,
a.x*b.y - a.y*b.x,
0
);
}
Note: cross(a, b) = -cross(b, a). Order matters!
Your Task
Implement both dot and cross functions.
Expected output:
Dot: 20
Cross: -1 2 -1JSCPP loading...
Loading...
Click "Run" to execute your code.