Esempio n. 1
0
        /// <summary>
        ///     Describes whether this instance synchronize fixtures
        /// </summary>
        /// <returns>The bool</returns>
        internal bool SynchronizeFixtures()
        {
            XForm xf1 = new XForm();

            xf1.R.Set(Sweep.A0);
            xf1.Position = Sweep.C0 - Math.Mul(xf1.R, Sweep.LocalCenter);

            bool inRange = true;

            for (Fixture f = FixtureList; f != null; f = f.Next)
            {
                inRange = f.Synchronize(world.BroadPhase, xf1, Xf);
                if (inRange == false)
                {
                    break;
                }
            }

            if (inRange == false)
            {
                Flags |= BodyFlags.Frozen;
                LinearVelocity.SetZero();
                AngularVelocity = 0.0f;

                // Failure
                return(false);
            }

            // Success
            return(true);
        }
Esempio n. 2
0
        // Returns existing pair or creates a new one.
        /// <summary>
        ///     Adds the pair using the specified proxy id 1
        /// </summary>
        /// <param name="proxyId1">The proxy id</param>
        /// <param name="proxyId2">The proxy id</param>
        /// <returns>The pair</returns>
        private Pair AddPair(int proxyId1, int proxyId2)
        {
            if (proxyId1 > proxyId2)
            {
                Math.Swap(ref proxyId1, ref proxyId2);
            }

            int hash = (int)(Hash((uint)proxyId1, (uint)proxyId2) & TableMask);

            Pair pair = Find(proxyId1, proxyId2, (uint)hash);

            if (pair != null)
            {
                return(pair);
            }

            Box2DxDebug.Assert(PairCount < Settings.MaxPairs && FreePair != NullPair);

            ushort pairIndex = FreePair;

            pair     = Pairs[pairIndex];
            FreePair = pair.Next;

            pair.ProxyId1 = (ushort)proxyId1;
            pair.ProxyId2 = (ushort)proxyId2;
            pair.Status   = 0;
            pair.UserData = null;
            pair.Next     = HashTable[hash];

            HashTable[hash] = pairIndex;

            ++PairCount;

            return(pair);
        }
Esempio n. 3
0
        // Removes a pair. The pair must exist.
        /// <summary>
        ///     Removes the pair using the specified proxy id 1
        /// </summary>
        /// <param name="proxyId1">The proxy id</param>
        /// <param name="proxyId2">The proxy id</param>
        /// <returns>The object</returns>
        private object RemovePair(int proxyId1, int proxyId2)
        {
            Box2DxDebug.Assert(PairCount > 0);

            if (proxyId1 > proxyId2)
            {
                Math.Swap(ref proxyId1, ref proxyId2);
            }

            int hash = (int)(Hash((uint)proxyId1, (uint)proxyId2) & TableMask);

            //uint16* node = &m_hashTable[hash];
            ushort node = HashTable[hash];
            bool   ion  = false;
            int    ni   = 0;

            while (node != NullPair)
            {
                if (Equals(Pairs[node], proxyId1, proxyId2))
                {
                    //uint16 index = *node;
                    //*node = m_pairs[*node].next;

                    ushort index = node;
                    node = Pairs[node].Next;
                    if (ion)
                    {
                        Pairs[ni].Next = node;
                    }
                    else
                    {
                        HashTable[hash] = node;
                    }

                    Pair   pair     = Pairs[index];
                    object userData = pair.UserData;

                    // Scrub
                    pair.Next     = FreePair;
                    pair.ProxyId1 = NullProxy;
                    pair.ProxyId2 = NullProxy;
                    pair.UserData = null;
                    pair.Status   = 0;

                    FreePair = index;
                    --PairCount;
                    return(userData);
                }

                //node = &m_pairs[*node].next;
                ni   = node;
                node = Pairs[ni].Next;
                ion  = true;
            }

            Box2DxDebug.Assert(false);
            return(null);
        }
Esempio n. 4
0
        /// <summary>
        ///     Finds the proxy id 1
        /// </summary>
        /// <param name="proxyId1">The proxy id</param>
        /// <param name="proxyId2">The proxy id</param>
        /// <returns>The pair</returns>
        private Pair Find(int proxyId1, int proxyId2)
        {
            if (proxyId1 > proxyId2)
            {
                Math.Swap(ref proxyId1, ref proxyId2);
            }

            uint hash = (uint)(Hash((uint)proxyId1, (uint)proxyId2) & TableMask);

            return(Find(proxyId1, proxyId2, hash));
        }
Esempio n. 5
0
        /// <summary>
        ///     Describes whether this instance solve position constraints
        /// </summary>
        /// <param name="baumgarte">The baumgarte</param>
        /// <returns>The bool</returns>
        public bool SolvePositionConstraints(float baumgarte)
        {
            float minSeparation = 0.0f;

            for (int i = 0; i < ConstraintCount; ++i)
            {
                ContactConstraint c = Constraints[i];
                Body bodyA          = c.BodyA;
                Body bodyB          = c.BodyB;

                float invMassA = bodyA.Mass * bodyA.InvMass;
                float invIa    = bodyA.Mass * bodyA.InvI;
                float invMassB = bodyB.Mass * bodyB.InvMass;
                float invIb    = bodyB.Mass * bodyB.InvI;

                SPositionSolverManifold.Initialize(c);
                Vec2 normal = SPositionSolverManifold.Normal;

                // Solver normal constraints
                for (int j = 0; j < c.PointCount; ++j)
                {
                    Vec2  point      = SPositionSolverManifold.Points[j];
                    float separation = SPositionSolverManifold.Separations[j];

                    Vec2 rA = point - bodyA.Sweep.C;
                    Vec2 rB = point - bodyB.Sweep.C;

                    // Track max constraint error.
                    minSeparation = Math.Min(minSeparation, separation);

                    // Prevent large corrections and allow slop.
                    float clamp = baumgarte * Math.Clamp(separation + Settings.LinearSlop,
                                                         -Settings.MaxLinearCorrection,
                                                         0.0f);

                    // Compute normal impulse
                    float impulse = -c.Points[j].EqualizedMass * clamp;

                    Vec2 p = impulse * normal;

                    bodyA.Sweep.C -= invMassA * p;
                    bodyA.Sweep.A -= invIa * Vec2.Cross(rA, p);
                    bodyA.SynchronizeTransform();

                    bodyB.Sweep.C += invMassB * p;
                    bodyB.Sweep.A += invIb * Vec2.Cross(rB, p);
                    bodyB.SynchronizeTransform();
                }
            }

            // We can't expect minSpeparation >= -Settings.LinearSlop because we don't
            // push the separation above -Settings.LinearSlop.
            return(minSeparation >= -1.5f * Settings.LinearSlop);
        }
Esempio n. 6
0
        // TODO_ERIN adjust linear velocity and torque to account for movement of center.
        /// <summary>
        ///     Set the mass properties. Note that this changes the center of mass position.
        ///     If you are not sure how to compute mass properties, use SetMassFromShapes.
        ///     The inertia tensor is assumed to be relative to the center of mass.
        /// </summary>
        /// <param name="massData">The mass properties.</param>
        public void SetMass(MassData massData)
        {
            Box2DxDebug.Assert(world.Lock == false);
            if (world.Lock)
            {
                return;
            }

            InvMass = 0.0f;
            I       = 0.0f;
            InvI    = 0.0f;

            Mass = massData.Mass;

            if (Mass > 0.0f)
            {
                InvMass = 1.0f / Mass;
            }

            I = massData.I;

            if (I > 0.0f && (Flags & BodyFlags.FixedRotation) == 0)
            {
                InvI = 1.0f / I;
            }

            // Move center of mass.
            Sweep.LocalCenter = massData.Center;
            Sweep.C0          = Sweep.C = Math.Mul(Xf, Sweep.LocalCenter);

            BodyType oldType = type;

            if (InvMass == 0.0f && InvI == 0.0f)
            {
                type = BodyType.Static;
            }
            else
            {
                type = BodyType.Dynamic;
            }

            // If the body type changed, we need to refilter the broad-phase proxies.
            if (oldType != type)
            {
                for (Fixture f = FixtureList; f != null; f = f.Next)
                {
                    f.RefilterProxy(world.BroadPhase, Xf);
                }
            }
        }
Esempio n. 7
0
        /// <summary>
        ///     Set the position of the body's origin and rotation (radians).
        ///     This breaks any contacts and wakes the other bodies.
        /// </summary>
        /// <param name="position">
        ///     The new world position of the body's origin (not necessarily
        ///     the center of mass).
        /// </param>
        /// <param name="angle">The new world rotation angle of the body in radians.</param>
        /// <returns>
        ///     Return false if the movement put a shape outside the world. In this case the
        ///     body is automatically frozen.
        /// </returns>
        public bool SetXForm(Vec2 position, float angle)
        {
            Box2DxDebug.Assert(world.Lock == false);
            if (world.Lock)
            {
                return(true);
            }

            if (IsFrozen())
            {
                return(false);
            }

            Xf.R.Set(angle);
            Xf.Position = position;

            Sweep.C0 = Sweep.C = Math.Mul(Xf, Sweep.LocalCenter);
            Sweep.A0 = Sweep.A = angle;

            bool freeze = false;

            for (Fixture f = FixtureList; f != null; f = f.Next)
            {
                bool inRange = f.Synchronize(world.BroadPhase, Xf, Xf);

                if (inRange == false)
                {
                    freeze = true;
                    break;
                }
            }

            if (freeze)
            {
                Flags |= BodyFlags.Frozen;
                LinearVelocity.SetZero();
                AngularVelocity = 0.0f;

                // Failure
                return(false);
            }

            // Success
            world.BroadPhase.Commit();
            return(true);
        }
Esempio n. 8
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="PairManager" /> class
        /// </summary>
        public PairManager()
        {
            Box2DxDebug.Assert(Math.IsPowerOfTwo((uint)TableCapacity));
            Box2DxDebug.Assert(TableCapacity >= Settings.MaxPairs);
            for (int i = 0; i < TableCapacity; ++i)
            {
                HashTable[i] = NullPair;
            }

            FreePair = 0;
            for (int i = 0; i < Settings.MaxPairs; ++i)
            {
                Pairs[i]          = new Pair(); //todo: need some pool here
                Pairs[i].ProxyId1 = NullProxy;
                Pairs[i].ProxyId2 = NullProxy;
                Pairs[i].UserData = null;
                Pairs[i].Status   = 0;
                Pairs[i].Next     = (ushort)(i + 1U);
            }

            Pairs[Settings.MaxPairs - 1].Next = NullPair;
            PairCount       = 0;
            PairBufferCount = 0;
        }
Esempio n. 9
0
 /// <summary>
 ///     Gets a local vector given a world vector.
 /// </summary>
 /// <param name="worldVector">A vector in world coordinates.</param>
 /// <returns>Return the corresponding local vector.</returns>
 public Vec2 GetLocalVector(Vec2 worldVector)
 {
     return(Math.MulT(Xf.R, worldVector));
 }
Esempio n. 10
0
 /// <summary>
 ///     Gets a local point relative to the body's origin given a world point.
 /// </summary>
 /// <param name="worldPoint">A point in world coordinates.</param>
 /// <returns>Return the corresponding local point relative to the body's origin.</returns>
 public Vec2 GetLocalPoint(Vec2 worldPoint)
 {
     return(Math.MulT(Xf, worldPoint));
 }
Esempio n. 11
0
 /// <summary>
 ///     Get the world coordinates of a vector given the local coordinates.
 /// </summary>
 /// <param name="localVector">A vector fixed in the body.</param>
 /// <returns>Return the same vector expressed in world coordinates.</returns>
 public Vec2 GetWorldVector(Vec2 localVector)
 {
     return(Math.Mul(Xf.R, localVector));
 }
Esempio n. 12
0
        // TODO_ERIN adjust linear velocity and torque to account for movement of center.
        /// <summary>
        ///     Compute the mass properties from the attached shapes. You typically call this
        ///     after adding all the shapes. If you add or remove shapes later, you may want
        ///     to call this again. Note that this changes the center of mass position.
        /// </summary>
        public void SetMassFromShapes()
        {
            Box2DxDebug.Assert(world.Lock == false);
            if (world.Lock)
            {
                return;
            }

            // Compute mass data from shapes. Each shape has its own density.
            Mass    = 0.0f;
            InvMass = 0.0f;
            I       = 0.0f;
            InvI    = 0.0f;

            Vec2 center = Vec2.Zero;

            for (Fixture f = FixtureList; f != null; f = f.Next)
            {
                MassData massData;
                f.ComputeMass(out massData);
                Mass   += massData.Mass;
                center += massData.Mass * massData.Center;
                I      += massData.I;
            }

            // Compute center of mass, and shift the origin to the COM.
            if (Mass > 0.0f)
            {
                InvMass = 1.0f / Mass;
                center *= InvMass;
            }

            if (I > 0.0f && (Flags & BodyFlags.FixedRotation) == 0)
            {
                // Center the inertia about the center of mass.
                I -= Mass * Vec2.Dot(center, center);
                Box2DxDebug.Assert(I > 0.0f);
                InvI = 1.0f / I;
            }
            else
            {
                I    = 0.0f;
                InvI = 0.0f;
            }

            // Move center of mass.
            Sweep.LocalCenter = center;
            Sweep.C0          = Sweep.C = Math.Mul(Xf, Sweep.LocalCenter);

            BodyType oldType = type;

            if (InvMass == 0.0f && InvI == 0.0f)
            {
                type = BodyType.Static;
            }
            else
            {
                type = BodyType.Dynamic;
            }

            // If the body type changed, we need to refilter the broad-phase proxies.
            if (oldType != type)
            {
                for (Fixture f = FixtureList; f != null; f = f.Next)
                {
                    f.RefilterProxy(world.BroadPhase, Xf);
                }
            }
        }
Esempio n. 13
0
        internal XForm Xf; // the body origin transform

        /// <summary>
        ///     Initializes a new instance of the <see cref="Body" /> class
        /// </summary>
        /// <param name="bd">The bd</param>
        /// <param name="world">The world</param>
        internal Body(BodyDef bd, World world)
        {
            Box2DxDebug.Assert(world.Lock == false);

            Flags = 0;

            if (bd.IsBullet)
            {
                Flags |= BodyFlags.Bullet;
            }

            if (bd.FixedRotation)
            {
                Flags |= BodyFlags.FixedRotation;
            }

            if (bd.AllowSleep)
            {
                Flags |= BodyFlags.AllowSleep;
            }

            if (bd.IsSleeping)
            {
                Flags |= BodyFlags.Sleep;
            }

            this.world = world;

            Xf.Position = bd.Position;
            Xf.R.Set(bd.Angle);

            Sweep.LocalCenter = bd.MassData.Center;
            Sweep.T0          = 1.0f;
            Sweep.A0          = Sweep.A = bd.Angle;
            Sweep.C0          = Sweep.C = Math.Mul(Xf, Sweep.LocalCenter);

            //_jointList = null;
            //_contactList = null;
            //_controllerList = null;
            //_prev = null;
            //_next = null;

            LinearVelocity  = bd.LinearVelocity;
            AngularVelocity = bd.AngularVelocity;

            LinearDamping  = bd.LinearDamping;
            AngularDamping = bd.AngularDamping;

            //_force.Set(0.0f, 0.0f);
            //_torque = 0.0f;

            //_linearVelocity.SetZero();
            //_angularVelocity = 0.0f;

            //_sleepTime = 0.0f;

            //_invMass = 0.0f;
            //_I = 0.0f;
            //_invI = 0.0f;

            Mass = bd.MassData.Mass;

            if (Mass > 0.0f)
            {
                InvMass = 1.0f / Mass;
            }

            I = bd.MassData.I;

            if (I > 0.0f && (Flags & BodyFlags.FixedRotation) == 0)
            {
                InvI = 1.0f / I;
            }

            if (InvMass == 0.0f && InvI == 0.0f)
            {
                type = BodyType.Static;
            }
            else
            {
                type = BodyType.Dynamic;
            }

            userData = bd.UserData;

            //_fixtureList = null;
            //_fixtureCount = 0;
        }
Esempio n. 14
0
 /// <summary>
 ///     Synchronizes the transform
 /// </summary>
 internal void SynchronizeTransform()
 {
     Xf.R.Set(Sweep.A);
     Xf.Position = Sweep.C - Math.Mul(Xf.R, Sweep.LocalCenter);
 }
Esempio n. 15
0
 /// <summary>
 ///     Get the world coordinates of a point given the local coordinates.
 /// </summary>
 /// <param name="localPoint">A point on the body measured relative the the body's origin.</param>
 /// <returns>Return the same point expressed in world coordinates.</returns>
 public Vec2 GetWorldPoint(Vec2 localPoint)
 {
     return(Math.Mul(Xf, localPoint));
 }
Esempio n. 16
0
        /// <summary>
        ///     Solves the step
        /// </summary>
        /// <param name="step">The step</param>
        /// <param name="gravity">The gravity</param>
        /// <param name="allowSleep">The allow sleep</param>
        public void Solve(TimeStep step, Vec2 gravity, bool allowSleep)
        {
            // Integrate velocities and apply damping.
            for (int i = 0; i < BodyCount; ++i)
            {
                Body b = Bodies[i];

                if (b.IsStatic())
                {
                    continue;
                }

                // Integrate velocities.
                b.LinearVelocity  += step.Dt * (gravity + b.InvMass * b.Force);
                b.AngularVelocity += step.Dt * b.InvI * b.Torque;

                // Reset forces.
                b.Force.Set(0.0f, 0.0f);
                b.Torque = 0.0f;

                // Apply damping.
                // ODE: dv/dt + c * v = 0
                // Solution: v(t) = v0 * exp(-c * t)
                // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt)
                // v2 = exp(-c * dt) * v1
                // Taylor expansion:
                // v2 = (1.0f - c * dt) * v1
                b.LinearVelocity  *= Math.Clamp(1.0f - step.Dt * b.LinearDamping, 0.0f, 1.0f);
                b.AngularVelocity *= Math.Clamp(1.0f - step.Dt * b.AngularDamping, 0.0f, 1.0f);
            }

            ContactSolver contactSolver = new ContactSolver(step, Contacts, ContactCount);

            // Initialize velocity constraints.
            contactSolver.InitVelocityConstraints(step);

            for (int i = 0; i < JointCount; ++i)
            {
                Joints[i].InitVelocityConstraints(step);
            }

            // Solve velocity constraints.
            for (int i = 0; i < step.VelocityIterations; ++i)
            {
                for (int j = 0; j < JointCount; ++j)
                {
                    Joints[j].SolveVelocityConstraints(step);
                }

                contactSolver.SolveVelocityConstraints();
            }

            // Post-solve (store impulses for warm starting).
            contactSolver.FinalizeVelocityConstraints();

            // Integrate positions.
            for (int i = 0; i < BodyCount; ++i)
            {
                Body b = Bodies[i];

                if (b.IsStatic())
                {
                    continue;
                }

                // Check for large velocities.
                Vec2 translation = step.Dt * b.LinearVelocity;
                if (Vec2.Dot(translation, translation) > Settings.MaxTranslationSquared)
                {
                    translation.Normalize();
                    b.LinearVelocity = Settings.MaxTranslation * step.InvDt * translation;
                }

                float rotation = step.Dt * b.AngularVelocity;
                if (rotation * rotation > Settings.MaxRotationSquared)
                {
                    if (rotation < 0.0)
                    {
                        b.AngularVelocity = -step.InvDt * Settings.MaxRotation;
                    }
                    else
                    {
                        b.AngularVelocity = step.InvDt * Settings.MaxRotation;
                    }
                }

                // Store positions for continuous collision.
                b.Sweep.C0 = b.Sweep.C;
                b.Sweep.A0 = b.Sweep.A;

                // Integrate
                b.Sweep.C += step.Dt * b.LinearVelocity;
                b.Sweep.A += step.Dt * b.AngularVelocity;

                // Compute new transform
                b.SynchronizeTransform();

                // Note: shapes are synchronized later.
            }

            // Iterate over constraints.
            for (int i = 0; i < step.PositionIterations; ++i)
            {
                bool contactsOkay = contactSolver.SolvePositionConstraints(Settings.ContactBaumgarte);

                bool jointsOkay = true;
                for (int j = 0; j < JointCount; ++j)
                {
                    bool jointOkay = Joints[j].SolvePositionConstraints(Settings.ContactBaumgarte);
                    jointsOkay = jointsOkay && jointOkay;
                }

                if (contactsOkay && jointsOkay)
                {
                    // Exit early if the position errors are small.
                    break;
                }
            }

            Report(contactSolver.Constraints);

            if (allowSleep)
            {
                float minSleepTime = Settings.FltMax;

#if !TARGET_FLOAT32_IS_FIXED
                float linTolSqr = Settings.LinearSleepTolerance * Settings.LinearSleepTolerance;
                float angTolSqr = Settings.AngularSleepTolerance * Settings.AngularSleepTolerance;
#endif

                for (int i = 0; i < BodyCount; ++i)
                {
                    Body b = Bodies[i];
                    if (b.InvMass == 0.0f)
                    {
                        continue;
                    }

                    if ((b.Flags & BodyFlags.AllowSleep) == 0)
                    {
                        b.SleepTime  = 0.0f;
                        minSleepTime = 0.0f;
                    }

                    if ((b.Flags & BodyFlags.AllowSleep) == 0 ||
#if TARGET_FLOAT32_IS_FIXED
                        Common.Math.Abs(b._angularVelocity) > Settings.AngularSleepTolerance ||
                        Common.Math.Abs(b._linearVelocity.X) > Settings.LinearSleepTolerance ||
                        Common.Math.Abs(b._linearVelocity.Y) > Settings.LinearSleepTolerance)
#else
                        b.AngularVelocity *b.AngularVelocity > angTolSqr ||
                        Vec2.Dot(b.LinearVelocity, b.LinearVelocity) > linTolSqr)
#endif
                    {
                        b.SleepTime  = 0.0f;
                        minSleepTime = 0.0f;
                    }
                    else
                    {
                        b.SleepTime += step.Dt;
                        minSleepTime = Math.Min(minSleepTime, b.SleepTime);
                    }
                }
Esempio n. 17
0
        /// <summary>
        ///     Solves the velocity constraints
        /// </summary>
        public void SolveVelocityConstraints()
        {
            for (int i = 0; i < ConstraintCount; ++i)
            {
                ContactConstraint c = Constraints[i];
                Body  bodyA         = c.BodyA;
                Body  bodyB         = c.BodyB;
                float wA            = bodyA.AngularVelocity;
                float wB            = bodyB.AngularVelocity;
                Vec2  vA            = bodyA.LinearVelocity;
                Vec2  vB            = bodyB.LinearVelocity;
                float invMassA      = bodyA.InvMass;
                float invIa         = bodyA.InvI;
                float invMassB      = bodyB.InvMass;
                float invIb         = bodyB.InvI;
                Vec2  normal        = c.Normal;
                Vec2  tangent       = Vec2.Cross(normal, 1.0f);
                float friction      = c.Friction;

                Box2DxDebug.Assert(c.PointCount == 1 || c.PointCount == 2);

                unsafe
                {
                    fixed(ContactConstraintPoint *pointsPtr = c.Points)
                    {
                        // Solve tangent constraints
                        for (int j = 0; j < c.PointCount; ++j)
                        {
                            ContactConstraintPoint *ccp = &pointsPtr[j];

                            // Relative velocity at contact
                            Vec2 dv = vB + Vec2.Cross(wB, ccp->Rb) - vA - Vec2.Cross(wA, ccp->Ra);

                            // Compute tangent force
                            float vt     = Vec2.Dot(dv, tangent);
                            float lambda = ccp->TangentMass * -vt;

                            // b2Clamp the accumulated force
                            float maxFriction = friction * ccp->NormalImpulse;
                            float newImpulse  = Math.Clamp(ccp->TangentImpulse + lambda, -maxFriction, maxFriction);
                            lambda = newImpulse - ccp->TangentImpulse;

                            // Apply contact impulse
                            Vec2 p = lambda * tangent;

                            vA -= invMassA * p;
                            wA -= invIa * Vec2.Cross(ccp->Ra, p);

                            vB += invMassB * p;
                            wB += invIb * Vec2.Cross(ccp->Rb, p);

                            ccp->TangentImpulse = newImpulse;
                        }

                        // Solve normal constraints
                        if (c.PointCount == 1)
                        {
                            ContactConstraintPoint ccp = c.Points[0];

                            // Relative velocity at contact
                            Vec2 dv = vB + Vec2.Cross(wB, ccp.Rb) - vA - Vec2.Cross(wA, ccp.Ra);

                            // Compute normal impulse
                            float vn     = Vec2.Dot(dv, normal);
                            float lambda = -ccp.NormalMass * (vn - ccp.VelocityBias);

                            // Clamp the accumulated impulse
                            float newImpulse = Math.Max(ccp.NormalImpulse + lambda, 0.0f);
                            lambda = newImpulse - ccp.NormalImpulse;

                            // Apply contact impulse
                            Vec2 p = lambda * normal;
                            vA -= invMassA * p;
                            wA -= invIa * Vec2.Cross(ccp.Ra, p);

                            vB += invMassB * p;
                            wB += invIb * Vec2.Cross(ccp.Rb, p);
                            ccp.NormalImpulse = newImpulse;
                        }
                        else
                        {
                            // Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite).
                            // Build the mini LCP for this contact patch
                            //
                            // vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2
                            //
                            // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n )
                            // b = vn_0 - velocityBias
                            //
                            // The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i
                            // implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases
                            // vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid
                            // solution that satisfies the problem is chosen.
                            //
                            // In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires
                            // that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i).
                            //
                            // Substitute:
                            //
                            // x = x' - a
                            //
                            // Plug into above equation:
                            //
                            // vn = A * x + b
                            //    = A * (x' - a) + b
                            //    = A * x' + b - A * a
                            //    = A * x' + b'
                            // b' = b - A * a;

                            ContactConstraintPoint *cp1 = &pointsPtr[0];
                            ContactConstraintPoint *cp2 = &pointsPtr[1];

                            Vec2 a = new Vec2(cp1->NormalImpulse, cp2->NormalImpulse);
                            Box2DxDebug.Assert(a.X >= 0.0f && a.Y >= 0.0f);

                            // Relative velocity at contact
                            Vec2 dv1 = vB + Vec2.Cross(wB, cp1->Rb) - vA - Vec2.Cross(wA, cp1->Ra);
                            Vec2 dv2 = vB + Vec2.Cross(wB, cp2->Rb) - vA - Vec2.Cross(wA, cp2->Ra);

                            // Compute normal velocity
                            float vn1 = Vec2.Dot(dv1, normal);
                            float vn2 = Vec2.Dot(dv2, normal);

                            Vec2 b;
                            b.X = vn1 - cp1->VelocityBias;
                            b.Y = vn2 - cp2->VelocityBias;
                            b  -= Math.Mul(c.K, a);

                            //const float k_errorTol = 1e-3f;
                            //B2_NOT_USED(k_errorTol);

                            for (;;)
                            {
                                //
                                // Case 1: vn = 0
                                //
                                // 0 = A * x' + b'
                                //
                                // Solve for x':
                                //
                                // x' = - inv(A) * b'
                                //
                                Vec2 x = -Math.Mul(c.NormalMass, b);

                                if (x.X >= 0.0f && x.Y >= 0.0f)
                                {
                                    // Resubstitute for the incremental impulse
                                    Vec2 d = x - a;

                                    // Apply incremental impulse
                                    Vec2 p1 = d.X * normal;
                                    Vec2 p2 = d.Y * normal;
                                    vA -= invMassA * (p1 + p2);
                                    wA -= invIa * (Vec2.Cross(cp1->Ra, p1) + Vec2.Cross(cp2->Ra, p2));

                                    vB += invMassB * (p1 + p2);
                                    wB += invIb * (Vec2.Cross(cp1->Rb, p1) + Vec2.Cross(cp2->Rb, p2));

                                    // Accumulate
                                    cp1->NormalImpulse = x.X;
                                    cp2->NormalImpulse = x.Y;

#if DEBUG_SOLVER
                                    // Postconditions
                                    dv1 = vB + Vec2.Cross(wB, cp1->RB) - vA - Vec2.Cross(wA, cp1->RA);
                                    dv2 = vB + Vec2.Cross(wB, cp2->RB) - vA - Vec2.Cross(wA, cp2->RA);

                                    // Compute normal velocity
                                    vn1 = Vec2.Dot(dv1, normal);
                                    vn2 = Vec2.Dot(dv2, normal);

                                    Box2DXDebug.Assert(Common.Math.Abs(vn1 - cp1.VelocityBias) < k_errorTol);
                                    Box2DXDebug.Assert(Common.Math.Abs(vn2 - cp2.VelocityBias) < k_errorTol);
#endif
                                    break;
                                }

                                //
                                // Case 2: vn1 = 0 and x2 = 0
                                //
                                //   0 = a11 * x1' + a12 * 0 + b1'
                                // vn2 = a21 * x1' + a22 * 0 + b2'
                                //
                                x.X = -cp1->NormalMass * b.X;
                                x.Y = 0.0f;

/*
 *                              vn1 = 0.0f;
 */
                                vn2 = c.K.Col1.Y * x.X + b.Y;

                                if (x.X >= 0.0f && vn2 >= 0.0f)
                                {
                                    // Resubstitute for the incremental impulse
                                    Vec2 d = x - a;

                                    // Apply incremental impulse
                                    Vec2 p1 = d.X * normal;
                                    Vec2 p2 = d.Y * normal;
                                    vA -= invMassA * (p1 + p2);
                                    wA -= invIa * (Vec2.Cross(cp1->Ra, p1) + Vec2.Cross(cp2->Ra, p2));

                                    vB += invMassB * (p1 + p2);
                                    wB += invIb * (Vec2.Cross(cp1->Rb, p1) + Vec2.Cross(cp2->Rb, p2));

                                    // Accumulate
                                    cp1->NormalImpulse = x.X;
                                    cp2->NormalImpulse = x.Y;

#if DEBUG_SOLVER
                                    // Postconditions
                                    dv1 = vB + Vec2.Cross(wB, cp1->RB) - vA - Vec2.Cross(wA, cp1->RA);

                                    // Compute normal velocity
                                    vn1 = Vec2.Dot(dv1, normal);

                                    Box2DXDebug.Assert(Common.Math.Abs(vn1 - cp1.VelocityBias) < k_errorTol);
#endif
                                    break;
                                }


                                //
                                // Case 3: w2 = 0 and x1 = 0
                                //
                                // vn1 = a11 * 0 + a12 * x2' + b1'
                                //   0 = a21 * 0 + a22 * x2' + b2'
                                //
                                x.X = 0.0f;
                                x.Y = -cp2->NormalMass * b.Y;
                                vn1 = c.K.Col2.X * x.Y + b.X;

/*
 *                              vn2 = 0.0f;
 */

                                if (x.Y >= 0.0f && vn1 >= 0.0f)
                                {
                                    // Resubstitute for the incremental impulse
                                    Vec2 d = x - a;

                                    // Apply incremental impulse
                                    Vec2 p1 = d.X * normal;
                                    Vec2 p2 = d.Y * normal;
                                    vA -= invMassA * (p1 + p2);
                                    wA -= invIa * (Vec2.Cross(cp1->Ra, p1) + Vec2.Cross(cp2->Ra, p2));

                                    vB += invMassB * (p1 + p2);
                                    wB += invIb * (Vec2.Cross(cp1->Rb, p1) + Vec2.Cross(cp2->Rb, p2));

                                    // Accumulate
                                    cp1->NormalImpulse = x.X;
                                    cp2->NormalImpulse = x.Y;

#if DEBUG_SOLVER
                                    // Postconditions
                                    dv2 = vB + Vec2.Cross(wB, cp2->RB) - vA - Vec2.Cross(wA, cp2->RA);

                                    // Compute normal velocity
                                    vn2 = Vec2.Dot(dv2, normal);

                                    Box2DXDebug.Assert(Common.Math.Abs(vn2 - cp2.VelocityBias) < k_errorTol);
#endif
                                    break;
                                }

                                //
                                // Case 4: x1 = 0 and x2 = 0
                                //
                                // vn1 = b1
                                // vn2 = b2;
                                x.X = 0.0f;
                                x.Y = 0.0f;
                                vn1 = b.X;
                                vn2 = b.Y;

                                if (vn1 >= 0.0f && vn2 >= 0.0f)
                                {
                                    // Resubstitute for the incremental impulse
                                    Vec2 d = x - a;

                                    // Apply incremental impulse
                                    Vec2 p1 = d.X * normal;
                                    Vec2 p2 = d.Y * normal;
                                    vA -= invMassA * (p1 + p2);
                                    wA -= invIa * (Vec2.Cross(cp1->Ra, p1) + Vec2.Cross(cp2->Ra, p2));

                                    vB += invMassB * (p1 + p2);
                                    wB += invIb * (Vec2.Cross(cp1->Rb, p1) + Vec2.Cross(cp2->Rb, p2));

                                    // Accumulate
                                    cp1->NormalImpulse = x.X;
                                    cp2->NormalImpulse = x.Y;
                                }

                                // No solution, give up. This is hit sometimes, but it doesn't seem to matter.
                                break;
                            }
                        }

                        bodyA.LinearVelocity  = vA;
                        bodyA.AngularVelocity = wA;
                        bodyB.LinearVelocity  = vB;
                        bodyB.AngularVelocity = wB;
                    }
                }
            }
        }