76 lines
2.1 KiB
Zig
76 lines
2.1 KiB
Zig
const std = @import("std");
|
|
const math = std.math;
|
|
const Random = std.rand.Random;
|
|
|
|
const Point3 = @import("vec3.zig").Point3;
|
|
const Vec3 = @import("vec3.zig").Vec3;
|
|
const Ray = @import("ray.zig").Ray;
|
|
|
|
fn degreesToRadians(degrees: f32) f32 {
|
|
return degrees * math.pi / 180.0;
|
|
}
|
|
|
|
fn random_in_unit_disk(rng: *Random) Vec3 {
|
|
while (true) {
|
|
const p = Vec3{ .x = rng.float(f32) * 2 - 1, .y = rng.float(f32) * 2 - 1, .z = 0 };
|
|
if (p.length_squared() >= 1) continue;
|
|
return p;
|
|
}
|
|
}
|
|
|
|
pub const Camera = struct {
|
|
origin: Point3,
|
|
lowerLeftCorner: Point3,
|
|
horizontal: Vec3,
|
|
vertical: Vec3,
|
|
u: Vec3,
|
|
v: Vec3,
|
|
w: Vec3,
|
|
lensRadius: f32,
|
|
|
|
pub fn init(
|
|
lookFrom: Point3,
|
|
lookAt: Point3,
|
|
vup: Vec3,
|
|
vfov: f32,
|
|
aspectRatio: f32,
|
|
aperture: f32,
|
|
focusDist: f32,
|
|
) Camera {
|
|
const theta = degreesToRadians(vfov);
|
|
const h = math.tan(theta / 2);
|
|
|
|
const viewportHeight = 2.0 * h;
|
|
const viewportWidth = aspectRatio * viewportHeight;
|
|
|
|
const w = lookFrom.sub(lookAt).unit();
|
|
const u = vup.cross(w).unit();
|
|
const v = w.cross(u);
|
|
|
|
const origin = lookFrom;
|
|
const horizontal = u.mul_s(viewportWidth).mul_s(focusDist);
|
|
const vertical = v.mul_s(viewportHeight).mul_s(focusDist);
|
|
const lowerLeftCorner = origin.sub(horizontal.div(2)).sub(vertical.div(2)).sub(w.mul_s(focusDist));
|
|
|
|
return Camera {
|
|
.origin = origin,
|
|
.horizontal = horizontal,
|
|
.vertical = vertical,
|
|
.lowerLeftCorner = lowerLeftCorner,
|
|
.u = u,
|
|
.v = v,
|
|
.w = w,
|
|
.lensRadius = aperture / 2,
|
|
};
|
|
}
|
|
|
|
pub fn getRay(self: Camera, s: f32, t: f32, rng: *Random) Ray {
|
|
const rd = random_in_unit_disk(rng).mul_s(self.lensRadius);
|
|
const offset = self.u.mul_s(rd.x).add(self.v.mul_s(rd.y));
|
|
|
|
return Ray{
|
|
.origin = self.origin.add(offset),
|
|
.direction = self.lowerLeftCorner.add(self.horizontal.mul_s(s)).add(self.vertical.mul_s(t)).sub(self.origin).sub(offset),
|
|
};
|
|
}
|
|
}; |