rend3_routine/common/
sorting.rs

1use std::borrow::Cow;
2
3use ordered_float::OrderedFloat;
4use rend3::managers::{CameraManager, InternalObject};
5
6/// An object sorting order.
7#[derive(Debug, Copy, Clone, PartialEq, Eq)]
8pub enum Sorting {
9    /// Sort with the nearest objects first.
10    FrontToBack,
11    /// Sort with the furthest objects first.
12    BackToFront,
13}
14
15/// Takes a set of objects and possibly sorts them if a sorting is provided.
16pub fn sort_objects<'a>(
17    objects: &'a [InternalObject],
18    camera_manager: &CameraManager,
19    sorting: Option<Sorting>,
20) -> Cow<'a, [InternalObject]> {
21    if let Some(sorting) = sorting {
22        profiling::scope!("Sorting");
23
24        let camera_location = camera_manager.location().into();
25
26        let mut sorted_objects = objects.to_vec();
27
28        match sorting {
29            Sorting::FrontToBack => {
30                sorted_objects
31                    .sort_unstable_by_key(|o| OrderedFloat(o.mesh_location().distance_squared(camera_location)));
32            }
33            Sorting::BackToFront => {
34                sorted_objects
35                    .sort_unstable_by_key(|o| OrderedFloat(-o.mesh_location().distance_squared(camera_location)));
36            }
37        }
38
39        Cow::Owned(sorted_objects)
40    } else {
41        Cow::Borrowed(objects)
42    }
43}