raytracing/in_one_weekend/src/camera.zig

54 lines
1.5 KiB
Zig
Raw Normal View History

2021-05-27 22:44:29 +02:00
const std = @import("std");
const math = std.math;
2021-04-26 22:51:49 +02:00
const Point3 = @import("vec3.zig").Point3;
const Vec3 = @import("vec3.zig").Vec3;
const Ray = @import("ray.zig").Ray;
2021-05-27 22:44:29 +02:00
fn degreesToRadians(degrees: f32) f32 {
return degrees * math.pi / 180.0;
}
2021-04-26 22:51:49 +02:00
pub const Camera = struct {
origin: Point3,
lowerLeftCorner: Point3,
horizontal: Vec3,
vertical: Vec3,
2021-05-27 22:44:29 +02:00
pub fn init(
lookFrom: Point3,
lookAt: Point3,
vup: Vec3,
vfov: f32,
aspectRatio: f32,
) Camera {
const theta = degreesToRadians(vfov);
const h = math.tan(theta / 2);
const viewportHeight = 2.0 * h;
2021-04-26 22:51:49 +02:00
const viewportWidth = aspectRatio * viewportHeight;
2021-05-27 22:44:29 +02:00
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);
const vertical = v.mul_s(viewportHeight);
const lowerLeftCorner = origin.sub(horizontal.div(2)).sub(vertical.div(2)).sub(w);
2021-04-26 22:51:49 +02:00
return Camera {
.origin = origin,
.horizontal = horizontal,
.vertical = vertical,
.lowerLeftCorner = lowerLeftCorner,
};
}
2021-05-27 22:44:29 +02:00
pub fn getRay(self: Camera, s: f32, t: f32) Ray {
2021-04-26 22:51:49 +02:00
return Ray{
.origin = self.origin,
2021-05-27 22:44:29 +02:00
.direction = self.lowerLeftCorner.add(self.horizontal.mul_s(s)).add(self.vertical.mul_s(t)).sub(self.origin),
2021-04-26 22:51:49 +02:00
};
}
};