Skip to main content

vertex_colors/
vertex_colors.rs

1//! Illustrates the use of vertex colors.
2
3use bevy::{mesh::VertexAttributeValues, prelude::*};
4
5fn main() {
6    App::new()
7        .add_plugins(DefaultPlugins)
8        .add_systems(Startup, setup)
9        .run();
10}
11
12/// set up a simple 3D scene
13fn setup(
14    mut commands: Commands,
15    mut meshes: ResMut<Assets<Mesh>>,
16    mut materials: ResMut<Assets<StandardMaterial>>,
17) {
18    // plane
19    commands.spawn((
20        Mesh3d(meshes.add(Plane3d::default().mesh().size(5.0, 5.0))),
21        MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
22    ));
23    // cube
24    // Assign vertex colors based on vertex positions
25    let mut colorful_cube = Mesh::from(Cuboid::default());
26    if let Some(VertexAttributeValues::Float32x3(positions)) =
27        colorful_cube.attribute(Mesh::ATTRIBUTE_POSITION)
28    {
29        let colors: Vec<[f32; 4]> = positions
30            .iter()
31            .map(|[r, g, b]| [(1. - *r) / 2., (1. - *g) / 2., (1. - *b) / 2., 1.])
32            .collect();
33        colorful_cube.insert_attribute(Mesh::ATTRIBUTE_COLOR, colors);
34    }
35    commands.spawn((
36        Mesh3d(meshes.add(colorful_cube)),
37        // This is the default color, but note that vertex colors are
38        // multiplied by the base color, so you'll likely want this to be
39        // white if using vertex colors.
40        MeshMaterial3d(materials.add(Color::srgb(1., 1., 1.))),
41        Transform::from_xyz(0.0, 0.5, 0.0),
42    ));
43
44    // Light
45    commands.spawn((
46        PointLight {
47            shadows_enabled: true,
48            ..default()
49        },
50        Transform::from_xyz(4.0, 5.0, 4.0).looking_at(Vec3::ZERO, Vec3::Y),
51    ));
52
53    // Camera
54    commands.spawn((
55        Camera3d::default(),
56        Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
57    ));
58}