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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
use ncollide3d::shape::*;
use ncollide3d::bounding_volume::{ AABB, BoundingSphere, HasBoundingVolume };
use rin_math::{
    Isometry3, Vec3, one, ToVec, ToPnt, vec3, Deg, zero, Swizzles3, Angle
};
use rin_graphics::{Vertex, Mesh,};
use super::{ Shape, Offset, rinmesh_to_trimesh };
use serde_derive::{Deserialize, Serialize};

#[derive(Clone,Debug,Copy, Serialize, Deserialize)]
#[repr(u16)]
pub enum RigidBodyType{
    Active=0,
    Passive,
}

#[derive(Clone,Debug,Copy, Serialize, Deserialize)]
#[repr(u16)]
pub enum RigidBodyShape{
    Cuboid,
    Sphere,
    Capsule,
    Cylinder,
    Cone,
    ConvexHull,
    Mesh,
}

#[derive(Clone,Debug,Copy, Serialize, Deserialize)]
#[repr(C)]
pub struct RigidBody{
    pub ty: RigidBodyType,
    pub shape: RigidBodyShape,
    pub friction: f32,
}

pub fn geometry_aabb<'a, I, V>(vertices: I) -> Option<AABB<f32>>
where
    I: IntoIterator<Item = &'a V>,
    V: Vertex + 'a,
    <V as Vertex>::Position: Swizzles3<f32, Swizzle3=Vec3>
{
    let mut vertices = vertices.into_iter();
    vertices.next().map(|first| {
        let mut mins = first.position().xyz();
        let mut maxs = first.position().xyz();
        for p in vertices.map(|v| v.position().xyz()){
            mins.x = mins.x.min(p.x);
            mins.y = mins.y.min(p.y);
            mins.z = mins.z.min(p.z);

            maxs.x = maxs.x.max(p.x);
            maxs.y = maxs.y.max(p.y);
            maxs.z = maxs.z.max(p.z);
        }
        AABB::new(mins.to_pnt(), maxs.to_pnt())
    })
}

pub fn geometry_bounding_sphere<V: Vertex>(mesh: &Mesh<V>) -> Option<BoundingSphere<f32>>
where <V as Vertex>::Position: Swizzles3<f32, Swizzle3=Vec3>
{
    if mesh.is_empty() {
        return None
    }

    let acc: Vec3 = mesh.vertices().iter()
        .map(|v| v.position().xyz())
        .sum();
    let centroid = acc / mesh.vertices().len() as f32;
    let first = mesh.vertices()[0].position().xyz();
    let distance_sq = (first - centroid).norm_squared();
    let (furthest, _) = mesh.iter()
        .skip(1)
        .fold((first, distance_sq), |(furthest, max_distance_sq), v| {
            let v = v.position().xyz();
            let distance_sq = (v - centroid).norm_squared();
            if distance_sq > max_distance_sq {
                (v, distance_sq)
            }else{
                (furthest, max_distance_sq)
            }
        });
    let radius = (furthest - centroid).norm();
    Some(BoundingSphere::new(centroid.to_pnt(), radius))
}

pub fn aabb_to_box_and_offset(aabb: &AABB<f32>) -> (Shape, Offset) {
    let cuboid = Cuboid::new(aabb.half_extents());
    let offset = Isometry3::new(aabb.center().to_vec(), zero());
    // let trimesh = procedural_to_rinmesh(&cuboid.to_trimesh(()), &offset, &inv_scale);
    (Shape::new(cuboid), Offset(offset))
}

pub fn geometry_box_and_offset<V: Vertex>(mesh: &Mesh<V>) -> Option<(Shape, Offset)>
where <V as Vertex>::Position: Swizzles3<f32, Swizzle3=Vec3>
{
    let aabb = geometry_aabb(mesh.vertices())?;
    Some(aabb_to_box_and_offset(&aabb))
}

pub fn aabb_to_capsule_and_offset(aabb: &AABB<f32>) -> (Shape, Offset) {
    let radius = aabb.half_extents().x.max(aabb.half_extents().y);
    let half_height = aabb.half_extents().z;
    let center = aabb.center();
    let capsule = Capsule::new(half_height, radius);
    let offset = Isometry3::new(
        center.to_vec(),
        vec3(Deg(90.).to_rad().value(), 0.,0.)
    );
    // let trimesh = procedural_to_rinmesh(&capsule.to_trimesh((10, 10)), &offset, &inv_scale);
    (Shape::new(capsule), Offset(offset))
}

pub fn geometry_capsule_and_offset<V: Vertex>(mesh: &Mesh<V>) -> Option<(Shape, Offset)>
where <V as Vertex>::Position: Swizzles3<f32, Swizzle3=Vec3>
{
    let aabb = geometry_aabb(mesh.vertices())?;
    Some(aabb_to_capsule_and_offset(&aabb))
}

// pub fn aabb_to_cylinder_and_offset(aabb: &AABB<f32>) -> (Shape, Offset) {
//     let radius = aabb.half_extents().x.max(aabb.half_extents().y);
//     let half_height = aabb.half_extents().z;
//     let center = aabb.center();
//     let cylinder = Cylinder::new(half_height, radius);
//     let offset = Isometry3::new(
//         center.to_vec(),
//         vec3(Deg(90.).to_rad().value(), 0.,0.)
//     );
//     // let trimesh = procedural_to_rinmesh(&cone.to_trimesh(10), &offset, &inv_scale);
//     (Shape::new(cylinder), Offset(offset))
// }

// TODO: Cone doesn't implement Shape yet
// pub fn geometry_cylinder_and_offset<V: Vertex>(mesh: &Mesh<V>) -> Option<(Shape, Offset)>
// where <V as Vertex>::Position: Swizzles3<f32, Swizzle3=Vec3>
// {
//     let aabb = geometry_aabb(mesh)?;
//     Some(aabb_to_cylinder_and_offset(&aabb))
// }

// pub fn aabb_to_cone_and_offset(aabb: &AABB<f32>) -> (Shape, Offset) {
//     let radius = aabb.half_extents().x.max(aabb.half_extents().y);
//     let half_height = aabb.half_extents().z;
//     let center = aabb.center();
//     let cone = Cone::new(half_height, radius);
//     let offset = Isometry3::new(
//         center.to_vec(),
//         vec3(Deg(90.).to_rad().value(), 0.,0.)
//     );
//     // let trimesh = procedural_to_rinmesh(&cylinder.to_trimesh(10), &offset, &inv_scale);
//     (Shape::new(cone), Offset(offset)
// }

// pub fn geometry_cylinder_and_offset<V: Vertex>(mesh: &Mesh<V>) -> Option<(Shape, Offset)>
// where <V as Vertex>::Position: Swizzles3<f32, Swizzle3=Vec3>
// {
//     let aabb = geometry_aabb(mesh)?;
//     Some(aabb_to_cone_and_offset(&aabb))
// }

pub fn aabb_to_sphere_and_offset(aabb: &AABB<f32>) -> (Shape, Offset) {
    let cuboid = Cuboid::new(aabb.half_extents());
    let bounding_sphere: BoundingSphere<f32> = cuboid.local_bounding_volume();
    let radius = bounding_sphere.radius();
    let ball = Ball::new(radius);
    let center = bounding_sphere.center();
    let offset = Isometry3::new(
        center.to_vec(),
        vec3(Deg(90.).to_rad().value(), 0.,0.)
    );
    // let trimesh = procedural_to_rinmesh(&ball.to_trimesh((10,10)), &offset, &inv_scale);
    (Shape::new(ball), Offset(offset))
}

pub fn geometry_sphere_and_offset<V: Vertex>(mesh: &Mesh<V>) -> Option<(Shape, Offset)>
where <V as Vertex>::Position: Swizzles3<f32, Swizzle3=Vec3>
{
    let bounding_sphere = geometry_bounding_sphere(mesh)?;
    let radius = bounding_sphere.radius();
    let ball = Ball::new(radius);
    let center = bounding_sphere.center();
    let offset = Isometry3::new(
        center.to_vec(),
        vec3(0., 0.,0.)
    );
    Some((Shape::new(ball), Offset(offset)))
}

pub fn geometry_trimesh_and_offset<V: Vertex>(mesh: &Mesh<V>) -> Option<(Shape, Offset)>
where <V as Vertex>::Position: Swizzles3<f32, Swizzle3=Vec3>
{
    let trimesh = rinmesh_to_trimesh(mesh, vec3!(1.));
    Some((Shape::new(trimesh), Offset(one())))
}

pub fn geometry_convexhull_and_offset<V: Vertex>(mesh: &Mesh<V>) -> Option<(Shape, Offset)>
where <V as Vertex>::Position: Swizzles3<f32, Swizzle3=Vec3>
{
    let points = mesh.vertices()
        .iter()
        .map(|v| v.position().xzy().to_pnt())
        .collect();
    let indices = mesh.indices()
        .iter()
        .map(|i| *i as usize)
        .collect::<Vec<_>>();
    let convex_hull = ConvexHull::try_new(points, &indices)?;
    Some((Shape::new(convex_hull), Offset(one())))
}


pub fn geometry_shape_and_offset<V: Vertex>(mesh: &Mesh<V>, shape: RigidBodyShape) -> Option<(Shape, Offset)>
where <V as Vertex>::Position: Swizzles3<f32, Swizzle3=Vec3>
{
    match shape {
        RigidBodyShape::Capsule => geometry_capsule_and_offset(mesh),
        RigidBodyShape::ConvexHull => geometry_convexhull_and_offset(mesh),
        RigidBodyShape::Cuboid => geometry_box_and_offset(mesh),
        RigidBodyShape::Mesh => geometry_trimesh_and_offset(mesh),
        RigidBodyShape::Sphere => geometry_sphere_and_offset(mesh),
        RigidBodyShape::Cone => unimplemented!("Cone shape not supported yet"),
        RigidBodyShape::Cylinder => unimplemented!("Cylinder shape not supported yet"),
    }
}