bevy_boxdd 0.5.0

Bevy integration for the boxdd Rust bindings to Box2D
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
//! Bevy ECS components used to author and observe Box2D physics objects.

use bevy_ecs::prelude::{Component, Entity};
use bevy_math::Vec2 as BevyVec2;
use boxdd::{
    ApiError, ApiResult, BodyId, BodyType, Filter, JointId, MotionLocks, ShapeDef, ShapeId,
    SurfaceMaterial,
};

/// Maximum number of vertices accepted by [`Collider::ConvexPolygon`].
pub const MAX_COLLIDER_POLYGON_VERTICES: usize = boxdd::MAX_POLYGON_VERTICES;

/// Body type to create for an entity that participates in the physics world.
#[derive(Component, Copy, Clone, Debug, Default, Eq, PartialEq)]
pub enum RigidBody {
    /// Immovable body used for terrain, walls, and other non-simulated geometry.
    Static,
    /// App-controlled body that can move but is not affected by gravity.
    Kinematic,
    /// Fully simulated body affected by gravity, contacts, joints, and forces.
    #[default]
    Dynamic,
}

impl From<RigidBody> for BodyType {
    fn from(value: RigidBody) -> Self {
        match value {
            RigidBody::Static => BodyType::Static,
            RigidBody::Kinematic => BodyType::Kinematic,
            RigidBody::Dynamic => BodyType::Dynamic,
        }
    }
}

/// Runtime body tuning applied to the native Box2D body.
///
/// This component is optional. Values are applied at body creation and reapplied
/// when the component changes.
#[derive(Component, Copy, Clone, Debug, PartialEq)]
pub struct BodySettings {
    /// Gravity multiplier applied to this body.
    pub gravity_scale: f32,
    /// Linear damping applied by Box2D.
    pub linear_damping: f32,
    /// Angular damping applied by Box2D.
    pub angular_damping: f32,
    /// Whether the body is allowed to sleep.
    pub sleep_enabled: bool,
    /// Whether the body uses bullet-style continuous collision handling.
    pub bullet: bool,
    /// Per-axis translation and rotation locks.
    pub motion_locks: MotionLocks,
}

impl BodySettings {
    /// Creates settings that mark a body as a bullet for continuous collision.
    pub fn bullet() -> Self {
        Self {
            bullet: true,
            ..Default::default()
        }
    }

    /// Validates finite tuning values before applying them.
    pub fn validate(self) -> ApiResult<()> {
        validate_scalar(self.gravity_scale)?;
        validate_nonnegative_scalar(self.linear_damping)?;
        validate_nonnegative_scalar(self.angular_damping)
    }
}

impl Default for BodySettings {
    fn default() -> Self {
        Self {
            gravity_scale: 1.0,
            linear_damping: 0.0,
            angular_damping: 0.0,
            sleep_enabled: true,
            bullet: false,
            motion_locks: MotionLocks::default(),
        }
    }
}

/// Shape descriptor used to create a Box2D shape for a body entity.
///
/// A collider may live on the same entity as [`RigidBody`] or on a child entity.
/// Child collider transforms are interpreted as local offsets from the parent
/// body entity.
#[derive(Component, Copy, Clone, Debug, PartialEq)]
pub enum Collider {
    /// Circle collider.
    Circle {
        /// Circle radius in local Bevy units.
        radius: f32,
        /// Local-space center relative to the body.
        center: BevyVec2,
    },
    /// Capsule collider between two local-space endpoints.
    Capsule {
        /// First endpoint of the capsule segment in local space.
        point1: BevyVec2,
        /// Second endpoint of the capsule segment in local space.
        point2: BevyVec2,
        /// Capsule radius around the segment.
        radius: f32,
    },
    /// Line segment collider. This is normally used on static bodies.
    Segment {
        /// First endpoint in local space.
        point1: BevyVec2,
        /// Second endpoint in local space.
        point2: BevyVec2,
    },
    /// Axis-aligned box collider, optionally transformed by the collider entity.
    Rectangle {
        /// Positive half extents in local space.
        half_extents: BevyVec2,
    },
    /// Rounded box collider.
    RoundedRectangle {
        /// Positive half extents in local space.
        half_extents: BevyVec2,
        /// Non-negative skin radius.
        radius: f32,
    },
    /// Convex polygon built from up to [`MAX_COLLIDER_POLYGON_VERTICES`] points.
    ConvexPolygon {
        /// Local vertices. Only the first `count` entries are used.
        vertices: [BevyVec2; MAX_COLLIDER_POLYGON_VERTICES],
        /// Number of active vertices.
        count: u8,
        /// Non-negative skin radius.
        radius: f32,
    },
}

impl Collider {
    /// Creates a circle collider centered on the body origin.
    pub const fn circle(radius: f32) -> Self {
        Self::Circle {
            radius,
            center: BevyVec2::ZERO,
        }
    }

    /// Creates a circle collider with a local-space center.
    pub const fn circle_at(center: BevyVec2, radius: f32) -> Self {
        Self::Circle { radius, center }
    }

    /// Creates a rectangle collider from half extents.
    pub const fn rectangle(half_width: f32, half_height: f32) -> Self {
        Self::Rectangle {
            half_extents: BevyVec2::new(half_width, half_height),
        }
    }

    /// Creates a square collider from one half extent.
    pub const fn square(half_extent: f32) -> Self {
        Self::Rectangle {
            half_extents: BevyVec2::splat(half_extent),
        }
    }

    /// Creates a rounded rectangle collider from half extents and skin radius.
    pub const fn rounded_rectangle(half_width: f32, half_height: f32, radius: f32) -> Self {
        Self::RoundedRectangle {
            half_extents: BevyVec2::new(half_width, half_height),
            radius,
        }
    }

    /// Creates a capsule oriented along the local Y axis.
    pub const fn capsule_y(half_height: f32, radius: f32) -> Self {
        Self::Capsule {
            point1: BevyVec2::new(0.0, -half_height),
            point2: BevyVec2::new(0.0, half_height),
            radius,
        }
    }

    /// Creates a segment collider from two local endpoints.
    pub const fn segment(point1: BevyVec2, point2: BevyVec2) -> Self {
        Self::Segment { point1, point2 }
    }

    /// Creates a convex polygon collider from local-space vertices.
    pub fn convex_polygon<I>(points: I, radius: f32) -> ApiResult<Self>
    where
        I: IntoIterator<Item = BevyVec2>,
    {
        let mut vertices = [BevyVec2::ZERO; MAX_COLLIDER_POLYGON_VERTICES];
        let mut count = 0usize;
        for point in points {
            if count == MAX_COLLIDER_POLYGON_VERTICES {
                return Err(ApiError::InvalidArgument);
            }
            vertices[count] = point;
            count += 1;
        }

        if count == 0 || count > u8::MAX as usize {
            return Err(ApiError::InvalidArgument);
        }

        let collider = Self::ConvexPolygon {
            vertices,
            count: count as u8,
            radius,
        };
        collider.validate()?;
        Ok(collider)
    }

    /// Validates finite, positive collider parameters before native shape creation.
    pub fn validate(self) -> ApiResult<()> {
        match self {
            Self::Circle { radius, center } => {
                validate_vec2(center)?;
                validate_positive_scalar(radius)
            }
            Self::Capsule {
                point1,
                point2,
                radius,
            } => {
                validate_vec2(point1)?;
                validate_vec2(point2)?;
                validate_distinct_points(point1, point2)?;
                validate_positive_scalar(radius)
            }
            Self::Segment { point1, point2 } => {
                validate_vec2(point1)?;
                validate_vec2(point2)?;
                validate_distinct_points(point1, point2)
            }
            Self::Rectangle { half_extents } => validate_positive_vec2(half_extents),
            Self::RoundedRectangle {
                half_extents,
                radius,
            } => {
                validate_positive_vec2(half_extents)?;
                validate_nonnegative_scalar(radius)
            }
            Self::ConvexPolygon {
                vertices,
                count,
                radius,
            } => {
                let count = count as usize;
                if count == 0 || count > MAX_COLLIDER_POLYGON_VERTICES {
                    return Err(ApiError::InvalidArgument);
                }
                validate_nonnegative_scalar(radius)?;
                for point in &vertices[..count] {
                    validate_vec2(*point)?;
                }
                Ok(())
            }
        }
    }
}

/// Shape material and event flags used when creating a collider shape.
#[derive(Component, Copy, Clone, Debug, PartialEq)]
pub struct PhysicsMaterial {
    /// Shape density passed to Box2D.
    pub density: f32,
    /// Shape friction passed to Box2D.
    pub friction: f32,
    /// Shape restitution passed to Box2D.
    pub restitution: f32,
    /// Shape rolling resistance passed to Box2D.
    pub rolling_resistance: f32,
    /// Shape tangent speed passed to Box2D.
    pub tangent_speed: f32,
    /// User material id passed through Box2D events and callbacks.
    pub user_material_id: u64,
    /// Whether the shape is a sensor.
    pub is_sensor: bool,
    /// Enables contact begin/end messages for this shape.
    pub enable_contact_events: bool,
    /// Enables sensor begin/end messages for this shape.
    pub enable_sensor_events: bool,
    /// Enables contact hit messages for this shape.
    pub enable_hit_events: bool,
    /// Enables pre-solve events for advanced users.
    pub enable_pre_solve_events: bool,
    /// Box2D collision filter data.
    pub filter: Filter,
}

impl PhysicsMaterial {
    /// Converts the component into the `boxdd` shape definition used by the plugin.
    pub fn shape_def(self) -> ShapeDef {
        let material = SurfaceMaterial::default()
            .with_friction(self.friction)
            .with_restitution(self.restitution)
            .with_rolling_resistance(self.rolling_resistance)
            .with_tangent_speed(self.tangent_speed)
            .with_user_material_id(self.user_material_id);

        ShapeDef::builder()
            .material(material)
            .density(self.density)
            .sensor(self.is_sensor)
            .enable_contact_events(self.enable_contact_events)
            .enable_sensor_events(self.enable_sensor_events)
            .enable_hit_events(self.enable_hit_events)
            .enable_pre_solve_events(self.enable_pre_solve_events)
            .filter(self.filter)
            .build()
    }

    /// Validates finite material fields before shape creation.
    pub fn validate(self) -> ApiResult<()> {
        validate_nonnegative_scalar(self.density)?;
        self.shape_def().validate()
    }
}

impl Default for PhysicsMaterial {
    fn default() -> Self {
        Self {
            density: 1.0,
            friction: 0.6,
            restitution: 0.0,
            rolling_resistance: 0.0,
            tangent_speed: 0.0,
            user_material_id: 0,
            is_sensor: false,
            enable_contact_events: false,
            enable_sensor_events: false,
            enable_hit_events: false,
            enable_pre_solve_events: false,
            filter: Filter::default(),
        }
    }
}

/// Native Box2D body id inserted after the plugin creates a body.
#[derive(Component, Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct BoxddBody(pub BodyId);

impl BoxddBody {
    /// Returns the native Box2D body id.
    pub const fn id(self) -> BodyId {
        self.0
    }
}

/// Native Box2D shape id inserted after the plugin creates a shape.
#[derive(Component, Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct BoxddShape(pub ShapeId);

impl BoxddShape {
    /// Returns the native Box2D shape id.
    pub const fn id(self) -> ShapeId {
        self.0
    }
}

/// Joint descriptor used to connect two Bevy body entities with a native Box2D joint.
#[derive(Component, Copy, Clone, Debug, PartialEq)]
pub struct JointDescriptor {
    /// First body entity connected by the joint.
    pub entity_a: Entity,
    /// Second body entity connected by the joint.
    pub entity_b: Entity,
    /// Joint-specific settings.
    pub kind: JointKind,
    /// Whether the connected bodies are allowed to collide.
    pub collide_connected: bool,
    /// Force threshold used for native joint events.
    pub force_threshold: f32,
    /// Torque threshold used for native joint events.
    pub torque_threshold: f32,
    /// Shared constraint tuning frequency in Hertz.
    pub constraint_hertz: f32,
    /// Shared constraint damping ratio.
    pub constraint_damping_ratio: f32,
    /// Debug draw scale used by Box2D debug drawing.
    pub draw_scale: f32,
}

impl JointDescriptor {
    /// Creates a distance joint descriptor using world-space anchors.
    pub const fn distance(
        entity_a: Entity,
        entity_b: Entity,
        anchor_a: BevyVec2,
        anchor_b: BevyVec2,
    ) -> Self {
        Self::new(
            entity_a,
            entity_b,
            JointKind::Distance(DistanceJointDescriptor {
                anchor_a,
                anchor_b,
                length: None,
            }),
        )
    }

    /// Creates a revolute joint descriptor using a world-space anchor.
    pub const fn revolute(entity_a: Entity, entity_b: Entity, anchor: BevyVec2) -> Self {
        Self::new(
            entity_a,
            entity_b,
            JointKind::Revolute(RevoluteJointDescriptor { anchor }),
        )
    }

    /// Creates a descriptor from a joint kind and default shared tuning.
    pub const fn new(entity_a: Entity, entity_b: Entity, kind: JointKind) -> Self {
        Self {
            entity_a,
            entity_b,
            kind,
            collide_connected: false,
            force_threshold: f32::MAX,
            torque_threshold: f32::MAX,
            constraint_hertz: 60.0,
            constraint_damping_ratio: 2.0,
            draw_scale: 1.0,
        }
    }

    /// Sets whether connected bodies should collide with each other.
    pub const fn with_collide_connected(mut self, flag: bool) -> Self {
        self.collide_connected = flag;
        self
    }

    /// Sets force and torque thresholds used for native joint events.
    pub const fn with_event_thresholds(mut self, force: f32, torque: f32) -> Self {
        self.force_threshold = force;
        self.torque_threshold = torque;
        self
    }

    /// Sets the shared native constraint tuning.
    pub const fn with_constraint_tuning(mut self, hertz: f32, damping_ratio: f32) -> Self {
        self.constraint_hertz = hertz;
        self.constraint_damping_ratio = damping_ratio;
        self
    }

    /// Sets the native debug-draw scale for this joint.
    pub const fn with_draw_scale(mut self, scale: f32) -> Self {
        self.draw_scale = scale;
        self
    }

    /// Validates finite descriptor values before native joint creation.
    pub fn validate(self) -> ApiResult<()> {
        if self.entity_a == self.entity_b {
            return Err(ApiError::InvalidArgument);
        }
        validate_nonnegative_scalar(self.force_threshold)?;
        validate_nonnegative_scalar(self.torque_threshold)?;
        validate_positive_scalar(self.constraint_hertz)?;
        validate_nonnegative_scalar(self.constraint_damping_ratio)?;
        validate_positive_scalar(self.draw_scale)?;
        self.kind.validate()
    }
}

/// Supported ECS-authored joint kinds.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum JointKind {
    /// Distance joint between two world-space anchors.
    Distance(DistanceJointDescriptor),
    /// Revolute joint around one world-space anchor.
    Revolute(RevoluteJointDescriptor),
}

impl JointKind {
    fn validate(self) -> ApiResult<()> {
        match self {
            Self::Distance(descriptor) => descriptor.validate(),
            Self::Revolute(descriptor) => descriptor.validate(),
        }
    }
}

/// Distance joint authoring data.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct DistanceJointDescriptor {
    /// World-space anchor on body A.
    pub anchor_a: BevyVec2,
    /// World-space anchor on body B.
    pub anchor_b: BevyVec2,
    /// Optional target length. When omitted, the distance between anchors is used.
    pub length: Option<f32>,
}

impl DistanceJointDescriptor {
    /// Sets an explicit target length.
    pub const fn with_length(mut self, length: f32) -> Self {
        self.length = Some(length);
        self
    }

    fn validate(self) -> ApiResult<()> {
        validate_vec2(self.anchor_a)?;
        validate_vec2(self.anchor_b)?;
        if let Some(length) = self.length {
            validate_positive_scalar(length)?;
        }
        Ok(())
    }
}

/// Revolute joint authoring data.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct RevoluteJointDescriptor {
    /// World-space hinge anchor.
    pub anchor: BevyVec2,
}

impl RevoluteJointDescriptor {
    fn validate(self) -> ApiResult<()> {
        validate_vec2(self.anchor)
    }
}

/// Native Box2D joint id inserted after the plugin creates a joint.
#[derive(Component, Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct BoxddJoint(pub JointId);

impl BoxddJoint {
    /// Returns the native Box2D joint id.
    pub const fn id(self) -> JointId {
        self.0
    }
}

/// Direction used when synchronizing Bevy and Box2D transforms.
#[derive(Component, Copy, Clone, Debug, Default, Eq, PartialEq)]
pub enum TransformSyncMode {
    /// Read the Box2D transform after stepping and write it into Bevy.
    #[default]
    PhysicsToBevy,
    /// Read the Bevy transform before stepping and write it into Box2D.
    BevyToPhysics,
    /// Disable automatic transform synchronization for this entity.
    None,
}

/// Linear velocity command applied to a body before each physics step.
#[derive(Component, Copy, Clone, Debug, Default, PartialEq)]
pub struct LinearVelocity(pub BevyVec2);

/// Angular velocity command applied to a body before each physics step.
#[derive(Component, Copy, Clone, Debug, Default, PartialEq)]
pub struct AngularVelocity(pub f32);

/// One-shot linear impulse applied at the body center before the next physics step.
#[derive(Component, Copy, Clone, Debug, PartialEq)]
pub struct LinearImpulse {
    /// Impulse vector in physics units.
    pub impulse: BevyVec2,
    /// Whether applying the impulse should wake a sleeping body.
    pub wake: bool,
}

impl LinearImpulse {
    /// Creates a one-shot impulse that wakes the body.
    pub const fn new(impulse: BevyVec2) -> Self {
        Self {
            impulse,
            wake: true,
        }
    }
}

/// One-shot angular impulse applied before the next physics step.
#[derive(Component, Copy, Clone, Debug, PartialEq)]
pub struct AngularImpulse {
    /// Angular impulse in physics units.
    pub impulse: f32,
    /// Whether applying the impulse should wake a sleeping body.
    pub wake: bool,
}

impl AngularImpulse {
    /// Creates a one-shot angular impulse that wakes the body.
    pub const fn new(impulse: f32) -> Self {
        Self {
            impulse,
            wake: true,
        }
    }
}

fn validate_vec2(value: BevyVec2) -> ApiResult<()> {
    if value.is_finite() {
        Ok(())
    } else {
        Err(ApiError::InvalidArgument)
    }
}

fn validate_scalar(value: f32) -> ApiResult<()> {
    if value.is_finite() {
        Ok(())
    } else {
        Err(ApiError::InvalidArgument)
    }
}

fn validate_positive_scalar(value: f32) -> ApiResult<()> {
    if value.is_finite() && value > 0.0 {
        Ok(())
    } else {
        Err(ApiError::InvalidArgument)
    }
}

fn validate_nonnegative_scalar(value: f32) -> ApiResult<()> {
    if value.is_finite() && value >= 0.0 {
        Ok(())
    } else {
        Err(ApiError::InvalidArgument)
    }
}

fn validate_positive_vec2(value: BevyVec2) -> ApiResult<()> {
    if value.is_finite() && value.x > 0.0 && value.y > 0.0 {
        Ok(())
    } else {
        Err(ApiError::InvalidArgument)
    }
}

fn validate_distinct_points(a: BevyVec2, b: BevyVec2) -> ApiResult<()> {
    if a.distance_squared(b) > 0.0 {
        Ok(())
    } else {
        Err(ApiError::InvalidArgument)
    }
}