custom_gltf_vertex_attribute/
custom_gltf_vertex_attribute.rs1use bevy::{
4 gltf::GltfPlugin,
5 mesh::{MeshVertexAttribute, MeshVertexBufferLayoutRef},
6 prelude::*,
7 reflect::TypePath,
8 render::render_resource::*,
9 shader::ShaderRef,
10 sprite_render::{Material2d, Material2dKey, Material2dPlugin},
11};
12
13const SHADER_ASSET_PATH: &str = "shaders/custom_gltf_2d.wgsl";
15
16const ATTRIBUTE_BARYCENTRIC: MeshVertexAttribute =
22 MeshVertexAttribute::new("Barycentric", 2137464976, VertexFormat::Float32x3);
23
24fn main() {
25 App::new()
26 .insert_resource(AmbientLight {
27 color: Color::WHITE,
28 brightness: 1.0 / 5.0f32,
29 ..default()
30 })
31 .add_plugins((
32 DefaultPlugins.set(
33 GltfPlugin::default()
34 .add_custom_vertex_attribute("_BARYCENTRIC", ATTRIBUTE_BARYCENTRIC),
39 ),
40 Material2dPlugin::<CustomMaterial>::default(),
41 ))
42 .add_systems(Startup, setup)
43 .run();
44}
45
46fn setup(
47 mut commands: Commands,
48 asset_server: Res<AssetServer>,
49 mut materials: ResMut<Assets<CustomMaterial>>,
50) {
51 let mesh = asset_server.load(
53 GltfAssetLabel::Primitive {
54 mesh: 0,
55 primitive: 0,
56 }
57 .from_asset("models/barycentric/barycentric.gltf"),
58 );
59 commands.spawn((
60 Mesh2d(mesh),
61 MeshMaterial2d(materials.add(CustomMaterial {})),
62 Transform::from_scale(150.0 * Vec3::ONE),
63 ));
64
65 commands.spawn(Camera2d);
66}
67
68#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)]
72struct CustomMaterial {}
73
74impl Material2d for CustomMaterial {
75 fn vertex_shader() -> ShaderRef {
76 SHADER_ASSET_PATH.into()
77 }
78 fn fragment_shader() -> ShaderRef {
79 SHADER_ASSET_PATH.into()
80 }
81
82 fn specialize(
83 descriptor: &mut RenderPipelineDescriptor,
84 layout: &MeshVertexBufferLayoutRef,
85 _key: Material2dKey<Self>,
86 ) -> Result<(), SpecializedMeshPipelineError> {
87 let vertex_layout = layout.0.get_layout(&[
88 Mesh::ATTRIBUTE_POSITION.at_shader_location(0),
89 Mesh::ATTRIBUTE_COLOR.at_shader_location(1),
90 ATTRIBUTE_BARYCENTRIC.at_shader_location(2),
91 ])?;
92 descriptor.vertex.buffers = vec![vertex_layout];
93 Ok(())
94 }
95}