I'm brand new to rust so all the lifetimes are probably wrong, please ignore.
Assume that the objects are stored somewhere separate.
Also that the structs, traits and impls have been filled in with useful stuff.
And finally the ordering of the lists doesn't matter.
Fully dynamic version:
trait Shape {}
struct Sphere {}
struct Triangle {}
impl Shape for Sphere{}
impl Shape for Triangle {}
trait Material {}
struct Diffuse {}
struct Glossy {}
impl Material for Diffuse {}
impl Material for Glossy {}
trait Object {}
struct PrimitiveObject<'a> {
shape: &'a dyn Shape,
material: &'a dyn Material,
position: [f32; 3]
}
struct InstancedObject<'a> {
shape: &'a dyn Shape,
material: &'a dyn Material,
positions: Vec<[f32; 3]>
}
impl<'a> Object for PrimitiveObject<'a> {}
impl<'a> Object for InstancedObject<'a> {}
struct Scene<'a> {
objects: Vec<&'a dyn Object>
}
Slightly more static version
struct Scene<'a> {
objects_PrimitiveObject: Vec<&'a PrimitiveObject<'a>>,
objects_InstancedObject: Vec<&'a InstancedObject<'a>>
}
Fully static version
struct PrimitiveObject<'a, Shape: Shape_, Material: Material_> {
shape: &'a Shape_,
material: &'a Material_,
position: [f32; 3]
}
struct InstancedObject<'a, Shape: Shape_, Material: Material_> {
shape: &'a Shape_,
material: &'a Material_,
positions: Vec<[f32; 3]>
}
impl<'a, Shape: Shape_, Material: Material_> Object for PrimitiveObject<'a, Shape_, Material_> {}
impl<'a, Shape: Shape_, Material: Material_> Object for InstancedObject<'a, Shape_, Material_> {}
struct Scene<'a> {
objects_PrimitiveObject_Sphere_Diffuse: Vec<&'a PrimitiveObject<'a, Sphere, Diffuse>>,
objects_PrimitiveObject_Sphere_Glossy: Vec<&'a PrimitiveObject<'a, Sphere, Glossy>>,
objects_PrimitiveObject_Triangle_Diffuse: Vec<&'a PrimitiveObject<'a, Triangle, Diffuse>>,
...
}
Is there a way to make the static versions not by hand, but using macros?
While the static version has exponential growth in the number of type parameters, it seems like it could be faster than dynamic by allowing inlining where it helps. A bunch of empty vectors doesn't seem like a huge cost.
I guess enums are also in the running, but they seem to have a space disadvantage.
question from:
https://stackoverflow.com/questions/65903095/static-vs-dynamic-heterogeneous-collection-in-rust