bevy/examples/2d/bounding_2d.rs

439 lines
12 KiB
Rust
Raw Normal View History

//! This example demonstrates bounding volume intersections.
Refactor Bounded2d/Bounded3d to use isometries (#14485) # Objective Previously, this area of bevy_math used raw translation and rotations to encode isometries, which did not exist earlier. The goal of this PR is to make the codebase of bevy_math more harmonious by using actual isometries (`Isometry2d`/`Isometry3d`) in these places instead — this will hopefully make the interfaces more digestible for end-users, in addition to facilitating conversions. For instance, together with the addition of #14478, this means that a bounding box for a collider with an isometric `Transform` can be computed as ```rust collider.aabb_3d(collider_transform.to_isometry()) ``` instead of using manual destructuring. ## Solution - The traits `Bounded2d` and `Bounded3d` now use `Isometry2d` and `Isometry3d` (respectively) instead of `translation` and `rotation` parameters; e.g.: ```rust /// A trait with methods that return 3D bounding volumes for a shape. pub trait Bounded3d { /// Get an axis-aligned bounding box for the shape translated and rotated by the given isometry. fn aabb_3d(&self, isometry: Isometry3d) -> Aabb3d; /// Get a bounding sphere for the shape translated and rotated by the given isometry. fn bounding_sphere(&self, isometry: Isometry3d) -> BoundingSphere; } ``` - Similarly, the `from_point_cloud` constructors for axis-aligned bounding boxes and bounding circles/spheres now take isometries instead of separate `translation` and `rotation`; e.g.: ```rust /// Computes the smallest [`Aabb3d`] containing the given set of points, /// transformed by the rotation and translation of the given isometry. /// /// # Panics /// /// Panics if the given set of points is empty. #[inline(always)] pub fn from_point_cloud( isometry: Isometry3d, points: impl Iterator<Item = impl Into<Vec3A>>, ) -> Aabb3d { //... } ``` This has a couple additional results: 1. The end-user no longer interacts directly with `Into<Vec3A>` or `Into<Rot2>` parameters; these conversions all happen earlier now, inside the isometry types. 2. Similarly, almost all intermediate `Vec3 -> Vec3A` conversions have been eliminated from the `Bounded3d` implementations for primitives. This probably has some performance benefit, but I have not measured it as of now. ## Testing Existing unit tests help ensure that nothing has been broken in the refactor. --- ## Migration Guide The `Bounded2d` and `Bounded3d` traits now take `Isometry2d` and `Isometry3d` parameters (respectively) instead of separate translation and rotation arguments. Existing calls to `aabb_2d`, `bounding_circle`, `aabb_3d`, and `bounding_sphere` will have to be changed to use isometries instead. A straightforward conversion is to refactor just by calling `Isometry2d/3d::new`, as follows: ```rust // Old: let aabb = my_shape.aabb_2d(my_translation, my_rotation); // New: let aabb = my_shape.aabb_2d(Isometry2d::new(my_translation, my_rotation)); ``` However, if the old translation and rotation are 3d translation/rotations originating from a `Transform` or `GlobalTransform`, then `to_isometry` may be used instead. For example: ```rust // Old: let bounding_sphere = my_shape.bounding_sphere(shape_transform.translation, shape_transform.rotation); // New: let bounding_sphere = my_shape.bounding_sphere(shape_transform.to_isometry()); ``` This discussion also applies to the `from_point_cloud` construction method of `Aabb2d`/`BoundingCircle`/`Aabb3d`/`BoundingSphere`, which has similarly been altered to use isometries.
2024-07-29 23:37:02 +00:00
use bevy::{
color::palettes::css::*,
math::{bounding::*, ops, Isometry2d},
Refactor Bounded2d/Bounded3d to use isometries (#14485) # Objective Previously, this area of bevy_math used raw translation and rotations to encode isometries, which did not exist earlier. The goal of this PR is to make the codebase of bevy_math more harmonious by using actual isometries (`Isometry2d`/`Isometry3d`) in these places instead — this will hopefully make the interfaces more digestible for end-users, in addition to facilitating conversions. For instance, together with the addition of #14478, this means that a bounding box for a collider with an isometric `Transform` can be computed as ```rust collider.aabb_3d(collider_transform.to_isometry()) ``` instead of using manual destructuring. ## Solution - The traits `Bounded2d` and `Bounded3d` now use `Isometry2d` and `Isometry3d` (respectively) instead of `translation` and `rotation` parameters; e.g.: ```rust /// A trait with methods that return 3D bounding volumes for a shape. pub trait Bounded3d { /// Get an axis-aligned bounding box for the shape translated and rotated by the given isometry. fn aabb_3d(&self, isometry: Isometry3d) -> Aabb3d; /// Get a bounding sphere for the shape translated and rotated by the given isometry. fn bounding_sphere(&self, isometry: Isometry3d) -> BoundingSphere; } ``` - Similarly, the `from_point_cloud` constructors for axis-aligned bounding boxes and bounding circles/spheres now take isometries instead of separate `translation` and `rotation`; e.g.: ```rust /// Computes the smallest [`Aabb3d`] containing the given set of points, /// transformed by the rotation and translation of the given isometry. /// /// # Panics /// /// Panics if the given set of points is empty. #[inline(always)] pub fn from_point_cloud( isometry: Isometry3d, points: impl Iterator<Item = impl Into<Vec3A>>, ) -> Aabb3d { //... } ``` This has a couple additional results: 1. The end-user no longer interacts directly with `Into<Vec3A>` or `Into<Rot2>` parameters; these conversions all happen earlier now, inside the isometry types. 2. Similarly, almost all intermediate `Vec3 -> Vec3A` conversions have been eliminated from the `Bounded3d` implementations for primitives. This probably has some performance benefit, but I have not measured it as of now. ## Testing Existing unit tests help ensure that nothing has been broken in the refactor. --- ## Migration Guide The `Bounded2d` and `Bounded3d` traits now take `Isometry2d` and `Isometry3d` parameters (respectively) instead of separate translation and rotation arguments. Existing calls to `aabb_2d`, `bounding_circle`, `aabb_3d`, and `bounding_sphere` will have to be changed to use isometries instead. A straightforward conversion is to refactor just by calling `Isometry2d/3d::new`, as follows: ```rust // Old: let aabb = my_shape.aabb_2d(my_translation, my_rotation); // New: let aabb = my_shape.aabb_2d(Isometry2d::new(my_translation, my_rotation)); ``` However, if the old translation and rotation are 3d translation/rotations originating from a `Transform` or `GlobalTransform`, then `to_isometry` may be used instead. For example: ```rust // Old: let bounding_sphere = my_shape.bounding_sphere(shape_transform.translation, shape_transform.rotation); // New: let bounding_sphere = my_shape.bounding_sphere(shape_transform.to_isometry()); ``` This discussion also applies to the `from_point_cloud` construction method of `Aabb2d`/`BoundingCircle`/`Aabb3d`/`BoundingSphere`, which has similarly been altered to use isometries.
2024-07-29 23:37:02 +00:00
prelude::*,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_state::<Test>()
.add_systems(Startup, setup)
.add_systems(
Update,
(update_text, spin, update_volumes, update_test_state),
)
.add_systems(
PostUpdate,
(
render_shapes,
(
aabb_intersection_system.run_if(in_state(Test::AabbSweep)),
circle_intersection_system.run_if(in_state(Test::CircleSweep)),
ray_cast_system.run_if(in_state(Test::RayCast)),
aabb_cast_system.run_if(in_state(Test::AabbCast)),
bounding_circle_cast_system.run_if(in_state(Test::CircleCast)),
),
render_volumes,
)
.chain(),
)
.run();
}
#[derive(Component)]
struct Spin;
fn spin(time: Res<Time>, mut query: Query<&mut Transform, With<Spin>>) {
for mut transform in query.iter_mut() {
transform.rotation *= Quat::from_rotation_z(time.delta_seconds() / 5.);
}
}
#[derive(States, Default, Debug, Hash, PartialEq, Eq, Clone, Copy)]
enum Test {
AabbSweep,
CircleSweep,
#[default]
RayCast,
AabbCast,
CircleCast,
}
fn update_test_state(
keycode: Res<ButtonInput<KeyCode>>,
cur_state: Res<State<Test>>,
mut state: ResMut<NextState<Test>>,
) {
if !keycode.just_pressed(KeyCode::Space) {
return;
}
use Test::*;
let next = match **cur_state {
AabbSweep => CircleSweep,
CircleSweep => RayCast,
RayCast => AabbCast,
AabbCast => CircleCast,
CircleCast => AabbSweep,
};
state.set(next);
}
fn update_text(mut text: Query<&mut Text>, cur_state: Res<State<Test>>) {
if !cur_state.is_changed() {
return;
}
let mut text = text.single_mut();
let text = &mut text.sections[0].value;
text.clear();
text.push_str("Intersection test:\n");
use Test::*;
for &test in &[AabbSweep, CircleSweep, RayCast, AabbCast, CircleCast] {
let s = if **cur_state == test { "*" } else { " " };
text.push_str(&format!(" {s} {test:?} {s}\n"));
}
text.push_str("\nPress space to cycle");
}
#[derive(Component)]
enum Shape {
Rectangle(Rectangle),
Circle(Circle),
Triangle(Triangle2d),
Line(Segment2d),
Capsule(Capsule2d),
Polygon(RegularPolygon),
}
fn render_shapes(mut gizmos: Gizmos, query: Query<(&Shape, &Transform)>) {
Migrate from `LegacyColor` to `bevy_color::Color` (#12163) # Objective - As part of the migration process we need to a) see the end effect of the migration on user ergonomics b) check for serious perf regressions c) actually migrate the code - To accomplish this, I'm going to attempt to migrate all of the remaining user-facing usages of `LegacyColor` in one PR, being careful to keep a clean commit history. - Fixes #12056. ## Solution I've chosen to use the polymorphic `Color` type as our standard user-facing API. - [x] Migrate `bevy_gizmos`. - [x] Take `impl Into<Color>` in all `bevy_gizmos` APIs - [x] Migrate sprites - [x] Migrate UI - [x] Migrate `ColorMaterial` - [x] Migrate `MaterialMesh2D` - [x] Migrate fog - [x] Migrate lights - [x] Migrate StandardMaterial - [x] Migrate wireframes - [x] Migrate clear color - [x] Migrate text - [x] Migrate gltf loader - [x] Register color types for reflection - [x] Remove `LegacyColor` - [x] Make sure CI passes Incidental improvements to ease migration: - added `Color::srgba_u8`, `Color::srgba_from_array` and friends - added `set_alpha`, `is_fully_transparent` and `is_fully_opaque` to the `Alpha` trait - add and immediately deprecate (lol) `Color::rgb` and friends in favor of more explicit and consistent `Color::srgb` - standardized on white and black for most example text colors - added vector field traits to `LinearRgba`: ~~`Add`, `Sub`, `AddAssign`, `SubAssign`,~~ `Mul<f32>` and `Div<f32>`. Multiplications and divisions do not scale alpha. `Add` and `Sub` have been cut from this PR. - added `LinearRgba` and `Srgba` `RED/GREEN/BLUE` - added `LinearRgba_to_f32_array` and `LinearRgba::to_u32` ## Migration Guide Bevy's color types have changed! Wherever you used a `bevy::render::Color`, a `bevy::color::Color` is used instead. These are quite similar! Both are enums storing a color in a specific color space (or to be more precise, using a specific color model). However, each of the different color models now has its own type. TODO... - `Color::rgba`, `Color::rgb`, `Color::rbga_u8`, `Color::rgb_u8`, `Color::rgb_from_array` are now `Color::srgba`, `Color::srgb`, `Color::srgba_u8`, `Color::srgb_u8` and `Color::srgb_from_array`. - `Color::set_a` and `Color::a` is now `Color::set_alpha` and `Color::alpha`. These are part of the `Alpha` trait in `bevy_color`. - `Color::is_fully_transparent` is now part of the `Alpha` trait in `bevy_color` - `Color::r`, `Color::set_r`, `Color::with_r` and the equivalents for `g`, `b` `h`, `s` and `l` have been removed due to causing silent relatively expensive conversions. Convert your `Color` into the desired color space, perform your operations there, and then convert it back into a polymorphic `Color` enum. - `Color::hex` is now `Srgba::hex`. Call `.into` or construct a `Color::Srgba` variant manually to convert it. - `WireframeMaterial`, `ExtractedUiNode`, `ExtractedDirectionalLight`, `ExtractedPointLight`, `ExtractedSpotLight` and `ExtractedSprite` now store a `LinearRgba`, rather than a polymorphic `Color` - `Color::rgb_linear` and `Color::rgba_linear` are now `Color::linear_rgb` and `Color::linear_rgba` - The various CSS color constants are no longer stored directly on `Color`. Instead, they're defined in the `Srgba` color space, and accessed via `bevy::color::palettes::css`. Call `.into()` on them to convert them into a `Color` for quick debugging use, and consider using the much prettier `tailwind` palette for prototyping. - The `LIME_GREEN` color has been renamed to `LIMEGREEN` to comply with the standard naming. - Vector field arithmetic operations on `Color` (add, subtract, multiply and divide by a f32) have been removed. Instead, convert your colors into `LinearRgba` space, and perform your operations explicitly there. This is particularly relevant when working with emissive or HDR colors, whose color channel values are routinely outside of the ordinary 0 to 1 range. - `Color::as_linear_rgba_f32` has been removed. Call `LinearRgba::to_f32_array` instead, converting if needed. - `Color::as_linear_rgba_u32` has been removed. Call `LinearRgba::to_u32` instead, converting if needed. - Several other color conversion methods to transform LCH or HSL colors into float arrays or `Vec` types have been removed. Please reimplement these externally or open a PR to re-add them if you found them particularly useful. - Various methods on `Color` such as `rgb` or `hsl` to convert the color into a specific color space have been removed. Convert into `LinearRgba`, then to the color space of your choice. - Various implicitly-converting color value methods on `Color` such as `r`, `g`, `b` or `h` have been removed. Please convert it into the color space of your choice, then check these properties. - `Color` no longer implements `AsBindGroup`. Store a `LinearRgba` internally instead to avoid conversion costs. --------- Co-authored-by: Alice Cecile <alice.i.cecil@gmail.com> Co-authored-by: Afonso Lage <lage.afonso@gmail.com> Co-authored-by: Rob Parrett <robparrett@gmail.com> Co-authored-by: Zachary Harrold <zac@harrold.com.au>
2024-02-29 19:35:12 +00:00
let color = GRAY;
for (shape, transform) in query.iter() {
let translation = transform.translation.xy();
let rotation = transform.rotation.to_euler(EulerRot::YXZ).2;
let isometry = Isometry2d::new(translation, Rot2::radians(rotation));
match shape {
Shape::Rectangle(r) => {
gizmos.primitive_2d(r, isometry, color);
}
Shape::Circle(c) => {
gizmos.primitive_2d(c, isometry, color);
}
Shape::Triangle(t) => {
gizmos.primitive_2d(t, isometry, color);
}
Shape::Line(l) => {
gizmos.primitive_2d(l, isometry, color);
}
Shape::Capsule(c) => {
gizmos.primitive_2d(c, isometry, color);
}
Shape::Polygon(p) => {
gizmos.primitive_2d(p, isometry, color);
}
}
}
}
#[derive(Component)]
enum DesiredVolume {
Aabb,
Circle,
}
#[derive(Component, Debug)]
enum CurrentVolume {
Aabb(Aabb2d),
Circle(BoundingCircle),
}
fn update_volumes(
mut commands: Commands,
query: Query<
(Entity, &DesiredVolume, &Shape, &Transform),
Or<(Changed<DesiredVolume>, Changed<Shape>, Changed<Transform>)>,
>,
) {
for (entity, desired_volume, shape, transform) in query.iter() {
let translation = transform.translation.xy();
let rotation = transform.rotation.to_euler(EulerRot::YXZ).2;
Refactor Bounded2d/Bounded3d to use isometries (#14485) # Objective Previously, this area of bevy_math used raw translation and rotations to encode isometries, which did not exist earlier. The goal of this PR is to make the codebase of bevy_math more harmonious by using actual isometries (`Isometry2d`/`Isometry3d`) in these places instead — this will hopefully make the interfaces more digestible for end-users, in addition to facilitating conversions. For instance, together with the addition of #14478, this means that a bounding box for a collider with an isometric `Transform` can be computed as ```rust collider.aabb_3d(collider_transform.to_isometry()) ``` instead of using manual destructuring. ## Solution - The traits `Bounded2d` and `Bounded3d` now use `Isometry2d` and `Isometry3d` (respectively) instead of `translation` and `rotation` parameters; e.g.: ```rust /// A trait with methods that return 3D bounding volumes for a shape. pub trait Bounded3d { /// Get an axis-aligned bounding box for the shape translated and rotated by the given isometry. fn aabb_3d(&self, isometry: Isometry3d) -> Aabb3d; /// Get a bounding sphere for the shape translated and rotated by the given isometry. fn bounding_sphere(&self, isometry: Isometry3d) -> BoundingSphere; } ``` - Similarly, the `from_point_cloud` constructors for axis-aligned bounding boxes and bounding circles/spheres now take isometries instead of separate `translation` and `rotation`; e.g.: ```rust /// Computes the smallest [`Aabb3d`] containing the given set of points, /// transformed by the rotation and translation of the given isometry. /// /// # Panics /// /// Panics if the given set of points is empty. #[inline(always)] pub fn from_point_cloud( isometry: Isometry3d, points: impl Iterator<Item = impl Into<Vec3A>>, ) -> Aabb3d { //... } ``` This has a couple additional results: 1. The end-user no longer interacts directly with `Into<Vec3A>` or `Into<Rot2>` parameters; these conversions all happen earlier now, inside the isometry types. 2. Similarly, almost all intermediate `Vec3 -> Vec3A` conversions have been eliminated from the `Bounded3d` implementations for primitives. This probably has some performance benefit, but I have not measured it as of now. ## Testing Existing unit tests help ensure that nothing has been broken in the refactor. --- ## Migration Guide The `Bounded2d` and `Bounded3d` traits now take `Isometry2d` and `Isometry3d` parameters (respectively) instead of separate translation and rotation arguments. Existing calls to `aabb_2d`, `bounding_circle`, `aabb_3d`, and `bounding_sphere` will have to be changed to use isometries instead. A straightforward conversion is to refactor just by calling `Isometry2d/3d::new`, as follows: ```rust // Old: let aabb = my_shape.aabb_2d(my_translation, my_rotation); // New: let aabb = my_shape.aabb_2d(Isometry2d::new(my_translation, my_rotation)); ``` However, if the old translation and rotation are 3d translation/rotations originating from a `Transform` or `GlobalTransform`, then `to_isometry` may be used instead. For example: ```rust // Old: let bounding_sphere = my_shape.bounding_sphere(shape_transform.translation, shape_transform.rotation); // New: let bounding_sphere = my_shape.bounding_sphere(shape_transform.to_isometry()); ``` This discussion also applies to the `from_point_cloud` construction method of `Aabb2d`/`BoundingCircle`/`Aabb3d`/`BoundingSphere`, which has similarly been altered to use isometries.
2024-07-29 23:37:02 +00:00
let isometry = Isometry2d::new(translation, Rot2::radians(rotation));
match desired_volume {
DesiredVolume::Aabb => {
let aabb = match shape {
Refactor Bounded2d/Bounded3d to use isometries (#14485) # Objective Previously, this area of bevy_math used raw translation and rotations to encode isometries, which did not exist earlier. The goal of this PR is to make the codebase of bevy_math more harmonious by using actual isometries (`Isometry2d`/`Isometry3d`) in these places instead — this will hopefully make the interfaces more digestible for end-users, in addition to facilitating conversions. For instance, together with the addition of #14478, this means that a bounding box for a collider with an isometric `Transform` can be computed as ```rust collider.aabb_3d(collider_transform.to_isometry()) ``` instead of using manual destructuring. ## Solution - The traits `Bounded2d` and `Bounded3d` now use `Isometry2d` and `Isometry3d` (respectively) instead of `translation` and `rotation` parameters; e.g.: ```rust /// A trait with methods that return 3D bounding volumes for a shape. pub trait Bounded3d { /// Get an axis-aligned bounding box for the shape translated and rotated by the given isometry. fn aabb_3d(&self, isometry: Isometry3d) -> Aabb3d; /// Get a bounding sphere for the shape translated and rotated by the given isometry. fn bounding_sphere(&self, isometry: Isometry3d) -> BoundingSphere; } ``` - Similarly, the `from_point_cloud` constructors for axis-aligned bounding boxes and bounding circles/spheres now take isometries instead of separate `translation` and `rotation`; e.g.: ```rust /// Computes the smallest [`Aabb3d`] containing the given set of points, /// transformed by the rotation and translation of the given isometry. /// /// # Panics /// /// Panics if the given set of points is empty. #[inline(always)] pub fn from_point_cloud( isometry: Isometry3d, points: impl Iterator<Item = impl Into<Vec3A>>, ) -> Aabb3d { //... } ``` This has a couple additional results: 1. The end-user no longer interacts directly with `Into<Vec3A>` or `Into<Rot2>` parameters; these conversions all happen earlier now, inside the isometry types. 2. Similarly, almost all intermediate `Vec3 -> Vec3A` conversions have been eliminated from the `Bounded3d` implementations for primitives. This probably has some performance benefit, but I have not measured it as of now. ## Testing Existing unit tests help ensure that nothing has been broken in the refactor. --- ## Migration Guide The `Bounded2d` and `Bounded3d` traits now take `Isometry2d` and `Isometry3d` parameters (respectively) instead of separate translation and rotation arguments. Existing calls to `aabb_2d`, `bounding_circle`, `aabb_3d`, and `bounding_sphere` will have to be changed to use isometries instead. A straightforward conversion is to refactor just by calling `Isometry2d/3d::new`, as follows: ```rust // Old: let aabb = my_shape.aabb_2d(my_translation, my_rotation); // New: let aabb = my_shape.aabb_2d(Isometry2d::new(my_translation, my_rotation)); ``` However, if the old translation and rotation are 3d translation/rotations originating from a `Transform` or `GlobalTransform`, then `to_isometry` may be used instead. For example: ```rust // Old: let bounding_sphere = my_shape.bounding_sphere(shape_transform.translation, shape_transform.rotation); // New: let bounding_sphere = my_shape.bounding_sphere(shape_transform.to_isometry()); ``` This discussion also applies to the `from_point_cloud` construction method of `Aabb2d`/`BoundingCircle`/`Aabb3d`/`BoundingSphere`, which has similarly been altered to use isometries.
2024-07-29 23:37:02 +00:00
Shape::Rectangle(r) => r.aabb_2d(isometry),
Shape::Circle(c) => c.aabb_2d(isometry),
Shape::Triangle(t) => t.aabb_2d(isometry),
Shape::Line(l) => l.aabb_2d(isometry),
Shape::Capsule(c) => c.aabb_2d(isometry),
Shape::Polygon(p) => p.aabb_2d(isometry),
};
commands.entity(entity).insert(CurrentVolume::Aabb(aabb));
}
DesiredVolume::Circle => {
let circle = match shape {
Refactor Bounded2d/Bounded3d to use isometries (#14485) # Objective Previously, this area of bevy_math used raw translation and rotations to encode isometries, which did not exist earlier. The goal of this PR is to make the codebase of bevy_math more harmonious by using actual isometries (`Isometry2d`/`Isometry3d`) in these places instead — this will hopefully make the interfaces more digestible for end-users, in addition to facilitating conversions. For instance, together with the addition of #14478, this means that a bounding box for a collider with an isometric `Transform` can be computed as ```rust collider.aabb_3d(collider_transform.to_isometry()) ``` instead of using manual destructuring. ## Solution - The traits `Bounded2d` and `Bounded3d` now use `Isometry2d` and `Isometry3d` (respectively) instead of `translation` and `rotation` parameters; e.g.: ```rust /// A trait with methods that return 3D bounding volumes for a shape. pub trait Bounded3d { /// Get an axis-aligned bounding box for the shape translated and rotated by the given isometry. fn aabb_3d(&self, isometry: Isometry3d) -> Aabb3d; /// Get a bounding sphere for the shape translated and rotated by the given isometry. fn bounding_sphere(&self, isometry: Isometry3d) -> BoundingSphere; } ``` - Similarly, the `from_point_cloud` constructors for axis-aligned bounding boxes and bounding circles/spheres now take isometries instead of separate `translation` and `rotation`; e.g.: ```rust /// Computes the smallest [`Aabb3d`] containing the given set of points, /// transformed by the rotation and translation of the given isometry. /// /// # Panics /// /// Panics if the given set of points is empty. #[inline(always)] pub fn from_point_cloud( isometry: Isometry3d, points: impl Iterator<Item = impl Into<Vec3A>>, ) -> Aabb3d { //... } ``` This has a couple additional results: 1. The end-user no longer interacts directly with `Into<Vec3A>` or `Into<Rot2>` parameters; these conversions all happen earlier now, inside the isometry types. 2. Similarly, almost all intermediate `Vec3 -> Vec3A` conversions have been eliminated from the `Bounded3d` implementations for primitives. This probably has some performance benefit, but I have not measured it as of now. ## Testing Existing unit tests help ensure that nothing has been broken in the refactor. --- ## Migration Guide The `Bounded2d` and `Bounded3d` traits now take `Isometry2d` and `Isometry3d` parameters (respectively) instead of separate translation and rotation arguments. Existing calls to `aabb_2d`, `bounding_circle`, `aabb_3d`, and `bounding_sphere` will have to be changed to use isometries instead. A straightforward conversion is to refactor just by calling `Isometry2d/3d::new`, as follows: ```rust // Old: let aabb = my_shape.aabb_2d(my_translation, my_rotation); // New: let aabb = my_shape.aabb_2d(Isometry2d::new(my_translation, my_rotation)); ``` However, if the old translation and rotation are 3d translation/rotations originating from a `Transform` or `GlobalTransform`, then `to_isometry` may be used instead. For example: ```rust // Old: let bounding_sphere = my_shape.bounding_sphere(shape_transform.translation, shape_transform.rotation); // New: let bounding_sphere = my_shape.bounding_sphere(shape_transform.to_isometry()); ``` This discussion also applies to the `from_point_cloud` construction method of `Aabb2d`/`BoundingCircle`/`Aabb3d`/`BoundingSphere`, which has similarly been altered to use isometries.
2024-07-29 23:37:02 +00:00
Shape::Rectangle(r) => r.bounding_circle(isometry),
Shape::Circle(c) => c.bounding_circle(isometry),
Shape::Triangle(t) => t.bounding_circle(isometry),
Shape::Line(l) => l.bounding_circle(isometry),
Shape::Capsule(c) => c.bounding_circle(isometry),
Shape::Polygon(p) => p.bounding_circle(isometry),
};
commands
.entity(entity)
.insert(CurrentVolume::Circle(circle));
}
}
}
}
fn render_volumes(mut gizmos: Gizmos, query: Query<(&CurrentVolume, &Intersects)>) {
for (volume, intersects) in query.iter() {
let color = if **intersects { AQUA } else { ORANGE_RED };
match volume {
CurrentVolume::Aabb(a) => {
gizmos.rect_2d(a.center(), a.half_size() * 2., color);
}
CurrentVolume::Circle(c) => {
gizmos.circle_2d(c.center(), c.radius(), color);
}
}
}
}
#[derive(Component, Deref, DerefMut, Default)]
struct Intersects(bool);
const OFFSET_X: f32 = 125.;
const OFFSET_Y: f32 = 75.;
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
commands.spawn((
SpatialBundle {
transform: Transform::from_xyz(-OFFSET_X, OFFSET_Y, 0.),
..default()
},
Shape::Circle(Circle::new(45.)),
DesiredVolume::Aabb,
Intersects::default(),
));
commands.spawn((
SpatialBundle {
transform: Transform::from_xyz(0., OFFSET_Y, 0.),
..default()
},
Shape::Rectangle(Rectangle::new(80., 80.)),
Spin,
DesiredVolume::Circle,
Intersects::default(),
));
commands.spawn((
SpatialBundle {
transform: Transform::from_xyz(OFFSET_X, OFFSET_Y, 0.),
..default()
},
Shape::Triangle(Triangle2d::new(
Vec2::new(-40., -40.),
Vec2::new(-20., 40.),
Vec2::new(40., 50.),
)),
Spin,
DesiredVolume::Aabb,
Intersects::default(),
));
commands.spawn((
SpatialBundle {
transform: Transform::from_xyz(-OFFSET_X, -OFFSET_Y, 0.),
..default()
},
Rename `Direction2d/3d` to `Dir2/3` (#12189) # Objective Split up from #12017, rename Bevy's direction types. Currently, Bevy has the `Direction2d`, `Direction3d`, and `Direction3dA` types, which provide a type-level guarantee that their contained vectors remain normalized. They can be very useful for a lot of APIs for safety, explicitness, and in some cases performance, as they can sometimes avoid unnecessary normalizations. However, many consider them to be inconvenient to use, and opt for standard vector types like `Vec3` because of this. One reason is that the direction type names are a bit long and can be annoying to write (of course you can use autocomplete, but just typing `Vec3` is still nicer), and in some intances, the extra characters can make formatting worse. The naming is also inconsistent with Glam's shorter type names, and results in names like `Direction3dA`, which (in my opinion) are difficult to read and even a bit ugly. This PR proposes renaming the types to `Dir2`, `Dir3`, and `Dir3A`. These names are nice and easy to write, consistent with Glam, and work well for variants like the SIMD aligned `Dir3A`. As a bonus, it can also result in nicer formatting in a lot of cases, which can be seen from the diff of this PR. Some examples of what it looks like: (copied from #12017) ```rust // Before let ray_cast = RayCast2d::new(Vec2::ZERO, Direction2d::X, 5.0); // After let ray_cast = RayCast2d::new(Vec2::ZERO, Dir2::X, 5.0); ``` ```rust // Before (an example using Bevy XPBD) let hit = spatial_query.cast_ray( Vec3::ZERO, Direction3d::X, f32::MAX, true, SpatialQueryFilter::default(), ); // After let hit = spatial_query.cast_ray( Vec3::ZERO, Dir3::X, f32::MAX, true, SpatialQueryFilter::default(), ); ``` ```rust // Before self.circle( Vec3::new(0.0, -2.0, 0.0), Direction3d::Y, 5.0, Color::TURQUOISE, ); // After (formatting is collapsed in this case) self.circle(Vec3::new(0.0, -2.0, 0.0), Dir3::Y, 5.0, Color::TURQUOISE); ``` ## Solution Rename `Direction2d`, `Direction3d`, and `Direction3dA` to `Dir2`, `Dir3`, and `Dir3A`. --- ## Migration Guide The `Direction2d` and `Direction3d` types have been renamed to `Dir2` and `Dir3`. ## Additional Context This has been brought up on the Discord a few times, and we had a small [poll](https://discord.com/channels/691052431525675048/1203087353850364004/1212465038711984158) on this. `Dir2`/`Dir3`/`Dir3A` was quite unanimously chosen as the best option, but of course it was a very small poll and inconclusive, so other opinions are certainly welcome too. --------- Co-authored-by: IceSentry <c.giguere42@gmail.com>
2024-02-28 22:48:43 +00:00
Shape::Line(Segment2d::new(Dir2::from_xy(1., 0.3).unwrap(), 90.)),
Spin,
DesiredVolume::Circle,
Intersects::default(),
));
commands.spawn((
SpatialBundle {
transform: Transform::from_xyz(0., -OFFSET_Y, 0.),
..default()
},
Shape::Capsule(Capsule2d::new(25., 50.)),
Spin,
DesiredVolume::Aabb,
Intersects::default(),
));
commands.spawn((
SpatialBundle {
transform: Transform::from_xyz(OFFSET_X, -OFFSET_Y, 0.),
..default()
},
Shape::Polygon(RegularPolygon::new(50., 6)),
Spin,
DesiredVolume::Circle,
Intersects::default(),
));
commands.spawn(
TextBundle::from_section("", TextStyle::default()).with_style(Style {
position_type: PositionType::Absolute,
bottom: Val::Px(12.0),
left: Val::Px(12.0),
..default()
}),
);
}
fn draw_filled_circle(gizmos: &mut Gizmos, position: Vec2, color: Srgba) {
for r in [1., 2., 3.] {
gizmos.circle_2d(position, r, color);
}
}
fn draw_ray(gizmos: &mut Gizmos, ray: &RayCast2d) {
gizmos.line_2d(
ray.ray.origin,
ray.ray.origin + *ray.ray.direction * ray.max,
Migrate from `LegacyColor` to `bevy_color::Color` (#12163) # Objective - As part of the migration process we need to a) see the end effect of the migration on user ergonomics b) check for serious perf regressions c) actually migrate the code - To accomplish this, I'm going to attempt to migrate all of the remaining user-facing usages of `LegacyColor` in one PR, being careful to keep a clean commit history. - Fixes #12056. ## Solution I've chosen to use the polymorphic `Color` type as our standard user-facing API. - [x] Migrate `bevy_gizmos`. - [x] Take `impl Into<Color>` in all `bevy_gizmos` APIs - [x] Migrate sprites - [x] Migrate UI - [x] Migrate `ColorMaterial` - [x] Migrate `MaterialMesh2D` - [x] Migrate fog - [x] Migrate lights - [x] Migrate StandardMaterial - [x] Migrate wireframes - [x] Migrate clear color - [x] Migrate text - [x] Migrate gltf loader - [x] Register color types for reflection - [x] Remove `LegacyColor` - [x] Make sure CI passes Incidental improvements to ease migration: - added `Color::srgba_u8`, `Color::srgba_from_array` and friends - added `set_alpha`, `is_fully_transparent` and `is_fully_opaque` to the `Alpha` trait - add and immediately deprecate (lol) `Color::rgb` and friends in favor of more explicit and consistent `Color::srgb` - standardized on white and black for most example text colors - added vector field traits to `LinearRgba`: ~~`Add`, `Sub`, `AddAssign`, `SubAssign`,~~ `Mul<f32>` and `Div<f32>`. Multiplications and divisions do not scale alpha. `Add` and `Sub` have been cut from this PR. - added `LinearRgba` and `Srgba` `RED/GREEN/BLUE` - added `LinearRgba_to_f32_array` and `LinearRgba::to_u32` ## Migration Guide Bevy's color types have changed! Wherever you used a `bevy::render::Color`, a `bevy::color::Color` is used instead. These are quite similar! Both are enums storing a color in a specific color space (or to be more precise, using a specific color model). However, each of the different color models now has its own type. TODO... - `Color::rgba`, `Color::rgb`, `Color::rbga_u8`, `Color::rgb_u8`, `Color::rgb_from_array` are now `Color::srgba`, `Color::srgb`, `Color::srgba_u8`, `Color::srgb_u8` and `Color::srgb_from_array`. - `Color::set_a` and `Color::a` is now `Color::set_alpha` and `Color::alpha`. These are part of the `Alpha` trait in `bevy_color`. - `Color::is_fully_transparent` is now part of the `Alpha` trait in `bevy_color` - `Color::r`, `Color::set_r`, `Color::with_r` and the equivalents for `g`, `b` `h`, `s` and `l` have been removed due to causing silent relatively expensive conversions. Convert your `Color` into the desired color space, perform your operations there, and then convert it back into a polymorphic `Color` enum. - `Color::hex` is now `Srgba::hex`. Call `.into` or construct a `Color::Srgba` variant manually to convert it. - `WireframeMaterial`, `ExtractedUiNode`, `ExtractedDirectionalLight`, `ExtractedPointLight`, `ExtractedSpotLight` and `ExtractedSprite` now store a `LinearRgba`, rather than a polymorphic `Color` - `Color::rgb_linear` and `Color::rgba_linear` are now `Color::linear_rgb` and `Color::linear_rgba` - The various CSS color constants are no longer stored directly on `Color`. Instead, they're defined in the `Srgba` color space, and accessed via `bevy::color::palettes::css`. Call `.into()` on them to convert them into a `Color` for quick debugging use, and consider using the much prettier `tailwind` palette for prototyping. - The `LIME_GREEN` color has been renamed to `LIMEGREEN` to comply with the standard naming. - Vector field arithmetic operations on `Color` (add, subtract, multiply and divide by a f32) have been removed. Instead, convert your colors into `LinearRgba` space, and perform your operations explicitly there. This is particularly relevant when working with emissive or HDR colors, whose color channel values are routinely outside of the ordinary 0 to 1 range. - `Color::as_linear_rgba_f32` has been removed. Call `LinearRgba::to_f32_array` instead, converting if needed. - `Color::as_linear_rgba_u32` has been removed. Call `LinearRgba::to_u32` instead, converting if needed. - Several other color conversion methods to transform LCH or HSL colors into float arrays or `Vec` types have been removed. Please reimplement these externally or open a PR to re-add them if you found them particularly useful. - Various methods on `Color` such as `rgb` or `hsl` to convert the color into a specific color space have been removed. Convert into `LinearRgba`, then to the color space of your choice. - Various implicitly-converting color value methods on `Color` such as `r`, `g`, `b` or `h` have been removed. Please convert it into the color space of your choice, then check these properties. - `Color` no longer implements `AsBindGroup`. Store a `LinearRgba` internally instead to avoid conversion costs. --------- Co-authored-by: Alice Cecile <alice.i.cecil@gmail.com> Co-authored-by: Afonso Lage <lage.afonso@gmail.com> Co-authored-by: Rob Parrett <robparrett@gmail.com> Co-authored-by: Zachary Harrold <zac@harrold.com.au>
2024-02-29 19:35:12 +00:00
WHITE,
);
draw_filled_circle(gizmos, ray.ray.origin, FUCHSIA);
}
fn get_and_draw_ray(gizmos: &mut Gizmos, time: &Time) -> RayCast2d {
let ray = Vec2::new(
ops::cos(time.elapsed_seconds()),
ops::sin(time.elapsed_seconds()),
);
let dist = 150. + ops::sin(0.5 * time.elapsed_seconds()).abs() * 500.;
let aabb_ray = Ray2d {
origin: ray * 250.,
Rename `Direction2d/3d` to `Dir2/3` (#12189) # Objective Split up from #12017, rename Bevy's direction types. Currently, Bevy has the `Direction2d`, `Direction3d`, and `Direction3dA` types, which provide a type-level guarantee that their contained vectors remain normalized. They can be very useful for a lot of APIs for safety, explicitness, and in some cases performance, as they can sometimes avoid unnecessary normalizations. However, many consider them to be inconvenient to use, and opt for standard vector types like `Vec3` because of this. One reason is that the direction type names are a bit long and can be annoying to write (of course you can use autocomplete, but just typing `Vec3` is still nicer), and in some intances, the extra characters can make formatting worse. The naming is also inconsistent with Glam's shorter type names, and results in names like `Direction3dA`, which (in my opinion) are difficult to read and even a bit ugly. This PR proposes renaming the types to `Dir2`, `Dir3`, and `Dir3A`. These names are nice and easy to write, consistent with Glam, and work well for variants like the SIMD aligned `Dir3A`. As a bonus, it can also result in nicer formatting in a lot of cases, which can be seen from the diff of this PR. Some examples of what it looks like: (copied from #12017) ```rust // Before let ray_cast = RayCast2d::new(Vec2::ZERO, Direction2d::X, 5.0); // After let ray_cast = RayCast2d::new(Vec2::ZERO, Dir2::X, 5.0); ``` ```rust // Before (an example using Bevy XPBD) let hit = spatial_query.cast_ray( Vec3::ZERO, Direction3d::X, f32::MAX, true, SpatialQueryFilter::default(), ); // After let hit = spatial_query.cast_ray( Vec3::ZERO, Dir3::X, f32::MAX, true, SpatialQueryFilter::default(), ); ``` ```rust // Before self.circle( Vec3::new(0.0, -2.0, 0.0), Direction3d::Y, 5.0, Color::TURQUOISE, ); // After (formatting is collapsed in this case) self.circle(Vec3::new(0.0, -2.0, 0.0), Dir3::Y, 5.0, Color::TURQUOISE); ``` ## Solution Rename `Direction2d`, `Direction3d`, and `Direction3dA` to `Dir2`, `Dir3`, and `Dir3A`. --- ## Migration Guide The `Direction2d` and `Direction3d` types have been renamed to `Dir2` and `Dir3`. ## Additional Context This has been brought up on the Discord a few times, and we had a small [poll](https://discord.com/channels/691052431525675048/1203087353850364004/1212465038711984158) on this. `Dir2`/`Dir3`/`Dir3A` was quite unanimously chosen as the best option, but of course it was a very small poll and inconclusive, so other opinions are certainly welcome too. --------- Co-authored-by: IceSentry <c.giguere42@gmail.com>
2024-02-28 22:48:43 +00:00
direction: Dir2::new_unchecked(-ray),
};
let ray_cast = RayCast2d::from_ray(aabb_ray, dist - 20.);
draw_ray(gizmos, &ray_cast);
ray_cast
}
fn ray_cast_system(
mut gizmos: Gizmos,
time: Res<Time>,
mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
let ray_cast = get_and_draw_ray(&mut gizmos, &time);
for (volume, mut intersects) in volumes.iter_mut() {
let toi = match volume {
CurrentVolume::Aabb(a) => ray_cast.aabb_intersection_at(a),
CurrentVolume::Circle(c) => ray_cast.circle_intersection_at(c),
};
**intersects = toi.is_some();
if let Some(toi) = toi {
draw_filled_circle(
&mut gizmos,
ray_cast.ray.origin + *ray_cast.ray.direction * toi,
LIME,
);
}
}
}
fn aabb_cast_system(
mut gizmos: Gizmos,
time: Res<Time>,
mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
let ray_cast = get_and_draw_ray(&mut gizmos, &time);
let aabb_cast = AabbCast2d {
aabb: Aabb2d::new(Vec2::ZERO, Vec2::splat(15.)),
ray: ray_cast,
};
for (volume, mut intersects) in volumes.iter_mut() {
let toi = match *volume {
CurrentVolume::Aabb(a) => aabb_cast.aabb_collision_at(a),
CurrentVolume::Circle(_) => None,
};
**intersects = toi.is_some();
if let Some(toi) = toi {
gizmos.rect_2d(
aabb_cast.ray.ray.origin + *aabb_cast.ray.ray.direction * toi,
aabb_cast.aabb.half_size() * 2.,
LIME,
);
}
}
}
fn bounding_circle_cast_system(
mut gizmos: Gizmos,
time: Res<Time>,
mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
let ray_cast = get_and_draw_ray(&mut gizmos, &time);
let circle_cast = BoundingCircleCast {
circle: BoundingCircle::new(Vec2::ZERO, 15.),
ray: ray_cast,
};
for (volume, mut intersects) in volumes.iter_mut() {
let toi = match *volume {
CurrentVolume::Aabb(_) => None,
CurrentVolume::Circle(c) => circle_cast.circle_collision_at(c),
};
**intersects = toi.is_some();
if let Some(toi) = toi {
gizmos.circle_2d(
circle_cast.ray.ray.origin + *circle_cast.ray.ray.direction * toi,
circle_cast.circle.radius(),
LIME,
);
}
}
}
fn get_intersection_position(time: &Time) -> Vec2 {
let x = ops::cos(0.8 * time.elapsed_seconds()) * 250.;
let y = ops::sin(0.4 * time.elapsed_seconds()) * 100.;
Vec2::new(x, y)
}
fn aabb_intersection_system(
mut gizmos: Gizmos,
time: Res<Time>,
mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
let center = get_intersection_position(&time);
let aabb = Aabb2d::new(center, Vec2::splat(50.));
gizmos.rect_2d(center, aabb.half_size() * 2., YELLOW);
for (volume, mut intersects) in volumes.iter_mut() {
let hit = match volume {
CurrentVolume::Aabb(a) => aabb.intersects(a),
CurrentVolume::Circle(c) => aabb.intersects(c),
};
**intersects = hit;
}
}
fn circle_intersection_system(
mut gizmos: Gizmos,
time: Res<Time>,
mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
let center = get_intersection_position(&time);
let circle = BoundingCircle::new(center, 50.);
gizmos.circle_2d(center, circle.radius(), YELLOW);
for (volume, mut intersects) in volumes.iter_mut() {
let hit = match volume {
CurrentVolume::Aabb(a) => circle.intersects(a),
CurrentVolume::Circle(c) => circle.intersects(c),
};
**intersects = hit;
}
}