Skip to main content

oxide_renderer/mesh/
vertex.rs

1//! Vertex types and attributes
2
3use bytemuck::{Pod, Zeroable};
4use wgpu::{VertexAttribute, VertexBufferLayout, VertexFormat, VertexStepMode};
5
6/// Simple vertex for basic demos (position + color)
7#[repr(C)]
8#[derive(Copy, Clone, Debug, Pod, Zeroable)]
9pub struct Vertex {
10    pub position: [f32; 3],
11    pub color: [f32; 3],
12}
13
14impl Vertex {
15    pub fn new(position: [f32; 3], color: [f32; 3]) -> Self {
16        Self { position, color }
17    }
18
19    pub fn desc<'a>() -> VertexBufferLayout<'a> {
20        VertexBufferLayout {
21            array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
22            step_mode: VertexStepMode::Vertex,
23            attributes: &[
24                VertexAttribute {
25                    offset: 0,
26                    shader_location: 0,
27                    format: VertexFormat::Float32x3,
28                },
29                VertexAttribute {
30                    offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
31                    shader_location: 1,
32                    format: VertexFormat::Float32x3,
33                },
34            ],
35        }
36    }
37}
38
39pub fn triangle_vertices() -> Vec<Vertex> {
40    vec![
41        Vertex::new([0.0, 0.5, 0.0], [1.0, 0.0, 0.0]),
42        Vertex::new([-0.5, -0.5, 0.0], [0.0, 1.0, 0.0]),
43        Vertex::new([0.5, -0.5, 0.0], [0.0, 0.0, 1.0]),
44    ]
45}
46
47/// Full 3D vertex format with position, normal, and UV
48#[repr(C)]
49#[derive(Copy, Clone, Debug, Pod, Zeroable)]
50pub struct Vertex3D {
51    pub position: [f32; 3],
52    pub normal: [f32; 3],
53    pub uv: [f32; 2],
54}
55
56impl Vertex3D {
57    pub fn new(position: [f32; 3], normal: [f32; 3], uv: [f32; 2]) -> Self {
58        Self {
59            position,
60            normal,
61            uv,
62        }
63    }
64
65    pub fn desc<'a>() -> VertexBufferLayout<'a> {
66        VertexBufferLayout {
67            array_stride: std::mem::size_of::<Vertex3D>() as wgpu::BufferAddress,
68            step_mode: VertexStepMode::Vertex,
69            attributes: &[
70                VertexAttribute {
71                    offset: 0,
72                    shader_location: 0,
73                    format: VertexFormat::Float32x3,
74                },
75                VertexAttribute {
76                    offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
77                    shader_location: 1,
78                    format: VertexFormat::Float32x3,
79                },
80                VertexAttribute {
81                    offset: std::mem::size_of::<[f32; 6]>() as wgpu::BufferAddress,
82                    shader_location: 2,
83                    format: VertexFormat::Float32x2,
84                },
85            ],
86        }
87    }
88}