Skip to content

Commit

Permalink
Allow Triangles to carry a color and transfer that to the vertices du…
Browse files Browse the repository at this point in the history
…ring meshing

This moves the hardcoded color specification (still red with full
opacity) one level closer to the actual model.

Signed-off-by: Daniel Egger <[email protected]>
  • Loading branch information
therealprof authored and hannobraun committed Mar 14, 2022
1 parent 643f39a commit e057635
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 8 deletions.
11 changes: 6 additions & 5 deletions src/graphics/vertices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,18 +56,19 @@ impl From<&Vec<Triangle<3>>> for Vertices {
let [a, b, c] = triangle.points();

let normal = (b - a).cross(&(c - a)).normalize();
let color = triangle.color();

mesh.push((a, normal));
mesh.push((b, normal));
mesh.push((c, normal));
mesh.push((a, normal, color));
mesh.push((b, normal, color));
mesh.push((c, normal, color));
}

let vertices = mesh
.vertices()
.map(|(vertex, normal)| Vertex {
.map(|(vertex, normal, color)| Vertex {
position: vertex.into(),
normal: normal.into(),
color: [1.0, 0.0, 0.0, 1.0],
color: color.map(|v| f32::from(v) / 255.0),
})
.collect();

Expand Down
26 changes: 23 additions & 3 deletions src/math/triangle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,20 @@ use super::{Point, Scalar};

/// A triangle
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Triangle<const D: usize>([Point<D>; 3]);
pub struct Triangle<const D: usize> {
points: [Point<D>; 3],
color: [u8; 4],
}

impl<const D: usize> Triangle<D> {
/// Access the triangle's points
pub fn points(&self) -> [Point<D>; 3] {
self.0
self.points
}

/// Return the specified color of the triangle in RGBA
pub fn color(&self) -> [u8; 4] {
self.color
}
}

Expand All @@ -27,7 +35,10 @@ impl<const D: usize> From<[Point<D>; 3]> for Triangle<D> {

// A triangle is not valid if it doesn't span any area
if area != Scalar::from(0.0) {
Self(points)
Self {
points,
color: [255, 0, 0, 255],
}
} else {
panic!("Invalid Triangle specified");
}
Expand Down Expand Up @@ -72,4 +83,13 @@ mod tests {
let c = Point::from([2.0, 2.0, 2.0]);
let _triangle = Triangle::from([a, b, c]);
}

#[test]
fn triangle_default_color() {
let a = Point::from([0.0, 0.0]);
let b = Point::from([1.0, 1.0]);
let c = Point::from([1.0, 2.0]);
let triangle = Triangle::from([a, b, c]);
assert_eq!(triangle.color(), [255, 0, 0, 255]);
}
}

0 comments on commit e057635

Please sign in to comment.