Skip to main content

box2d_rust/contact/
api.rs

1// Contact public API from contact.c / physics_world.c (b2Contact_*).
2// The C resolves the world from the id via the global registry; the Rust
3// port takes `world` explicitly. b2Contact_GetWorld is not ported (there is
4// no world registry).
5//
6// SPDX-FileCopyrightText: 2023 Erin Catto
7// SPDX-License-Identifier: MIT
8
9use super::{get_contact_full_id, get_contact_sim_ref};
10use crate::core::NULL_INDEX;
11use crate::events::ContactData;
12use crate::id::{ContactId, ShapeId};
13use crate::world::World;
14
15/// Contact identifier validation. Provides validation for up to 2^32
16/// allocations. (b2Contact_IsValid — the world-registry check collapses to
17/// the index/generation check in the registry-less port)
18pub fn contact_is_valid(world: &World, id: ContactId) -> bool {
19    let contact_id = id.index1 - 1;
20    if contact_id < 0 || world.contacts.len() as i32 <= contact_id {
21        return false;
22    }
23
24    let contact = &world.contacts[contact_id as usize];
25    if contact.contact_id == NULL_INDEX {
26        // contact is free
27        return false;
28    }
29
30    debug_assert!(contact.contact_id == contact_id);
31
32    id.generation == contact.generation
33}
34
35/// Get the data for a contact. The manifold may have no points if the
36/// contact is not touching. (b2Contact_GetData)
37pub fn contact_get_data(world: &World, contact_id: ContactId) -> ContactData {
38    let id = get_contact_full_id(world, contact_id);
39    let contact = &world.contacts[id as usize];
40    let contact_sim = get_contact_sim_ref(world, id);
41    let shape_a = &world.shapes[contact.shape_id_a as usize];
42    let shape_b = &world.shapes[contact.shape_id_b as usize];
43
44    ContactData {
45        contact_id,
46        shape_id_a: ShapeId {
47            index1: shape_a.id + 1,
48            world0: contact_id.world0,
49            generation: shape_a.generation,
50        },
51        shape_id_b: ShapeId {
52            index1: shape_b.id + 1,
53            world0: contact_id.world0,
54            generation: shape_b.generation,
55        },
56        manifold: contact_sim.manifold,
57    }
58}