custom_vertex_attribute/
custom_vertex_attribute.rs

1//! A shader that reads a mesh's custom vertex attribute.
2
3use bevy::{
4    mesh::{MeshVertexAttribute, MeshVertexBufferLayoutRef},
5    pbr::{MaterialPipeline, MaterialPipelineKey},
6    prelude::*,
7    reflect::TypePath,
8    render::render_resource::{
9        AsBindGroup, RenderPipelineDescriptor, SpecializedMeshPipelineError, VertexFormat,
10    },
11    shader::ShaderRef,
12};
13
14/// This example uses a shader source file from the assets subdirectory
15const SHADER_ASSET_PATH: &str = "shaders/custom_vertex_attribute.wgsl";
16
17fn main() {
18    App::new()
19        .add_plugins((DefaultPlugins, MaterialPlugin::<CustomMaterial>::default()))
20        .add_systems(Startup, setup)
21        .run();
22}
23
24// A "high" random id should be used for custom attributes to ensure consistent sorting and avoid collisions with other attributes.
25// See the MeshVertexAttribute docs for more info.
26const ATTRIBUTE_BLEND_COLOR: MeshVertexAttribute =
27    MeshVertexAttribute::new("BlendColor", 988540917, VertexFormat::Float32x4);
28
29/// set up a simple 3D scene
30fn setup(
31    mut commands: Commands,
32    mut meshes: ResMut<Assets<Mesh>>,
33    mut materials: ResMut<Assets<CustomMaterial>>,
34) {
35    let mesh = Mesh::from(Cuboid::default())
36        // Sets the custom attribute
37        .with_inserted_attribute(
38            ATTRIBUTE_BLEND_COLOR,
39            // The cube mesh has 24 vertices (6 faces, 4 vertices per face), so we insert one BlendColor for each
40            vec![[1.0, 0.0, 0.0, 1.0]; 24],
41        );
42
43    // cube
44    commands.spawn((
45        Mesh3d(meshes.add(mesh)),
46        MeshMaterial3d(materials.add(CustomMaterial {
47            color: LinearRgba::WHITE,
48        })),
49        Transform::from_xyz(0.0, 0.5, 0.0),
50    ));
51
52    // camera
53    commands.spawn((
54        Camera3d::default(),
55        Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
56    ));
57}
58
59// This is the struct that will be passed to your shader
60#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)]
61struct CustomMaterial {
62    #[uniform(0)]
63    color: LinearRgba,
64}
65
66impl Material for CustomMaterial {
67    fn vertex_shader() -> ShaderRef {
68        SHADER_ASSET_PATH.into()
69    }
70    fn fragment_shader() -> ShaderRef {
71        SHADER_ASSET_PATH.into()
72    }
73
74    fn specialize(
75        _pipeline: &MaterialPipeline,
76        descriptor: &mut RenderPipelineDescriptor,
77        layout: &MeshVertexBufferLayoutRef,
78        _key: MaterialPipelineKey<Self>,
79    ) -> Result<(), SpecializedMeshPipelineError> {
80        let vertex_layout = layout.0.get_layout(&[
81            Mesh::ATTRIBUTE_POSITION.at_shader_location(0),
82            ATTRIBUTE_BLEND_COLOR.at_shader_location(1),
83        ])?;
84        descriptor.vertex.buffers = vec![vertex_layout];
85        Ok(())
86    }
87}