bevy/crates
Matty 325f0fd982
Alignment API for Transforms (#12187)
# Objective

- Closes #11793 
- Introduces a general API for aligning local coordinates of Transforms
with given vectors.

## Solution

- We introduce `Transform::align`, which allows a rotation to be
specified by four pieces of alignment data, as explained by the
documentation:
````rust
/// Rotates this [`Transform`] so that the `main_axis` vector, reinterpreted in local coordinates, points
/// in the given `main_direction`, while `secondary_axis` points towards `secondary_direction`.
///
/// For example, if a spaceship model has its nose pointing in the X-direction in its own local coordinates
/// and its dorsal fin pointing in the Y-direction, then `align(Vec3::X, v, Vec3::Y, w)` will make the spaceship's
/// nose point in the direction of `v`, while the dorsal fin does its best to point in the direction `w`.
///
/// More precisely, the [`Transform::rotation`] produced will be such that:
/// * applying it to `main_axis` results in `main_direction`
/// * applying it to `secondary_axis` produces a vector that lies in the half-plane generated by `main_direction` and
/// `secondary_direction` (with positive contribution by `secondary_direction`)
///
/// [`Transform::look_to`] is recovered, for instance, when `main_axis` is `Vec3::NEG_Z` (the [`Transform::forward`]
/// direction in the default orientation) and `secondary_axis` is `Vec3::Y` (the [`Transform::up`] direction in the default
/// orientation). (Failure cases may differ somewhat.)
///
/// In some cases a rotation cannot be constructed. Another axis will be picked in those cases:
/// * if `main_axis` or `main_direction` is zero, `Vec3::X` takes its place
/// * if `secondary_axis` or `secondary_direction` is zero, `Vec3::Y` takes its place
/// * if `main_axis` is parallel with `secondary_axis` or `main_direction` is parallel with `secondary_direction`,
/// a rotation is constructed which takes `main_axis` to `main_direction` along a great circle, ignoring the secondary
/// counterparts
/// 
/// Example
/// ```
/// # use bevy_math::{Vec3, Quat};
/// # use bevy_transform::components::Transform;
/// let mut t1 = Transform::IDENTITY;
/// let mut t2 = Transform::IDENTITY;
/// t1.align(Vec3::ZERO, Vec3::Z, Vec3::ZERO, Vec3::X);
/// t2.align(Vec3::X, Vec3::Z, Vec3::Y, Vec3::X);
/// assert_eq!(t1.rotation, t2.rotation);
/// 
/// t1.align(Vec3::X, Vec3::Z, Vec3::X, Vec3::Y);
/// assert_eq!(t1.rotation, Quat::from_rotation_arc(Vec3::X, Vec3::Z));
/// ```
pub fn align(
    &mut self,
    main_axis: Vec3,
    main_direction: Vec3,
    secondary_axis: Vec3,
    secondary_direction: Vec3,
) { //... }
````

- We introduce `Transform::aligned_by`, the returning-Self version of
`align`:
````rust
pub fn aligned_by(
    mut self,
    main_axis: Vec3,
    main_direction: Vec3,
    secondary_axis: Vec3,
    secondary_direction: Vec3,
) -> Self { //... }
````

- We introduce an example (examples/transforms/align.rs) that shows the
usage of this API. It is likely to be mathier than most other
`Transform` APIs, so when run, the example demonstrates what the API
does in space:
<img width="1440" alt="Screenshot 2024-03-12 at 11 01 19 AM"
src="https://github.com/bevyengine/bevy/assets/2975848/884b3cc3-cbd9-48ae-8f8c-49a677c59dfe">

---

## Changelog

- Added methods `align`, `aligned_by` to `Transform`.
- Added transforms/align.rs to examples.

---

## Discussion

### On the form of `align`

The original issue linked above suggests an API similar to that of the
existing `Transform::look_to` method:
````rust
pub fn align_to(&mut self, direction: Vec3, up: Vec3) { //... }
````
Not allowing an input axis of some sort that is to be aligned with
`direction` would not really solve the problem in the issue, since the
user could easily be in a scenario where they have to compose with
another rotation on their own (undesirable). This leads to something
like:
````rust
pub fn align_to(&mut self, axis: Vec3, direction: Vec3, up: Vec3) { //... }
````
However, this still has two problems:
- If the vector that the user wants to align is parallel to the Y-axis,
then the API basically does not work (we cannot fully specify a
rotation)
- More generally, it does not give the user the freedom to specify which
direction is to be treated as the local "up" direction, so it fails as a
general alignment API

Specifying both leads us to the present situation, with two local axis
inputs (`main_axis` and `secondary_axis`) and two target directions
(`main_direction` and `secondary_direction`). This might seem a little
cumbersome for general use, but for the time being I stand by the
decision not to expand further without prompting from users. I'll expand
on this below.

### Additional APIs?

Presently, this PR introduces only `align` and `aligned_by`. Other
potentially useful bundles of API surface arrange into a few different
categories:

1. Inferring direction from position, a la `Transform::look_at`, which
might look something like this:
````rust
pub fn align_at(&mut self, axis: Vec3, target: Vec3, up: Vec3) {
    self.align(axis, target - self.translation, Vec3::Y, up);
}
````
(This is simple but still runs into issues when the user wants to point
the local Y-axis somewhere.)

2. Filling in some data for the user for common use-cases; e.g.:
````rust
pub fn align_x(&mut self, direction: Vec3, up: Vec3) {
    self.align(Vec3::X, direction, Vec3::Y, up);
}
````
(Here, use of the `up` vector doesn't lose any generality, but it might
be less convenient to specify than something else. This does naturally
leave open the question of what `align_y` would look like if we provided
it.)

Morally speaking, I do think that the `up` business is more pertinent
when the intention is to work with cameras, which the `look_at` and
`look_to` APIs seem to cover pretty well. If that's the case, then I'm
not sure what the ideal shape for these API functions would be, since it
seems like a lot of input would have to be baked into the function
definitions. For some cases, this might not be the end of the world:
````rust
pub fn align_x_z(&mut self, direction: Vec3, weak_direction: Vec3) {
    self.align(Vec3::X, direction, Vec3::Z, weak_direction);
}
````
(However, this is not symmetrical in x and z, so you'd still need six
API functions just to support the standard positive coordinate axes, and
if you support negative axes then things really start to balloon.)

The reasons that these are not actually produced in this PR are as
follows:
1. Without prompting from actual users in the wild, it is unknown to me
whether these additional APIs would actually see a lot of use. Extending
these to our users in the future would be trivial if we see there is a
demand for something specific from the above-mentioned categories.
2. As discussed above, there are so many permutations of these that
could be provided that trying to do so looks like it risks unduly
ballooning the API surface for this feature.
3. Finally, and most importantly, creating these helper functions in
user-space is trivial, since they all just involve specializing `align`
to particular inputs; e.g.:
````rust
fn align_ship(ship_transform: &mut Transform, nose_direction: Vec3, dorsal_direction: Vec3) {
    ship_transform.align(Ship::NOSE, nose_direction, Ship::DORSAL, dorsal_direction);
}
````

With that in mind, I would prefer instead to focus on making the
documentation and examples for a thin API as clear as possible, so that
users can get a grip on the tool and specialize it for their own needs
when they feel the desire to do so.

### `Dir3`?

As in the case of `Transform::look_to` and `Transform::look_at`, the
inputs to this function are, morally speaking, *directions* rather than
vectors (actually, if we're being pedantic, the input is *really really*
a pair of orthonormal frames), so it's worth asking whether we should
really be using `Dir3` as inputs instead of `Vec3`. I opted for `Vec3`
for the following reasons:
1. Specifying a `Dir3` in user-space is just more annoying than
providing a `Vec3`. Even in the most basic cases (e.g. providing a
vector literal), you still have to do error handling or call an unsafe
unwrap in your function invocations.
2. The existing API mentioned above uses `Vec3`, so we are just adhering
to the same thing.

Of course, the use of `Vec3` has its own downsides; it can be argued
that the replacement of zero-vectors with fixed ones (which we do in
`Transform::align` as well as `Transform::look_to`) more-or-less amounts
to failing silently.

### Future steps

The question of additional APIs was addressed above. For me, the main
thing here to handle more immediately is actually just upstreaming this
API (or something similar and slightly mathier) to `glam::Quat`. The
reason that this would be desirable for users is that this API currently
only works with `Transform`s even though all it's actually doing is
specifying a rotation. Upstreaming to `glam::Quat`, properly done, could
buy a lot basically for free, since a number of `Transform` methods take
a rotation as an input. Using these together would require a little bit
of mathematical savvy, but it opens up some good things (e.g.
`Transform::rotate_around`).
2024-03-14 14:55:55 +00:00
..
bevy_a11y Bump Version after Release (#12020) 2024-02-21 20:58:59 +00:00
bevy_animation Implement the AnimationGraph, allowing for multiple animations to be blended together. (#11989) 2024-03-07 20:22:42 +00:00
bevy_app Add "all-features = true" to docs.rs metadata for most crates (#12366) 2024-03-08 20:03:09 +00:00
bevy_asset Fix doc comment on AssetActionMinimal (#11105) 2024-03-11 18:59:27 +00:00
bevy_audio Fix leftover references to children when despawning audio entities (#12407) 2024-03-11 18:16:13 +00:00
bevy_color Fix green colors becoming darker in various examples (#12328) 2024-03-05 23:42:03 +00:00
bevy_core Add "all-features = true" to docs.rs metadata for most crates (#12366) 2024-03-08 20:03:09 +00:00
bevy_core_pipeline Add "all-features = true" to docs.rs metadata for most crates (#12366) 2024-03-08 20:03:09 +00:00
bevy_derive Bump Version after Release (#12020) 2024-02-21 20:58:59 +00:00
bevy_dev_tools Fps overlay (#12382) 2024-03-11 19:26:14 +00:00
bevy_diagnostic Add "all-features = true" to docs.rs metadata for most crates (#12366) 2024-03-08 20:03:09 +00:00
bevy_dylib Bump Version after Release (#12020) 2024-02-21 20:58:59 +00:00
bevy_dynamic_plugin Document all members of bevy_dynamic_plugin (#12029) 2024-02-22 13:28:52 +00:00
bevy_ecs Make a note about the performance of Query::is_empty (#12466) 2024-03-14 01:36:03 +00:00
bevy_ecs_compile_fail_tests Remove APIs deprecated in 0.13 (#11974) 2024-02-19 19:04:47 +00:00
bevy_encase_derive Bump Version after Release (#12020) 2024-02-21 20:58:59 +00:00
bevy_gilrs Send GamepadEvent for gamepads connected at startup (#12424) 2024-03-11 20:05:10 +00:00
bevy_gizmos Gizmo 3d grids (#12430) 2024-03-13 18:51:53 +00:00
bevy_gltf Allow setting RenderAssetUsages for gLTF meshes & materials during load (#12302) 2024-03-12 00:11:01 +00:00
bevy_hierarchy Add "all-features = true" to docs.rs metadata for most crates (#12366) 2024-03-08 20:03:09 +00:00
bevy_input Add table showing complexity of methods for Input (#10126) 2024-03-10 23:00:20 +00:00
bevy_internal move ci testing to dev_tools (#12371) 2024-03-07 22:38:21 +00:00
bevy_log Add "all-features = true" to docs.rs metadata for most crates (#12366) 2024-03-08 20:03:09 +00:00
bevy_macro_utils fix deprecations from toml_edit (#12421) 2024-03-11 17:53:38 +00:00
bevy_macros_compile_fail_tests Standardize toml format with taplo (#10594) 2023-11-21 01:04:14 +00:00
bevy_math Add scale_around_center method to BoundingVolume trait (#12142) 2024-03-11 21:48:25 +00:00
bevy_mikktspace fix some typos (#12038) 2024-02-22 18:55:22 +00:00
bevy_pbr Extracting ambient light from light.rs, and creating light directory (#12369) 2024-03-13 01:24:00 +00:00
bevy_ptr Add more comprehensive crate level docs for bevy_ptr (#12391) 2024-03-12 14:04:16 +00:00
bevy_reflect Fix: deserialize DynamicEnum using index (#12464) 2024-03-14 05:15:20 +00:00
bevy_reflect_compile_fail_tests bevy_reflect: Recursive registration (#5781) 2024-03-04 19:04:10 +00:00
bevy_render Update ruzstd requirement from 0.5.0 to 0.6.0 (#12416) 2024-03-11 06:35:56 +00:00
bevy_scene Add "all-features = true" to docs.rs metadata for most crates (#12366) 2024-03-08 20:03:09 +00:00
bevy_sprite Fix docs for atlas + slicing support (#12325) 2024-03-05 18:04:22 +00:00
bevy_tasks Add "all-features = true" to docs.rs metadata for most crates (#12366) 2024-03-08 20:03:09 +00:00
bevy_text Add "all-features = true" to docs.rs metadata for most crates (#12366) 2024-03-08 20:03:09 +00:00
bevy_time Add "all-features = true" to docs.rs metadata for most crates (#12366) 2024-03-08 20:03:09 +00:00
bevy_transform Alignment API for Transforms (#12187) 2024-03-14 14:55:55 +00:00
bevy_ui Fix blurry text (#12429) 2024-03-13 01:21:10 +00:00
bevy_utils Disentangle bevy_utils/bevy_core's reexported dependencies (#12313) 2024-03-07 02:30:15 +00:00
bevy_window Add "all-features = true" to docs.rs metadata for most crates (#12366) 2024-03-08 20:03:09 +00:00
bevy_winit Make CreateWindowParams type and create_windows system public (#12428) 2024-03-12 14:54:06 +00:00