0204-可移动相机

环境

  • Time 2022-11-17
  • WSL-Ubuntu 22.04
  • Rust 1.65.0

前言

说明

参考:https://raytracing.github.io/books/RayTracingInOneWeekend.html

目标

将相机的位置和远近参数化,可以调节相机的位置。

叉乘

// 向量的叉乘
pub fn cross(self, other: Vector3) -> Vector3 {
    Vector3 {
        x: self.y * other.z - self.z * other.y,
        y: self.z * other.x - self.x * other.z,
        z: self.x * other.y - self.y * other.x,
    }
}

camera.rs

use super::ray::Ray;
use super::vector3::{Point3, Vector3};

pub struct Camera {
    origin: Point3,
    corner: Point3,
    horizontal: Vector3,
    vertical: Vector3,
}

pub const RATIO: f64 = 16.0 / 9.0;

impl Camera {
    pub fn new(origin: Point3, at: Point3, vup: Vector3, fov: f64, ratio: f64) -> Camera {
        let theta = std::f64::consts::PI / 180.0 * fov;
        let viewport_height = 2.0 * (theta / 2.0).tan();
        let viewport_width = ratio * viewport_height;

        let cw = (origin - at).unit();
        let cu = vup.cross(cw);
        let cv = cw.cross(cu);

        let horizontal = viewport_width * cu;
        let vertical = viewport_height * cv;

        let corner = origin - horizontal / 2.0 - vertical / 2.0 - cw;

        Camera {
            origin,
            horizontal,
            vertical,
            corner,
        }
    }

    pub fn get_ray(&self, u: f64, v: f64) -> Ray {
        let vector3 = self.corner + u * self.horizontal + v * self.vertical;

        Ray {
            origin: self.origin,
            direction: vector3 - self.origin,
        }
    }
}

Camera

// 相机
let camera = Camera::new(
    Point3::new(-2.0, 2.0, 1.0),
    Point3::new(0.0, 0.0, -1.0),
    Vector3::new(0.0, 1.0, 0.0),
    // 20.0,
    90.0,
    camera::RATIO,
);

效果

距离 90:
90

距离 20:
20

总结

将相机参数,可以改变相机的位置等。

附录

posted @ 2024-07-22 09:22  波尔  阅读(4)  评论(0编辑  收藏  举报