| 1 |
|
| 2 |
|
| 3 |
use 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, Material2dPipeline, Material2dPlugin}, |
| 11 |
}; |
| 12 |
|
| 13 |
|
| 14 |
const SHADER_ASSET_PATH: &str = "shaders/custom_gltf_2d.wesl"; |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
const ATTRIBUTE_BARYCENTRIC: MeshVertexAttribute = |
| 22 |
MeshVertexAttribute::new("Barycentric", 2137464976, VertexFormat::Float32x3); |
| 23 |
|
| 24 |
fn main() { |
| 25 |
App::new() |
| 26 |
.insert_resource(GlobalAmbientLight { |
| 27 |
color: Color::WHITE, |
| 28 |
brightness: 1.0 / 5.0f32, |
| 29 |
..default() |
| 30 |
}) |
| 31 |
.add_plugins(( |
| 32 |
DefaultPlugins.set( |
| 33 |
GltfPlugin::default() |
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
.add_custom_vertex_attribute("_BARYCENTRIC", ATTRIBUTE_BARYCENTRIC), |
| 39 |
), |
| 40 |
Material2dPlugin::<CustomMaterial>::default(), |
| 41 |
)) |
| 42 |
.add_systems(Startup, setup) |
| 43 |
.run(); |
| 44 |
} |
| 45 |
|
| 46 |
fn setup( |
| 47 |
mut commands: Commands, |
| 48 |
asset_server: Res<AssetServer>, |
| 49 |
mut materials: ResMut<Assets<CustomMaterial>>, |
| 50 |
) { |
| 51 |
|
| 52 |
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 |
|
| 69 |
|
| 70 |
|
| 71 |
#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)] |
| 72 |
struct CustomMaterial {} |
| 73 |
|
| 74 |
impl 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 |
_pipeline: &Material2dPipeline, |
| 84 |
descriptor: &mut RenderPipelineDescriptor, |
| 85 |
layout: &MeshVertexBufferLayoutRef, |
| 86 |
_key: Material2dKey<Self>, |
| 87 |
) -> Result<(), SpecializedMeshPipelineError> { |
| 88 |
let vertex_layout = layout.0.get_layout(&[ |
| 89 |
Mesh::ATTRIBUTE_POSITION.at_shader_location(0), |
| 90 |
Mesh::ATTRIBUTE_COLOR.at_shader_location(1), |
| 91 |
ATTRIBUTE_BARYCENTRIC.at_shader_location(2), |
| 92 |
])?; |
| 93 |
descriptor.vertex.buffers = vec![vertex_layout]; |
| 94 |
Ok(()) |
| 95 |
} |
| 96 |
} |