1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
// Module declaration
pub(crate) mod mesh_builder;

// External dependencies
use cgmath::Matrix4;
use ndarray::Array1;
use num::ToPrimitive;

// Internal dependencies
use crate::{
    simulation::drawable::binder::{Binder, Bindable, Drawable},
    Error,
};
use mesh_builder::MeshBuilder;

/// # General Information
///
/// Representation of a plane figure / 3d body. Contains information to draw to screen and move/rotate mesh representation to final position.
///
/// # Fields
///
/// * `max_length` - Maximum length of figure. Used to center camera arround objective.
/// * `model_matrix` - Translates and rotates object to final world position.
/// * `binder` - vao, vbo and ebo variables bound to mesh drawable in GPU.
/// * `indices` - Indices that map to vertices. Normally used in triads. Specified in gl configuration.
/// * `vertices` -  Vertices in 3d space. Normally used in sextuples (coordinate and color). Specified in gl configuration.
///
#[allow(dead_code)]
#[derive(Debug)]
pub(crate) struct Mesh {
    pub(crate) max_length: f64,
    pub(crate) model_matrix: Matrix4<f32>,
    pub(crate) boundary_indices: Option<Vec<u32>>,
    binder: Binder,
    pub(crate) indices: Array1<u32>,
    pub(crate) vertices: Array1<f64>,
}

impl Mesh {
    /// Getter for model_matrix
    pub fn get_model_matrix(&self) -> &Matrix4<f32> {
        &self.model_matrix
    }

    /// Creates new instance of builder
    pub fn builder<B>(location: B) -> MeshBuilder
    where
        B: AsRef<str>,
    {
        MeshBuilder::new(location)
    }

    /// Filtering vertices to give to 1d solver. Temporal function. To be changed for better solution.
    pub(crate) fn filter_for_solving_1d(&self) -> Array1<f64> {
        // size of vertex is 6. There are double the vertices in 1d since a new pair is generated to draw a bar, therefore len is divided by 12.
        let vertices_len = self.vertices.len() / 12;
        self.vertices
            .iter()
            .enumerate()
            .filter_map(|(idx, x)| {
                if idx % 6 == 0 && idx < vertices_len * 6 {
                    Some(*x)
                } else {
                    None
                }
            })
            .collect()
    }

    /// Improvable solution to move gradient updating out of dzahui window. Probably will be changed in the future.
    /// Obtains max and min of solution (normallly some sort of rate of change), divides every element by the difference and then multiplies them by
    /// pi/2 so that, when calculating their sine and cosine, there's a mapping between max velocity <-> red and min velocity <-> blue
    pub(crate) fn update_gradient_1d(&mut self, velocity_norm: Vec<f64>) {
        let sol_max = velocity_norm
            .iter()
            .copied()
            .fold(f64::NEG_INFINITY, f64::max);

        let sol_min = velocity_norm.iter().copied().fold(f64::INFINITY, f64::min);
        let vertices_len = self.vertices.len();
        
        for i in 0..(vertices_len / 12) {
            let norm_sol =
                (velocity_norm[i] - sol_min) / (sol_max - sol_min) * (std::f64::consts::PI / 2.);
            self.vertices[6 * i + 3] = norm_sol.sin();
            self.vertices[6 * i + 5] = norm_sol.cos();
            self.vertices[6 * i + 3 + vertices_len / 2] = norm_sol.sin();
            self.vertices[6 * i + 5 + vertices_len / 2] = norm_sol.cos();
        }
    }
}

impl Bindable for Mesh {
    fn get_binder(&self) -> Result<&Binder, Error> {
        Ok(&self.binder)
    }

    fn get_mut_binder(&mut self) -> Result<&mut Binder, Error> {
        Ok(&mut self.binder)
    }
}

impl Drawable for Mesh {
    fn get_indices(&self) -> Result<&Array1<u32>, Error> {
        Ok(&self.indices)
    }

    fn get_vertices(&self) -> Result<Array1<f32>, Error> {
        Ok(Array1::from_vec(
            self.vertices.iter().map(|x| -> Result<f32,Error> { x.to_f32().ok_or(Error::FloatConversion) })
            .collect::<Result<Vec<f32>,_>>()?
        ))
    }

    fn get_max_length(&self) -> Result<f32, Error> {
        let max_len = self.max_length.to_f32();

        match max_len {
            Some(f) => {
                if f.is_finite() {
                    Ok(f)
                } else {
                    Err(Error::Overflow)
                }
            }
            None => Err(Error::Unimplemented),
        }
    }
}

#[cfg(test)]
mod test {
    use super::Mesh;
    use ndarray::Array1;

    #[test]
    fn parse_coordinates() {
        let new_mesh = Mesh::builder("/home/Arthur/Tesis/Dzahui/assets/test.obj")
            .build_mesh_3d()
            .unwrap();
        assert!(
            new_mesh.vertices
                == Array1::from_vec(vec![
                    -1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0,
                    0.0, 0.0, 1.0
                ])
        );
        assert!(new_mesh.indices == Array1::from_vec(vec![0, 1, 2]));
    }

    #[test]
    fn is_max_distance() {
        let new_mesh = Mesh::builder("/home/Arthur/Tesis/Dzahui/assets/test.obj")
            .build_mesh_2d()
            .unwrap();
        assert!(new_mesh.max_length >= 1.90);
        assert!(new_mesh.max_length <= 2.10);
    }
}