I’m translating a C++ code base (raytracing in one weekend) to Zig for learning and the original material heavily uses operator overload.
This C++ code looks simple, as I need to just subtract Vec3 structs from each other.
C++ code snippet:
auto viewport_upper_left = camera_center - vec3(0, 0, focal_length) - viewport_u/2 - viewport_v/2;
In Zig, I had to make a function in my vec3 struct, so I can specifically subtract 4 vec3s to make this work.
First I tried to use all my functions in the vec3 struct and did this:
main.zig
const viewport_upper_left = vec3.subs(camera_center, vec3.subs((vec3.init(0, 0, focal_length)), vec3.subs((vec3.scalarDiv(viewport_u, 2)), vec3.scalarDiv(viewport_v, 2))));
Needless to say, this made a bug in my code, where the upper left pixel wasn’t placed correctly.
So I broke up the subtraction to smaller pieces for readability, and made a function that has 4 Vec3 parameters that subtracts.
main.zig
const viewport_a = vec3.init(0, 0, focal_length);
const viewport_b = vec3.scalarDiv(viewport_u, 2);
const viewport_c = vec3.scalarDiv(viewport_v, 2);
const viewport_upper_left = vec3.subs4(camera_center, viewport_a, viewport_b, viewport_c);
vec3.zig
pub fn subs4(v: Vec3, w: Vec3, a: Vec3, b: Vec3) Vec3 {
return .{
.x = v.x - w.x - a.x - b.x,
.y = v.y - w.y - a.y - b.y,
.z = v.z - w.z - a.z - b.z,
};
}
For this Zig implementation I challanged myself to not use any AI prompt, and try to minimize online searching to the zig documentation and a few zig learning sites. I feel like it’s a right time to ask this question, as I can see later this will be getting out of hand and the whole purpose is to learn to use the language correctly.