Skip to main content

nexcore_softrender/geometry/
mesh.rs

1//! Mesh: triangle list — the universal rendering primitive
2//!
3//! Everything is triangles. Rects are 2 triangles. Circles are N triangles.
4//! The GPU doesn't know what a "rectangle" is. It only knows triangles.
5
6use super::vertex::Vertex;
7
8#[derive(Debug, Clone)]
9#[non_exhaustive]
10pub struct Triangle {
11    pub v0: Vertex,
12    pub v1: Vertex,
13    pub v2: Vertex,
14}
15
16impl Triangle {
17    pub fn new(v0: Vertex, v1: Vertex, v2: Vertex) -> Self {
18        Self { v0, v1, v2 }
19    }
20}
21
22#[derive(Debug, Clone)]
23#[non_exhaustive]
24pub struct Mesh {
25    pub triangles: Vec<Triangle>,
26}
27
28impl Mesh {
29    pub fn new() -> Self {
30        Self {
31            triangles: Vec::new(),
32        }
33    }
34
35    pub fn with_capacity(n: usize) -> Self {
36        Self {
37            triangles: Vec::with_capacity(n),
38        }
39    }
40
41    pub fn push(&mut self, tri: Triangle) {
42        self.triangles.push(tri);
43    }
44
45    pub fn triangle_count(&self) -> usize {
46        self.triangles.len()
47    }
48
49    pub fn vertex_count(&self) -> usize {
50        self.triangles.len() * 3
51    }
52
53    /// Merge another mesh into this one
54    pub fn extend(&mut self, other: &Mesh) {
55        self.triangles.extend_from_slice(&other.triangles);
56    }
57}
58
59impl Default for Mesh {
60    fn default() -> Self {
61        Self::new()
62    }
63}
64
65impl FromIterator<Triangle> for Mesh {
66    fn from_iter<I: IntoIterator<Item = Triangle>>(iter: I) -> Self {
67        Self {
68            triangles: iter.into_iter().collect(),
69        }
70    }
71}