Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_render/src/render_phase/rangefinder.rs
6596 views
1
use bevy_math::{Affine3A, Mat4, Vec3, Vec4};
2
3
/// A distance calculator for the draw order of [`PhaseItem`](crate::render_phase::PhaseItem)s.
4
pub struct ViewRangefinder3d {
5
view_from_world_row_2: Vec4,
6
}
7
8
impl ViewRangefinder3d {
9
/// Creates a 3D rangefinder for a view matrix.
10
pub fn from_world_from_view(world_from_view: &Affine3A) -> ViewRangefinder3d {
11
let view_from_world = world_from_view.inverse();
12
13
ViewRangefinder3d {
14
view_from_world_row_2: Mat4::from(view_from_world).row(2),
15
}
16
}
17
18
/// Calculates the distance, or view-space `Z` value, for the given `translation`.
19
#[inline]
20
pub fn distance_translation(&self, translation: &Vec3) -> f32 {
21
// NOTE: row 2 of the inverse view matrix dotted with the translation from the model matrix
22
// gives the z component of translation of the mesh in view-space
23
self.view_from_world_row_2.dot(translation.extend(1.0))
24
}
25
26
/// Calculates the distance, or view-space `Z` value, for the given `transform`.
27
#[inline]
28
pub fn distance(&self, transform: &Mat4) -> f32 {
29
// NOTE: row 2 of the inverse view matrix dotted with column 3 of the model matrix
30
// gives the z component of translation of the mesh in view-space
31
self.view_from_world_row_2.dot(transform.col(3))
32
}
33
}
34
35
#[cfg(test)]
36
mod tests {
37
use super::ViewRangefinder3d;
38
use bevy_math::{Affine3A, Mat4, Vec3};
39
40
#[test]
41
fn distance() {
42
let view_matrix = Affine3A::from_translation(Vec3::new(0.0, 0.0, -1.0));
43
let rangefinder = ViewRangefinder3d::from_world_from_view(&view_matrix);
44
assert_eq!(rangefinder.distance(&Mat4::IDENTITY), 1.0);
45
assert_eq!(
46
rangefinder.distance(&Mat4::from_translation(Vec3::new(0.0, 0.0, 1.0))),
47
2.0
48
);
49
}
50
}
51
52