1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
use crate::physics::RapierConfiguration;
use crate::rapier::geometry::ColliderShape;
use crate::render::ColliderDebugRender;
use bevy::prelude::*;
use bevy::render::mesh::{Indices, VertexAttributeValues};
use rapier::geometry::ShapeType;

/// System responsible for attaching a PbrBundle to each entity having a collider.
pub fn create_collider_renders_system(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    configuration: Res<RapierConfiguration>,
    collider_shapes: Query<&ColliderShape>,
    render_tags: Query<(Entity, Option<&Parent>, &ColliderDebugRender), Without<Handle<Mesh>>>,
) {
    for (entity, parent, co_render) in &mut render_tags.iter() {
        let co_shape = collider_shapes
            .get(entity)
            .ok()
            .or_else(|| collider_shapes.get(**parent?).ok());

        if let Some(co_shape) = co_shape {
            if let Some((mesh, scale)) = generate_collider_mesh(co_shape) {
                let ground_pbr = PbrBundle {
                    mesh: meshes.add(mesh),
                    material: materials.add(co_render.color.into()),
                    transform: Transform::from_scale(scale * configuration.scale),
                    ..Default::default()
                };

                commands.entity(entity).insert_bundle(ground_pbr);
            }
        }
    }
}

pub fn update_collider_render_mesh(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    configuration: Res<RapierConfiguration>,
    colliders: Query<
        (Entity, &ColliderShape),
        (
            Changed<ColliderShape>,
            With<Handle<Mesh>>,
            With<ColliderDebugRender>,
        ),
    >,
) {
    // TODO: what if the renderer is on the collider's child?
    for (entity, co_shape) in colliders.iter() {
        if let Some((mesh, scale)) = generate_collider_mesh(co_shape) {
            // TODO: remove the old mesh asset?
            let mesh = meshes.add(mesh);
            let scale = Transform::from_scale(scale * configuration.scale);
            commands.entity(entity).insert_bundle((mesh, scale));
        }
    }
}

fn generate_collider_mesh(co_shape: &ColliderShape) -> Option<(Mesh, Vec3)> {
    let mesh = match co_shape.shape_type() {
        #[cfg(feature = "dim3")]
        ShapeType::Cuboid => Mesh::from(shape::Cube { size: 2.0 }),
        #[cfg(feature = "dim2")]
        ShapeType::Cuboid => Mesh::from(shape::Quad {
            size: Vec2::new(2.0, 2.0),
            flip: false,
        }),
        ShapeType::Ball => Mesh::from(shape::Icosphere {
            subdivisions: 2,
            radius: 1.0,
        }),
        #[cfg(feature = "dim2")]
        ShapeType::TriMesh => {
            let mut mesh = Mesh::new(bevy::render::pipeline::PrimitiveTopology::TriangleList);
            let trimesh = co_shape.as_trimesh().unwrap();
            mesh.set_attribute(
                Mesh::ATTRIBUTE_POSITION,
                VertexAttributeValues::from(
                    trimesh
                        .vertices()
                        .iter()
                        .map(|vertice| [vertice.x, vertice.y])
                        .collect::<Vec<_>>(),
                ),
            );
            mesh.set_indices(Some(Indices::U32(
                trimesh
                    .indices()
                    .iter()
                    .flat_map(|triangle| triangle.iter())
                    .cloned()
                    .collect(),
            )));
            mesh
        }
        #[cfg(feature = "dim3")]
        ShapeType::TriMesh => {
            let mut mesh = Mesh::new(bevy::render::pipeline::PrimitiveTopology::TriangleList);
            let trimesh = co_shape.as_trimesh().unwrap();
            mesh.set_attribute(
                Mesh::ATTRIBUTE_POSITION,
                VertexAttributeValues::from(
                    trimesh
                        .vertices()
                        .iter()
                        .map(|vertex| [vertex.x, vertex.y, vertex.z])
                        .collect::<Vec<_>>(),
                ),
            );
            // Compute vertex normals by averaging the normals
            // of every triangle they appear in.
            // NOTE: This is a bit shonky, but good enough for visualisation.
            let verts = trimesh.vertices();
            let mut normals: Vec<Vec3> = vec![Vec3::ZERO; trimesh.vertices().len()];
            for triangle in trimesh.indices().iter() {
                let ab = verts[triangle[1] as usize] - verts[triangle[0] as usize];
                let ac = verts[triangle[2] as usize] - verts[triangle[0] as usize];
                let normal = ab.cross(&ac);
                // Contribute this normal to each vertex in the triangle.
                for i in 0..3 {
                    normals[triangle[i] as usize] += Vec3::new(normal.x, normal.y, normal.z);
                }
            }
            let normals: Vec<[f32; 3]> = normals
                .iter()
                .map(|normal| {
                    let normal = normal.normalize();
                    [normal.x, normal.y, normal.z]
                })
                .collect();
            mesh.set_attribute(Mesh::ATTRIBUTE_NORMAL, VertexAttributeValues::from(normals));
            // There's nothing particularly meaningful we can do
            // for this one without knowing anything about the overall topology.
            mesh.set_attribute(
                Mesh::ATTRIBUTE_UV_0,
                VertexAttributeValues::from(
                    trimesh
                        .vertices()
                        .iter()
                        .map(|_vertex| [0.0, 0.0])
                        .collect::<Vec<_>>(),
                ),
            );
            mesh.set_indices(Some(Indices::U32(
                trimesh
                    .indices()
                    .iter()
                    .flat_map(|triangle| triangle.iter())
                    .cloned()
                    .collect(),
            )));
            mesh
        }
        _ => return None,
    };

    let scale = match co_shape.shape_type() {
        #[cfg(feature = "dim2")]
        ShapeType::Cuboid => {
            let c = co_shape.as_cuboid().unwrap();
            Vec3::new(c.half_extents.x, c.half_extents.y, 1.0)
        }
        #[cfg(feature = "dim3")]
        ShapeType::Cuboid => {
            let c = co_shape.as_cuboid().unwrap();
            Vec3::from_slice_unaligned(c.half_extents.as_slice())
        }
        ShapeType::Ball => {
            let b = co_shape.as_ball().unwrap();
            Vec3::new(b.radius, b.radius, b.radius)
        }
        ShapeType::TriMesh => Vec3::ONE,
        _ => unimplemented!(),
    };

    Some((mesh, scale))
}