Beispiel #1
0
        unsafe public override void SetShapePairFlags(Shape shape1, Shape shape2, ShapePairFlags flags)
        {
            base.SetShapePairFlags(shape1, shape2, flags);

            Body body1 = shape1.Body;
            Body body2 = shape2.Body;

            if (body1.PushedToWorld && body2.PushedToWorld)
            {
                PhysXBody physXBody1 = (PhysXBody)body1;
                PhysXBody physXBody2 = (PhysXBody)body2;

                if (physXBody1.nativeBody != IntPtr.Zero && physXBody2.nativeBody != IntPtr.Zero)
                {
                    PhysXBody.ShapeData shapeData1 = physXBody1.shapesData[shape1.BodyIndex];
                    PhysXBody.ShapeData shapeData2 = physXBody2.shapesData[shape2.BodyIndex];

                    bool disableContacts = (flags & ShapePairFlags.DisableContacts) != 0;

                    foreach (IntPtr nativeShape1 in shapeData1.nativeShapes)
                    {
                        foreach (IntPtr nativeShape2 in shapeData2.nativeShapes)
                        {
                            PhysXNativeScene.SetShapePairFlags(physXBody1.scene.nativeScene, nativeShape1, nativeShape2,
                                                               disableContacts);
                        }
                    }
                }
            }
        }
Beispiel #2
0
    // Start is called before the first frame update.
    void Start()
    {
        myRb = GetComponent <PhysXRigidBody>();

        meshstateTracker = FindObjectOfType <MeshstateTracker>();

        deformableMeshes = new List <DeformableMesh>(GetComponentsInChildren <DeformableMesh>());
        DeformableMesh.Subdivide(deformableMeshes[0].maxEdgeLength, deformableMeshes[0].GetMeshFilter().mesh);
        vertices = new List <Vector3>(deformableMeshes[0].GetMeshFilter().mesh.vertices);

        //  Group similar vertices.
        meshGraph = meshstateTracker.GetMyMeshGraph(meshType);

        originalMesh          = Instantiate(deformableMeshes[0].GetMeshFilter().mesh);
        collisionResolver     = Instantiate(collisionResolver);
        resolverBody          = collisionResolver.GetComponent <PhysXBody>();
        resolverBody.position = new Vector3(0, 10000, 0);

        interfaceCar = GetComponent <InterfaceCarDrive4W>();
        if (interfaceCar != null)
        {
            frWheel            = interfaceCar.frontRightW;
            frWheelVertexGroup = NearestVertexTo(frWheel.transform.position);
            flWheel            = interfaceCar.frontLeftW;
            flWheelVertexGroup = NearestVertexTo(flWheel.transform.position);
            rrWheel            = interfaceCar.rearRightW;
            rrWheelVertexGroup = NearestVertexTo(rrWheel.transform.position);
            rlWheel            = interfaceCar.rearLeftW;
            rlWheelVertexGroup = NearestVertexTo(rlWheel.transform.position);
        }

        teamId = GetComponent <NetworkPlayerVehicle>().teamId;
    }
Beispiel #3
0
        public void UpdatePhysXJoint()
        {
            bool needCreate = PushedToWorld && !Broken;
            bool created    = nativeJoint != IntPtr.Zero;

            if (needCreate == created)
            {
                return;
            }

            if (needCreate)
            {
                if (Axis.LimitsEnabled && Axis.LimitLow > Axis.LimitHigh)
                {
                    Log.Warning("HingeJoint: Invalid axis limits (low > high).");
                    return;
                }

                PhysXBody physXBody0 = (PhysXBody)Body1;
                PhysXBody physXBody1 = (PhysXBody)Body2;

                if ((!physXBody0.Static || !physXBody1.Static) &&
                    (physXBody0.nativeBody != IntPtr.Zero && physXBody1.nativeBody != IntPtr.Zero))
                {
                    Quat globalAxisRotation = Quat.FromDirectionZAxisUp(Axis.Direction);
                    Vec3 localPosition0     = physXBody0.Rotation.GetInverse() * (Anchor - physXBody0.Position);
                    Quat localRotation0     = (physXBody0.Rotation.GetInverse() * globalAxisRotation).GetNormalize();
                    Vec3 localPosition1     = physXBody1.Rotation.GetInverse() * (Anchor - physXBody1.Position);
                    Quat localRotation1     = (physXBody1.Rotation.GetInverse() * globalAxisRotation).GetNormalize();

                    nativeJoint = PhysXNativeWrapper.PhysXNativeHingeJoint.Create(
                        physXBody0.nativeBody, ref localPosition0, ref localRotation0,
                        physXBody1.nativeBody, ref localPosition1, ref localRotation1);

                    UpdateLimits();

                    if (ContactsEnabled)
                    {
                        PhysXNativeWrapper.PhysXJoint.SetCollisionEnable(nativeJoint, true);
                    }
                    UpdatePhysXBreakData();
                    if (Scene._EnableDebugVisualization)
                    {
                        SetVisualizationEnable(true);
                    }

                    //PhysXNativeWrapper.PhysXJoint.SetProjectionEnable( nativeJoint, true );
                    //desc->projectionMode = NxJointProjectionMode.NX_JPM_POINT_MINDIST;
                    //desc->projectionDistance = 0.1f;
                    //desc->projectionAngle = new Radian( new Degree( 3 ) );

                    initialRelativeRotationInverse = (physXBody1.Rotation * physXBody0.Rotation.GetInverse()).GetInverse();
                }
            }
            else
            {
                DestroyPhysXJoint();
            }
        }
    // Start is called before the first frame update
    public override void Setup(PhysXBody attachedRigidBody, uint vehicleId)
    {
        IntPtr geom = PhysXLib.CreateSphereGeometry(radius);

        shape = PhysXLib.CreateShape(geom, physXMaterial, 0.02f);

        base.Setup(attachedRigidBody, vehicleId);
    }
Beispiel #5
0
        // public float distance { get; private set; }

        // public Transform transform { get; private set; }

        internal void PopulateFields(IntPtr vehicle, int wheelNum)
        {
            IntPtr    hitActor = PhysXLib.GetGroundHitActor(vehicle, wheelNum);
            PhysXBody body     = PhysXSceneManager.GetBodyFromPointer(hitActor);

            IntPtr shape = PhysXLib.GetGroundHitShape(vehicle, wheelNum);

            collider = body.GetColliderFromShape(shape);

            PhysXLib.GetGroundHitPosition(vehicle, wheelNum, _pxpoint);
            _pxpoint.ToVector(ref _point);
        }
Beispiel #6
0
        protected override void OnSimulationStep()
        {
            //Vehicles

            // Take a simulation step.
            PhysXNativeScene.Simulate(nativeScene, StepSize);

            // Fetch simulation results
            if (!PhysXNativeScene.FetchResults(nativeScene, true))
            {
                Log.Fatal("PhysXPhysicsScene: OnSimulationStep: Error while PhysX fetching results.");
            }

            //we can get list of not sleeping bodies from PhysX.
            //joints too?
            //update from PhysX
            foreach (Body body in Bodies)
            {
                PhysXBody physXBody = (PhysXBody)body;
                if (!body.Static)
                {
                    physXBody.UpdateDataFromLibrary();
                }
            }

            foreach (IPhysXJoint joint in Joints)
            {
                joint.UpdateDataFromLibrary();
            }

            if (EnableCollisionEvents)
            {
                IntPtr contactList;
                int    contactCount;
                PhysXNativeScene.GetContactReportList(nativeScene, out contactList, out contactCount);
                unsafe
                {
                    ContactReport *pContact = (ContactReport *)contactList;
                    for (int n = 0; n < contactCount; n++)
                    {
                        Shape shape1       = PhysXPhysicsWorld.Instance.GetShapeByIdentifier(pContact->shapeIndex1);
                        Shape shape2       = PhysXPhysicsWorld.Instance.GetShapeByIdentifier(pContact->shapeIndex2);
                        Vec3  contactPoint = pContact->contactPoint;
                        Vec3  normal       = pContact->normal;
                        AddCollisionEvent(shape1, shape2, ref contactPoint, ref normal, -pContact->separation);
                        pContact++;
                    }
                }
            }
        }
Beispiel #7
0
 public void AddActor(PhysXBody body)
 {
     if (scene == IntPtr.Zero)
     {
         preRegisteredBodies.Add(body);
     }
     else
     {
         body.Setup();
         bodies.Add(body.physXBody.ToInt64(), body);
         PhysXLib.AddActorToScene(scene, body.physXBody);
         body.PostSceneInsertionSetup();
     }
 }
Beispiel #8
0
    public void Simulate()
    {
        if (doPhysics)
        {
            PhysXLib.StepPhysics(scene, Time.fixedDeltaTime, scratchMem, scratchKilobytes * 1024);

            foreach (PhysXBody body in bodies.Values)
            {
                body.UpdatePositionAndVelocity();
            }

            collisionCallbackMarker.Begin();
            foreach (PhysXCollision collision in PhysXSceneManager.ongoingCollisions)
            {
                collision.PopulateWithUnityObjects(bodies);
                PhysXBody body = null;
                if (bodies.TryGetValue(collision.self.ToInt64(), out body))
                {
                    try {
                        body.FireCollisionEvents(collision);
                    }
                    catch (Exception e) {
                        Debug.LogError("Exception: " + e.Message + "\n" + e.StackTrace);
                    }
                }
                PhysXCollision.ReleaseCollision(collision);
            }
            PhysXSceneManager.ongoingCollisions.Clear();

            foreach (PhysXTrigger trigger in PhysXSceneManager.ongoingTriggers)
            {
                trigger.PopulateWithUnityObjects(bodies);
                PhysXBody body = null;
                if (bodies.TryGetValue(trigger.self.ToInt64(), out body))
                {
                    try {
                        body.FireTriggerEvents(trigger);
                    }
                    catch (Exception e) {
                        Debug.LogError("Exception: " + e.Message + "\n" + e.StackTrace);
                    }
                }
                PhysXTrigger.ReleaseTrigger(trigger);
            }
            PhysXSceneManager.ongoingTriggers.Clear();
            collisionCallbackMarker.End();

            PhysXLib.StepGhostPhysics(scene, Time.fixedDeltaTime, scratchMem, scratchKilobytes * 1024);
        }
    }
Beispiel #9
0
        internal void PopulateFields()
        {
            IntPtr    hitActor = PhysXLib.GetRaycastHitActor(physXRaycastHit);
            PhysXBody body     = PhysXSceneManager.GetBodyFromPointer(hitActor);

            transform = body.transform;

            IntPtr shape = PhysXLib.GetRaycastHitShape(physXRaycastHit);

            collider = body.GetColliderFromShape(shape);

            distance = PhysXLib.GetRaycastHitDistance(physXRaycastHit);

            PhysXLib.GetRaycastHitNormal(physXRaycastHit, _pxnormal);
            _pxnormal.ToVector(ref _normal);

            PhysXLib.GetRaycastHitPoint(physXRaycastHit, _pxpoint);
            _pxpoint.ToVector(ref _point);
        }
Beispiel #10
0
    // Start is called before the first frame update
    public virtual void Setup(PhysXBody attachedRigidBody, uint vehicleId)
    {
        this.attachedRigidBody = attachedRigidBody as PhysXRigidBody;
        Transform bodyParent = attachedRigidBody.transform;

        PhysXVec3 position = new PhysXVec3(bodyParent.InverseTransformPoint(transform.TransformPoint(offset)));
        PhysXQuat rotation = new PhysXQuat(transform.rotation * Quaternion.Inverse(bodyParent.rotation));

        IntPtr localTransform = PhysXLib.CreateTransform(position, rotation);

        PhysXLib.SetShapeLocalTransform(shape, localTransform);

        PhysXLib.SetShapeSimulationFlag(shape, !trigger);
        PhysXLib.SetShapeSceneQueryFlag(shape, !trigger);
        PhysXLib.SetShapeTriggerFlag(shape, trigger);

        PhysXLib.CollisionEvent collisionEventFlags = attachedRigidBody.collisionEventFlags;
        PhysXLib.SetCollisionFilterData(shape, (UInt32)ownLayers, (UInt32)collisionLayers, (UInt32)collisionEventFlags, vehicleId);
        PhysXLib.SetQueryFilterData(shape, (UInt32)ownLayers, 0, 0, vehicleId);
        shapeNum = attachedRigidBody.AddCollider(this);
    }
        public void UpdatePhysXJoint()
        {
            bool needCreate = PushedToWorld && !Broken;
            bool created    = nativeJoint != IntPtr.Zero;

            if (needCreate == created)
            {
                return;
            }

            if (needCreate)
            {
                PhysXBody physXBody0 = (PhysXBody)Body1;
                PhysXBody physXBody1 = (PhysXBody)Body2;

                if ((!physXBody0.Static || !physXBody1.Static) &&
                    (physXBody0.nativeBody != IntPtr.Zero && physXBody1.nativeBody != IntPtr.Zero))
                {
                    Vec3 localPosition0 = physXBody0.Rotation.GetInverse() * (-physXBody0.Position);
                    Quat localRotation0 = physXBody0.Rotation.GetInverse();
                    Vec3 localPosition1 = physXBody1.Rotation.GetInverse() * (-physXBody1.Position);
                    Quat localRotation1 = physXBody1.Rotation.GetInverse();

                    nativeJoint = PhysXNativeWrapper.PhysXNativeFixedJoint.Create(physXBody0.nativeBody, ref localPosition0,
                                                                                  ref localRotation0, physXBody1.nativeBody, ref localPosition1, ref localRotation1);

                    UpdatePhysXBreakData();

                    if (Scene._EnableDebugVisualization)
                    {
                        SetVisualizationEnable(true);
                    }
                }
            }
            else
            {
                DestroyPhysXJoint();
            }
        }
        void PushToWorld()
        {
            PhysXPhysicsScene scene    = (PhysXPhysicsScene)Scene;
            PhysXBody         baseBody = (PhysXBody)BaseBody;

            IntPtr generalData         = PhysXNativeVehicleInitData.Create();
            IntPtr wheelFrontLeftData  = PhysXNativeVehicleInitData.Create();
            IntPtr wheelFrontRightData = PhysXNativeVehicleInitData.Create();
            IntPtr wheelRearLeftData   = PhysXNativeVehicleInitData.Create();
            IntPtr wheelRearRightData  = PhysXNativeVehicleInitData.Create();

            //Chassis mass
            PhysXNativeVehicleInitData.SetParameter(generalData, "massChassis", InitData.MassChassis);

            //Differential
            PhysXNativeVehicleInitData.SetParameter(generalData, "differentialType", (float)(int)InitData.DifferentialType);
            PhysXNativeVehicleInitData.SetParameter(generalData, "differentialFrontRearSplit", InitData.DifferentialFrontRearSplit);
            PhysXNativeVehicleInitData.SetParameter(generalData, "differentialFrontLeftRightSplit", InitData.DifferentialFrontLeftRightSplit);
            PhysXNativeVehicleInitData.SetParameter(generalData, "differentialRearLeftRightSplit", InitData.DifferentialRearLeftRightSplit);
            PhysXNativeVehicleInitData.SetParameter(generalData, "differentialCenterBias", InitData.DifferentialCenterBias);
            PhysXNativeVehicleInitData.SetParameter(generalData, "differentialFrontBias", InitData.DifferentialFrontBias);
            PhysXNativeVehicleInitData.SetParameter(generalData, "differentialRearBias", InitData.DifferentialRearBias);

            //Engine
            {
                PhysXNativeVehicleInitData.SetParameter(generalData, "enginePeakTorque", InitData.EnginePeakTorque);
                PhysXNativeVehicleInitData.SetParameter(generalData, "engineMaxRPM", InitData.EngineMaxRPM);
                PhysXNativeVehicleInitData.SetParameter(generalData, "engineDampingRateFullThrottle",
                                                        InitData.EngineDampingRateFullThrottle);
                PhysXNativeVehicleInitData.SetParameter(generalData, "engineDampingRateZeroThrottleClutchEngaged",
                                                        InitData.EngineDampingRateZeroThrottleClutchEngaged);
                PhysXNativeVehicleInitData.SetParameter(generalData, "engineDampingRateZeroThrottleClutchDisengaged",
                                                        InitData.EngineDampingRateZeroThrottleClutchDisengaged);

                if (InitData.EngineTorqueCurve.Count == 0)
                {
                    Log.Fatal("PhysXPhysicsVehicle: PushToWorld: EngineTorqueCurve is not configured.");
                }
                if (InitData.EngineTorqueCurve.Count > 8)
                {
                    Log.Fatal("PhysXPhysicsVehicle: PushToWorld: EngineTorqueCurve can't have more than 8 values.");
                }
                for (int n = 0; n < InitData.EngineTorqueCurve.Count; n++)
                {
                    InitDataClass.EngineTorqueCurveItem item = InitData.EngineTorqueCurve[n];
                    PhysXNativeVehicleInitData.SetParameter(generalData, string.Format("engineTorqueCurveTorque{0}", n),
                                                            item.NormalizedTorque);
                    PhysXNativeVehicleInitData.SetParameter(generalData, string.Format("engineTorqueCurveRev{0}", n),
                                                            item.NormalizedRev);
                }
            }

            //Gears
            {
                if (InitData.Gears.Count == 0)
                {
                    Log.Fatal("PhysXPhysicsVehicle: PushToWorld: The gears are not defined.");
                }
                if (InitData.FindGearByNumber(0) == null)
                {
                    Log.Fatal("PhysXPhysicsVehicle: PushToWorld: Neutral gear is not defined.");
                }
                if (InitData.FindGearByNumber(-1) == null)
                {
                    Log.Fatal("PhysXPhysicsVehicle: PushToWorld: Reverse gear is not defined.");
                }

                foreach (PhysicsVehicle.InitDataClass.GearItem gearItem in InitData.Gears)
                {
                    if (gearItem.Number < -1)
                    {
                        Log.Fatal("PhysXPhysicsVehicle: PushToWorld: Gear number can't be less than -1.");
                    }
                    if (gearItem.Number > 30)
                    {
                        Log.Fatal("PhysXPhysicsVehicle: PushToWorld: Gear number can't be more than 30.");
                    }

                    if (gearItem.Number < 0 && gearItem.Ratio >= 0)
                    {
                        Log.Fatal("PhysXPhysicsVehicle: PushToWorld: Reverse gear ratio must be less than zero.");
                    }
                    if (gearItem.Number == 0 && gearItem.Ratio != 0)
                    {
                        Log.Fatal("PhysXPhysicsVehicle: PushToWorld: Neutral gear ratio must be zero.");
                    }
                    if (gearItem.Number > 0 && gearItem.Ratio < 0)
                    {
                        Log.Fatal("PhysXPhysicsVehicle: PushToWorld: Forward gear ratios must be greater than zero.");
                    }

                    if (gearItem.Number >= 2)
                    {
                        PhysicsVehicle.InitDataClass.GearItem nextGearItem = InitData.FindGearByNumber(gearItem.Number - 1);
                        if (nextGearItem == null || gearItem.Ratio > nextGearItem.Ratio)
                        {
                            Log.Fatal("PhysXPhysicsVehicle: PushToWorld: Forward gear ratios must be a descending sequence of gear ratios.");
                        }
                    }

                    PhysXNativeVehicleInitData.SetParameter(generalData, string.Format("gear{0}", gearItem.Number), gearItem.Ratio);
                }
                PhysXNativeVehicleInitData.SetParameter(generalData, "gearsSwitchTime", InitData.GearsSwitchTime);
            }

            //Clutch
            PhysXNativeVehicleInitData.SetParameter(generalData, "clutchStrength", InitData.ClutchStrength);

            //Ackermann steer accuracy
            PhysXNativeVehicleInitData.SetParameter(generalData, "ackermannSteerAccuracy", InitData.AckermannSteerAccuracy);

            //Wheels
            InitWheelData(wheelFrontLeftData, InitData.WheelFrontLeft);
            InitWheelData(wheelFrontRightData, InitData.WheelFrontRight);
            InitWheelData(wheelRearLeftData, InitData.WheelRearLeft);
            InitWheelData(wheelRearRightData, InitData.WheelRearRight);

            //Tire settings
            {
                int n = 0;
                foreach (InitDataClass.TireFrictionMultiplierItem frictionItem in InitData.TireFrictionMultipliers)
                {
                    PhysXNativeVehicleInitData.SetParameter(generalData,
                                                            string.Format("tireFrictionMaterial{0}", n), frictionItem.SurfaceMaterialName);
                    PhysXNativeVehicleInitData.SetParameter(generalData,
                                                            string.Format("tireFrictionValue{0}", n), frictionItem.Value);
                    n++;
                }
            }

            nativeVehicle = PhysXNativeVehicle.Create(scene.nativeScene, baseBody.nativeBody, generalData,
                                                      wheelFrontLeftData, wheelFrontRightData, wheelRearLeftData, wheelRearRightData);

            PhysXNativeVehicleInitData.Destroy(generalData);
            PhysXNativeVehicleInitData.Destroy(wheelFrontLeftData);
            PhysXNativeVehicleInitData.Destroy(wheelFrontRightData);
            PhysXNativeVehicleInitData.Destroy(wheelRearLeftData);
            PhysXNativeVehicleInitData.Destroy(wheelRearRightData);

            OnUpdateAutoGearSettings();
        }
        //

        public PhysXPhysicsVehicle(PhysXPhysicsScene scene, PhysXBody baseBody)
            : base(scene, baseBody)
        {
        }
Beispiel #14
0
        void UpdatePhysXJoint()
        {
            bool needCreate = PushedToWorld && !Broken;
            bool created    = nativeJoint != IntPtr.Zero;

            if (needCreate == created)
            {
                return;
            }

            if (needCreate)
            {
                PhysXBody physXBody0 = (PhysXBody)Body1;
                PhysXBody physXBody1 = (PhysXBody)Body2;

                if ((!physXBody0.Static || !physXBody1.Static) &&
                    (physXBody0.nativeBody != IntPtr.Zero && physXBody1.nativeBody != IntPtr.Zero))
                {
                    Vec3 globalAnchor = (Body1.Position + Body2.Position) * .5f;

                    //float diff = axis.LimitHigh - axis.LimitLow;
                    //Vec3 low = globalAnchor + Axis.Direction * axis.LimitLow;
                    //Vec3 high = globalAnchor + Axis.Direction * axis.LimitHigh;
                    //if( axis.LimitsEnabled )
                    //{
                    //   globalAnchor = ( low + high ) / 2;
                    //   //float d = axis.LimitHigh + axis.LimitLow;
                    //   //если low положительный?
                    //   //globalAnchor += ( d / 2 ) * Axis.Direction;
                    //}

                    Quat globalAxisRotation = Quat.FromDirectionZAxisUp(Axis.Direction);
                    Vec3 localPosition0     = physXBody0.Rotation.GetInverse() * (globalAnchor - physXBody0.Position);
                    Quat localRotation0     = (physXBody0.Rotation.GetInverse() * globalAxisRotation).GetNormalize();
                    Vec3 localPosition1     = physXBody1.Rotation.GetInverse() * (globalAnchor - physXBody1.Position);
                    Quat localRotation1     = (physXBody1.Rotation.GetInverse() * globalAxisRotation).GetNormalize();

                    nativeJoint = PhysXNativeWrapper.PhysXNativeD6Joint.Create(
                        physXBody0.nativeBody, ref localPosition0, ref localRotation0,
                        physXBody1.nativeBody, ref localPosition1, ref localRotation1);

                    PhysXNativeD6Joint.SetMotion(nativeJoint, PhysXD6Axis.X, PhysXD6Motion.Free);
                    PhysXNativeD6Joint.SetMotion(nativeJoint, PhysXD6Axis.Y, PhysXD6Motion.Locked);
                    PhysXNativeD6Joint.SetMotion(nativeJoint, PhysXD6Axis.Z, PhysXD6Motion.Locked);
                    PhysXNativeD6Joint.SetMotion(nativeJoint, PhysXD6Axis.Twist, PhysXD6Motion.Locked);
                    PhysXNativeD6Joint.SetMotion(nativeJoint, PhysXD6Axis.Swing1, PhysXD6Motion.Locked);
                    PhysXNativeD6Joint.SetMotion(nativeJoint, PhysXD6Axis.Swing2, PhysXD6Motion.Locked);

                    UpdateLimits();

                    //Vec3 globalAnchor = ( Body1.Position + Body2.Position ) * .5f;
                    //Quat globalAxisRotation = Quat.FromDirectionZAxisUp( Axis.Direction );
                    //Vec3 localPosition0 = physXBody0.Rotation.GetInverse() * ( globalAnchor - physXBody0.Position );
                    //Quat localRotation0 = ( physXBody0.Rotation.GetInverse() * globalAxisRotation ).GetNormalize();
                    //Vec3 localPosition1 = physXBody1.Rotation.GetInverse() * ( globalAnchor - physXBody1.Position );
                    //Quat localRotation1 = ( physXBody1.Rotation.GetInverse() * globalAxisRotation ).GetNormalize();

                    //nativeJoint = PhysXNativeWrapper.PhysXNativeSliderJoint.Create(
                    //   physXBody0.nativeBody, ref localPosition0, ref localRotation0,
                    //   physXBody1.nativeBody, ref localPosition1, ref localRotation1 );

                    //if( axis.LimitsEnabled )
                    //{
                    //   Log.Warning( "PhysXSliderJoint: Limits for Slider joint are not supported by the PhysX Physics System." );
                    //   //PhysXNativeWrapper.PhysXNativeSliderJoint.SetLimit( nativeJoint, true, axis.LimitLow, axis.LimitHigh,
                    //   //   PhysXGeneral.jointLimitContactDistance, axis.LimitsBounciness, axis.LimitsHardness );
                    //}

                    if (ContactsEnabled)
                    {
                        PhysXNativeWrapper.PhysXJoint.SetCollisionEnable(nativeJoint, true);
                    }
                    UpdatePhysXBreakData();
                    if (Scene._EnableDebugVisualization)
                    {
                        SetVisualizationEnable(true);
                    }
                }
            }
            else
            {
                DestroyPhysXJoint();
            }
        }
        void UpdatePhysXJoint()
        {
            bool needCreate = PushedToWorld && !Broken;
            bool created    = nativeJoint != IntPtr.Zero;

            if (needCreate == created)
            {
                return;
            }

            if (needCreate)
            {
                if (Math.Abs(Vec3.Dot(axis1.Direction, axis2.Direction)) > .095f)
                {
                    Log.Warning("UniversalJoint: Invalid axes.");
                    return;
                }
                //if( Axis1.LimitsEnabled && Axis1.LimitLow > Axis1.LimitHigh )
                //{
                //   Log.Warning( "UniversalJoint: Invalid axis1 limits (low > high)." );
                //   return;
                //}
                //if( Axis2.LimitsEnabled && Axis2.LimitLow > Axis2.LimitHigh )
                //{
                //   Log.Warning( "UniversalJoint: Invalid axis2 limits (low > high)." );
                //   return;
                //}

                PhysXBody physXBody0 = (PhysXBody)Body1;
                PhysXBody physXBody1 = (PhysXBody)Body2;

                if ((!physXBody0.Static || !physXBody1.Static) &&
                    (physXBody0.nativeBody != IntPtr.Zero && physXBody1.nativeBody != IntPtr.Zero))
                {
                    axis1LocalAxis = Body1.Rotation.GetInverse() * axis1.Direction;
                    axis2LocalAxis = Body1.Rotation.GetInverse() * axis2.Direction;

                    Mat3 axisMatrix = new Mat3(axis1.Direction, -Vec3.Cross(axis1.Direction, axis2.Direction), axis2.Direction) *
                                      Mat3.FromRotateByZ(MathFunctions.PI / 2);
                    Quat globalAxisRotation = axisMatrix.ToQuat().GetNormalize();
                    //Quat globalAxisRotation = new Mat3( axis1.Direction, -Vec3.Cross( axis1.Direction, axis2.Direction ),
                    //   axis2.Direction ).ToQuat().GetNormalize();

                    Vec3 localPosition0 = physXBody0.Rotation.GetInverse() * (Anchor - physXBody0.Position);
                    Quat localRotation0 = (physXBody0.Rotation.GetInverse() * globalAxisRotation).GetNormalize();
                    Vec3 localPosition1 = physXBody1.Rotation.GetInverse() * (Anchor - physXBody1.Position);
                    Quat localRotation1 = (physXBody1.Rotation.GetInverse() * globalAxisRotation).GetNormalize();

                    nativeJoint = PhysXNativeWrapper.PhysXNativeD6Joint.Create(
                        physXBody0.nativeBody, ref localPosition0, ref localRotation0,
                        physXBody1.nativeBody, ref localPosition1, ref localRotation1);

                    PhysXNativeD6Joint.SetMotion(nativeJoint, PhysXD6Axis.X, PhysXD6Motion.Locked);
                    PhysXNativeD6Joint.SetMotion(nativeJoint, PhysXD6Axis.Y, PhysXD6Motion.Locked);
                    PhysXNativeD6Joint.SetMotion(nativeJoint, PhysXD6Axis.Z, PhysXD6Motion.Locked);

                    UpdateLimits();

                    if (ContactsEnabled)
                    {
                        PhysXNativeWrapper.PhysXJoint.SetCollisionEnable(nativeJoint, true);
                    }
                    UpdatePhysXBreakData();
                    if (Scene._EnableDebugVisualization)
                    {
                        SetVisualizationEnable(true);
                    }

                    //PhysXNativeD6Joint.SetProjectionTolerances( nativeJoint, .2f, MathFunctions.PI );
                    //PhysXNativeWrapper.PhysXJoint.SetProjectionEnable( nativeJoint, true );
                }
            }
            else
            {
                DestroyPhysXJoint();
            }
        }
    // private Mesh meshMesh = null;

    // Start is called before the first frame update
    public override void Setup(PhysXBody attachedRigidBody, uint vehicleId)
    {
        if (mesh == null)
        {
            Debug.LogError("Collider mesh is null on " + gameObject.name);
        }
        else if (!mesh.isReadable)
        {
            Debug.LogError("Collider mesh: " + mesh.name + " is not readable");
        }
        else
        {
            // meshMesh = Instantiate(mesh);
            // meshMesh.Clear();
            // List<Vector3> meshMeshVertices = new List<Vector3>();

            IntPtr vertexArray = PhysXLib.CreateVectorArray();

            Vector3[] unscaledVertices = mesh.vertices;
            Vector3[] vertices         = new Vector3[unscaledVertices.Length];
            for (int i = 0; i < unscaledVertices.Length; i++)
            {
                vertices[i] = new Vector3(unscaledVertices[i].x * scale.x, unscaledVertices[i].y * scale.y, unscaledVertices[i].z * scale.z);
                // vertices[i] = unscaledVertices[i];//new Vector3(unscaledVertices[i].x * scale.x, unscaledVertices[i].y * scale.y, unscaledVertices[i].z * scale.z);
            }

            Vector3 centre = Vector3.zero;
            foreach (Vector3 vertex in vertices)
            {
                centre += vertex;
            }
            centre /= vertices.Length;

            // offset += new Vector3(centre.x * scale.x, centre.y * scale.y, centre.z * scale.z);
            offset += centre;

            PhysXVec3 physXVertex = new PhysXVec3(Vector3.zero);
            foreach (Vector3 vertex in vertices)
            {
                physXVertex.FromVector(vertex - centre);
                PhysXLib.AddVectorToArray(vertexArray, physXVertex);
            }

            IntPtr geom = IntPtr.Zero;
            if (convex)
            {
                geom = PhysXLib.CreateConvexMeshGeometry(vertexArray, new PhysXVec3(Vector3.one));
            }
            else
            {
                geom = PhysXLib.CreateMeshGeometry(vertexArray, mesh.triangles, mesh.triangles.Length / 3, new PhysXVec3(Vector3.one));
            }

            shape = PhysXLib.CreateShape(geom, physXMaterial, 0.02f);

            // if (!convex) {
            //     int vertexCount = PhysXLib.GetMeshVertexCount(geom);
            //     int triCount = PhysXLib.GetMeshTriangleCount(geom);
            //     IntPtr usedVertices = PhysXLib.CreateVectorArray();
            //     int[] usedTris = new int[triCount * 3];
            //     PhysXLib.GetMeshGeometry(geom, usedVertices, usedTris);

            //     for (int i = 0; i < vertexCount; i++) {
            //         PhysXLib.GetVectorFromArray(usedVertices, physXVertex, i);
            //         meshMeshVertices.Add(physXVertex.ToVector());
            //     }
            //     meshMesh.SetVertices(meshMeshVertices);
            //     meshMesh.triangles = usedTris;
            //     meshMesh.RecalculateNormals();
            // }

            base.Setup(attachedRigidBody, vehicleId);
        }
    }
Beispiel #17
0
 public void RemoveActor(PhysXBody body)
 {
     bodies.Remove(body.physXBody.ToInt64());
 }
        internal void PopulateWithUnityObjects(Dictionary <long, PhysXBody> rigidBodies)
        {
            PhysXBody body = rigidBodies[otherActor.ToInt64()];

            collider = body.GetColliderFromShape(colliderShape);
        }