pixel_weaver/
image_functions.rs

1use cgmath::{
2    Vector2,
3    Vector3,
4    vec2,
5    vec3
6};
7use crate::ImageData;
8
9/// Returns the UV space conversion of the pixel coordinate.
10/// Centered at (0,0).
11/// Adjusted for aspect ratio.
12pub fn uv(image_data: &ImageData, coord: &Vector2<u32>) -> Vector2<f64> {
13    let mut uv: Vector2<f64> = vec2(0., 0.);
14    uv.y = ((coord.x as f64 / image_data.resolution.y as f64) * 2. - 1.0) * -1.;
15    uv.x = ((coord.y as f64 / image_data.resolution.x as f64) * 2. - 1.0) * image_data.aspect_ratio;
16    uv
17}
18
19/// Returns the length of UV coordinate
20pub fn length(coord: Vector2<f64>) -> f64 {
21    (coord.x.powi(2) + coord.y.powi(2)).sqrt()
22}
23
24/// Takes a normalized `Vector3<f64>` and returns a conversion to `Vector3<u8>` in 24 bit color space
25pub fn f64_vector3_to_u8(vector: Vector3<f64>) -> Vector3<u8> {
26    vec3(
27        (vector.x * 255.).clamp(0.0, 255.0) as u8,
28        (vector.y * 255.).clamp(0.0, 255.0) as u8,
29        (vector.z * 255.).clamp(0.0, 255.0) as u8,
30    )
31}
32
33/// Takes a normalized value and returns a conversion to a single 8 bit color channel
34pub fn normal_to_rgb(val: f64) -> u8 {
35    (val * 255.0).clamp(0., 255.) as u8
36}
37