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
use crate::{
    owner::Owner,
    traits::{Class, UserData},
};

use std::marker::PhantomData;

use enumflags2::{bitflags, BitFlags};

use physx_sys::{
    PxCombineMode,
    PxMaterialFlags,
    PxMaterial_acquireReference_mut,
    PxMaterial_getDynamicFriction,
    PxMaterial_getFlags,
    PxMaterial_getFrictionCombineMode,
    PxMaterial_getReferenceCount,
    PxMaterial_getRestitution,
    PxMaterial_getRestitutionCombineMode,
    PxMaterial_getStaticFriction,
    PxMaterial_release_mut,
    PxMaterial_setDynamicFriction_mut,
    PxMaterial_setFlag_mut,
    PxMaterial_setFlags_mut,
    PxMaterial_setFrictionCombineMode_mut,
    PxMaterial_setRestitutionCombineMode_mut,
    PxMaterial_setRestitution_mut,
    PxMaterial_setStaticFriction_mut,
    //PxMaterial_getConcreteTypeName,
};

#[bitflags]
#[derive(Copy, Clone, Debug)]
#[repr(u16)]
pub enum MaterialFlag {
    DisableFriction = 1 << 0,
    DisableStrongFriction = 1 << 1,
    ImprovedPatchFriction = 1 << 2,
}

pub type MaterialFlags = BitFlags<MaterialFlag>;

/// Determines how the restitution and friction properties of materials are combined
/// to produce the coefficients for that interaction.
#[derive(Copy, Clone, Debug)]
#[repr(u32)]
pub enum CombineMode {
    Average = 0,
    Min = 1,
    Multiply = 2,
    Max = 3,
    //NValues, // These are not valid variants, and they don't need to be defined in Rust
    //Pad32,
}

impl From<PxCombineMode::Enum> for CombineMode {
    fn from(mode: PxCombineMode::Enum) -> Self {
        match mode {
            PxCombineMode::eAVERAGE => CombineMode::Average,
            PxCombineMode::eMIN => CombineMode::Min,
            PxCombineMode::eMULTIPLY => CombineMode::Multiply,
            PxCombineMode::eMAX => CombineMode::Max,
            _ => unreachable!("Invalid enum variant: {:?}.", mode),
        }
    }
}

/// A new type wrapper for PxMaterial.  Parametrized by it's user data type.
#[repr(transparent)]
pub struct PxMaterial<U> {
    pub(crate) obj: physx_sys::PxMaterial,
    phantom_user_data: PhantomData<U>,
}

unsafe impl<U> UserData for PxMaterial<U> {
    type UserData = U;

    fn user_data_ptr(&self) -> &*mut std::ffi::c_void {
        &self.obj.userData
    }

    fn user_data_ptr_mut(&mut self) -> &mut *mut std::ffi::c_void {
        &mut self.obj.userData
    }
}

impl<U> Drop for PxMaterial<U> {
    fn drop(&mut self) {
        unsafe {
            PxMaterial_release_mut(self.as_mut_ptr());
        }
    }
}

unsafe impl<P, U> Class<P> for PxMaterial<U>
where
    physx_sys::PxMaterial: Class<P>,
{
    fn as_ptr(&self) -> *const P {
        self.obj.as_ptr()
    }

    fn as_mut_ptr(&mut self) -> *mut P {
        self.obj.as_mut_ptr()
    }
}

unsafe impl<U: Send> Send for PxMaterial<U> {}
unsafe impl<U: Sync> Sync for PxMaterial<U> {}

impl<M> Material for PxMaterial<M> {}

pub trait Material: Class<physx_sys::PxMaterial> + UserData {
    /// # Safety
    /// Owner's own the pointer they wrap, using the pointer after dropping the Owner,
    /// or creating multiple Owners from the same pointer will cause UB.  Use `into_ptr` to
    /// retrieve the pointer and consume the Owner without dropping the pointee.
    unsafe fn from_raw(
        ptr: *mut physx_sys::PxMaterial,
        user_data: Self::UserData,
    ) -> Option<Owner<Self>> {
        Owner::from_raw((ptr as *mut Self).as_mut()?.init_user_data(user_data))
    }

    /// Get a reference to the user data.
    #[inline]
    fn get_user_data(&self) -> &Self::UserData {
        // Safety: all constructors go through from_raw which calls init_user_data
        unsafe { UserData::get_user_data(self) }
    }

    /// Get a mutable reference to the user data.
    #[inline]
    fn get_user_data_mut(&mut self) -> &mut Self::UserData {
        // Safety: all constructors go through from_raw which calls init_user_data
        unsafe { UserData::get_user_data_mut(self) }
    }

    /// Get the current ref count of the material.
    #[inline]
    fn get_reference_count(&self) -> u32 {
        unsafe { PxMaterial_getReferenceCount(self.as_ptr()) }
    }

    /// Increment the ref count of the material.
    #[inline]
    fn acquire_reference(&mut self) {
        unsafe { PxMaterial_acquireReference_mut(self.as_mut_ptr()) }
    }

    /// Set the dynamic friction.
    /// - Friction must be positive.
    /// - If greater than static friction, effective static friction will be increased to match.
    /// - Will not wake actors.
    #[inline]
    fn set_dynamic_friction(&mut self, mut coefficient: f32) {
        if coefficient.is_sign_negative() {
            coefficient = 0.0;
        }
        unsafe {
            PxMaterial_setDynamicFriction_mut(self.as_mut_ptr(), coefficient);
        }
    }

    /// Get the dynamic friction.
    #[inline]
    fn get_dynamic_friction(&self) -> f32 {
        unsafe { PxMaterial_getDynamicFriction(self.as_ptr()) }
    }

    /// Set the static friction.
    /// - Friction must be positive, negative friction is set to 0.0.
    /// - Will not wake actors.
    #[inline]
    fn set_static_friction(&mut self, mut coefficient: f32) {
        if coefficient.is_sign_negative() {
            coefficient = 0.0;
        }
        unsafe {
            PxMaterial_setStaticFriction_mut(self.as_mut_ptr(), coefficient);
        }
    }

    /// Get the static frction.
    #[inline]
    fn get_static_friction(&self) -> f32 {
        unsafe { PxMaterial_getStaticFriction(self.as_ptr()) }
    }

    /// Set the restitution.
    /// - Restitution must be in [0.0 ..= 1.0], values outside tyhe range are clamped.
    /// - A reitution of 0.0 minimizes bouncing, higher values mean more bounce.
    #[inline]
    fn set_restitution(&mut self, mut restitution: f32) {
        if restitution.is_sign_negative() {
            restitution = 0.0;
        } else if restitution > 1.0 {
            restitution = 1.0
        };
        unsafe {
            PxMaterial_setRestitution_mut(self.as_mut_ptr(), restitution);
        }
    }

    /// Get the restitution.
    #[inline]
    fn get_restitution(&self) -> f32 {
        unsafe { PxMaterial_getRestitution(self.as_ptr()) }
    }

    /// Set a material flag.
    #[inline]
    fn set_flag(&mut self, flag: MaterialFlag, set: bool) {
        unsafe { PxMaterial_setFlag_mut(self.as_mut_ptr(), flag as _, set) }
    }

    /// Set all the material flags.
    #[inline]
    fn set_flags(&mut self, flags: MaterialFlags) {
        unsafe {
            PxMaterial_setFlags_mut(
                self.as_mut_ptr(),
                PxMaterialFlags {
                    mBits: flags.bits(),
                },
            );
        }
    }

    /// Get the material flags.
    #[inline]
    fn get_flags(&self) -> MaterialFlags {
        unsafe {
            let PxMaterialFlags { mBits } = PxMaterial_getFlags(self.as_ptr());
            BitFlags::from_bits_unchecked(mBits)
        }
    }

    /// Set the friction combine mode.
    #[inline]
    fn set_friction_combined_mode(&mut self, combine_mode: CombineMode) {
        unsafe {
            PxMaterial_setFrictionCombineMode_mut(self.as_mut_ptr(), combine_mode as _);
        }
    }

    /// Get the friction combine mode.
    #[inline]
    fn get_friction_combine_mode(&self) -> CombineMode {
        let combine_mode = unsafe { PxMaterial_getFrictionCombineMode(self.as_ptr()) };
        debug_assert!(combine_mode < PxCombineMode::eN_VALUES);
        combine_mode.into()
    }

    /// Set the restitution combine mode.
    #[inline]
    fn set_restitution_combine_mode(&mut self, combine_mode: CombineMode) {
        unsafe {
            PxMaterial_setRestitutionCombineMode_mut(self.as_mut_ptr(), combine_mode as _);
        }
    }

    /// Get the restitution combine mode.
    #[inline]
    fn get_restitution_combine_mode(&self) -> CombineMode {
        let combine_mode = unsafe { PxMaterial_getRestitutionCombineMode(self.as_ptr()) };
        debug_assert!(combine_mode < PxCombineMode::eN_VALUES);
        combine_mode.into()
    }
}