1use bevy_ecs::{
4 prelude::Entity,
5 query::QueryEntityError,
6 system::{Query, SystemParam},
7};
8use bevy_hierarchy::{HierarchyQueryExt, Parent};
9use thiserror::Error;
10
11use crate::components::{GlobalTransform, Transform};
12
13#[derive(SystemParam)]
20pub struct TransformHelper<'w, 's> {
21 parent_query: Query<'w, 's, &'static Parent>,
22 transform_query: Query<'w, 's, &'static Transform>,
23}
24
25impl<'w, 's> TransformHelper<'w, 's> {
26 pub fn compute_global_transform(
28 &self,
29 entity: Entity,
30 ) -> Result<GlobalTransform, ComputeGlobalTransformError> {
31 let transform = self
32 .transform_query
33 .get(entity)
34 .map_err(|err| map_error(err, false))?;
35
36 let mut global_transform = GlobalTransform::from(*transform);
37
38 for entity in self.parent_query.iter_ancestors(entity) {
39 let transform = self
40 .transform_query
41 .get(entity)
42 .map_err(|err| map_error(err, true))?;
43
44 global_transform = *transform * global_transform;
45 }
46
47 Ok(global_transform)
48 }
49}
50
51fn map_error(err: QueryEntityError, ancestor: bool) -> ComputeGlobalTransformError {
52 use ComputeGlobalTransformError::*;
53 match err {
54 QueryEntityError::QueryDoesNotMatch(entity) => MissingTransform(entity),
55 QueryEntityError::NoSuchEntity(entity) => {
56 if ancestor {
57 MalformedHierarchy(entity)
58 } else {
59 NoSuchEntity(entity)
60 }
61 }
62 QueryEntityError::AliasedMutability(_) => unreachable!(),
63 }
64}
65
66#[derive(Debug, Error)]
68pub enum ComputeGlobalTransformError {
69 #[error("The entity {0:?} or one of its ancestors is missing the `Transform` component")]
71 MissingTransform(Entity),
72 #[error("The entity {0:?} does not exist")]
74 NoSuchEntity(Entity),
75 #[error("The ancestor {0:?} is missing")]
78 MalformedHierarchy(Entity),
79}
80
81#[cfg(test)]
82mod tests {
83 use std::f32::consts::TAU;
84
85 use bevy_app::App;
86 use bevy_ecs::system::SystemState;
87 use bevy_hierarchy::BuildWorldChildren;
88 use bevy_math::{Quat, Vec3};
89
90 use crate::{
91 bundles::TransformBundle,
92 components::{GlobalTransform, Transform},
93 helper::TransformHelper,
94 plugins::TransformPlugin,
95 };
96
97 #[test]
98 fn match_transform_propagation_systems() {
99 match_transform_propagation_systems_inner(vec![Transform::from_translation(Vec3::X)
101 .with_rotation(Quat::from_rotation_y(TAU / 4.))
102 .with_scale(Vec3::splat(2.))]);
103
104 match_transform_propagation_systems_inner(vec![
106 Transform::from_translation(Vec3::X)
107 .with_rotation(Quat::from_rotation_y(TAU / 4.))
108 .with_scale(Vec3::splat(2.)),
109 Transform::from_translation(Vec3::Y)
110 .with_rotation(Quat::from_rotation_z(TAU / 3.))
111 .with_scale(Vec3::splat(1.5)),
112 Transform::from_translation(Vec3::Z)
113 .with_rotation(Quat::from_rotation_x(TAU / 2.))
114 .with_scale(Vec3::splat(0.3)),
115 ]);
116 }
117
118 fn match_transform_propagation_systems_inner(transforms: Vec<Transform>) {
119 let mut app = App::new();
120 app.add_plugins(TransformPlugin);
121
122 let mut entity = None;
123
124 for transform in transforms {
125 let mut e = app.world_mut().spawn(TransformBundle::from(transform));
126
127 if let Some(entity) = entity {
128 e.set_parent(entity);
129 }
130
131 entity = Some(e.id());
132 }
133
134 let leaf_entity = entity.unwrap();
135
136 app.update();
137
138 let transform = *app.world().get::<GlobalTransform>(leaf_entity).unwrap();
139
140 let mut state = SystemState::<TransformHelper>::new(app.world_mut());
141 let helper = state.get(app.world());
142
143 let computed_transform = helper.compute_global_transform(leaf_entity).unwrap();
144
145 approx::assert_abs_diff_eq!(transform.affine(), computed_transform.affine());
146 }
147}