diff --git a/.gitignore b/.gitignore index 27aff38..bc2b56a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target *.lock +*.log diff --git a/README.md b/README.md new file mode 100644 index 0000000..c21ec0d --- /dev/null +++ b/README.md @@ -0,0 +1,264 @@ + + + +[![Contributors][contributors-shield]][contributors-url] +[![Forks][forks-shield]][forks-url] +[![Stargazers][stars-shield]][stars-url] +[![Issues][issues-shield]][issues-url] +[![Unlicense License][license-shield]][license-url] +[![LinkedIn][linkedin-shield]][linkedin-url] + + + + +
+
+ + Logo + + +

Best-README-Template

+ +

+ An awesome README template to jumpstart your projects! +
+ Explore the docs ยป +
+
+ View Demo + · + Report Bug + · + Request Feature +

+
+ + + + +
+ Table of Contents +
    +
  1. + About The Project + +
  2. +
  3. + Getting Started + +
  4. +
  5. Usage
  6. +
  7. Roadmap
  8. +
  9. Contributing
  10. +
  11. License
  12. +
  13. Contact
  14. +
  15. Acknowledgments
  16. +
+
+ + + + +## About The Project + +[![Product Name Screen Shot][product-screenshot]](https://example.com) + +There are many great README templates available on GitHub; however, I didn't find one that really suited my needs so I created this enhanced one. I want to create a README template so amazing that it'll be the last one you ever need -- I think this is it. + +Here's why: +* Your time should be focused on creating something amazing. A project that solves a problem and helps others +* You shouldn't be doing the same tasks over and over like creating a README from scratch +* You should implement DRY principles to the rest of your life :smile: + +Of course, no one template will serve all projects since your needs may be different. So I'll be adding more in the near future. You may also suggest changes by forking this repo and creating a pull request or opening an issue. Thanks to all the people have contributed to expanding this template! + +Use the `BLANK_README.md` to get started. + +

(back to top)

+ + + +### Built With + +This section should list any major frameworks/libraries used to bootstrap your project. Leave any add-ons/plugins for the acknowledgements section. Here are a few examples. + +* [![Next][Next.js]][Next-url] +* [![React][React.js]][React-url] +* [![Vue][Vue.js]][Vue-url] +* [![Angular][Angular.io]][Angular-url] +* [![Svelte][Svelte.dev]][Svelte-url] +* [![Laravel][Laravel.com]][Laravel-url] +* [![Bootstrap][Bootstrap.com]][Bootstrap-url] +* [![JQuery][JQuery.com]][JQuery-url] + +

(back to top)

+ + + + +## Getting Started + +This is an example of how you may give instructions on setting up your project locally. +To get a local copy up and running follow these simple example steps. + +### Prerequisites + +This is an example of how to list things you need to use the software and how to install them. +* npm + ```sh + npm install npm@latest -g + ``` + +### Installation + +_Below is an example of how you can instruct your audience on installing and setting up your app. This template doesn't rely on any external dependencies or services._ + +1. Get a free API Key at [https://example.com](https://example.com) +2. Clone the repo + ```sh + git clone https://github.com/github_username/repo_name.git + ``` +3. Install NPM packages + ```sh + npm install + ``` +4. Enter your API in `config.js` + ```js + const API_KEY = 'ENTER YOUR API'; + ``` +5. Change git remote url to avoid accidental pushes to base project + ```sh + git remote set-url origin github_username/repo_name + git remote -v # confirm the changes + ``` + +

(back to top)

+ + + + +## Usage + +Use this space to show useful examples of how a project can be used. Additional screenshots, code examples and demos work well in this space. You may also link to more resources. + +_For more examples, please refer to the [Documentation](https://example.com)_ + +

(back to top)

+ + + + +## Roadmap + +- [x] Add Changelog +- [x] Add back to top links +- [ ] Add Additional Templates w/ Examples +- [ ] Add "components" document to easily copy & paste sections of the readme +- [ ] Multi-language Support + - [ ] Chinese + - [ ] Spanish + +See the [open issues](https://github.com/othneildrew/Best-README-Template/issues) for a full list of proposed features (and known issues). + +

(back to top)

+ + + + +## Contributing + +Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**. + +If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". +Don't forget to give the project a star! Thanks again! + +1. Fork the Project +2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`) +3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`) +4. Push to the Branch (`git push origin feature/AmazingFeature`) +5. Open a Pull Request + +### Top contributors: + + + contrib.rocks image + + +

(back to top)

+ + + + +## License + +Distributed under the Unlicense License. See `LICENSE.txt` for more information. + +

(back to top)

+ + + + +## Contact + +Your Name - [@your_twitter](https://twitter.com/your_username) - email@example.com + +Project Link: [https://github.com/your_username/repo_name](https://github.com/your_username/repo_name) + +

(back to top)

+ + + + +## Acknowledgments + +Use this space to list resources you find helpful and would like to give credit to. I've included a few of my favorites to kick things off! + +* [Choose an Open Source License](https://choosealicense.com) +* [GitHub Emoji Cheat Sheet](https://www.webpagefx.com/tools/emoji-cheat-sheet) +* [Malven's Flexbox Cheatsheet](https://flexbox.malven.co/) +* [Malven's Grid Cheatsheet](https://grid.malven.co/) +* [Img Shields](https://shields.io) +* [GitHub Pages](https://pages.github.com) +* [Font Awesome](https://fontawesome.com) +* [React Icons](https://react-icons.github.io/react-icons/search) + +

(back to top)

+ + + + + +[contributors-shield]: https://img.shields.io/github/contributors/othneildrew/Best-README-Template.svg?style=for-the-badge +[contributors-url]: https://github.com/othneildrew/Best-README-Template/graphs/contributors +[forks-shield]: https://img.shields.io/github/forks/othneildrew/Best-README-Template.svg?style=for-the-badge +[forks-url]: https://github.com/othneildrew/Best-README-Template/network/members +[stars-shield]: https://img.shields.io/github/stars/othneildrew/Best-README-Template.svg?style=for-the-badge +[stars-url]: https://github.com/othneildrew/Best-README-Template/stargazers +[issues-shield]: https://img.shields.io/github/issues/othneildrew/Best-README-Template.svg?style=for-the-badge +[issues-url]: https://github.com/othneildrew/Best-README-Template/issues +[license-shield]: https://img.shields.io/github/license/othneildrew/Best-README-Template.svg?style=for-the-badge +[license-url]: https://github.com/othneildrew/Best-README-Template/blob/master/LICENSE.txt +[linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=for-the-badge&logo=linkedin&colorB=555 +[linkedin-url]: https://linkedin.com/in/othneildrew +[product-screenshot]: images/screenshot.png +[Next.js]: https://img.shields.io/badge/next.js-000000?style=for-the-badge&logo=nextdotjs&logoColor=white +[Next-url]: https://nextjs.org/ +[React.js]: https://img.shields.io/badge/React-20232A?style=for-the-badge&logo=react&logoColor=61DAFB +[React-url]: https://reactjs.org/ +[Vue.js]: https://img.shields.io/badge/Vue.js-35495E?style=for-the-badge&logo=vuedotjs&logoColor=4FC08D +[Vue-url]: https://vuejs.org/ +[Angular.io]: https://img.shields.io/badge/Angular-DD0031?style=for-the-badge&logo=angular&logoColor=white +[Angular-url]: https://angular.io/ +[Svelte.dev]: https://img.shields.io/badge/Svelte-4A4A55?style=for-the-badge&logo=svelte&logoColor=FF3E00 +[Svelte-url]: https://svelte.dev/ +[Laravel.com]: https://img.shields.io/badge/Laravel-FF2D20?style=for-the-badge&logo=laravel&logoColor=white +[Laravel-url]: https://laravel.com +[Bootstrap.com]: https://img.shields.io/badge/Bootstrap-563D7C?style=for-the-badge&logo=bootstrap&logoColor=white +[Bootstrap-url]: https://getbootstrap.com +[JQuery.com]: https://img.shields.io/badge/jQuery-0769AD?style=for-the-badge&logo=jquery&logoColor=white +[JQuery-url]: https://jquery.com diff --git a/src/core/geometry.rs b/src/core/geometry.rs index 3fb89e1..9ceba3b 100644 --- a/src/core/geometry.rs +++ b/src/core/geometry.rs @@ -1,320 +1,478 @@ +use num_traits::{Num, Bounded, Float as NumFloat}; use std::ops::{Sub, SubAssign, Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Index, IndexMut}; +use std::sync::Arc; +use std::f32::consts::PI; + use crate::core::pbrt::Float; -use num_traits::{Num, Bounded}; +use crate::core::pbrt; +use crate::core::medium::Medium; -pub trait Tuple : Index + IndexMut + Copy { - fn get(&self, i: usize) -> T; - fn set(&mut self, i: usize, val: T); -} - -#[derive(Copy, Clone, PartialEq)] -pub struct Vector2 { pub x: T, pub y: T } -#[derive(Copy, Clone, PartialEq)] -pub struct Point2 { pub x: T, pub y: T } -#[derive(Copy, Clone, PartialEq)] -pub struct Vector3 { pub x: T, pub y: T, pub z: T } -#[derive(Copy, Clone, PartialEq)] -pub struct Normal3 { pub x: T, pub y: T, pub z: T } -#[derive(Debug, Copy, Clone, PartialEq)] -pub struct Point3 { pub x: T, pub y: T, pub z : T } - -// Using macros to make this more concise -// This is pretty useful, gotta use it more often -macro_rules! impl_tuple_core { - ($Struct:ident, [$($field:ident), +]) => { - impl $Struct { - pub fn new($($field: T), +) -> Self { Self { $($field), + }} - - pub fn has_nan(&self) -> bool where T: num_traits::Float { - $(self.$field.is_nan())||+ - } - } - - impl $Struct { - pub fn dot(self, other: Self) -> T { - let mut sum = T::zero(); - $( sum = sum + self.$field * other.$field; )+ - sum - } - - pub fn abs_dot(self, other: Self) -> T { - self.dot(other).abs() - } - - pub fn length_squared(self) -> T { - self.dot(self) - } - } - - impl $Struct { - pub fn length(self) -> T { - self.length_squared().sqrt() - } - - pub fn normalize(self) -> Self { - self / self.length() - } - } - - impl> Neg for $Struct { - type Output = Self; - fn neg(self) -> Self { Self::new($(-self.$field),+) } - } - - impl + Copy> Mul for $Struct { - type Output = Self; - fn mul(self, s: T) -> Self { Self::new($(self.$field * s),+) }} - - impl MulAssign for $Struct { - fn mul_assign(&mut self, s: T) { $(self.$field *= s;)+ } - } - - impl + Copy> Div for $Struct { - type Output = Self; - fn div(self, s: T) -> Self { Self::new($(self.$field / s),+) } - } - impl DivAssign for $Struct { - fn div_assign(&mut self, s: T) { $(self.$field /= s;)+ } - } - - // Indexing - impl Index for $Struct { - type Output = T; - fn index(&self, i: usize) -> &T { - let mut idx = 0; - $( if i == idx { return &self.$field; } idx += 1; )+ - panic!("Index out of bounds"); - } - } - impl IndexMut for $Struct { - fn index_mut(&mut self, i: usize) -> &mut T { - let mut idx = 0; - $( if i == idx { return &mut self.$field; } idx += 1; )+ - panic!("Index out of bounds"); - } - } - }; -} - -macro_rules! impl_tuple_ops { - ($Struct:ident) => { - impl> Add for $Struct { - type Output = Self; - fn add(self, rhs: Self) -> Self { Self::new(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z) } - } - impl AddAssign for $Struct { - fn add_assign(&mut self, rhs: Self) - { self.x += rhs.x; self.y += rhs.y; self.z += rhs.z; } - } - impl> Sub for $Struct { - type Output = Self; - fn sub(self, rhs: Self) -> Self { Self::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z) } - } - impl SubAssign for $Struct { - fn sub_assign(&mut self, rhs: Self) { self.x -= rhs.x; self.y -= rhs.y; self.z -= rhs.z; } - } - }; -} - - -impl_tuple_core!(Vector3, [x, y, z]); -impl_tuple_core!(Normal3, [x, y, z]); -impl_tuple_core!(Point2, [x, y]); -impl_tuple_core!(Point3, [x, y, z]); - -impl_tuple_ops!(Vector3); -impl_tuple_ops!(Normal3); - -// Point - Point -> Vector -impl> Sub> for Point3 { - type Output = Vector3; - fn sub(self, rhs: Point3) -> Vector3 { - Vector3::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z) - } -} - -// Point + Vector -> Point -impl> Add> for Point3 { - type Output = Point3; - fn add(self, rhs: Vector3) -> Point3 { - Point3::new(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z) - } -} -impl AddAssign> for Point3 { - fn add_assign(&mut self, rhs: Vector3) { - self.x += rhs.x; - self.y += rhs.y; - self.z += rhs.z; - } -} - -// Point - Vector -> Point -impl> Sub> for Point3 { - type Output = Point3; - fn sub(self, rhs: Vector3) -> Point3 { - Point3::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z) - } -} -impl SubAssign> for Point3 { - fn sub_assign(&mut self, rhs: Vector3) { - self.x -= rhs.x; - self.y -= rhs.y; - self.z -= rhs.z; - } -} - -impl Vector3 { - 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, - } - } -} - -pub trait Norm { - type Scalar; - - fn norm(self) -> Self::Scalar; - fn norm_squared(self) -> Self::Scalar; -} - -impl Norm for Vector2 { - type Scalar = T; - fn norm(self) -> T { self.length_squared().sqrt() } - fn norm_squared(self) -> T { self.length_squared } -} - -pub fn distance(p1: Point2, p2: Point2) -> T -where - T: num_traits::Float, - Point2: Sub>, - Vector2: Copy + Mul, +pub trait Tuple: + Sized + Copy + Index + IndexMut { - (p1 - p2).length() -} - -pub fn distance_squared(p1: Point2) { - -} - - -pub type Point3f = Point3; -pub type Point3i = Point3; -pub type Vector3f = Vector3; -pub type Vector3i = Vector3; -pub type Normal3f = Normal3; -pub type Normal3i = Normal3; - - -#[derive(Debug, Copy, Clone, PartialEq)] -pub struct Bounds3 { - pub p_min: Point3, - pub p_max: Point3, -} - -impl Default for Bounds3 -where - T: Num + Bounded -{ - fn default() -> Self { - Self { - p_min: Point3::new(T::max_value(), T::max_value(), T::max_value()), - p_max: Point3::new(T::min_value(), T::min_value(), T::min_value()), - } - } -} - -impl Bounds3 -where - T: Num + PartialOrd + Copy, -{ - pub fn from_point(p: Point3) -> Self { - Self { p_min: p, p_max: p } - } - - pub fn from_points(p1: Point3, p2: Point3) -> Self { - Self { - p_min: Point3::new( - if p1.x < p2.x { p1.x } else { p2.x }, - if p1.y < p2.y { p1.y } else { p2.y }, - if p1.z < p2.z { p1.z } else { p2.z }, - ), - p_max: Point3::new( - if p1.x > p2.x { p1.x } else { p2.x }, - if p1.y > p2.y { p1.y } else { p2.y }, - if p1.z > p2.z { p1.z } else { p2.z }, - ), - } - } - - pub fn diagonal(&self) -> Vector3 { - self.p_max - self.p_min - } - - pub fn surface_area(&self) -> T { - let d = self.diagonal(); - let two = T::one() + T::one(); - two * (d.x * d.y + d.x * d.z + d.y * d.z) - } - - pub fn volume(&self) -> T { - let d = self.diagonal(); - d.x * d.y * d.z - } - - pub fn is_empty(&self) -> bool { - self.p_min.x >= self.p_max.x || self.p_min.y >= self.p_max.y || self.p_min.z >= self.p_max.z - } - - pub fn max_dimension(&self) -> usize { - let d = self.diagonal(); - if d.x > d.y && d.x > d.z { - 0 - } else if d.y > d.z { - 1 - } else { - 2 - } - } - - pub fn offset(p: Point3) {} + fn data(&self) -> &[T; N]; + fn data_mut(&mut self) -> &mut [T; N]; + fn from_array(arr: [T; N]) -> Self; } fn min(a: T, b: T) -> T { if a < b { a } else { b }} fn max(a: T, b: T) -> T { if a > b { a } else { b }} -pub fn union_bounds_point(b: Bounds3, p: Point3) -> Bounds3 { - Bounds3 { - p_min: Point3::new(min(b.p_min.x, p.x), min(b.p_min.y, p.y), min(b.p_min.z, p.z)), - p_max: Point3::new(max(b.p_max.x, p.x), max(b.p_max.y, p.y), max(b.p_max.z, p.z)), - } -} +// N-dimensional displacement +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub struct Vector(pub [T; N]); +// N-dimensional location +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub struct Point(pub [T; N]); +// N-dimensional surface normal +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub struct Normal(pub [T; N]); -pub fn union_bounds(b1: Bounds3, b2: Bounds3) -> Bounds3 { - Bounds3 { - p_min: Point3::new(min(b1.p_min.x, b2.p_min.x), min(b1.p_min.y, b2.p_min.y), min(b1.p_min.z, b2.p_min.z)), - p_max: Point3::new(max(b1.p_max.x, b2.p_max.x), max(b1.p_max.y, b2.p_max.y), max(b1.p_max.z, b2.p_max.z)), - } -} +macro_rules! impl_tuple_core { + ($Struct:ident) => { + impl Tuple for $Struct { + #[inline] fn data(&self) -> &[T; N] { &self.0 } + #[inline] fn data_mut(&mut self) -> &mut [T; N] { &mut self.0 } + #[inline] fn from_array(arr: [T; N]) -> Self { Self(arr) } + } -pub fn face_forward_v(v: Vector3f, n: Normal3f) -> Vector3f { - if v.dot(Vector3::new(n.x, n.y, n.z)) < 0.0 { -v } else { v } -} + impl Default for $Struct { + fn default() -> Self { + Self([T::default(); N]) + } + } + + impl Index for $Struct { + type Output = T; + #[inline] fn index(&self, index: usize) -> &Self::Output { &self.0[index] } + } + impl IndexMut for $Struct { + #[inline] fn index_mut(&mut self, index: usize) -> &mut Self::Output { &mut self.0[index] } + } -pub fn face_forward_n(n1: Normal3f, n2: Normal3f) -> Normal3f { - if n1.dot(n2) < 0.0 { -n1 } else { n1 } -} + impl Neg for $Struct where T: Neg + Copy { + type Output = Self; + fn neg(self) -> Self::Output { + let mut result = self.0; + for i in 0..N { result[i] = -result[i]; } + Self(result) + } + } -pub fn coordinate_system(v1: Vector3f) -> (Vector3f, Vector3f) { - let v2 = if v1.x.abs() > v1.y.abs() { - Vector3::new(-v1.z, 0.0, v1.x) / (v1.x * v1.x + v1.z * v1.z).sqrt() - } else { - Vector3::new(0.0, v1.z, -v1.y) / (v1.y * v1.y + v1.z * v1.z).sqrt() + impl Mul for $Struct where T: Mul + Copy { + type Output = Self; + fn mul(self, rhs: T) -> Self::Output { + let mut result = self.0; + for i in 0..N { result[i] = result[i] * rhs; } + Self(result) + } + } + impl MulAssign for $Struct where T: MulAssign + Copy { + fn mul_assign(&mut self, rhs: T) { + for i in 0..N { self.0[i] *= rhs; } + } + } + + impl Div for $Struct where T: Div + Copy { + type Output = Self; + fn div(self, rhs: T) -> Self::Output { + let mut result = self.0; + for i in 0..N { result[i] = result[i] / rhs; } + Self(result) + } + } + impl DivAssign for $Struct where T: DivAssign + Copy { + fn div_assign(&mut self, rhs: T) { + for i in 0..N { self.0[i] /= rhs; } + } + } }; - let v3 = v1.cross(v2); - (v2, v3) +} + +impl_tuple_core!(Vector); +impl_tuple_core!(Point); +impl_tuple_core!(Normal); + +macro_rules! impl_tuple_ops { + ($Struct:ident) => { + impl Add for $Struct where T: Add + Copy { + type Output = Self; + fn add(self, rhs: Self) -> Self::Output { + let mut result = self.0; + for i in 0..N { result[i] = self.0[i] + rhs.0[i]; } + Self(result) + } + } + impl AddAssign for $Struct where T: AddAssign + Copy { + fn add_assign(&mut self, rhs: Self) { + for i in 0..N { self.0[i] += rhs.0[i]; } + } + } + impl Sub for $Struct where T: Sub + Copy { + type Output = Self; + fn sub(self, rhs: Self) -> Self::Output { + let mut result = self.0; + for i in 0..N { result[i] = self.0[i] - rhs.0[i]; } + Self(result) + } + } + impl SubAssign for $Struct where T: SubAssign + Copy { + fn sub_assign(&mut self, rhs: Self) { + for i in 0..N { self.0[i] -= rhs.0[i]; } + } + } + }; +} + +impl_tuple_ops!(Vector); +impl_tuple_ops!(Normal); + +impl From> for Normal { + fn from(v: Vector) -> Self { Self(v.0) } +} +impl From> for Vector { + fn from(n: Normal) -> Self { Self(n.0) } +} + +impl Sub for Point where T: Sub + Copy { + type Output = Vector; + fn sub(self, rhs: Self) -> Self::Output { + let mut result = self.0; + for i in 0..N { result[i] = self.0[i] - rhs.0[i]; } + Vector(result) + } +} + +// Point + Vector -> Point +impl Add> for Point where T: Add + Copy { + type Output = Self; + fn add(self, rhs: Vector) -> Self::Output { + let mut result = self.0; + for i in 0..N { result[i] = self.0[i] + rhs.0[i]; } + Self(result) + } +} +impl AddAssign> for Point where T: AddAssign + Copy { + fn add_assign(&mut self, rhs: Vector) { + for i in 0..N { self.0[i] += rhs.0[i]; } + } +} + +// Point - Vector -> Point +impl Sub> for Point where T: Sub + Copy { + type Output = Self; + fn sub(self, rhs: Vector) -> Self::Output { + let mut result = self.0; + for i in 0..N { result[i] = self.0[i] - rhs.0[i]; } + Self(result) + } +} +impl SubAssign> for Point where T: SubAssign + Copy { + fn sub_assign(&mut self, rhs: Vector) { + for i in 0..N { self.0[i] -= rhs.0[i]; } + } +} + +macro_rules! impl_accessors { + ($Struct:ident) => { + impl $Struct { + pub fn x(&self) -> T { self.0[0] } + pub fn y(&self) -> T { self.0[1] } + } + impl $Struct { + pub fn x(&self) -> T { self.0[0] } + pub fn y(&self) -> T { self.0[1] } + pub fn z(&self) -> T { self.0[2] } + } + }; +} + +impl_accessors!(Vector); +impl_accessors!(Point); +impl_accessors!(Normal); + + +// Vector stuff +pub trait Dot { + type Output; + fn dot(self, rhs: Rhs) -> Self::Output; +} + +pub trait Normed { + type Scalar; + fn norm_squared(&self) -> Self::Scalar; + fn norm(&self) -> Self::Scalar where Self::Scalar: NumFloat { self.norm_squared().sqrt() } + fn normalize(self) -> Self where Self: Sized, Self: Div, Self::Scalar: NumFloat; +} + +macro_rules! impl_vector_math_for { + ($Struct:ident) => { + impl Dot for $Struct { + type Output = T; + fn dot(self, rhs: Self) -> T { + let mut sum = T::zero(); + for i in 0..N { sum = sum + self[i] * rhs[i]; } + sum + } + } + impl Normed for $Struct { + type Scalar = T; + fn norm_squared(&self) -> T { self.dot(*self) } + fn normalize(self) -> Self where Self: Div, T: NumFloat { self / self.norm() } + } + }; +} + +impl_vector_math_for!(Vector); +impl_vector_math_for!(Normal); + +impl Point +where + T: NumFloat + Copy, + Point: Sub>, // Point - Point -> Vector + Vector: Normed, // Vector has a norm +{ + pub fn distance(self, other: Self) -> T { + (self - other).norm() + } + + pub fn distance_squared(self, other: Self) -> T { + (self - other).norm_squared() + } +} + + +// Utility aliases and functions +pub type Point2 = Point; +pub type Point3 = Point; +pub type Point3f = Point3; +pub type Point3i = Point3; +pub type Vector2 = Vector; +pub type Vector3 = Vector; +pub type Vector3f = Vector3; +pub type Vector3i = Vector3; +pub type Normal3 = Normal; +pub type Normal3f = Normal3; +pub type Normal3i = Normal3; + +impl Vector2 { pub fn new(x: T, y: T) -> Self { Self([x, y]) } } +impl Point2 { pub fn new(x: T, y: T) -> Self { Self([x, y]) } } +impl Vector3 { pub fn new(x: T, y: T, z: T) -> Self { Self([x, y, z]) } } +impl Point3 { pub fn new(x: T, y: T, z: T) -> Self { Self([x, y, z]) } } +impl Normal3 { pub fn new(x: T, y: T, z: T) -> Self { Self([x, y, z]) } } + + +// Vector operations +impl Vector3 +where T: Num + Copy + Neg +{ + pub fn cross(self, rhs: Self) -> Self { + Self([ + self[1] * rhs[2] - self[2] * rhs[1], + self[2] * rhs[0] - self[0] * rhs[2], + self[0] * rhs[1] - self[1] * rhs[0], + ]) + } +} + +impl Vector3 +where T: Num + NumFloat + Copy + Neg +{ + pub fn coordinate_system(&self) -> (Self, Self) where T: NumFloat { + let v2 = if self[0].abs() > self[1].abs() { + Self::new(-self[2], T::zero(), self[0]) / (self[0] * self[0] + self[2] * self[2]).sqrt() + } else { + Self::new(T::zero(), self[2], -self[1]) / (self[1] * self[1] + self[2] * self[2]).sqrt() + }; + (v2, self.cross(v2)) + } +} + +impl Normal3 +where T: Num + PartialOrd + Copy + Neg +{ + pub fn face_forward(self, v: Vector3) -> Self { + if self.dot(v.into()) < T::zero() { -self } else { self } + } +} + +// SPHERICAL GEOMETRY +pub fn spherical_direction(sin_theta: Float, cos_theta: Float, phi: Float) -> Vector3f { + Vector3f::new(sin_theta * phi.cos(), sin_theta * phi.sin(), cos_theta) +} + +pub fn spherical_triangle_area(a: Vector3f, b: Vector3f, c: Vector3f) -> Float { + (2.0 * (a.dot(b.cross(c))).atan2(1.0 + a.dot(b) + a.dot(c) + b.dot(c))).abs() +} + +pub fn spherical_theta(v: Vector3f) -> Float { + pbrt::clamp_t(v.z(), -1.0, 1.0).acos() +} + +pub fn spherical_phi(v: Vector3f) -> Float { + let p = v.y().atan2(v.x()); + if p < 0.0 { + p + 2.0 * PI + } else { + p + } +} + +// AABB bouding boxes +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct Bounds { + pub p_min: Point, + pub p_max: Point, +} + +impl Bounds +where + T: Num + PartialOrd + Copy +{ + pub fn from_point(p: Point) -> Self { + Self { p_min: p, p_max: p } + } + + pub fn from_points(p1: Point, p2: Point) -> Self { + let mut p_min_arr = [T::zero(); N]; + let mut p_max_arr = [T::zero(); N]; + + for i in 0..N { + if p1[i] < p2[i] { + p_min_arr[i] = p1[i]; + p_max_arr[i] = p2[i]; + } else { + p_min_arr[i] = p2[i]; + p_max_arr[i] = p1[i]; + } + } + + Self { p_min: Point(p_min_arr), p_max: Point(p_max_arr) } + } + + pub fn union_point(self, p: Point) -> Self { + let mut p_min = self.p_min; + let mut p_max = self.p_max; + for i in 0..N { + p_min[i] = min(p_min[i], p[i]); + p_max[i] = max(p_max[i], p[i]); + } + Self { p_min, p_max } + } + + pub fn union(self, b2: Self) -> Self { + let mut p_min = self.p_min; + let mut p_max = self.p_max; + for i in 0..N { + p_min[i] = min(p_min[i], b2.p_min[i]); + p_max[i] = max(p_max[i], b2.p_max[i]); + } + Self { p_min, p_max } + } + + pub fn diagonal(&self) -> Vector { + self.p_max - self.p_min + } + + pub fn volume(&self) -> T { + let d = self.diagonal(); + d.0.iter().fold(T::one(), |acc, &val| acc * val) + } + + pub fn lerp(&self, t: Point) -> Point + { + let mut results_arr = [T::zero(); N]; + for i in 0..N { + results_arr[i] = pbrt::lerp(t[i], self.p_min[i], self.p_max[i]) + } + + Point(results_arr) + } + + pub fn max_dimension(&self) -> usize + where + Point: Sub>, + { + let d = self.diagonal(); + let mut max_dim = 0; + let mut max_span = d[0]; + + for i in 1..N { + if d[i] > max_span { + max_span = d[i]; + max_dim = i; + } + } + max_dim + } + + pub fn offset(&self, p: &Point) -> Vector + where + Point: Sub>, + Vector: DivAssign + { + let mut o = *p - self.p_min; + let d = self.diagonal(); + for i in 0..N { + if d[i] > T::zero() { + o[i] = o[i] / d[i]; + } + } + o + } + + pub fn contains(&self, p: Point) -> bool { + (0..N).all(|i| p[i] >= self.p_min[i] && p[i] <= self.p_max[i]) + } + + pub fn contains_exclusive(&self, p: Point) -> bool { + (0..N).all(|i| p[i] >= self.p_min[i] && p[i] < self.p_max[i]) + } + + pub fn is_empty(&self) -> bool { + (0..N).any(|i| self.p_min[i] >= self.p_max[i]) + } + + pub fn is_degenerate(&self) -> bool { + (0..N).any(|i| self.p_min[i] > self.p_max[i]) + } +} + +impl Default for Bounds +where + T: Bounded + Copy, +{ + fn default() -> Self { + Self { + p_min: Point([T::max_value(); N]), + p_max: Point([T::min_value(); N]), + } + } +} + +pub type Bounds2 = Bounds; +pub type Bounds3 = Bounds; +pub type Bounds3f = Bounds3; + +impl Bounds3 +where + T: Num + PartialOrd + Copy + Default +{ + pub fn surface_area(&self) -> T { + let d = self.diagonal(); + let two = T::one() + T::one(); + two * (d.x() * d.y() + d.x() * d.z() + d.y() * d.z()) + } + + pub fn bounding_sphere(&self) -> (Point3, T) + where + < as Sub>::Output as Normed>::Scalar: NumFloat, + { + let two = T::one() + T::one(); + let center = (self.p_min + self.diagonal()) / two; + let radius = if self.contains(center) { center.distance(self.p_max) } else { T::zero() }; + (center, radius) + } } #[derive(Copy, Clone, Default, PartialEq)] @@ -326,7 +484,7 @@ pub struct Frame { impl Frame { pub fn from_z(z: Vector3f) -> Self { - let (x, y) = coordinate_system(z.normalize()); + let (x, y) = z.normalize().coordinate_system(); Self { x, y, z: z.normalize() } } @@ -335,62 +493,39 @@ impl Frame { } pub fn from_local(&self, v: Vector3f) -> Vector3f { - self.x * v.x + self.y * v.y + self.z * v.z - } - -} - -#[derive(Copy, Clone, PartialEq)] -pub struct Quaternion { - pub v: Vector3f, - pub w: Float, -} - -impl Default for Quaternion { - fn default() -> Self { - Self { v: Vector3f::default(), w: 1.0 } + self.x * v.x() + self.y * v.y() + self.z * v.z() } } -impl Add for Quaternion { - type Output = Self; - fn add(self, rhs: Quaternion) -> Self { - Self { v: self.v + rhs.v, w: self.w + rhs.w } +#[derive(Clone, Default)] +pub struct Ray { + pub o: Point3f, + pub d: Vector3f, + pub medium: Option>, + pub time: Float, + // We do this instead of creating a trait for Rayable or some gnarly thing like that + pub differential: Option, +} + +impl Ray { + pub fn operator(&self, t: Float) -> Point3f { + self.o + self.d * t + } + + pub fn scale_differentials(&mut self, s: Float) { + if let Some(differential) = &mut self.differential { + differential.rx_origin = self.o + (differential.rx_origin - self.o) * s; + differential.ry_origin = self.o + (differential.ry_origin - self.o) * s; + differential.rx_direction = self.d + (differential.rx_direction - self.d) * s; + differential.ry_direction = self.d + (differential.ry_direction - self.d) * s; + } } } -impl AddAssign for Quaternion { - fn add_assign(&mut self, rhs: Self) { self.v += rhs.v; self.w += rhs.w; } -} - -impl Sub for Quaternion { - type Output = Self; - fn sub(self, rhs: Self) -> Self { Self { v: self.v - rhs.v, w: self.w - rhs.w }} -} - -impl SubAssign for Quaternion { - fn sub_assign(&mut self, rhs: Self) { self.v -= rhs.v; self.w -= rhs.w; } -} - -impl Mul for Quaternion { - type Output = Self; - fn mul(self, rhs: Float) -> Self { Self { v: self.v * rhs, w: self.w * rhs }} -} - -impl MulAssign for Quaternion { - fn mul_assign(&mut self, rhs: Float) { self.v *= rhs; self.w *= rhs; } -} - -impl Div for Quaternion { - type Output = Self; - fn div(self, rhs: Float) -> Self { Self { v: self.v / rhs, w: self.w / rhs }} -} - -impl DivAssign for Quaternion { - fn div_assign(&mut self, rhs: Float) { self.v /= rhs; self.w /= rhs; } -} - -impl Neg for Quaternion { - type Output = Self; - fn neg(self) -> Self { Self { v: -self.v, w: -self.w }} +#[derive(Debug, Default, Copy, Clone)] +pub struct RayDifferential { + pub rx_origin: Point3f, + pub ry_origin: Point3f, + pub rx_direction: Vector3f, + pub ry_direction: Vector3f, } diff --git a/src/core/integrator.rs b/src/core/integrator.rs index 60623ab..41a4c65 100644 --- a/src/core/integrator.rs +++ b/src/core/integrator.rs @@ -1,8 +1,14 @@ -use std::sync::Arc; +pub struct BPDTIntegrator; +pub struct MLTIntegrator; +pub struct SPPMIntegrator; +pub struct SamplerIntegrator; -use crate::core::primitive::Primitive; - -pub struct Integrator { - aggregate: Arc, - lights: Vec>, +pub enum Integrator { + BPDT(BPDTIntegrator), + MLT(MLTIntegrator), + SPPM(SPPMIntegrator), + Sampler(SamplerIntegrator), +} + +impl Integrator { } diff --git a/src/mod.rs b/src/core/interaction.rs similarity index 100% rename from src/mod.rs rename to src/core/interaction.rs diff --git a/src/core/light.rs b/src/core/light.rs index e69de29..c9e2826 100644 --- a/src/core/light.rs +++ b/src/core/light.rs @@ -0,0 +1,17 @@ +pub struct DiffuseAreaLight; +pub struct DistantLight; +pub struct GonioPhotometricLight; +pub struct InfiniteAreaLight; +pub struct PointLight; +pub struct ProjectionLight; +pub struct SpotLight; + +pub enum Light { + DiffuseArea(Box), + Distant(Box), + GonioPhotometric(Box), + InfiniteArea(Box), + Point(Box), + Projection(Box), + Spot(Box), +} diff --git a/src/core/material.rs b/src/core/material.rs index 3fa532d..2172a0e 100644 --- a/src/core/material.rs +++ b/src/core/material.rs @@ -25,20 +25,4 @@ pub enum Material { } impl Material { - pub fn get_bsdf( - &self, tex_eval: T, ctx: MaterialEvalContext, lambda: &mut SampledWavelengths, buf: &mut ScratchBuffer) -> BSDF { - match self { - Material::CoatedDiffuse(m) => m.get_bsdf(tex_eval, ctx, lambda, buf), - Material::CoatedConductor(m) => m.get_bsdf(tex_eval, ctx, lambda, buf), - Material::Conductor(m) => m.get_bsdf(tex_eval, ctx, lambda, buf), - Material::Dielectric(m) => m.get_bsdf(tex_eval, ctx, lambda, buf), - Material::Diffuse(m) => m.get_bsdf(tex_eval, ctx, lambda, buf), - Material::DiffuseTransmission(m) => m.get_bsdf(tex_eval, ctx, lambda, buf), - Material::Hair(m) => m.get_bsdf(tex_eval, ctx, lambda, buf), - Material::Measured(m) => m.get_bsdf(tex_eval, ctx, lambda, buf), - Material::Subsurface(m) => m.get_bsdf(tex_eval, ctx, lambda, buf), - Material::ThinDielectric(m) => m.get_bsdf(tex_eval, ctx, lambda, buf), - Material::Mix(m) => m.get_bsdf(tex_eval, ctx, lambda, buf), - } - } } diff --git a/src/core/medium.rs b/src/core/medium.rs new file mode 100644 index 0000000..77f3160 --- /dev/null +++ b/src/core/medium.rs @@ -0,0 +1,52 @@ +use std::sync::Arc; + +pub struct HomogeneousMedium; +pub struct GridMedium; +pub struct RGBGridMedium; +pub struct CloudMedium; +pub struct NanoVDBMedium; + +pub enum Medium { + Homogeneous(HomogeneousMedium), + Grid(GridMedium), + RGBGrid(RGBGridMedium), + Cloud(CloudMedium), + NanoVDB(NanoVDBMedium), +} + + +#[derive(Default, Clone)] +pub struct MediumInterface { + pub inside: Option>, + pub outside: Option>, +} + +impl MediumInterface { + pub fn new(inside: Option>, outside: Option>) -> Self { + Self { inside, outside } + } + + pub fn is_medium_transition(&self) -> bool { + if let Some(ref inside) = self.inside { + // self.inside == Some + if let Some(ref outside) = self.outside { + // self.outside == Some + let pi = inside as *const _ as *const usize; + let po = outside as *const _ as *const usize; + pi != po + } else { + // self.outside == None + true + } + } else { + // self.inside == None + if let Some(ref _outside) = self.outside { + // self.outside == Some + true + } else { + // self.outside == None + false + } + } + } +} diff --git a/src/core/mod.rs b/src/core/mod.rs index 845320d..c78e8a3 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -1,8 +1,13 @@ pub mod geometry; pub mod integrator; pub mod light; +pub mod interaction; pub mod material; +pub mod medium; pub mod pbrt; pub mod primitive; +pub mod quaternion; pub mod shape; pub mod texture; +pub mod transform; +pub mod spectrum; diff --git a/src/core/pbrt.rs b/src/core/pbrt.rs index d0813f7..4856305 100644 --- a/src/core/pbrt.rs +++ b/src/core/pbrt.rs @@ -1,25 +1,56 @@ +use num_traits::Num; pub type Float = f32; pub const MACHINE_EPSILON: Float = std::f32::EPSILON * 0.5; pub const SHADOW_EPSILON: Float = 0.0001; +pub const INV_PI: Float = 0.318_309_886_183_790_671_54; +pub const INV_2_PI: Float = 0.159_154_943_091_895_335_77; +pub const INV_4_PI: Float = 0.079_577_471_545_947_667_88; +pub const PI_OVER_2: Float = 1.570_796_326_794_896_619_23; +pub const PI_OVER_4: Float = 0.785_398_163_397_448_309_61; +pub const SQRT_2: Float = 1.414_213_562_373_095_048_80; #[inline] -pub fn lerp(x: T, a: f64, b: f64) -> f64 { - (T::onw() - x) * a + x * b +pub fn lerp(x: T, a: T, b: T) -> T +where + T: Num + Copy, +{ + (T::one() - x) * a + x * b } -pub fn linear_pdf(x: f64, a: f64, b: f64) -> f64 { - if x < 0.0 || x > 1.0 { - return 0.0; +pub fn linear_pdf(x: T, a: T, b: T) -> T +where + T: Num + Copy + PartialOrd, +{ + if x < T::zero() || x > T::one() { + return T::zero(); } - 2.0 * lerp(x, a, b) / (a + b) + (T::one() + T::one()) * lerp(x, a, b) / (a + b) } -pub fn sample_linear(u: f64, a: f64, b: f64) -> f64 { - if u == 0.0 && a == 0.0 { - return 0.0; +pub fn sample_linear(u: T, a: T, b: T) -> T +where + T: Num, +{ + if u == T::zero() && a == T::zero() { + return T::zero(); } u * (a + b) } + +pub fn clamp_t(val: T, low: T, high: T) -> T +where + T: PartialOrd, +{ + let r: T; + if val < low { + r = low; + } else if val > high { + r = high; + } else { + r = val; + } + r +} diff --git a/src/core/primitive.rs b/src/core/primitive.rs index 444ea51..77bfcdb 100644 --- a/src/core/primitive.rs +++ b/src/core/primitive.rs @@ -1,6 +1,6 @@ // use crate::core::medium::MediumInterface; // use crate::core::light::Light; -use crate::utils::types::Bounds3f; +// use crate::core::geometry::Bounds3f; // // pub struct GeometricPrimitive; @@ -18,17 +18,15 @@ pub enum Primitive { } impl Primitive { - pub fn bounds(&self) -> Bounds3f { - match self { - Primitive::Geometric(primitive) => primitive.bounds(), - Primitive::Transformed(primitive) => primitive.bounds(), - Primitive::Animated(primitive) => primitive.bounds(), - Primitive::BVH(primitive) => primitive.bounds(), - Primitive::KdTree(primitive) => primitive.bounds(), - } - } - - pub fn + // pub fn bounds(&self) -> Bounds3f { + // match self { + // Primitive::Geometric(primitive) => primitive.bounds(), + // Primitive::Transformed(primitive) => primitive.bounds(), + // Primitive::Animated(primitive) => primitive.bounds(), + // Primitive::BVH(primitive) => primitive.bounds(), + // Primitive::KdTree(primitive) => primitive.bounds(), + // } + // } } // struct GeometricPrimitive { diff --git a/src/core/quaternion.rs b/src/core/quaternion.rs new file mode 100644 index 0000000..58769e8 --- /dev/null +++ b/src/core/quaternion.rs @@ -0,0 +1,58 @@ +use crate::core::geometry::Vector3f; +use crate::core::pbrt::Float; +use std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, Neg}; + +#[derive(Copy, Clone, PartialEq)] +pub struct Quaternion { + pub v: Vector3f, + pub w: Float, +} + +impl Default for Quaternion { + fn default() -> Self { + Self { v: Vector3f::default(), w: 1.0 } + } +} + +impl Add for Quaternion { + type Output = Self; + fn add(self, rhs: Quaternion) -> Self { + Self { v: self.v + rhs.v, w: self.w + rhs.w } + } +} + +impl AddAssign for Quaternion { + fn add_assign(&mut self, rhs: Self) { self.v += rhs.v; self.w += rhs.w; } +} + +impl Sub for Quaternion { + type Output = Self; + fn sub(self, rhs: Self) -> Self { Self { v: self.v - rhs.v, w: self.w - rhs.w }} +} + +impl SubAssign for Quaternion { + fn sub_assign(&mut self, rhs: Self) { self.v -= rhs.v; self.w -= rhs.w; } +} + +impl Mul for Quaternion { + type Output = Self; + fn mul(self, rhs: Float) -> Self { Self { v: self.v * rhs, w: self.w * rhs }} +} + +impl MulAssign for Quaternion { + fn mul_assign(&mut self, rhs: Float) { self.v *= rhs; self.w *= rhs; } +} + +impl Div for Quaternion { + type Output = Self; + fn div(self, rhs: Float) -> Self { Self { v: self.v / rhs, w: self.w / rhs }} +} + +impl DivAssign for Quaternion { + fn div_assign(&mut self, rhs: Float) { self.v /= rhs; self.w /= rhs; } +} + +impl Neg for Quaternion { + type Output = Self; + fn neg(self) -> Self { Self { v: -self.v, w: -self.w }} +} diff --git a/src/core/spectrum.rs b/src/core/spectrum.rs new file mode 100644 index 0000000..62ab452 --- /dev/null +++ b/src/core/spectrum.rs @@ -0,0 +1,8 @@ +use crate::core::pbrt::Float; + +#[derive(Debug, Default, Copy, Clone)] +pub struct RGBSpectrum { + pub c: [Float; 3], +} + +pub struct Spectrum; diff --git a/src/core/texture.rs b/src/core/texture.rs index f4df3d9..b2700fc 100644 --- a/src/core/texture.rs +++ b/src/core/texture.rs @@ -33,24 +33,24 @@ pub enum FloatTexture { } impl FloatTexture { - pub fn evaluate(&self, ctx: TextureEvalContext) -> f32 { - match self { - FloatTexture::FloatImage(texture) => texture.evaluate(ctx), - FloatTexture::GPUFloatImage(texture) => texture.evaluate(ctx), - FloatTexture::FloatMix(texture) => texture.evaluate(ctx), - FloatTexture::FloatDirectionMix(texture) => texture.evaluate(ctx), - FloatTexture::FloatScaled(texture) => texture.evaluate(ctx), - FloatTexture::FloatConstant(texture) => texture.evaluate(ctx), - FloatTexture::FloatBilerp(texture) => texture.evaluate(ctx), - FloatTexture::FloatCheckerboard(texture) => texture.evaluate(ctx), - FloatTexture::FloatDots(texture) => texture.evaluate(ctx), - FloatTexture::FBm(texture) => texture.evaluate(ctx), - FloatTexture::FloatPtex(texture) => texture.evaluate(ctx), - FloatTexture::GPUFloatPtex(texture) => texture.evaluate(ctx), - FloatTexture::Windy(texture) => texture.evaluate(ctx), - FloatTexture::Wrinkled(texture) => texture.evaluate(ctx), - } - } +// pub fn evaluate(&self, ctx: TextureEvalContext) -> f32 { +// match self { +// FloatTexture::FloatImage(texture) => texture.evaluate(ctx), +// FloatTexture::GPUFloatImage(texture) => texture.evaluate(ctx), +// FloatTexture::FloatMix(texture) => texture.evaluate(ctx), +// FloatTexture::FloatDirectionMix(texture) => texture.evaluate(ctx), +// FloatTexture::FloatScaled(texture) => texture.evaluate(ctx), +// FloatTexture::FloatConstant(texture) => texture.evaluate(ctx), +// FloatTexture::FloatBilerp(texture) => texture.evaluate(ctx), +// FloatTexture::FloatCheckerboard(texture) => texture.evaluate(ctx), +// FloatTexture::FloatDots(texture) => texture.evaluate(ctx), +// FloatTexture::FBm(texture) => texture.evaluate(ctx), +// FloatTexture::FloatPtex(texture) => texture.evaluate(ctx), +// FloatTexture::GPUFloatPtex(texture) => texture.evaluate(ctx), +// FloatTexture::Windy(texture) => texture.evaluate(ctx), +// FloatTexture::Wrinkled(texture) => texture.evaluate(ctx), +// } +// } } pub struct RGBConstantTexture; @@ -86,22 +86,22 @@ pub enum SpectrumTexture { } impl SpectrumTexture { - pub fn evaluate(&self, ctx: TextureEvalContext) -> f32 { - match self { - SpectrumTexture::FloatImage(texture) => texture.evaluate(ctx), - SpectrumTexture::GPUFloatImage(texture) => texture.evaluate(ctx), - SpectrumTexture::FloatMix(texture) => texture.evaluate(ctx), - SpectrumTexture::FloatDirectionMix(texture) => texture.evaluate(ctx), - SpectrumTexture::FloatScaled(texture) => texture.evaluate(ctx), - SpectrumTexture::FloatConstant(texture) => texture.evaluate(ctx), - SpectrumTexture::FloatBilerp(texture) => texture.evaluate(ctx), - SpectrumTexture::FloatCheckerboard(texture) => texture.evaluate(ctx), - SpectrumTexture::FloatDots(texture) => texture.evaluate(ctx), - SpectrumTexture::FBm(texture) => texture.evaluate(ctx), - SpectrumTexture::FloatPtex(texture) => texture.evaluate(ctx), - SpectrumTexture::GPUFloatPtex(texture) => texture.evaluate(ctx), - SpectrumTexture::Windy(texture) => texture.evaluate(ctx), - SpectrumTexture::Wrinkled(texture) => texture.evaluate(ctx), - } - } +// pub fn evaluate(&self, ctx: TextureEvalContext) -> f32 { +// match self { +// SpectrumTexture::FloatImage(texture) => texture.evaluate(ctx), +// SpectrumTexture::GPUFloatImage(texture) => texture.evaluate(ctx), +// SpectrumTexture::FloatMix(texture) => texture.evaluate(ctx), +// SpectrumTexture::FloatDirectionMix(texture) => texture.evaluate(ctx), +// SpectrumTexture::FloatScaled(texture) => texture.evaluate(ctx), +// SpectrumTexture::FloatConstant(texture) => texture.evaluate(ctx), +// SpectrumTexture::FloatBilerp(texture) => texture.evaluate(ctx), +// SpectrumTexture::FloatCheckerboard(texture) => texture.evaluate(ctx), +// SpectrumTexture::FloatDots(texture) => texture.evaluate(ctx), +// SpectrumTexture::FBm(texture) => texture.evaluate(ctx), +// SpectrumTexture::FloatPtex(texture) => texture.evaluate(ctx), +// SpectrumTexture::GPUFloatPtex(texture) => texture.evaluate(ctx), +// SpectrumTexture::Windy(texture) => texture.evaluate(ctx), +// SpectrumTexture::Wrinkled(texture) => texture.evaluate(ctx), +// } +// } } diff --git a/src/core/transform.rs b/src/core/transform.rs new file mode 100644 index 0000000..96cf857 --- /dev/null +++ b/src/core/transform.rs @@ -0,0 +1,424 @@ +use num_traits::{Num, One, Zero, Signed, Float as NumFloat}; +use std::ops::{Add, Div, Index, IndexMut, Mul}; +use std::fmt; +use std::fmt::{Display, Debug}; + +use crate::core::geometry::{Vector, Point, Vector3f, Point3f}; + +#[derive(Copy, Clone)] +pub struct SquareMatrix { + m: [[T; N]; N], +} + +impl SquareMatrix +{ + fn new() -> Self where T: Copy + Zero { + Self::zero() + } + + fn identity() -> Self where T: Copy + Zero + One { + let mut m = [[T::zero(); N]; N]; + for i in 0..N { + m[i][i] = T::one(); + } + Self { m } + } + + pub fn zero() -> Self where T: Copy + Zero { + SquareMatrix { m: [[T::zero(); N]; N] } + } + + pub fn is_identity(&self) -> bool where T: Copy + Zero + One + PartialEq { + for i in 0..N { + for j in 0..N { + if i == j { + if self.m[i][j] != T::one() { + return false; + } + } else if self.m[i][j] != T::zero() { + return false; + } + } + } + true + } + + pub fn transpose(&self) -> Self where T: Copy + Zero { + let mut result = SquareMatrix::zero(); + for i in 0..N { + for j in 0..N { + result.m[j][i] = self.m[i][j]; + } + } + result + } +} + + +impl SquareMatrix + where + T: NumFloat +{ + pub fn inverse(&self) -> Option { + if N == 0 { + return Some(Self::new()); + } + + let mut mat = self.m; + let mut inv = Self::new(); + + for i in 0..N { + let mut pivot_row = i; + for j in (i + 1)..N { + if mat[j][i].abs() > mat[pivot_row][i].abs() { + pivot_row = j; + } + } + + if pivot_row != i { + mat.swap(i, pivot_row); + inv.m.swap(i, pivot_row); + } + + let pivot = mat[i][i]; + if pivot.is_zero() { + return None; + } + + for j in i..N { + mat[i][j] = mat[i][j] / pivot; + } + + for j in 0..N { + inv.m[i][j] = inv.m[i][j] / pivot; + } + + for j in 0..N { + if i != j { + let factor = mat[j][i]; + for k in i..N { + mat[j][k] = mat[j][k] - factor * mat[i][k]; + } + for k in 0..N { + inv.m[j][k] = inv.m[j][k] - factor * inv.m[i][k]; + } + } + } + } + Some(inv) + } + + pub fn determinant(&self) -> T { + if N == 0 { + return T::one(); + } + + let mut lum = self.m; // Make a mutable copy of the matrix data + let mut parity = 0; // Number of row swaps + + for i in 0..N { + // Pivoting: find the row with the largest element in the current column + let mut max_row = i; + for k in (i + 1)..N { + if lum[k][i].abs() > lum[max_row][i].abs() { + max_row = k; + } + } + + // If the pivot is on a different row, swap them + if max_row != i { + lum.swap(i, max_row); + parity += 1; + } + + // If the pivot element is zero, the determinant is zero + // (the matrix is singular). + if lum[i][i] == T::zero() { + return T::zero(); + } + + // Gaussian elimination to form the upper-triangular matrix + for j in (i + 1)..N { + let factor = lum[j][i] / lum[i][i]; + for k in i..N { + lum[j][k] = lum[j][k] - factor * lum[i][k]; + } + } + } + + let mut det = T::one(); + for i in 0..N { + det = det * lum[i][i]; + } + + if parity % 2 != 0 { + det = -det; + } + + det + } +} + +impl Default for SquareMatrix +where + T: Copy + Zero + One, +{ + fn default() -> Self { + Self::identity() + } +} + +impl PartialEq for SquareMatrix +where + T: PartialEq, +{ + fn eq(&self, other: &Self) -> bool { + self.m == other.m + } +} + +impl Eq for SquareMatrix {} + + +impl Index for SquareMatrix { + type Output = [T; N]; + + fn index(&self, index: usize) -> &Self::Output { + &self.m[index] + } +} + +impl PartialOrd for SquareMatrix +where + T: PartialOrd, +{ + fn partial_cmp(&self, other: &Self) -> Option { + self.m.iter().flatten().partial_cmp(other.m.iter().flatten()) + } +} + +impl IndexMut for SquareMatrix { + fn index_mut(&mut self, index: usize) -> &mut Self::Output { + &mut self.m[index] + } +} + +impl Debug for SquareMatrix { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("SquareMatrix") + .field("m", &self.m) + .finish() + } +} + +impl Display for SquareMatrix +where + T: Display + Copy, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut col_widths = [0; N]; + for row in self.m.iter() { + for (j, element) in row.iter().enumerate() { + let width = format!("{}", element).len(); + if width > col_widths[j] { + col_widths[j] = width; + } + } + } + + for i in 0..N { + write!(f, "[")?; + for j in 0..N { + write!(f, "{: >width$} ", self.m[i][j], width = col_widths[j])?; + } + writeln!(f, "]")?; + } + Ok(()) + } +} + +impl Add for SquareMatrix +where + T: Copy + Add + Zero, +{ + type Output = Self; + fn add(mut self, rhs: Self) -> Self::Output { + for i in 0..N { + for j in 0..N { + self.m[i][j] = self.m[i][j] + rhs.m[i][j]; + } + } + self + } +} + +impl Mul for SquareMatrix +where + T: Copy + Num, +{ + type Output = Self; + fn mul(self, rhs: Self) -> Self::Output { + let mut result = SquareMatrix::zero(); + for i in 0..N { + for j in 0..N { + let mut sum = T::zero(); + for k in 0..N { + sum = sum + self.m[i][k] * rhs.m[k][j]; + } + result.m[i][j] = sum; + } + } + result + } +} + +impl Div for SquareMatrix +where + T: Copy + Div, +{ + type Output = Self; + fn div(mut self, rhs: T) -> Self::Output { + for row in self.m.iter_mut() { + for element in row.iter_mut() { + *element = *element / rhs; + } + } + self + } +} + +impl Mul> for SquareMatrix +where + T: Num + Copy, +{ + type Output = Vector; + fn mul(self, rhs: Vector) -> Self::Output { + let mut result_arr = [T::zero(); N]; + for i in 0..N { + for j in 0..N { + result_arr[i] = result_arr[i] + self.m[i][j] * rhs.0[j]; + } + } + Vector(result_arr) + } +} + +impl Mul> for SquareMatrix +where + T: Num + Copy, +{ + type Output = Point; + + fn mul(self, rhs: Point) -> Self::Output { + let mut result_arr = [T::zero(); N]; + for i in 0..N { + for j in 0..N { + result_arr[i] = result_arr[i] + self.m[i][j] * rhs.0[j]; + } + } + Point(result_arr) + } +} + +#[derive(Copy, Clone)] +pub struct Transform { + m: SquareMatrix, + m_inv: SquareMatrix, +} + +impl Transform { + pub fn new(m: &SquareMatrix) -> Self { + let inv = match m.inverse() { + Some(inv) => inv , + None => SquareMatrix::zero(), + }; + + Self { m: *m, m_inv: inv } + } + + pub fn is_identity(&self) -> bool { + self.m.is_identity() + } + + pub fn inv(&self) -> Self { + Self { m: self.m_inv, m_inv: self.m} + } + + pub fn translate(delta: Vector3f) -> Transform { + Transform { + m: Matrix::new( + 1.0, 0.0, 0.0, delta.x, 0.0, 1.0, 0.0, delta.y, 0.0, 0.0, 1.0, delta.z, 0.0, 0.0, + 0.0, 1.0, + ), + m_inv: Matrix4x4::new( + 1.0, 0.0, 0.0, -delta.x(), 0.0, 1.0, 0.0, -delta.y(), 0.0, 0.0, 1.0, -delta.z(), 0.0, + 0.0, 0.0, 1.0, + ), + } + } +} + +impl PartialEq for Transform { + fn eq(&self, other: &Self) -> bool { + self.m == other.m && self.m_inv == other.m_inv + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn assert_matrix_approx_eq(a: &SquareMatrix, b: &SquareMatrix) { + const EPSILON: f64 = 1e-9; + for i in 0..N { + for j in 0..N { + assert!( + (a[i][j] - b[i][j]).abs() < EPSILON, + "Matrices differ at ({},{}): {} vs {}\nLeft:\n{}\nRight:\n{}", + i, j, a[i][j], b[i][j], a, b + ); + } + } + } + + #[test] + fn test_inverse_2x2() { + let m = SquareMatrix { m: [[4.0, 7.0], [2.0, 6.0]] }; + let identity = SquareMatrix::identity(); + let inv = m.inverse().expect("Matrix should be invertible"); + let product = m * inv; + assert_matrix_approx_eq(&product, &identity); + } + + #[test] + fn test_inverse_3x3() { + let m = SquareMatrix { m: [[1.0, 2.0, 3.0], [0.0, 1.0, 4.0], [5.0, 6.0, 0.0]] }; + let identity = SquareMatrix::identity(); + let inv = m.inverse().expect("Matrix should be invertible"); + let product = m * inv; + let product_inv = inv * m; + assert_matrix_approx_eq(&product, &identity); + assert_matrix_approx_eq(&product_inv, &identity); + } + + #[test] + fn test_singular_inverse() { + let m = SquareMatrix { m: [[1.0, 2.0], [2.0, 4.0]] }; // Determinant is 0 + assert!(m.inverse().is_none()); + } + + #[test] + fn test_multiplication_2x2() { + let a = SquareMatrix { m: [[1.0, 2.0], [3.0, 4.0]] }; + let b = SquareMatrix { m: [[2.0, 0.0], [1.0, 2.0]] }; + let expected = SquareMatrix { m: [[4.0, 4.0], [10.0, 8.0]] }; + let result = a * b; + assert_matrix_approx_eq(&result, &expected); + } + + #[test] + fn test_determinant_3x3() { + let m = SquareMatrix { m: [[1.0, 2.0, 3.0], [0.0, 1.0, 4.0], [5.0, 6.0, 0.0]] }; + assert_eq!(m.determinant(), 1.0); + } +} diff --git a/src/lib.rs b/src/lib.rs index 0b43446..71e8aab 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,2 +1,4 @@ +#![allow(unused_imports, dead_code)] + mod core; -mod utils; +mod lights; diff --git a/src/lights/diffuse.rs b/src/lights/diffuse.rs new file mode 100644 index 0000000..989af06 --- /dev/null +++ b/src/lights/diffuse.rs @@ -0,0 +1,16 @@ +use crate::core::medium::MediumInterface; +use crate::core::pbrt::Float; +use crate::core::spectrum::Spectrum; + +pub struct DiffuseAreaLight { + pub l_emit: Spectrum, + // pub shape: Arc, + pub two_sided: bool, + pub area: Float, + // inherited from class Light (see light.h) + pub flags: u8, + pub n_samples: i32, + pub medium_interface: MediumInterface, + // light_to_world: Transform, + // world_to_light: Transform, +} diff --git a/src/lights/mod.rs b/src/lights/mod.rs new file mode 100644 index 0000000..ac6f588 --- /dev/null +++ b/src/lights/mod.rs @@ -0,0 +1 @@ +pub mod diffuse; diff --git a/src/utils/mod.rs b/src/utils/mod.rs deleted file mode 100644 index cd40856..0000000 --- a/src/utils/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod types; diff --git a/src/utils/types.rs b/src/utils/types.rs deleted file mode 100644 index e2dbb90..0000000 --- a/src/utils/types.rs +++ /dev/null @@ -1,245 +0,0 @@ -use std::ops::{Sub, Add, Div, Mul, Neg, Index, IndexMut}; -use num_traits::{Num, Float, Bounded}; - -pub trait Tuple : Index + IndexMut + Copy { - fn get(&self, i: usize) -> T; - fn set(&mut self, i: usize, val: T); - fn has_nan(&self) -> bool where T: Float { - for i in 0..N { - if self.get(i).is_nan() { - return true - } - } - false - } -} - -#[derive(Copy, Clone, PartialEq)] -pub struct Vector2 { pub x: T, pub y: T } -#[derive(Copy, Clone, PartialEq)] -pub struct Point2 { pub x: T, pub y: T } -#[derive(Copy, Clone, PartialEq)] -pub struct Vector3 { pub x: T, pub y: T, pub z: T } -#[derive(Copy, Clone, PartialEq)] -pub struct Normal3 { pub x: T, pub y: T, pub z: T } -#[derive(Debug, Copy, Clone, PartialEq)] -pub struct Point3 { pub x: T, pub y: T, pub z : T } - -// Using macros to make this more concise -macro_rules! impl_tuple3 { - ($Struct:ident, [$($field:ident), +]) => { - impl $Struct { - pub fn new($($field: T), +) -> Self { Self { $($field), + }} - } - - impl $Struct { - pub fn dot(&self, other: Self) -> T { - self.x * other.x + self.y * other.y + self.z * other.z - } - - pub fn length_squared(self) -> T { - self.dot(self) - } - } - - impl $Struct { - pub fn length(self) -> T { - self.length_squared().sqrt() - } - - pub fn normalize(self) -> Self { - self / self.length() - } - } - - // Operators - impl> Add for $Struct { - type Output = Self; - fn add(self, rhs: Self) -> Self { Self::new(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z )} - } - - impl + Copy > Mul for $Struct { - type Output = Self; - fn mul(self, rhs: T) -> Self { Self::new(self.x * rhs, self.y * rhs, self.z * rhs )} - } - - impl + Copy > Div for $Struct { - type Output = Self; - fn div(self, rhs: T) -> Self { Self::new(self.x / rhs, self.y / rhs, self.z / rhs )} - } - - impl> Neg for $Struct { - type Output = Self; - fn neg(self) -> Self { Self::new(-self.x, -self.y, -self.z)} - } - - impl Index for $Struct { - type Output = T; - fn index(&self, i: usize) -> &T { - match i { 0 => &self.x, 1 => &self.y, 2 => &self.z, _ => panic!("Index out of bonds") } - } - } - - impl IndexMut for $Struct { - fn index_mut(&mut self, i: usize) -> &mut T { - match i { 0 => &mut self.x, 1 => &mut self.y, 2 => &mut self.z, _ => panic!("Index out of bonds") } - } - } - }; -} - -macro_rules! impl_component_ops { - ($Struct:ident) => { - impl> Sub for $Struct { - type Output = Self; - fn sub(self, rhs: Self) -> Self { Self::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z) } - } - } -} - -impl_tuple3!(Vector3, [x, y, z]); -impl_tuple3!(Point3, [x, y, z]); -impl_tuple3!(Normal3, [x, y, z]); -impl_component_ops!(Vector3); -impl_component_ops!(Normal3); - -// Point3 - Point3 -> Vector3 -impl> Sub> for Point3 { - type Output = Vector3; - fn sub(self, rhs: Point3) -> Vector3 { - Vector3::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z) - } -} - -// Point3 + Vector3 -> Point3 -impl> Add> for Point3 { - type Output = Point3; - fn add(self, rhs: Vector3) -> Point3 { - Point3::new(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z) - } -} - -// Point3 - Vector3 -> Point3 -impl> Sub> for Point3 { - type Output = Point3; - fn sub(self, rhs: Vector3) -> Point3 { - Point3::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z) - } -} - - -// Cross Product for Vector3 -impl Vector3 { - 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, - } - } -} - - -pub type Point3f = Point3; -pub type Point3i = Point3; -pub type Vector3f = Vector3; -pub type Vector3i = Vector3; -pub type Normal3f = Normal3; -pub type Normal3i = Normal3; - - -#[derive(Debug, Copy, Clone, PartialEq)] -pub struct Bounds3 { - pub p_min: Point3, - pub p_max: Point3, -} - -impl Bounds3 -where - T: Num + Bounded + PartialOrd + Copy, -{ - pub fn new() -> Self { - Self { - p_min: Point3::new(T::max_value(), T::max_value(), T::max_value()), - p_max: Point3::new(T::min_value(), T::min_value(), T::min_value()), - } - } - - pub fn from_point(p: Point3) -> Self { - Self { p_min: p, p_max: p } - } - - pub fn from_points(p1: Point3, p2: Point3) -> Self { - Self { - p_min: Point3::new( - if p1.x < p2.x { p1.x } else { p2.x }, - if p1.y < p2.y { p1.y } else { p2.y }, - if p1.z < p2.z { p1.z } else { p2.z }, - ), - p_max: Point3::new( - if p1.x > p2.x { p1.x } else { p2.x }, - if p1.y > p2.y { p1.y } else { p2.y }, - if p1.z > p2.z { p1.z } else { p2.z }, - ), - } - } - - pub fn diagonal(&self) -> Vector3 { - self.p_max - self.p_min - } - - pub fn surface_area(&self) -> T { - let d = self.diagonal(); - let two = T::one() + T::one(); - two * (d.x * d.y + d.x * d.z + d.y * d.z) - } - - pub fn volume(&self) -> T { - let d = self.diagonal(); - d.x * d.y * d.z - } - - pub fn is_empty(&self) -> bool { - self.p_min.x >= self.p_max.x || self.p_min.y >= self.p_max.y || self.p_min.z >= self.p_max.z - } - - pub fn max_dimension(&self) -> usize { - let d = self.diagonal(); - if d.x > d.y && d.x > d.z { - return 0; - } else if d.y > d.z { - return 1; - } - 2 - } -} - -pub fn union_bounds(b1: Bounds3, b2: Bounds3) -> Bounds3 { - Bounds3 { - p_min: Point3::new( - if b1.p_min.x < b2.p_min.x { b1.p_min.x } else { b2.p_min.x }, - if b1.p_min.y < b2.p_min.y { b1.p_min.y } else { b2.p_min.y }, - if b1.p_min.z < b2.p_min.z { b1.p_min.z } else { b2.p_min.z }, - ), - p_max: Point3::new( - if b1.p_max.x > b2.p_max.x { b1.p_max.x } else { b2.p_max.x }, - if b1.p_max.y > b2.p_max.y { b1.p_max.y } else { b2.p_max.y }, - if b1.p_max.z > b2.p_max.z { b1.p_max.z } else { b2.p_max.z }, - ), - } -} - -pub fn union_bounds_point(b: Bounds3, p: Point3) -> Bounds3 { - Bounds3 { - p_min: Point3::new( - if b.p_min.x < p.x { b.p_min.x } else { p.x }, - if b.p_min.y < p.y { b.p_min.y } else { p.y }, - if b.p_min.z < p.z { b.p_min.z } else { p.z }, - ), - p_max: Point3::new( - if b.p_max.x > p.x { b.p_max.x } else { p.x }, - if b.p_max.y > p.y { b.p_max.y } else { p.y }, - if b.p_max.z > p.z { b.p_max.z } else { p.z }, - ), - } -}