Skip to main content

nexcore_softrender/geometry/
vertex.rs

1//! Vertex: position + color + UV coordinates
2//!
3//! The fundamental unit of geometry. Every shape decomposes to vertices.
4
5use crate::math::{Color, Vec2, Vec3};
6
7#[derive(Debug, Clone, Copy)]
8#[non_exhaustive]
9pub struct Vertex {
10    pub position: Vec3,
11    pub color: Color,
12    pub uv: Vec2,
13}
14
15impl Vertex {
16    pub fn new(position: Vec3, color: Color, uv: Vec2) -> Self {
17        Self {
18            position,
19            color,
20            uv,
21        }
22    }
23
24    /// Simple vertex with position and color, UV defaults to (0,0)
25    pub fn colored(x: f64, y: f64, color: Color) -> Self {
26        Self {
27            position: Vec3::new(x, y, 0.0),
28            color,
29            uv: Vec2::ZERO,
30        }
31    }
32
33    /// Vertex at 2D position with white color
34    pub fn pos2d(x: f64, y: f64) -> Self {
35        Self::colored(x, y, Color::WHITE)
36    }
37
38    /// Barycentric interpolation of three vertices
39    pub fn interpolate(v0: &Self, v1: &Self, v2: &Self, w0: f64, w1: f64, w2: f64) -> Self {
40        Self {
41            position: Vec3::new(
42                v0.position.x * w0 + v1.position.x * w1 + v2.position.x * w2,
43                v0.position.y * w0 + v1.position.y * w1 + v2.position.y * w2,
44                v0.position.z * w0 + v1.position.z * w1 + v2.position.z * w2,
45            ),
46            color: Color::rgba(
47                v0.color.r * w0 + v1.color.r * w1 + v2.color.r * w2,
48                v0.color.g * w0 + v1.color.g * w1 + v2.color.g * w2,
49                v0.color.b * w0 + v1.color.b * w1 + v2.color.b * w2,
50                v0.color.a * w0 + v1.color.a * w1 + v2.color.a * w2,
51            ),
52            uv: Vec2::new(
53                v0.uv.x * w0 + v1.uv.x * w1 + v2.uv.x * w2,
54                v0.uv.y * w0 + v1.uv.y * w1 + v2.uv.y * w2,
55            ),
56        }
57    }
58}