boxddd 0.4.0

Safe, ergonomic Rust bindings for Box3D
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
use super::creation_transaction::{
    BodyNative, NativeCreationInput, ShapeNative, finish_native_creation, observed_shape_parent,
};
use super::ledger::{BodyResource, PendingResource, PendingShape, WorldLedger};
use super::*;
use crate::types::Transform;

#[derive(Clone, Copy)]
enum ExpectedShapeType {
    Exact(ShapeType),
    CapsuleOrSphere,
}

enum ShapeCreation<'a> {
    Sphere(&'a Sphere),
    BoxHull(&'a BoxHull),
    Capsule(&'a Capsule),
    Hull(&'a Hull),
    TransformedHull {
        hull: &'a Hull,
        transform: Transform,
        scale: Vec3,
    },
    Mesh {
        scale: Vec3,
    },
    HeightField,
    Compound,
}

impl ExpectedShapeType {
    fn accepts(self, observed: Option<ShapeType>) -> bool {
        match self {
            Self::Exact(expected) => observed == Some(expected),
            Self::CapsuleOrSphere => {
                matches!(observed, Some(ShapeType::Capsule | ShapeType::Sphere))
            }
        }
    }
}

struct ShapeBackingGuard<'a> {
    backing: Option<ShapeResource>,
    owner_poisoned: &'a Cell<bool>,
    quarantine: &'a mut Vec<ShapeResource>,
}

struct ShapeFinishContext<'a, 'owner> {
    target_world: ffi::b3WorldId,
    poisoned: &'a Cell<bool>,
    ledger: &'a mut WorldLedger,
    backing: &'a mut ShapeBackingGuard<'owner>,
}

impl<'a> ShapeBackingGuard<'a> {
    fn new(
        backing: Option<ShapeResource>,
        owner_poisoned: &'a Cell<bool>,
        quarantine: &'a mut Vec<ShapeResource>,
    ) -> Self {
        Self {
            backing,
            owner_poisoned,
            quarantine,
        }
    }

    fn slot(&mut self) -> &mut Option<ShapeResource> {
        &mut self.backing
    }

    fn resource(&self) -> Option<&ShapeResource> {
        self.backing.as_ref()
    }
}

impl Drop for ShapeBackingGuard<'_> {
    fn drop(&mut self) {
        if (self.owner_poisoned.get() || std::thread::panicking())
            && let Some(backing) = self.backing.take()
        {
            debug_assert!(self.quarantine.len() < self.quarantine.capacity());
            self.quarantine.push(backing);
        }
    }
}

impl World {
    /// Tries to create a body in this world.
    pub fn create_body(&mut self, def: BodyDef) -> Result<BodyId> {
        callback_state::check_not_in_callback()?;
        self.check_owner_healthy()?;
        let expected_type = def.body_type;
        let prepared = def.prepare()?;
        let pending = self.state_mut().ledger.reserve_body()?;
        let _call = self.enter_call()?;
        self.check_world_valid()?;
        let raw = prepared.create(self.raw());
        self.finish_body_creation(raw, pending, expected_type)
    }

    /// Tries to attach a sphere shape to a body.
    pub fn create_sphere_shape(
        &mut self,
        body_id: BodyId,
        def: &ShapeDef,
        sphere: &Sphere,
    ) -> Result<ShapeId> {
        callback_state::check_not_in_callback()?;
        self.check_owner_healthy()?;
        let prepared = def.prepare(ShapeMaterialUsage::BaseOnly)?;
        sphere.validate()?;
        let pending = self.state_mut().ledger.reserve_shape(body_id)?;
        self.create_shape_from_prepared(
            body_id,
            prepared,
            pending,
            None,
            ExpectedShapeType::Exact(ShapeType::Sphere),
            ShapeCreation::Sphere(sphere),
        )
    }

    /// Tries to attach a box-hull shape to a body.
    pub fn create_hull_shape(
        &mut self,
        body_id: BodyId,
        def: &ShapeDef,
        hull: &BoxHull,
    ) -> Result<ShapeId> {
        callback_state::check_not_in_callback()?;
        self.check_owner_healthy()?;
        let prepared = def.prepare(ShapeMaterialUsage::BaseOnly)?;
        let pending = self.state_mut().ledger.reserve_shape(body_id)?;
        self.create_shape_from_prepared(
            body_id,
            prepared,
            pending,
            None,
            ExpectedShapeType::Exact(ShapeType::Hull),
            ShapeCreation::BoxHull(hull),
        )
    }

    /// Tries to attach a capsule shape to a body.
    pub fn create_capsule_shape(
        &mut self,
        body_id: BodyId,
        def: &ShapeDef,
        capsule: &Capsule,
    ) -> Result<ShapeId> {
        callback_state::check_not_in_callback()?;
        self.check_owner_healthy()?;
        let prepared = def.prepare(ShapeMaterialUsage::BaseOnly)?;
        capsule.validate()?;
        let pending = self.state_mut().ledger.reserve_shape(body_id)?;
        self.create_shape_from_prepared(
            body_id,
            prepared,
            pending,
            None,
            ExpectedShapeType::CapsuleOrSphere,
            ShapeCreation::Capsule(capsule),
        )
    }

    /// Tries to attach an owned convex hull resource to a body.
    pub fn create_created_hull_shape(
        &mut self,
        body_id: BodyId,
        def: &ShapeDef,
        hull: &Hull,
    ) -> Result<ShapeId> {
        callback_state::check_not_in_callback()?;
        self.check_owner_healthy()?;
        let prepared = def.prepare(ShapeMaterialUsage::BaseOnly)?;
        let pending = self.state_mut().ledger.reserve_shape(body_id)?;
        self.create_shape_from_prepared(
            body_id,
            prepared,
            pending,
            None,
            ExpectedShapeType::Exact(ShapeType::Hull),
            ShapeCreation::Hull(hull),
        )
    }

    /// Tries to attach a transformed owned convex hull resource to a body.
    pub fn create_transformed_hull_shape(
        &mut self,
        body_id: BodyId,
        def: &ShapeDef,
        hull: &Hull,
        transform: impl Into<crate::types::Transform>,
        scale: impl Into<Vec3>,
    ) -> Result<ShapeId> {
        callback_state::check_not_in_callback()?;
        self.check_owner_healthy()?;
        let prepared = def.prepare(ShapeMaterialUsage::BaseOnly)?;
        let transform = transform.into();
        transform.validate()?;
        let scale = scale.into().validate()?;
        let pending = self.state_mut().ledger.reserve_shape(body_id)?;
        self.create_shape_from_prepared(
            body_id,
            prepared,
            pending,
            None,
            ExpectedShapeType::Exact(ShapeType::Hull),
            ShapeCreation::TransformedHull {
                hull,
                transform,
                scale,
            },
        )
    }

    /// Tries to attach a triangle mesh shape to a static body.
    pub fn create_mesh_shape(
        &mut self,
        body_id: BodyId,
        def: &ShapeDef,
        mesh: MeshData,
        scale: impl Into<Vec3>,
    ) -> Result<ShapeId> {
        callback_state::check_not_in_callback()?;
        self.check_owner_healthy()?;
        let prepared = def.prepare(ShapeMaterialUsage::PerTriangle)?;
        let scale = validate_mesh_scale(scale.into())?;
        if self.body_type(body_id)? != BodyType::Static {
            return Err(validation::invalid(
                "mesh_shape.body_type",
                crate::error::InvalidValueReason::InvalidCombination,
            ));
        }
        let pending = self.state_mut().ledger.reserve_shape(body_id)?;
        self.create_shape_from_prepared(
            body_id,
            prepared,
            pending,
            Some(ShapeResource::Mesh { _data: mesh }),
            ExpectedShapeType::Exact(ShapeType::Mesh),
            ShapeCreation::Mesh { scale },
        )
    }

    /// Tries to attach a height-field shape to a static body.
    pub fn create_height_field_shape(
        &mut self,
        body_id: BodyId,
        def: &ShapeDef,
        height_field: HeightField,
    ) -> Result<ShapeId> {
        callback_state::check_not_in_callback()?;
        self.check_owner_healthy()?;
        let prepared = def.prepare(ShapeMaterialUsage::PerTriangle)?;
        if self.body_type(body_id)? != BodyType::Static {
            return Err(validation::invalid(
                "height_field_shape.body_type",
                crate::error::InvalidValueReason::InvalidCombination,
            ));
        }
        let pending = self.state_mut().ledger.reserve_shape(body_id)?;
        self.create_shape_from_prepared(
            body_id,
            prepared,
            pending,
            Some(ShapeResource::HeightField {
                _data: height_field,
            }),
            ExpectedShapeType::Exact(ShapeType::HeightField),
            ShapeCreation::HeightField,
        )
    }

    /// Tries to attach a compound shape to a static body.
    pub fn create_compound_shape(
        &mut self,
        body_id: BodyId,
        def: &ShapeDef,
        compound: Compound,
    ) -> Result<ShapeId> {
        callback_state::check_not_in_callback()?;
        self.check_owner_healthy()?;
        let prepared = def.prepare(ShapeMaterialUsage::BaseOnly)?;
        if def.sensor {
            return Err(validation::invalid(
                "compound_shape.sensor",
                crate::error::InvalidValueReason::InvalidCombination,
            ));
        }
        if self.body_type(body_id)? != BodyType::Static {
            return Err(validation::invalid(
                "compound_shape.body_type",
                crate::error::InvalidValueReason::InvalidCombination,
            ));
        }
        let pending = self.state_mut().ledger.reserve_shape(body_id)?;
        self.create_shape_from_prepared(
            body_id,
            prepared,
            pending,
            Some(ShapeResource::Compound { _data: compound }),
            ExpectedShapeType::Exact(ShapeType::Compound),
            ShapeCreation::Compound,
        )
    }

    fn create_shape_from_prepared(
        &mut self,
        body_id: BodyId,
        prepared: PreparedShapeDef<'_>,
        pending: PendingShape,
        backing: Option<ShapeResource>,
        expected_type: ExpectedShapeType,
        creation: ShapeCreation<'_>,
    ) -> Result<ShapeId> {
        if backing.is_some() {
            self.state_mut()
                .backing_quarantine
                .try_reserve(1)
                .map_err(|_| Error::AllocationFailed)?;
        }
        let _call = self.enter_body_call(body_id)?;
        let update_body_mass = prepared.update_body_mass();
        let target_world = self.raw();
        let WorldState {
            poisoned,
            ledger,
            backing_quarantine,
            ..
        } = self.state_mut();
        let mut backing = ShapeBackingGuard::new(backing, poisoned, backing_quarantine);
        let raw_body = body_id.into_raw();
        let raw = match creation {
            ShapeCreation::Sphere(sphere) => prepared.create_sphere(raw_body, sphere),
            ShapeCreation::BoxHull(hull) => prepared.create_box_hull(raw_body, hull),
            ShapeCreation::Capsule(capsule) => prepared.create_capsule(raw_body, capsule),
            ShapeCreation::Hull(hull) => prepared.create_hull(raw_body, hull),
            ShapeCreation::TransformedHull {
                hull,
                transform,
                scale,
            } => prepared.create_transformed_hull(raw_body, hull, transform, scale),
            ShapeCreation::Mesh { scale } => {
                let Some(ShapeResource::Mesh { _data: mesh }) = backing.resource() else {
                    unreachable!("mesh creation requires mesh backing")
                };
                prepared.create_mesh(raw_body, mesh, scale)
            }
            ShapeCreation::HeightField => {
                let Some(ShapeResource::HeightField {
                    _data: height_field,
                }) = backing.resource()
                else {
                    unreachable!("height-field creation requires height-field backing")
                };
                prepared.create_height_field(raw_body, height_field)
            }
            ShapeCreation::Compound => {
                let Some(ShapeResource::Compound { _data: compound }) = backing.resource() else {
                    unreachable!("compound creation requires compound backing")
                };
                prepared.create_compound(raw_body, compound)
            }
        };
        let result = finish_shape_creation(
            ShapeFinishContext {
                target_world,
                poisoned,
                ledger,
                backing: &mut backing,
            },
            raw,
            pending,
            update_body_mass,
            expected_type,
        );
        drop(_call);
        drop(backing);
        result
    }

    fn finish_body_creation(
        &mut self,
        raw: ffi::b3BodyId,
        pending: PendingResource<BodyResource>,
        expected_type: BodyType,
    ) -> Result<BodyId> {
        let target_world = self.raw();
        let WorldState {
            poisoned, ledger, ..
        } = self.state_mut();
        let identity = ledger.classify_body(raw);
        finish_native_creation::<BodyNative, _, _, _>(
            NativeCreationInput::new(raw, (), target_world, poisoned, identity),
            ledger,
            |ledger, raw, available| ledger.bind_body(raw, available, pending),
            |_, raw| {
                if BodyType::from_raw(unsafe { ffi::b3Body_GetType(raw) }) == Some(expected_type) {
                    Ok(())
                } else {
                    Err(Error::NativeFailure)
                }
            },
            |ledger, _, bound| ledger.publish_body(bound),
        )
    }
}

fn finish_shape_creation(
    context: ShapeFinishContext<'_, '_>,
    raw: ffi::b3ShapeId,
    pending: PendingShape,
    update_body_mass: bool,
    expected_type: ExpectedShapeType,
) -> Result<ShapeId> {
    let ShapeFinishContext {
        target_world,
        poisoned,
        ledger,
        backing,
    } = context;
    let identity = ledger.classify_shape(raw);
    let mut context = (ledger, backing);
    finish_native_creation::<ShapeNative, _, _, _>(
        NativeCreationInput::new(raw, update_body_mass, target_world, poisoned, identity),
        &mut context,
        |context, raw, available| {
            let (ledger, _) = context;
            ledger.validate_shape_binding(&pending, observed_shape_parent(raw))?;
            ledger.bind_shape(raw, available, pending)
        },
        |_, raw| {
            if expected_type.accepts(ShapeType::from_raw(unsafe { ffi::b3Shape_GetType(raw) })) {
                Ok(())
            } else {
                Err(Error::NativeFailure)
            }
        },
        |context, _, bound| {
            let (ledger, backing) = context;
            ledger.publish_shape(bound, backing.slot())
        },
    )
}