Code Monkey home page Code Monkey logo

Comments (6)

rlidwka avatar rlidwka commented on June 20, 2024 1

@JitendraDogra, you need to specify simulation filter shader for your scene, which should return for which pairs physx should return collisions. By default, no collisions are detected.

Here's an example:

use physx::prelude::*;
use physx_sys::{PxPairFlags, PxFilterFlags, FilterShaderCallbackInfo};

type PxMaterial = physx::material::PxMaterial<()>;
type PxShape = physx::shape::PxShape<(), PxMaterial>;
type PxArticulationLink = physx::articulation_link::PxArticulationLink<(), PxShape>;
type PxRigidStatic = physx::rigid_static::PxRigidStatic<(), PxShape>;
type PxRigidDynamic = physx::rigid_dynamic::PxRigidDynamic<(), PxShape>;
type PxArticulationReducedCoordinate =
    physx::articulation_reduced_coordinate::PxArticulationReducedCoordinate<(), PxArticulationLink>;
type PxScene = physx::scene::PxScene<
    (),
    PxArticulationLink,
    PxRigidStatic,
    PxRigidDynamic,
    PxArticulationReducedCoordinate,
    OnCollision,
    OnTrigger,
    OnConstraintBreak,
    OnWakeSleep,
    OnAdvance>;

struct OnCollision;
impl CollisionCallback for OnCollision {
    fn on_collision(
        &mut self,
        _header: &physx_sys::PxContactPairHeader,
        _pairs: &[physx_sys::PxContactPair],
    ) {
         println!("collision occured");
    }
}
struct OnTrigger;
impl TriggerCallback for OnTrigger {
    fn on_trigger(&mut self, _pairs: &[physx_sys::PxTriggerPair]) {}
}

struct OnConstraintBreak;
impl ConstraintBreakCallback for OnConstraintBreak {
    fn on_constraint_break(&mut self, _constraints: &[physx_sys::PxConstraintInfo]) {}
}
struct OnWakeSleep;
impl WakeSleepCallback<PxArticulationLink, PxRigidStatic, PxRigidDynamic> for OnWakeSleep {
    fn on_wake_sleep(
        &mut self,
        _actors: &[&physx::actor::ActorMap<PxArticulationLink, PxRigidStatic, PxRigidDynamic>],
        _is_waking: bool,
    ) {
    }
}

struct OnAdvance;
impl AdvanceCallback<PxArticulationLink, PxRigidDynamic> for OnAdvance {
    fn on_advance(
        &self,
        _actors: &[&physx::rigid_body::RigidBodyMap<PxArticulationLink, PxRigidDynamic>],
        _transforms: &[PxTransform],
    ) {
    }
}

unsafe extern "C" fn simulation_filter_shader(s: *mut FilterShaderCallbackInfo) -> PxFilterFlags {
    let s = &mut *s as &mut FilterShaderCallbackInfo;
    let pair_flags = &mut *(s.pairFlags) as &mut PxPairFlags;

    *pair_flags = PxPairFlags::SolveContact |
        PxPairFlags::DetectDiscreteContact |
        PxPairFlags::NotifyTouchFound |
        //PxPairFlags::NotifyTouchLost |
        PxPairFlags::NotifyContactPoints;

    PxFilterFlags::empty()
}

fn main() {
    // Holds a PxFoundation and a PxPhysics.
    // Also has an optional Pvd and transport, not enabled by default.
    // The default allocator is the one provided by PhysX.
    let mut physics = PhysicsFoundation::<_, PxShape>::default();

    // Setup the scene object.  The PxScene type alias makes this much cleaner.
    // There are lots of unwrap calls due to potential null pointers.
    let mut scene: Owner<PxScene> = physics
        .create(SceneDescriptor {
            gravity: PxVec3::new(0.0, -9.81, 0.0),
            on_collide: Some(OnCollision),
            on_advance: Some(OnAdvance),
            simulation_filter_shader: FilterShaderDescriptor::CallDefaultFirst(simulation_filter_shader),
            ..SceneDescriptor::new(())
        })
        .unwrap();

    let mut material = physics.create_material(0.5, 0.5, 0.6, ()).unwrap();

    let ground_plane = physics
        .create_plane(PxVec3::new(0.0, 1.0, 0.0), 0.0, material.as_mut(), ())
        .unwrap();
    // The scene owns actors that are added to it.  They can be retrieved using the
    // various getters on the scene.
    scene.add_static_actor(ground_plane);

    let sphere_geo = PxSphereGeometry::new(10.0);

    let mut sphere_actor = physics
        .create_rigid_dynamic(
            PxTransform::from_translation(&PxVec3::new(0.0, 40.0, 100.0)),
            &sphere_geo,
            material.as_mut(),
            10.0,
            PxTransform::default(),
            (),
        )
        .unwrap();
    sphere_actor.set_angular_damping(0.5);
    sphere_actor.set_rigid_body_flag(RigidBodyFlag::EnablePoseIntegrationPreview, true);
    scene.add_dynamic_actor(sphere_actor);

    // SAFETY: scratch buffer creation
    #[allow(unsafe_code)]
    let mut scratch = unsafe { ScratchBuffer::new(4) };

    // Updating
    let heights_over_time = (0..100)
        .map(|_| {
            // Calls both simulate and fetch_results.  More complex simulation update
            // controls are not fully supported.
            scene
                .step(
                    0.1,
                    None::<&mut physx_sys::PxBaseTask>,
                    Some(&mut scratch),
                    true,
                )
                .expect("error occured during simulation");
            // For simplicity, just read out the only dynamic actor in the scene.
            // getActiveActors is also supported, it returns a Vec<&mut ActorMap> which has
            // a map method that takes a function for each actor type, and `as_<T>` methods
            // that return an Option<&mut T>.
            let actors = scene.get_dynamic_actors();
            actors[0].get_global_position().y() as i32 - 10
        })
        .collect::<Vec<_>>();

    // Draw to stdout
    let max_h = 18;
    (0..max_h)
        .map(|h| {
            let h = max_h - 1 - h;
            heights_over_time
                .iter()
                .enumerate()
                .map(|(_t, p)| if h == *p { 'o' } else { ' ' })
                .collect::<String>()
        })
        .for_each(|line| println!("{}", line));
}

from physx-rs.

tgolsson avatar tgolsson commented on June 20, 2024

Hey @JitendraDogra!

I think this is a configuration issue; but right now I can't recall the details. Can you see if adding a second ball above the first one gets you any contacts reported when the balls collide?

from physx-rs.

JitendraDogra avatar JitendraDogra commented on June 20, 2024

@tgolsson and @rlidwka thanks for response i was also looking into simulation filter shader but doing some mistakes i guess and getting errors but i will surely try @rlidwka solution on Monday .

from physx-rs.

JitendraDogra avatar JitendraDogra commented on June 20, 2024

@tgolsson and @rlidwka thanks for response i was also looking into simulation filter shader but doing some mistakes i guess and getting errors but i will surely try @rlidwka solution on Monday .

@rlidwka So it is working fine now but can you tell me if there is any documentation for physx-rs where i can find some examples of uses because currently so many things are there which are not clear for me for example how should i use "userData" field, many different objects like PxScene , PxRigidDynamic etc have it also how i can perform an operation in on_collision callback when there is a specific actor/object is in collision pairs. And thanks again for your time and assistance.

from physx-rs.

rlidwka avatar rlidwka commented on June 20, 2024

So it is working fine now but can you tell me if there is any documentation for physx-rs

You can look up the documentation for PhysX (https://nvidia-omniverse.github.io/PhysX/physx/5.2.1/), that's the most comprehensive source of documentation out there.

from physx-rs.

tgolsson avatar tgolsson commented on June 20, 2024

Closing this for now, feel free to open new issues if you run into any more problems.

from physx-rs.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.