ponko 0.0.1

A fast 2D game engine for simulating millions of things: ECS on all cores, hot reload, an in-game inspector, AI-agent control, and a C++ API.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
//! 2D physics with rapier (feature `physics`): rigid bodies and colliders as
//! components, stepped inside the simulation clock.
//!
//! [`Transform2D`] stays the source of truth: set it and the body teleports;
//! dynamic bodies write their new position back after every step.
//! Physics is opt-in per entity, so the million-entity paths (spatial grid,
//! flow fields) stay as fast as before.

use std::sync::mpsc;

use rapier2d::prelude as rp;
use serde::{Deserialize, Serialize};

use crate::collision::{BodyKind, CollisionStarted, CollisionStopped};
use crate::{Ctx, Entity, Transform2D, Vec2, World};

/// Makes an entity a physics body. It also needs a [`Collider`] and a
/// [`Transform2D`].
///
/// ```
/// use ponko::*;
/// let crate_body = RigidBody::dynamic();
/// let wall = RigidBody::fixed();
/// assert_eq!(crate_body.gravity_scale, 1.0);
/// assert_eq!(wall.kind, BodyKind::Fixed);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct RigidBody {
    /// Dynamic, fixed or kinematic.
    pub kind: BodyKind,
    /// 1 normal, 0 floats, negative falls up.
    pub gravity_scale: f32,
    /// Slows movement down over time (air drag); 0 none.
    pub linear_damping: f32,
    /// Slows spinning down over time; 0 none.
    pub angular_damping: f32,
    /// Never rotates (characters).
    pub lock_rotation: bool,
    /// Continuous collision detection: fast bodies (bullets) don't pass
    /// through thin walls. Costs a little more.
    pub ccd: bool,
}

impl Default for RigidBody {
    fn default() -> Self {
        Self::dynamic()
    }
}

impl RigidBody {
    /// A body moved by gravity and collisions.
    #[must_use]
    pub const fn dynamic() -> Self {
        Self {
            kind: BodyKind::Dynamic,
            gravity_scale: 1.0,
            linear_damping: 0.0,
            angular_damping: 0.0,
            lock_rotation: false,
            ccd: false,
        }
    }
    /// A body that never moves.
    #[must_use]
    pub const fn fixed() -> Self {
        Self {
            kind: BodyKind::Fixed,
            ..Self::dynamic()
        }
    }
    /// A body only you move.
    #[must_use]
    pub const fn kinematic() -> Self {
        Self {
            kind: BodyKind::Kinematic,
            ..Self::dynamic()
        }
    }
}

/// Most corners a [`Shape::Polygon`] can have.
pub const MAX_POLYGON_POINTS: usize = 8;

/// A collider's shape, in pixels, centered on the entity (plus
/// [`Collider::offset`]) and turned with it.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum Shape {
    /// A circle.
    Circle {
        /// In pixels.
        radius: f32,
    },
    /// A rectangle `size` wide and high.
    Rect {
        /// Width and height in pixels.
        size: Vec2,
    },
    /// A vertical capsule: `height` between the centers of its round ends.
    Capsule {
        /// Distance between the centers of the round ends, in pixels.
        height: f32,
        /// Radius of the round ends, in pixels.
        radius: f32,
    },
    /// A convex polygon: the convex hull of its corners, in pixels around
    /// the entity's position. Make one with [`Collider::polygon`]; read the
    /// corners with [`Shape::points`].
    Polygon {
        /// The corners; only the first `count` are used.
        points: [Vec2; MAX_POLYGON_POINTS],
        /// How many corners: 3 to [`MAX_POLYGON_POINTS`].
        count: u8,
    },
}

impl Shape {
    /// A polygon's corners (empty for other shapes).
    ///
    /// ```
    /// use ponko::*;
    /// let wedge = Collider::polygon(&[vec2(0.0, 0.0), vec2(40.0, 0.0), vec2(0.0, -20.0)]);
    /// assert_eq!(wedge.shape.points().len(), 3);
    /// assert!(Collider::circle(5.0).shape.points().is_empty());
    /// ```
    #[must_use]
    pub fn points(&self) -> &[Vec2] {
        match self {
            Shape::Polygon { points, count } => &points[..usize::from(*count).min(MAX_POLYGON_POINTS)],
            _ => &[],
        }
    }
}

/// The solid shape of a body, and how it touches others.
///
/// ```
/// use ponko::*;
/// let ball = Collider::circle(8.0).restitution(0.9);
/// let trigger = Collider::rect(vec2(64.0, 64.0)).sensor();
/// assert!(trigger.sensor);
/// assert_eq!(ball.restitution, 0.9);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Collider {
    /// Circle, rectangle, capsule or convex polygon.
    pub shape: Shape,
    /// Mass per square pixel (mass = density × area). Default 1.
    #[serde(default = "one")]
    pub density: f32,
    /// 0 ice, 1 rubber. Default 0.5.
    #[serde(default = "half")]
    pub friction: f32,
    /// Bounciness: 0 none, 1 keeps all its speed. Default 0.
    #[serde(default)]
    pub restitution: f32,
    /// Detects overlaps (sends [`CollisionStarted`]) but doesn't push.
    #[serde(default)]
    pub sensor: bool,
    /// Where the shape sits relative to the entity's position.
    #[serde(default)]
    pub offset: Vec2,
}

// Collider defaults for fields missing from JSON, as in `Collider::of`.
fn one() -> f32 {
    1.0
}
fn half() -> f32 {
    0.5
}

impl Collider {
    fn of(shape: Shape) -> Self {
        Self {
            shape,
            density: 1.0,
            friction: 0.5,
            restitution: 0.0,
            sensor: false,
            offset: Vec2::ZERO,
        }
    }
    /// A circle.
    #[must_use]
    pub fn circle(radius: f32) -> Self {
        Self::of(Shape::Circle { radius })
    }
    /// A rectangle `size` wide and high.
    #[must_use]
    pub fn rect(size: Vec2) -> Self {
        Self::of(Shape::Rect { size })
    }
    /// A vertical capsule (good for characters).
    #[must_use]
    pub fn capsule(height: f32, radius: f32) -> Self {
        Self::of(Shape::Capsule { height, radius })
    }
    /// A convex polygon around the entity's position: the convex hull of
    /// `points` (3 to 8 of them, any order). Ramps, wedges, rocks, ships.
    /// For a concave shape, put convex pieces on separate bodies.
    ///
    /// ```
    /// use ponko::*;
    /// let ramp = Collider::polygon(&[vec2(-50.0, 10.0), vec2(50.0, 10.0), vec2(50.0, -10.0)]);
    /// assert_eq!(ramp.shape.points().len(), 3);
    /// ```
    ///
    /// # Panics
    ///
    /// With fewer than 3 or more than [`MAX_POLYGON_POINTS`] points, or a
    /// point that isn't finite.
    #[must_use]
    #[track_caller]
    pub fn polygon(points: &[Vec2]) -> Self {
        assert!(
            (3..=MAX_POLYGON_POINTS).contains(&points.len()),
            "Collider::polygon: 3 to {MAX_POLYGON_POINTS} points, got {}",
            points.len()
        );
        assert!(
            points.iter().all(|p| p.is_finite()),
            "Collider::polygon: points must be finite"
        );
        let mut corners = [Vec2::ZERO; MAX_POLYGON_POINTS];
        corners[..points.len()].copy_from_slice(points);
        Self::of(Shape::Polygon {
            points: corners,
            count: points.len() as u8,
        })
    }
    /// With this density.
    #[must_use]
    pub fn density(self, density: f32) -> Self {
        Self { density, ..self }
    }
    /// With this friction.
    #[must_use]
    pub fn friction(self, friction: f32) -> Self {
        Self { friction, ..self }
    }
    /// With this bounciness.
    #[must_use]
    pub fn restitution(self, restitution: f32) -> Self {
        Self { restitution, ..self }
    }
    /// As a sensor: reports overlaps, doesn't collide.
    #[must_use]
    pub fn sensor(self) -> Self {
        Self { sensor: true, ..self }
    }
    /// Shifted from the entity's position.
    #[must_use]
    pub fn offset(self, offset: Vec2) -> Self {
        Self { offset, ..self }
    }
}

/// A body's speed, in pixels and radians per second. Read it after a step;
/// write it to set the speed (a jump, a thrown crate, a moving platform).
///
/// ```
/// use ponko::*;
/// let v = Velocity::linear(vec2(0.0, -300.0)); // a jump, y is down
/// assert_eq!(v.angular, 0.0);
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
#[repr(C)] // C sees it as CrabbyVelocity.
pub struct Velocity {
    /// Pixels per second.
    pub linear: Vec2,
    /// Radians per second, clockwise on screen.
    pub angular: f32,
}

impl Velocity {
    /// Moving at `linear`, not spinning.
    #[must_use]
    pub const fn linear(linear: Vec2) -> Self {
        Self { linear, angular: 0.0 }
    }
}

/// What a ray hit.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RayHit {
    /// The entity whose collider was hit.
    pub entity: Entity,
    /// Where the ray hit, in world pixels.
    pub point: Vec2,
    /// The surface's outward direction at `point`.
    pub normal: Vec2,
    /// From the ray's start to `point`.
    pub distance: f32,
}

/// What the world last knew of one body, to notice your changes.
#[derive(Clone, Copy)]
struct Link {
    entity: Entity,
    body: rp::RigidBodyHandle,
    rigid: RigidBody,
    shape: Collider,
    transform: Transform2D,
    velocity: Velocity,
    seen: u64,
}

/// The physics world: `ctx.physics`. Add it to a game with
/// [`Game::physics`](crate::Game::physics); then entities with
/// [`RigidBody`], [`Collider`] and [`Transform2D`] are simulated.
pub struct Physics {
    world: rp::PhysicsWorld,
    /// By entity index.
    links: Vec<Option<Link>>,
    gravity: Vec2,
    step: u64,
    collisions: mpsc::Receiver<rp::CollisionEvent>,
    collector: rp::ChannelEventCollector,
    _forces: mpsc::Receiver<rp::ContactForceEvent>,
    _tears: mpsc::Receiver<rp::SoftBodyTearEvent>,
}

impl Default for Physics {
    fn default() -> Self {
        Self::new(Vec2::ZERO)
    }
}

fn to_rp(v: Vec2) -> rp::Vector {
    rp::Vector::new(v.x, v.y)
}
fn from_rp(v: rp::Vector) -> Vec2 {
    Vec2::new(v.x, v.y)
}

impl Physics {
    /// Physics pulling everything by `gravity` (pixels/s²; y is down, so
    /// `vec2(0.0, 980.0)` falls).
    #[must_use]
    pub fn new(gravity: Vec2) -> Self {
        let (collision_tx, collisions) = mpsc::channel();
        let (force_tx, forces) = mpsc::channel();
        let (tear_tx, tears) = mpsc::channel();
        let mut world = rp::PhysicsWorld::new();
        // Objects are tens of pixels, not about a meter: tells rapier's
        // tolerances what "small" means.
        world.integration_parameters.length_unit = 50.0;
        Self {
            world,
            links: Vec::new(),
            gravity,
            step: 0,
            collisions,
            collector: rp::ChannelEventCollector::new(collision_tx, force_tx, tear_tx),
            _forces: forces,
            _tears: tears,
        }
    }

    /// The pull on every dynamic body.
    pub fn gravity(&self) -> Vec2 {
        self.gravity
    }
    /// Changes the pull on every dynamic body.
    pub fn set_gravity(&mut self, gravity: Vec2) {
        self.gravity = gravity;
    }

    /// How many bodies are simulated.
    pub fn body_count(&self) -> usize {
        self.world.bodies.len()
    }

    fn entity_of(&self, collider: rp::ColliderHandle) -> Option<Entity> {
        self.world
            .colliders
            .get(collider)
            .map(|c| Entity::from_bits(c.user_data as u64))
    }

    /// The first collider a ray from `origin` towards `direction` hits
    /// within `max_distance`. Up to date as of the last physics step.
    ///
    /// ```
    /// use ponko::*;
    /// let world = Game::new("t", 1, 1).physics(Vec2::ZERO).run_headless(1, |ctx| {
    ///     ctx.world.spawn((Transform2D::at(vec2(100.0, 0.0)), RigidBody::fixed(), Collider::circle(10.0)));
    /// });
    /// # let _ = world;
    /// ```
    pub fn cast_ray(&self, origin: Vec2, direction: Vec2, max_distance: f32) -> Option<RayHit> {
        let dir = direction.normalize_or_zero();
        if dir == Vec2::ZERO {
            return None;
        }
        let ray = rp::Ray::new(to_rp(origin), to_rp(dir));
        let (handle, hit) = self
            .world
            .cast_ray_and_get_normal(&ray, max_distance, true, rp::QueryFilter::default())?;
        Some(RayHit {
            entity: self.entity_of(handle)?,
            point: origin + dir * hit.time_of_impact,
            normal: from_rp(hit.normal),
            distance: hit.time_of_impact,
        })
    }

    /// Every entity whose collider contains `point`, into `out` (cleared first).
    pub fn entities_at(&self, point: Vec2, out: &mut Vec<Entity>) {
        out.clear();
        for (handle, _) in self.world.intersect_point(to_rp(point), rp::QueryFilter::default()) {
            out.extend(self.entity_of(handle));
        }
    }

    /// Every entity whose collider overlaps the circle, into `out` (cleared first).
    pub fn entities_in_circle(&self, center: Vec2, radius: f32, out: &mut Vec<Entity>) {
        out.clear();
        let ball = rp::Ball::new(radius);
        let pose = rp::Pose::from_translation(to_rp(center));
        for (handle, _) in self.world.intersect_shape(pose, &ball, rp::QueryFilter::default()) {
            out.extend(self.entity_of(handle));
        }
    }

    /// Pushes a dynamic body once (an explosion, a kick), in mass ×
    /// pixels/s. Returns false if `e` isn't a physics body.
    pub fn apply_impulse(&mut self, e: Entity, impulse: Vec2) -> bool {
        let Some(link) = self.link(e) else { return false };
        let handle = link.body;
        match self.world.bodies.get_mut(handle) {
            Some(body) => {
                body.apply_impulse(to_rp(impulse), true);
                true
            }
            None => false,
        }
    }

    /// The mass of a body (from its collider's density and area).
    pub fn mass(&self, e: Entity) -> Option<f32> {
        let link = self.link(e)?;
        self.world.bodies.get(link.body).map(|b| b.mass())
    }

    fn link(&self, e: Entity) -> Option<&Link> {
        self.links.get(e.index() as usize)?.as_ref().filter(|l| l.entity == e)
    }

    fn insert(&mut self, e: Entity, t: &Transform2D, rigid: RigidBody, shape: Collider, velocity: Velocity) {
        let body = self.world.insert_body(body_of(t, rigid, velocity));
        self.world.insert_collider(collider_of(shape, e), Some(body));
        let i = e.index() as usize;
        if self.links.len() <= i {
            self.links.resize(i + 1, None);
        }
        self.links[i] = Some(Link {
            entity: e,
            body,
            rigid,
            shape,
            transform: *t,
            velocity,
            seen: self.step,
        });
    }

    fn remove(&mut self, i: usize) {
        if let Some(link) = self.links[i].take() {
            self.world.remove_body(link.body);
        }
    }
}

fn body_of(t: &Transform2D, rigid: RigidBody, velocity: Velocity) -> rp::RigidBody {
    let builder = match rigid.kind {
        BodyKind::Dynamic => rp::RigidBodyBuilder::dynamic(),
        BodyKind::Fixed => rp::RigidBodyBuilder::fixed(),
        BodyKind::Kinematic => rp::RigidBodyBuilder::kinematic_velocity_based(),
    };
    let mut builder = builder
        .pose(rp::Pose::new(to_rp(t.position), t.rotation))
        .linvel(to_rp(velocity.linear))
        .angvel(velocity.angular)
        .gravity_scale(rigid.gravity_scale)
        .linear_damping(rigid.linear_damping)
        .angular_damping(rigid.angular_damping)
        .ccd_enabled(rigid.ccd);
    if rigid.lock_rotation {
        builder = builder.lock_rotations();
    }
    builder.build()
}

fn collider_of(c: Collider, e: Entity) -> rp::Collider {
    let builder = match c.shape {
        Shape::Circle { radius } => rp::ColliderBuilder::ball(radius.max(f32::EPSILON)),
        Shape::Rect { size } => {
            rp::ColliderBuilder::cuboid((size.x * 0.5).max(f32::EPSILON), (size.y * 0.5).max(f32::EPSILON))
        }
        Shape::Capsule { height, radius } => {
            rp::ColliderBuilder::capsule_y((height * 0.5).max(0.0), radius.max(f32::EPSILON))
        }
        Shape::Polygon { .. } => {
            let points: Vec<rp::Vector> = c.shape.points().iter().map(|&p| to_rp(p)).collect();
            // All corners on one line: no area, so a sliver of a ball instead.
            rp::ColliderBuilder::convex_hull(&points).unwrap_or_else(|| rp::ColliderBuilder::ball(f32::EPSILON))
        }
    };
    builder
        .density(c.density)
        .friction(c.friction)
        .restitution(c.restitution)
        .sensor(c.sensor)
        .translation(to_rp(c.offset))
        .active_events(rp::ActiveEvents::COLLISION_EVENTS)
        .user_data(u128::from(e.to_bits()))
        .build()
}

/// Sets up `ctx.physics` for a game that uses physics, and makes its
/// components visible to the inspector, saves and agents.
pub(crate) fn start(ctx: &mut Ctx, gravity: Vec2) {
    use crate::WorldReflect;
    ctx.physics = Physics::new(gravity);
    ctx.world.reflect::<RigidBody>();
    ctx.world.reflect::<Collider>();
    ctx.world.reflect::<Velocity>();
}

/// Steps the physics world one simulation tick: picks up new, changed and
/// removed bodies, simulates, writes positions and velocities back, and
/// sends [`CollisionStarted`] / [`CollisionStopped`] events. Added by
/// [`Game::physics`](crate::Game::physics); remove or reorder it like any
/// other system.
pub fn step_physics(ctx: &mut Ctx) {
    let dt = ctx.dt();
    let physics = &mut ctx.physics;
    physics.step += 1;
    sync_into(physics, &mut ctx.world);
    physics.world.gravity = to_rp(physics.gravity);
    physics.world.integration_parameters.dt = dt;
    physics.world.step_with_events(&(), &physics.collector);
    write_back(physics, &mut ctx.world);
    while let Ok(event) = physics.collisions.try_recv() {
        let (a, b, flags, started) = match event {
            rp::CollisionEvent::Started(a, b, f) => (a, b, f, true),
            rp::CollisionEvent::Stopped(a, b, f) => (a, b, f, false),
        };
        let (Some(a), Some(b)) = (physics.entity_of(a), physics.entity_of(b)) else {
            continue;
        };
        let sensor = flags.contains(rp::CollisionEventFlags::SENSOR);
        if started {
            ctx.events.send(CollisionStarted { a, b, sensor });
        } else {
            ctx.events.send(CollisionStopped { a, b, sensor });
        }
    }
}

/// New bodies in, your changes applied, gone ones out.
fn sync_into(physics: &mut Physics, world: &mut World) {
    let step = physics.step;
    world
        .query::<(Entity, &Transform2D, &RigidBody, &Collider, Option<&Velocity>)>()
        .for_each(|(e, t, rigid, shape, velocity)| {
            let i = e.index() as usize;
            let Some(link) = physics
                .links
                .get_mut(i)
                .and_then(Option::as_mut)
                .filter(|l| l.entity == e)
            else {
                if let Some(Some(old)) = physics.links.get(i).copied() {
                    // A recycled index: the old entity's body goes first.
                    physics.world.remove_body(old.body);
                    physics.links[i] = None;
                }
                physics.insert(e, t, *rigid, *shape, velocity.copied().unwrap_or_default());
                return;
            };
            link.seen = step;
            if link.rigid != *rigid || link.shape != *shape {
                // Rare (a door that becomes dynamic, a resized collider): rebuild.
                let current = link.velocity;
                physics.world.remove_body(link.body);
                physics.insert(e, t, *rigid, *shape, velocity.copied().unwrap_or(current));
                return;
            }
            // `bodies.get_mut` marks a body as changed (rapier then redoes its
            // broad phase and wakes it), so only touch bodies you changed.
            if link.transform != *t
                && let Some(body) = physics.world.bodies.get_mut(link.body)
            {
                body.set_position(rp::Pose::new(to_rp(t.position), t.rotation), true);
                link.transform = *t;
            }
            if let Some(&v) = velocity
                && link.velocity != v
                && let Some(body) = physics.world.bodies.get_mut(link.body)
            {
                body.set_linvel(to_rp(v.linear), true);
                body.set_angvel(v.angular, true);
                link.velocity = v;
            }
        });
    // Despawned entities and ones that lost a physics component, in index
    // order so runs stay deterministic.
    for i in 0..physics.links.len() {
        if physics.links[i].is_some_and(|l| l.seen != step) {
            physics.remove(i);
        }
    }
}

fn write_back(physics: &mut Physics, world: &mut World) {
    world
        .query::<(Entity, &mut Transform2D, Option<&mut Velocity>)>()
        .with::<RigidBody>()
        .with::<Collider>()
        .for_each(|(e, t, velocity)| {
            let Some(link) = physics
                .links
                .get_mut(e.index() as usize)
                .and_then(Option::as_mut)
                .filter(|l| l.entity == e)
            else {
                return;
            };
            if link.rigid.kind == BodyKind::Fixed {
                return;
            }
            // A sleeping body hasn't moved since it fell asleep.
            let Some(body) = physics.world.bodies.get(link.body).filter(|b| !b.is_sleeping()) else {
                return;
            };
            t.position = from_rp(body.translation());
            t.rotation = body.rotation().angle();
            link.transform = *t;
            let v = Velocity {
                linear: from_rp(body.linvel()),
                angular: body.angvel(),
            };
            link.velocity = v;
            if let Some(velocity) = velocity {
                *velocity = v;
            }
        });
}