| 1 |
|
| 2 |
|
| 3 |
use 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 |
|
| 15 |
const SHADER_ASSET_PATH: &str = "shaders/custom_vertex_attribute.wesl"; |
| 16 |
|
| 17 |
fn main() { |
| 18 |
App::new() |
| 19 |
.add_plugins((DefaultPlugins, MaterialPlugin::<CustomMaterial>::default())) |
| 20 |
.add_systems(Startup, setup) |
| 21 |
.run(); |
| 22 |
} |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
const ATTRIBUTE_BLEND_COLOR: MeshVertexAttribute = |
| 27 |
MeshVertexAttribute::new("BlendColor", 988540917, VertexFormat::Float32x4); |
| 28 |
|
| 29 |
|
| 30 |
fn 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 |
|
| 37 |
.with_inserted_attribute( |
| 38 |
ATTRIBUTE_BLEND_COLOR, |
| 39 |
|
| 40 |
vec![[1.0, 0.0, 0.0, 1.0]; 24], |
| 41 |
); |
| 42 |
|
| 43 |
|
| 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 |
|
| 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 |
|
| 60 |
#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)] |
| 61 |
struct CustomMaterial { |
| 62 |
#[uniform(0)] |
| 63 |
color: LinearRgba, |
| 64 |
} |
| 65 |
|
| 66 |
impl 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 |
} |