1use bevy::{
4 color::palettes::css::*,
5 math::{bounding::*, ops, Isometry2d},
6 prelude::*,
7};
8
9fn main() {
10 App::new()
11 .add_plugins(DefaultPlugins)
12 .init_state::<Test>()
13 .add_systems(Startup, setup)
14 .add_systems(
15 Update,
16 (update_text, spin, update_volumes, update_test_state),
17 )
18 .add_systems(
19 PostUpdate,
20 (
21 render_shapes,
22 (
23 aabb_intersection_system.run_if(in_state(Test::AabbSweep)),
24 circle_intersection_system.run_if(in_state(Test::CircleSweep)),
25 ray_cast_system.run_if(in_state(Test::RayCast)),
26 aabb_cast_system.run_if(in_state(Test::AabbCast)),
27 bounding_circle_cast_system.run_if(in_state(Test::CircleCast)),
28 ),
29 render_volumes,
30 )
31 .chain(),
32 )
33 .run();
34}
35
36#[derive(Component)]
37struct Spin;
38
39fn spin(time: Res<Time>, mut query: Query<&mut Transform, With<Spin>>) {
40 for mut transform in query.iter_mut() {
41 transform.rotation *= Quat::from_rotation_z(time.delta_secs() / 5.);
42 }
43}
44
45#[derive(States, Default, Debug, Hash, PartialEq, Eq, Clone, Copy)]
46enum Test {
47 AabbSweep,
48 CircleSweep,
49 #[default]
50 RayCast,
51 AabbCast,
52 CircleCast,
53}
54
55fn update_test_state(
56 keycode: Res<ButtonInput<KeyCode>>,
57 cur_state: Res<State<Test>>,
58 mut state: ResMut<NextState<Test>>,
59) {
60 if !keycode.just_pressed(KeyCode::Space) {
61 return;
62 }
63
64 use Test::*;
65 let next = match **cur_state {
66 AabbSweep => CircleSweep,
67 CircleSweep => RayCast,
68 RayCast => AabbCast,
69 AabbCast => CircleCast,
70 CircleCast => AabbSweep,
71 };
72 state.set(next);
73}
74
75fn update_text(mut text: Single<&mut Text>, cur_state: Res<State<Test>>) {
76 if !cur_state.is_changed() {
77 return;
78 }
79
80 text.clear();
81
82 text.push_str("Intersection test:\n");
83 use Test::*;
84 for &test in &[AabbSweep, CircleSweep, RayCast, AabbCast, CircleCast] {
85 let s = if **cur_state == test { "*" } else { " " };
86 text.push_str(&format!(" {s} {test:?} {s}\n"));
87 }
88 text.push_str("\nPress space to cycle");
89}
90
91#[derive(Component)]
92enum Shape {
93 Rectangle(Rectangle),
94 Circle(Circle),
95 Triangle(Triangle2d),
96 Line(Segment2d),
97 Capsule(Capsule2d),
98 Polygon(RegularPolygon),
99}
100
101fn render_shapes(mut gizmos: Gizmos, query: Query<(&Shape, &Transform)>) {
102 let color = GRAY;
103 for (shape, transform) in query.iter() {
104 let translation = transform.translation.xy();
105 let rotation = transform.rotation.to_euler(EulerRot::YXZ).2;
106 let isometry = Isometry2d::new(translation, Rot2::radians(rotation));
107 match shape {
108 Shape::Rectangle(r) => {
109 gizmos.primitive_2d(r, isometry, color);
110 }
111 Shape::Circle(c) => {
112 gizmos.primitive_2d(c, isometry, color);
113 }
114 Shape::Triangle(t) => {
115 gizmos.primitive_2d(t, isometry, color);
116 }
117 Shape::Line(l) => {
118 gizmos.primitive_2d(l, isometry, color);
119 }
120 Shape::Capsule(c) => {
121 gizmos.primitive_2d(c, isometry, color);
122 }
123 Shape::Polygon(p) => {
124 gizmos.primitive_2d(p, isometry, color);
125 }
126 }
127 }
128}
129
130#[derive(Component)]
131enum DesiredVolume {
132 Aabb,
133 Circle,
134}
135
136#[derive(Component, Debug)]
137enum CurrentVolume {
138 Aabb(Aabb2d),
139 Circle(BoundingCircle),
140}
141
142fn update_volumes(
143 mut commands: Commands,
144 query: Query<
145 (Entity, &DesiredVolume, &Shape, &Transform),
146 Or<(Changed<DesiredVolume>, Changed<Shape>, Changed<Transform>)>,
147 >,
148) {
149 for (entity, desired_volume, shape, transform) in query.iter() {
150 let translation = transform.translation.xy();
151 let rotation = transform.rotation.to_euler(EulerRot::YXZ).2;
152 let isometry = Isometry2d::new(translation, Rot2::radians(rotation));
153 match desired_volume {
154 DesiredVolume::Aabb => {
155 let aabb = match shape {
156 Shape::Rectangle(r) => r.aabb_2d(isometry),
157 Shape::Circle(c) => c.aabb_2d(isometry),
158 Shape::Triangle(t) => t.aabb_2d(isometry),
159 Shape::Line(l) => l.aabb_2d(isometry),
160 Shape::Capsule(c) => c.aabb_2d(isometry),
161 Shape::Polygon(p) => p.aabb_2d(isometry),
162 };
163 commands.entity(entity).insert(CurrentVolume::Aabb(aabb));
164 }
165 DesiredVolume::Circle => {
166 let circle = match shape {
167 Shape::Rectangle(r) => r.bounding_circle(isometry),
168 Shape::Circle(c) => c.bounding_circle(isometry),
169 Shape::Triangle(t) => t.bounding_circle(isometry),
170 Shape::Line(l) => l.bounding_circle(isometry),
171 Shape::Capsule(c) => c.bounding_circle(isometry),
172 Shape::Polygon(p) => p.bounding_circle(isometry),
173 };
174 commands
175 .entity(entity)
176 .insert(CurrentVolume::Circle(circle));
177 }
178 }
179 }
180}
181
182fn render_volumes(mut gizmos: Gizmos, query: Query<(&CurrentVolume, &Intersects)>) {
183 for (volume, intersects) in query.iter() {
184 let color = if **intersects { AQUA } else { ORANGE_RED };
185 match volume {
186 CurrentVolume::Aabb(a) => {
187 gizmos.rect_2d(a.center(), a.half_size() * 2., color);
188 }
189 CurrentVolume::Circle(c) => {
190 gizmos.circle_2d(c.center(), c.radius(), color);
191 }
192 }
193 }
194}
195
196#[derive(Component, Deref, DerefMut, Default)]
197struct Intersects(bool);
198
199const OFFSET_X: f32 = 125.;
200const OFFSET_Y: f32 = 75.;
201
202fn setup(mut commands: Commands) {
203 commands.spawn(Camera2d);
204 commands.spawn((
205 Transform::from_xyz(-OFFSET_X, OFFSET_Y, 0.),
206 Shape::Circle(Circle::new(45.)),
207 DesiredVolume::Aabb,
208 Intersects::default(),
209 ));
210
211 commands.spawn((
212 Transform::from_xyz(0., OFFSET_Y, 0.),
213 Shape::Rectangle(Rectangle::new(80., 80.)),
214 Spin,
215 DesiredVolume::Circle,
216 Intersects::default(),
217 ));
218
219 commands.spawn((
220 Transform::from_xyz(OFFSET_X, OFFSET_Y, 0.),
221 Shape::Triangle(Triangle2d::new(
222 Vec2::new(-40., -40.),
223 Vec2::new(-20., 40.),
224 Vec2::new(40., 50.),
225 )),
226 Spin,
227 DesiredVolume::Aabb,
228 Intersects::default(),
229 ));
230
231 commands.spawn((
232 Transform::from_xyz(-OFFSET_X, -OFFSET_Y, 0.),
233 Shape::Line(Segment2d::new(Dir2::from_xy(1., 0.3).unwrap(), 90.)),
234 Spin,
235 DesiredVolume::Circle,
236 Intersects::default(),
237 ));
238
239 commands.spawn((
240 Transform::from_xyz(0., -OFFSET_Y, 0.),
241 Shape::Capsule(Capsule2d::new(25., 50.)),
242 Spin,
243 DesiredVolume::Aabb,
244 Intersects::default(),
245 ));
246
247 commands.spawn((
248 Transform::from_xyz(OFFSET_X, -OFFSET_Y, 0.),
249 Shape::Polygon(RegularPolygon::new(50., 6)),
250 Spin,
251 DesiredVolume::Circle,
252 Intersects::default(),
253 ));
254
255 commands.spawn((
256 Text::default(),
257 Node {
258 position_type: PositionType::Absolute,
259 bottom: Val::Px(12.0),
260 left: Val::Px(12.0),
261 ..default()
262 },
263 ));
264}
265
266fn draw_filled_circle(gizmos: &mut Gizmos, position: Vec2, color: Srgba) {
267 for r in [1., 2., 3.] {
268 gizmos.circle_2d(position, r, color);
269 }
270}
271
272fn draw_ray(gizmos: &mut Gizmos, ray: &RayCast2d) {
273 gizmos.line_2d(
274 ray.ray.origin,
275 ray.ray.origin + *ray.ray.direction * ray.max,
276 WHITE,
277 );
278 draw_filled_circle(gizmos, ray.ray.origin, FUCHSIA);
279}
280
281fn get_and_draw_ray(gizmos: &mut Gizmos, time: &Time) -> RayCast2d {
282 let ray = Vec2::new(ops::cos(time.elapsed_secs()), ops::sin(time.elapsed_secs()));
283 let dist = 150. + ops::sin(0.5 * time.elapsed_secs()).abs() * 500.;
284
285 let aabb_ray = Ray2d {
286 origin: ray * 250.,
287 direction: Dir2::new_unchecked(-ray),
288 };
289 let ray_cast = RayCast2d::from_ray(aabb_ray, dist - 20.);
290
291 draw_ray(gizmos, &ray_cast);
292 ray_cast
293}
294
295fn ray_cast_system(
296 mut gizmos: Gizmos,
297 time: Res<Time>,
298 mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
299) {
300 let ray_cast = get_and_draw_ray(&mut gizmos, &time);
301
302 for (volume, mut intersects) in volumes.iter_mut() {
303 let toi = match volume {
304 CurrentVolume::Aabb(a) => ray_cast.aabb_intersection_at(a),
305 CurrentVolume::Circle(c) => ray_cast.circle_intersection_at(c),
306 };
307 **intersects = toi.is_some();
308 if let Some(toi) = toi {
309 draw_filled_circle(
310 &mut gizmos,
311 ray_cast.ray.origin + *ray_cast.ray.direction * toi,
312 LIME,
313 );
314 }
315 }
316}
317
318fn aabb_cast_system(
319 mut gizmos: Gizmos,
320 time: Res<Time>,
321 mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
322) {
323 let ray_cast = get_and_draw_ray(&mut gizmos, &time);
324 let aabb_cast = AabbCast2d {
325 aabb: Aabb2d::new(Vec2::ZERO, Vec2::splat(15.)),
326 ray: ray_cast,
327 };
328
329 for (volume, mut intersects) in volumes.iter_mut() {
330 let toi = match *volume {
331 CurrentVolume::Aabb(a) => aabb_cast.aabb_collision_at(a),
332 CurrentVolume::Circle(_) => None,
333 };
334
335 **intersects = toi.is_some();
336 if let Some(toi) = toi {
337 gizmos.rect_2d(
338 aabb_cast.ray.ray.origin + *aabb_cast.ray.ray.direction * toi,
339 aabb_cast.aabb.half_size() * 2.,
340 LIME,
341 );
342 }
343 }
344}
345
346fn bounding_circle_cast_system(
347 mut gizmos: Gizmos,
348 time: Res<Time>,
349 mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
350) {
351 let ray_cast = get_and_draw_ray(&mut gizmos, &time);
352 let circle_cast = BoundingCircleCast {
353 circle: BoundingCircle::new(Vec2::ZERO, 15.),
354 ray: ray_cast,
355 };
356
357 for (volume, mut intersects) in volumes.iter_mut() {
358 let toi = match *volume {
359 CurrentVolume::Aabb(_) => None,
360 CurrentVolume::Circle(c) => circle_cast.circle_collision_at(c),
361 };
362
363 **intersects = toi.is_some();
364 if let Some(toi) = toi {
365 gizmos.circle_2d(
366 circle_cast.ray.ray.origin + *circle_cast.ray.ray.direction * toi,
367 circle_cast.circle.radius(),
368 LIME,
369 );
370 }
371 }
372}
373
374fn get_intersection_position(time: &Time) -> Vec2 {
375 let x = ops::cos(0.8 * time.elapsed_secs()) * 250.;
376 let y = ops::sin(0.4 * time.elapsed_secs()) * 100.;
377 Vec2::new(x, y)
378}
379
380fn aabb_intersection_system(
381 mut gizmos: Gizmos,
382 time: Res<Time>,
383 mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
384) {
385 let center = get_intersection_position(&time);
386 let aabb = Aabb2d::new(center, Vec2::splat(50.));
387 gizmos.rect_2d(center, aabb.half_size() * 2., YELLOW);
388
389 for (volume, mut intersects) in volumes.iter_mut() {
390 let hit = match volume {
391 CurrentVolume::Aabb(a) => aabb.intersects(a),
392 CurrentVolume::Circle(c) => aabb.intersects(c),
393 };
394
395 **intersects = hit;
396 }
397}
398
399fn circle_intersection_system(
400 mut gizmos: Gizmos,
401 time: Res<Time>,
402 mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
403) {
404 let center = get_intersection_position(&time);
405 let circle = BoundingCircle::new(center, 50.);
406 gizmos.circle_2d(center, circle.radius(), YELLOW);
407
408 for (volume, mut intersects) in volumes.iter_mut() {
409 let hit = match volume {
410 CurrentVolume::Aabb(a) => circle.intersects(a),
411 CurrentVolume::Circle(c) => circle.intersects(c),
412 };
413
414 **intersects = hit;
415 }
416}