1use bevy::{
6 app::{App, Plugin},
7 ecs::{
8 entity::Entity,
9 entity_disabling::Disabled,
10 lifecycle::{HookContext, Insert, Replace},
11 observer::On,
12 query::{Changed, Has, Or, With, Without},
13 resource::Resource,
14 schedule::{
15 IntoScheduleConfigs,
16 common_conditions::{resource_changed, resource_exists},
17 },
18 system::{
19 Command, Commands, Local, ParamSet, Query, Res, ResMut, SystemChangeTick, SystemState,
20 lifetimeless::{SQuery, SResMut},
21 },
22 world::{DeferredWorld, Mut, Ref, World},
23 },
24 log::warn,
25 prelude::{Deref, DerefMut},
26 time::Time,
27};
28
29use crate::{
30 data_structures::bit_vec::BitVec,
31 dynamics::solver::{
32 constraint_graph::ConstraintGraph,
33 islands::{BodyIslandNode, IslandId, PhysicsIslands},
34 joint_graph::JointGraph,
35 solver_body::SolverBody,
36 },
37 prelude::*,
38 schedule::{LastPhysicsTick, is_changed_after_tick},
39};
40
41pub struct IslandSleepingPlugin;
43
44impl Plugin for IslandSleepingPlugin {
45 fn build(&self, app: &mut App) {
46 app.init_resource::<AwakeIslandBitVec>();
47 app.init_resource::<TimeToSleep>();
48
49 app.register_required_components::<SolverBody, SleepThreshold>();
51 app.register_required_components::<SolverBody, SleepTimer>();
52
53 let cached_system_state1 = CachedBodySleepingSystemState(SystemState::new(app.world_mut()));
55 let cached_system_state2 =
56 CachedIslandSleepingSystemState(SystemState::new(app.world_mut()));
57 let cached_system_state3 = CachedIslandWakingSystemState(SystemState::new(app.world_mut()));
58 app.insert_resource(cached_system_state1);
59 app.insert_resource(cached_system_state2);
60 app.insert_resource(cached_system_state3);
61
62 app.world_mut()
64 .register_component_hooks::<Sleeping>()
65 .on_add(sleep_on_add_sleeping)
66 .on_remove(wake_on_remove_sleeping);
67
68 app.add_observer(wake_on_replace_rigid_body);
69 app.add_observer(wake_on_enable_rigid_body);
70
71 app.add_systems(
72 PhysicsSchedule,
73 (
74 update_sleeping_states,
75 wake_islands_with_sleeping_disabled,
76 wake_on_changed,
77 wake_all_islands.run_if(resource_changed::<Gravity>),
78 sleep_islands,
79 )
80 .chain()
81 .run_if(resource_exists::<PhysicsIslands>)
82 .in_set(PhysicsStepSystems::Sleeping),
83 );
84 }
85}
86
87fn sleep_on_add_sleeping(mut world: DeferredWorld, ctx: HookContext) {
88 let Some(body_island) = world.get::<BodyIslandNode>(ctx.entity) else {
89 return;
90 };
91
92 let island_id = body_island.island_id;
93
94 if let Some(island) = world
96 .get_resource::<PhysicsIslands>()
97 .and_then(|islands| islands.get(island_id))
98 && island.is_sleeping
99 {
100 return;
101 }
102
103 world.commands().queue(SleepBody(ctx.entity));
104}
105
106fn wake_on_remove_sleeping(mut world: DeferredWorld, ctx: HookContext) {
107 let Some(body_island) = world.get::<BodyIslandNode>(ctx.entity) else {
108 return;
109 };
110
111 let island_id = body_island.island_id;
112
113 if let Some(island) = world
115 .get_resource::<PhysicsIslands>()
116 .and_then(|islands| islands.get(island_id))
117 && !island.is_sleeping
118 {
119 return;
120 }
121
122 world.commands().queue(WakeBody(ctx.entity));
123}
124
125fn wake_on_replace_rigid_body(
126 trigger: On<Replace, RigidBody>,
127 mut commands: Commands,
128 query: Query<&BodyIslandNode>,
129) {
130 let Ok(body_island) = query.get(trigger.entity) else {
131 return;
132 };
133
134 commands.queue(WakeIslands(vec![body_island.island_id]));
135}
136
137fn wake_on_enable_rigid_body(
138 trigger: On<Insert, BodyIslandNode>,
139 mut commands: Commands,
140 mut query: Query<
141 (&BodyIslandNode, &mut SleepTimer, Has<Sleeping>),
142 Or<(With<Disabled>, Without<Disabled>)>,
143 >,
144) {
145 let Ok((body_island, mut sleep_timer, is_sleeping)) = query.get_mut(trigger.entity) else {
146 return;
147 };
148
149 if is_sleeping {
150 commands.entity(trigger.entity).try_remove::<Sleeping>();
151 }
152
153 if sleep_timer.0 > 0.0 {
155 sleep_timer.0 = 0.0;
156 commands.queue(WakeIslands(vec![body_island.island_id]));
157 }
158}
159
160#[derive(Resource, Default, Deref, DerefMut)]
162pub(crate) struct AwakeIslandBitVec(pub(crate) BitVec);
163
164fn wake_islands_with_sleeping_disabled(
165 mut awake_island_bit_vec: ResMut<AwakeIslandBitVec>,
166 mut query: Query<
167 (&BodyIslandNode, &mut SleepTimer),
168 Or<(
169 With<SleepingDisabled>,
170 With<Disabled>,
171 With<RigidBodyDisabled>,
172 )>,
173 >,
174) {
175 for (body_island, mut sleep_timer) in &mut query {
177 awake_island_bit_vec.set_and_grow(body_island.island_id.0 as usize);
178
179 sleep_timer.0 = 0.0;
181 }
182}
183
184fn update_sleeping_states(
185 mut awake_island_bit_vec: ResMut<AwakeIslandBitVec>,
186 mut islands: ResMut<PhysicsIslands>,
187 mut query: Query<
188 (
189 &mut SleepTimer,
190 &SleepThreshold,
191 &SolverBody,
192 &BodyIslandNode,
193 ),
194 (Without<Sleeping>, Without<SleepingDisabled>),
195 >,
196 length_unit: Res<PhysicsLengthUnit>,
197 time_to_sleep: Res<TimeToSleep>,
198 time: Res<Time>,
199) {
200 let length_unit_squared = length_unit.0 * length_unit.0;
201 let delta_secs = time.delta_secs();
202
203 islands.split_candidate_sleep_timer = 0.0;
204
205 for (mut sleep_timer, sleep_threshold, solver_body, island_data) in query.iter_mut() {
207 let lin_vel_squared = solver_body.linear_velocity.length_squared();
208 #[cfg(feature = "2d")]
209 let ang_vel_squared = solver_body.angular_velocity * solver_body.angular_velocity;
210 #[cfg(feature = "3d")]
211 let ang_vel_squared = solver_body.angular_velocity.length_squared();
212
213 let lin_threshold_squared = sleep_threshold.linear * sleep_threshold.linear.abs();
215 let ang_threshold_squared = sleep_threshold.angular * sleep_threshold.angular.abs();
216
217 if lin_vel_squared < length_unit_squared * lin_threshold_squared as Scalar
218 && ang_vel_squared < ang_threshold_squared as Scalar
219 {
220 sleep_timer.0 += delta_secs;
222 } else {
223 sleep_timer.0 = 0.0;
225 }
226
227 if sleep_timer.0 < time_to_sleep.0 {
228 awake_island_bit_vec.set_and_grow(island_data.island_id.0 as usize);
230 } else if let Some(island) = islands.get(island_data.island_id)
231 && island.constraints_removed > 0
232 {
233 if sleep_timer.0 > islands.split_candidate_sleep_timer {
235 islands.split_candidate = Some(island_data.island_id);
237 islands.split_candidate_sleep_timer = sleep_timer.0;
238 }
239 }
240 }
241}
242
243fn sleep_islands(
244 mut awake_island_bit_vec: ResMut<AwakeIslandBitVec>,
245 mut islands: ResMut<PhysicsIslands>,
246 mut commands: Commands,
247 mut sleep_buffer: Local<Vec<IslandId>>,
248 mut wake_buffer: Local<Vec<IslandId>>,
249) {
250 sleep_buffer.clear();
252 wake_buffer.clear();
253
254 for island in islands.iter_mut() {
256 if awake_island_bit_vec.get(island.id.0 as usize) {
257 if island.is_sleeping {
258 wake_buffer.push(island.id);
259 }
260 } else if !island.is_sleeping && island.constraints_removed == 0 {
261 sleep_buffer.push(island.id);
263 }
264 }
265
266 let sleep_buffer = sleep_buffer.clone();
268 commands.queue(|world: &mut World| {
269 SleepIslands(sleep_buffer).apply(world);
270 });
271
272 let wake_buffer = wake_buffer.clone();
274 commands.queue(|world: &mut World| {
275 WakeIslands(wake_buffer).apply(world);
276 });
277
278 awake_island_bit_vec.set_bit_count_and_clear(islands.len());
280}
281
282#[derive(Resource)]
283struct CachedBodySleepingSystemState(
284 SystemState<(
285 SQuery<&'static mut BodyIslandNode, Or<(With<Disabled>, Without<Disabled>)>>,
286 SQuery<&'static RigidBodyColliders>,
287 SResMut<PhysicsIslands>,
288 SResMut<ContactGraph>,
289 SResMut<JointGraph>,
290 )>,
291);
292
293pub struct SleepBody(pub Entity);
295
296impl Command for SleepBody {
297 fn apply(self, world: &mut World) {
298 if let Some(island_id) = world
299 .get::<BodyIslandNode>(self.0)
300 .map(|node| node.island_id)
301 {
302 world.try_resource_scope(|world, mut state: Mut<CachedBodySleepingSystemState>| {
303 let (
304 mut body_islands,
305 body_colliders,
306 mut islands,
307 mut contact_graph,
308 mut joint_graph,
309 ) = state.0.get_mut(world);
310
311 let Some(island) = islands.get_mut(island_id) else {
312 return;
313 };
314
315 if island.constraints_removed > 0 {
318 islands.split_island(
319 island_id,
320 &mut body_islands,
321 &body_colliders,
322 &mut contact_graph,
323 &mut joint_graph,
324 );
325 }
326
327 let island_id = body_islands.get(self.0).map(|node| node.island_id).unwrap();
330
331 SleepIslands(vec![island_id]).apply(world);
333 });
334 } else {
335 warn!("Tried to sleep body {:?} that does not exist", self.0);
336 }
337 }
338}
339
340#[derive(Resource)]
341struct CachedIslandSleepingSystemState(
342 SystemState<(
343 SQuery<(
344 &'static BodyIslandNode,
345 &'static mut SleepTimer,
346 Option<&'static RigidBodyColliders>,
347 )>,
348 SResMut<PhysicsIslands>,
349 SResMut<ContactGraph>,
350 SResMut<ConstraintGraph>,
351 )>,
352);
353
354pub struct SleepIslands(pub Vec<IslandId>);
356
357impl Command for SleepIslands {
358 fn apply(self, world: &mut World) {
359 world.try_resource_scope(|world, mut state: Mut<CachedIslandSleepingSystemState>| {
360 let (bodies, mut islands, mut contact_graph, mut constraint_graph) =
361 state.0.get_mut(world);
362
363 let mut bodies_to_sleep = Vec::<(Entity, Sleeping)>::new();
364
365 for island_id in self.0 {
366 if let Some(island) = islands.get_mut(island_id) {
367 if island.is_sleeping {
368 return;
370 }
371
372 island.is_sleeping = true;
373
374 let mut body = island.head_body;
375
376 while let Some(entity) = body {
377 let Ok((body_island, _, colliders)) = bodies.get(entity) else {
378 body = None;
379 continue;
380 };
381
382 if let Some(colliders) = colliders {
384 for collider in colliders {
385 contact_graph.sleep_entity_with(collider, |graph, contact_pair| {
386 if !contact_pair.is_touching()
388 || !contact_pair.generates_constraints()
389 {
390 return;
391 }
392 let contact_edge = graph
393 .get_edge_mut_by_id(contact_pair.contact_id)
394 .unwrap_or_else(|| {
395 panic!(
396 "Contact edge with id {:?} not found in contact graph.",
397 contact_pair.contact_id
398 )
399 });
400 if let (Some(body1), Some(body2)) =
401 (contact_pair.body1, contact_pair.body2)
402 {
403 for _ in 0..contact_edge.constraint_handles.len() {
404 constraint_graph.pop_manifold(
405 &mut graph.edges,
406 contact_pair.contact_id,
407 body1,
408 body2,
409 );
410 }
411 }
412 });
413 }
414 }
415
416 bodies_to_sleep.push((entity, Sleeping));
417 body = body_island.next;
418 }
419 }
420 }
421
422 world.insert_batch(bodies_to_sleep);
424 });
425 }
426}
427
428#[derive(Resource)]
429struct CachedIslandWakingSystemState(
430 SystemState<(
431 SQuery<(
432 &'static BodyIslandNode,
433 &'static mut SleepTimer,
434 Option<&'static RigidBodyColliders>,
435 )>,
436 SResMut<PhysicsIslands>,
437 SResMut<ContactGraph>,
438 SResMut<ConstraintGraph>,
439 )>,
440);
441
442pub struct WakeBody(pub Entity);
444
445impl Command for WakeBody {
446 fn apply(self, world: &mut World) {
447 if let Some(body_island) = world.get::<BodyIslandNode>(self.0) {
448 WakeIslands(vec![body_island.island_id]).apply(world);
449 } else {
450 warn!("Tried to wake body {:?} that does not exist", self.0);
451 }
452 }
453}
454
455#[deprecated(since = "0.4.0", note = "Renamed to `WakeBody`.")]
457pub struct WakeUpBody(pub Entity);
458
459#[expect(deprecated)]
460impl Command for WakeUpBody {
461 fn apply(self, world: &mut World) {
462 WakeBody(self.0).apply(world);
463 }
464}
465
466pub struct WakeIslands(pub Vec<IslandId>);
468
469impl Command for WakeIslands {
470 fn apply(self, world: &mut World) {
471 world.try_resource_scope(|world, mut state: Mut<CachedIslandWakingSystemState>| {
472 let (mut bodies, mut islands, mut contact_graph, mut constraint_graph) =
473 state.0.get_mut(world);
474
475 let mut bodies_to_wake = Vec::<Entity>::new();
476
477 for island_id in self.0 {
478 if let Some(island) = islands.get_mut(island_id) {
479 if !island.is_sleeping {
480 continue;
482 }
483
484 island.is_sleeping = false;
485
486 let mut body = island.head_body;
487
488 while let Some(entity) = body {
489 let Ok((body_island, mut sleep_timer, colliders)) = bodies.get_mut(entity)
490 else {
491 body = None;
492 continue;
493 };
494
495 if let Some(colliders) = colliders {
497 for collider in colliders {
498 contact_graph.wake_entity_with(collider, |graph, contact_pair| {
499 if !contact_pair.is_touching()
501 || !contact_pair.generates_constraints()
502 {
503 return;
504 }
505 let contact_edge = graph
506 .get_edge_mut_by_id(contact_pair.contact_id)
507 .unwrap_or_else(|| {
508 panic!(
509 "Contact edge with id {:?} not found in contact graph.",
510 contact_pair.contact_id
511 )
512 });
513 for _ in contact_pair.manifolds.iter() {
514 constraint_graph.push_manifold(contact_edge, contact_pair);
515 }
516 });
517 }
518 }
519
520 bodies_to_wake.push(entity);
521 body = body_island.next;
522 sleep_timer.0 = 0.0;
523 }
524 }
525 }
526
527 bodies_to_wake.into_iter().for_each(|entity| {
529 world.entity_mut(entity).remove::<Sleeping>();
530 });
531 });
532 }
533}
534
535#[cfg(feature = "2d")]
536type ConstantForceChanges = Or<(
537 Changed<ConstantForce>,
538 Changed<ConstantTorque>,
539 Changed<ConstantLinearAcceleration>,
540 Changed<ConstantAngularAcceleration>,
541 Changed<ConstantLocalForce>,
542 Changed<ConstantLocalLinearAcceleration>,
543)>;
544#[cfg(feature = "3d")]
545type ConstantForceChanges = Or<(
546 Changed<ConstantForce>,
547 Changed<ConstantTorque>,
548 Changed<ConstantLinearAcceleration>,
549 Changed<ConstantAngularAcceleration>,
550 Changed<ConstantLocalForce>,
551 Changed<ConstantLocalTorque>,
552 Changed<ConstantLocalLinearAcceleration>,
553 Changed<ConstantLocalAngularAcceleration>,
554)>;
555
556fn wake_on_changed(
559 mut query: ParamSet<(
560 Query<
563 (
564 Ref<Position>,
565 Ref<Rotation>,
566 Ref<LinearVelocity>,
567 Ref<AngularVelocity>,
568 Ref<SleepTimer>,
569 &BodyIslandNode,
570 ),
571 (
572 With<Sleeping>,
573 Or<(
574 Changed<Position>,
575 Changed<Rotation>,
576 Changed<LinearVelocity>,
577 Changed<AngularVelocity>,
578 Changed<SleepTimer>,
579 )>,
580 ),
581 >,
582 Query<&BodyIslandNode, Or<(ConstantForceChanges, Changed<GravityScale>)>>,
585 )>,
586 mut awake_island_bit_vec: ResMut<AwakeIslandBitVec>,
587 last_physics_tick: Res<LastPhysicsTick>,
588 system_tick: SystemChangeTick,
589) {
590 let this_run = system_tick.this_run();
591
592 for (pos, rot, lin_vel, ang_vel, sleep_timer, body_island) in &query.p0() {
593 if is_changed_after_tick(pos, last_physics_tick.0, this_run)
594 || is_changed_after_tick(rot, last_physics_tick.0, this_run)
595 || is_changed_after_tick(lin_vel, last_physics_tick.0, this_run)
596 || is_changed_after_tick(ang_vel, last_physics_tick.0, this_run)
597 || is_changed_after_tick(sleep_timer, last_physics_tick.0, this_run)
598 {
599 awake_island_bit_vec.set_and_grow(body_island.island_id.0 as usize);
600 }
601 }
602
603 for body_island in &query.p1() {
604 awake_island_bit_vec.set_and_grow(body_island.island_id.0 as usize);
605 }
606}
607
608fn wake_all_islands(mut commands: Commands, islands: Res<PhysicsIslands>) {
610 let sleeping_islands: Vec<IslandId> = islands
611 .iter()
612 .filter_map(|island| island.is_sleeping.then_some(island.id))
613 .collect();
614
615 if !sleeping_islands.is_empty() {
616 commands.queue(WakeIslands(sleeping_islands));
617 }
618}