public FroudeCalculator(double u, double l, Velocity element)
 {
     SetSpeedTranslator( element );
     U = u;
     L = l;
     Value = U/Math.Sqrt( g * L );
 }
		public void Rotate_1Pi_Rotated180degrees()
		{
			var act = TestStruct.Rotate((Single)Math.PI);
			var exp = new Velocity(-8.5f, -2.3f);

			CloudBallAssert.AreEqual(exp, act);
		}
示例#3
0
 public SetPosAndVelMsg(double x, double y, Velocity vx, Velocity vy) : base(DateTime.Now)
 {
     X = x;
     Y = y;
     VelX = vx;
     VelY = vy;
 }
		public void Rotate_100x0yPlus45_71x71y()
		{
			var velocity = new Velocity(10, 0);
			var angle = new Angle(Math.PI / 4d);
			var act = velocity.Rotate(angle);
			var exp = new Velocity(Math.Sqrt(50), Math.Sqrt(50));

			CloudBallAssert.AreEqual(exp, act);
		}
		public void Rotate_Minus135_71x71y()
		{
			var velocity = new Velocity(10, 0);
			var angle = new Angle(-3 * Math.PI / 4d);
			var act = velocity.Rotate(angle);
			var exp = new Velocity(-Math.Sqrt(50), -Math.Sqrt(50));

			CloudBallAssert.AreEqual(exp, act);
		}
		public static void AreEqual(Velocity expected, Velocity actual, float delta = 0.0001f)
		{
			var dX = Math.Abs(expected.X - actual.X);
			var dY = Math.Abs(expected.Y - actual.Y);
			if (dX > delta || dY > delta)
			{
				Assert.AreEqual(expected, actual);
			}
		}
		public void ToTarget_SomeWhere_XSqrt18YSqrt18()
		{
			var source = new Position(100, 100);
			var target = new Position(200, 200);
			var power = new Power(5);

			var act = Shoot.ToTarget(source, target, power);
			var exp = new Velocity(Math.Sqrt(18), Math.Sqrt(18));

			CloudBallAssert.AreEqual(exp, act);
		}
		public void WithVelocity_SomeWhere_X100plusSqrt17Y100plusSqrt18()
		{
			var source = new Position(100, 100);
			var target = new Velocity(15, 15);
			var power = new Power(5);

			var act = Shoot.WithVelocity(source, target, power);
			var exp = new Velocity(100d + Math.Sqrt(18), 100d+ Math.Sqrt(18));

			Assert.AreEqual(exp.X, act.X, 0.0001f);
			Assert.AreEqual(exp.Y, act.Y, 0.0001f);
		}
		public void Create_GoalOwn_After47Turns()
		{
			var ball = new Position(400, 400);
			var velo = new Velocity(-10, 1.9f);

			var act = BallPath.Create(ball, velo, 0, 1000);

			var expEnding = BallPath.Ending.GoalOwn;
			var expLength = 47;

			Assert.AreEqual(expEnding, act.End);
			Assert.AreEqual(expLength, act.Count);
		}
		public void Create_GoalOther_After58Turns()
		{
			var ball = new Position(1400, 600);
			var velo = new Velocity(11, 0);

			var act = BallPath.Create(ball, velo, 0, 1000);

			var expEnding = BallPath.Ending.GoalOther;
			var expLength = 58;

			Assert.AreEqual(expEnding, act.End);
			Assert.AreEqual(expLength, act.Count);
		}
		public void Create_EndOfGame_After10Turns()
		{
			var ball = new Position(1400, 600);
			var velo = new Velocity(11, 0);

			var act = BallPath.Create(ball, velo, 0,10);

			var expEnding = BallPath.Ending.EndOfGame;
			var expLength = 10;

			Assert.AreEqual(expEnding, act.End);
			Assert.AreEqual(expLength, act.Count);
		}
示例#12
0
 public Ship(Random randomGenerator, Graphics canvas, Rectangle harbourBounds)
 {
     this.randomGenerator = randomGenerator;
     this.canvas = canvas;
     this.harbourBounds = harbourBounds;
     brush = new SolidBrush(generateColour());
     location = new Point(randomGenerator.Next(0, harbourBounds.Width - SHIP_SIZE), randomGenerator.Next(0, harbourBounds.Height - SHIP_SIZE));
     State = EShipState.WANDERING;
     velocity = new Velocity(randomGenerator);
     size = new Size(SHIP_SIZE, SHIP_SIZE);
     amountOfFuel = randomGenerator.Next(MIN_START_FUEL, MAX_FUEL_AMOUNT + 1);
     fuelLossRate = randomGenerator.Next(MIN_FUEL_LOSS_RATE, MAX_FUEL_LOSS_RATE);
 }
        public void ExtractVelocityFromInput(KeySample __keyDown, Velocity value)
        {


            value.AngularVelocity = 0;
            value.LinearVelocityX = 0;
            value.LinearVelocityY = 0;



            if (__keyDown != null)
            {

                if (__keyDown[Keys.Up])
                {
                    // we have reasone to keep walking

                    value.LinearVelocityY = 1;
                }

                if (__keyDown[Keys.Down])
                {
                    // we have reasone to keep walking
                    // go slow backwards
                    value.LinearVelocityY = -0.5;

                }


                if (__keyDown[Keys.Left])
                {
                    // we have reasone to keep walking

                    value.AngularVelocity = -1;

                }

                if (__keyDown[Keys.Right])
                {
                    // we have reasone to keep walking

                    value.AngularVelocity = 1;

                }

            }


        }
 public void SetSpeedTranslator( Velocity element )
 {
     switch( element )
     {
         case Velocity.MetersPerSecond:
             speedTranslator = 1;
             break;
         case Velocity.Knot:
             speedTranslator = 1.852 / 3.6;
             break;
         case Velocity.KilomesterPerHour:
             speedTranslator = 1 / 3.6;
             break;
     }
 }
示例#15
0
 public BallState(
     double x,
     double y,
     DateTime time,
     Velocity velX,
     Velocity velY,
     double ballSize,
     double boxWidth,
     double boxHeight,
     double surfaceImpulse
 )
 {
     X = x;
     Y = y;
     Time = time;
     VelX = velX;
     VelY = velY;
     BallSize = ballSize;
     BoxWidth = boxWidth;
     BoxHeight = boxHeight;
     SurfaceImpulse = surfaceImpulse;
 }
示例#16
0
 /// <summary>
 /// Named argument partial update
 /// </summary>
 public BallState With(
     double? X = null,
     double? Y = null,
     DateTime? Time = null,
     Velocity? VelX = null,
     Velocity? VelY = null,
     double? BallSize = null,
     double? BoxWidth = null,
     double? BoxHeight = null,
     double? SurfaceImpulse = null
 )
 {
     return new BallState(
         X              ?? this.X,
         Y              ?? this.Y,
         Time           ?? this.Time,
         VelX           ?? this.VelX,
         VelY           ?? this.VelY,
         BallSize       ?? this.BallSize,
         BoxWidth       ?? this.BoxWidth,
         BoxHeight      ?? this.BoxHeight,
         SurfaceImpulse ?? this.SurfaceImpulse
     );
 }
        public void ExtractVelocityFromInput(KeySample __keyDown, Velocity value)
        {
            value.AngularVelocity = 0;

            if (__keyDown != null)
            {
                if (__keyDown[Keys.Left])
                {
                    // we have reasone to keep walking

                    value.AngularVelocity = -1;

                }

                if (__keyDown[Keys.Right])
                {
                    // we have reasone to keep walking

                    value.AngularVelocity = 1;

                }
            }
        }
示例#18
0
 public object Clone()
 {
     Velocity ret = new Velocity();
     ret.Direction = Direction;
     ret.Speed = Speed;
     return ret;
 }
示例#19
0
        public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            NativeArray <Translation> translations = chunk.GetNativeArray(translationType);
            NativeArray <Velocity>    velocities   = chunk.GetNativeArray(velocityType);

            NativeArray <Line> orcaLines = new NativeArray <Line>(maxNeighbors, Allocator.Temp);
            NativeArray <KeyValuePair <float, AgentNeighbor> > agentNeighbors =
                new NativeArray <KeyValuePair <float, AgentNeighbor> >(maxNeighbors, Allocator.Temp);
            NativeArray <int> quadrantKeys = new NativeArray <int>(MAX_QUADRANT_NEIGHBORS, Allocator.Temp);

            float invTimeStep       = 1.0f / dt;
            float combinedRadius    = radius * 2.0f;
            float combinedRadiusSqr = math.pow(combinedRadius, 2);
            float rangeSqr          = neighborsDist * neighborsDist;

            for (int entityIdx = 0; entityIdx < chunk.ChunkEntityCount; entityIdx++)
            {
                float2 velocity = velocities[entityIdx].Value;

                //Early exit if the agent is not moving
                if (math.lengthsq(velocity) < 0.001f)
                {
                    continue;
                }

                float2 position = translations[entityIdx].Value.xz;

                int countNeighborQuadrant = 0;
                QuadrantSystem.GetCurrentCellAndNeighborsKeys(position, ref quadrantKeys, ref countNeighborQuadrant);

                //ORCA setup
                int neighborsCount = 0;

                int nbObstacleLine = 0;

                //Get nearest neighbors
                for (int i = 0; i < countNeighborQuadrant; i++)
                {
                    if (!quadrantMap.TryGetFirstValue(quadrantKeys[i], out var neighbor,
                                                      out var nativeMultiHashMapIterator))
                    {
                        continue;
                    }
                    do
                    {
                        float2 dir     = position - neighbor.position;
                        float  distSqr = math.dot(dir, dir);

                        //Condition to avoid self
                        if (distSqr > 0.001f)
                        {
                            //If the other agent is under the minimum range => add it
                            if (!(distSqr < rangeSqr))
                            {
                                continue;
                            }

                            //If there is a free space, add it immediately
                            if (neighborsCount < maxNeighbors)
                            {
                                agentNeighbors[neighborsCount] = new KeyValuePair <float, AgentNeighbor>(distSqr,
                                                                                                         new AgentNeighbor()
                                {
                                    position = neighbor.position,
                                    velocity = neighbor.velocity
                                });

                                neighborsCount++;
                            }

                            //Make sure the list is sorted
                            int j = neighborsCount - 1;
                            while (j != 0 && distSqr < agentNeighbors[j - 1].Key)
                            {
                                agentNeighbors[j] = agentNeighbors[j - 1];
                                j--;
                            }

                            //Once a spot with a further agent is found, place if
                            agentNeighbors[j] = new KeyValuePair <float, AgentNeighbor>(distSqr, new AgentNeighbor()
                            {
                                position = neighbor.position,
                                velocity = neighbor.velocity
                            });

                            //If the list is full, only check agent nearer than the farrest neighbor.
                            if (neighborsCount == maxNeighbors)
                            {
                                rangeSqr = agentNeighbors[maxNeighbors - 1].Key;
                            }
                        }
                    } while (quadrantMap.TryGetNextValue(out neighbor, ref nativeMultiHashMapIterator));
                }

                //Evaluate each neighbors
                for (int neighborIdx = 0; neighborIdx < neighborsCount; neighborIdx++)
                {
                    AgentNeighbor otherAgent = agentNeighbors[neighborIdx].Value;

                    float2 relativePosition = otherAgent.position - position;
                    float2 relativeVelocity = velocity - otherAgent.velocity;
                    float  distSqr          = math.lengthsq(relativePosition);

                    Line   line;
                    float2 u;

                    if (distSqr > combinedRadiusSqr)
                    {
                        // No Collision
                        float2 w = relativeVelocity - invTimeHorizon * relativePosition;

                        // Vector from center to relative velocity
                        float wLengthSqr  = math.lengthsq(w);
                        float dotProduct1 = math.dot(w, relativePosition);

                        if (dotProduct1 < 0.0f && math.pow(dotProduct1, 2) > combinedRadiusSqr * wLengthSqr)
                        {
                            // Project on circle
                            float  wLength = math.sqrt(wLengthSqr);
                            float2 unitW   = w / wLength;

                            line.direction = new float2(unitW.y, -unitW.x);
                            u = (combinedRadius * invTimeHorizon - wLength) * unitW;
                        }
                        else
                        {
                            // Projection on legs
                            float leg = math.sqrt(distSqr - combinedRadiusSqr);

                            if (Det(relativePosition, w) > 0.0f)
                            {
                                line.direction = new float2(
                                    relativePosition.x * leg - relativePosition.y * combinedRadius,
                                    relativePosition.x * combinedRadius + relativePosition.y * leg) /
                                                 distSqr;
                            }
                            else
                            {
                                line.direction = -new float2(
                                    relativePosition.x * leg - relativePosition.y * combinedRadius,
                                    -relativePosition.x * combinedRadius + relativePosition.y * leg) /
                                                 distSqr;
                            }

                            float dotProduct2 = math.dot(relativeVelocity, line.direction);
                            u = dotProduct2 * line.direction - relativeVelocity;
                        }
                    }
                    else
                    {
                        //Collision
                        float2 w = relativeVelocity - invTimeStep * relativePosition;

                        float  wLength = math.length(w);
                        float2 wUnit   = w / wLength;

                        line.direction = new float2(wUnit.y, -wUnit.x);
                        u = (combinedRadius * invTimeStep - wLength) * wUnit;
                    }

                    line.point = velocity + 0.5f * u;

                    orcaLines[neighborIdx] = line;
                }

                float2 optimalVel = velocity;
                float2 vel        = float2.zero;
                float  maxSpeed   = velocities[entityIdx].maxSpeed;
                int    lineFail   = LinearProgram2(orcaLines, neighborsCount, maxSpeed, optimalVel, false, ref vel);

                if (lineFail < neighborsCount)
                {
                    LinearProgram3(orcaLines, neighborsCount, nbObstacleLine, lineFail, maxSpeed, ref vel);
                }

                velocities[entityIdx] = new Velocity()
                {
                    Value    = vel,
                    maxSpeed = maxSpeed
                };
            }

            quadrantKeys.Dispose();
            orcaLines.Dispose();
            agentNeighbors.Dispose();
        }
 internal void ApplyPatch(RigidBodyPatch patch)
 {
     // Apply any changes made to the state of the mixed reality extension runtime version of the rigid body.
     if (patch.Velocity != null && patch.Velocity.IsPatched())
     {
         _rigidbody.velocity = _rigidbody.velocity.GetPatchApplied(_sceneRoot.TransformDirection(Velocity.ApplyPatch(patch.Velocity).ToVector3()));
     }
     if (patch.AngularVelocity != null && patch.AngularVelocity.IsPatched())
     {
         _rigidbody.angularVelocity = _rigidbody.angularVelocity.GetPatchApplied(_sceneRoot.TransformDirection(AngularVelocity.ApplyPatch(patch.AngularVelocity).ToVector3()));
     }
     if (patch.Mass.HasValue)
     {
         _rigidbody.mass = _rigidbody.mass.GetPatchApplied(Mass.ApplyPatch(patch.Mass));
     }
     if (patch.DetectCollisions.HasValue)
     {
         _rigidbody.detectCollisions = _rigidbody.detectCollisions.GetPatchApplied(DetectCollisions.ApplyPatch(patch.DetectCollisions));
     }
     if (patch.CollisionDetectionMode.HasValue)
     {
         _rigidbody.collisionDetectionMode = _rigidbody.collisionDetectionMode.GetPatchApplied(CollisionDetectionMode.ApplyPatch(patch.CollisionDetectionMode));
     }
     if (patch.UseGravity.HasValue)
     {
         _rigidbody.useGravity = _rigidbody.useGravity.GetPatchApplied(UseGravity.ApplyPatch(patch.UseGravity));
     }
     _rigidbody.constraints = (RigidbodyConstraints)((int)_rigidbody.constraints).GetPatchApplied((int)ConstraintFlags.ApplyPatch(patch.ConstraintFlags));
 }
示例#21
0
文件: Form1.cs 项目: solson/DSAE
        void updateTimer_Tick(object sender, EventArgs e)
        {
            if (client != null)
                client.Update();

            if (quitting)
            {
                if (Program.isDebug == false)
                    PhidgetController.turnOffVibration();

                if (Program.useTouch)
                {
                    tuioClient.removeTuioListener(this);
                    tuioClient.disconnect();
                }

                Application.Exit();
            }

            if (studyController.currentCondition.UsesKinect() || calibratingKinect || studyController.currentCondition.IsCollocated())
            {
                if (tuioCursorID != -1 || tuioMouseUp)
                {
                    handleMouseMove(tuioCursor, playerID);
                    Cursor.Position = PointToScreen(tuioCursor);
                }

                if (tuioMouseDown)
                {
                    handleMouseDown(false);
                    tuioMouseDown = false;
                }

                if (tuioMouseUp)
                {
                    handleMouseUp(false);
                    tuioMouseUp = false;
                }
            }

            if (studyController.currentCondition.IsCollocated())
            {
                int oppositePlayerID = 1 - playerID;

                if (tuioCursorID2 != -1 || tuioMouseUp2)
                {
                    handleMouseMove(tuioCursor2, oppositePlayerID);
                    //Cursor.Position = PointToScreen(tuioCursor2);
                }

                if (tuioMouseDown2)
                {
                    handleMouseDown(false, oppositePlayerID);
                    tuioMouseDown2 = false;
                }

                if (tuioMouseUp2)
                {
                    handleMouseUp(false, oppositePlayerID);
                    tuioMouseUp2 = false;
                }
            }

            if (Program.useVelocity)
            {
                // Remove old cursor positions
                var now = DateTime.Now;

                while (user1LastMousePositions.Count > 0
                    && now - user1LastMousePositions.First().Time > TimeSpan.FromMilliseconds(300))
                    user1LastMousePositions.Dequeue();

                while (user2LastMousePositions.Count > 0
                    && now - user2LastMousePositions.First().Time > TimeSpan.FromMilliseconds(300))
                    user2LastMousePositions.Dequeue();

                // Calculate cursor velocity
                if (user1LastMousePositions.Count > 1)
                {
                    Point start = user1LastMousePositions.First().Location;
                    Point end = user1LastMousePositions.Last().Location;
                    user1Velocity = Velocity.FromCursorPositions(start, end);
                }
                else
                {
                    user1Velocity = new Velocity(0, 0);
                }

                // Calculate cursor velocity
                if (user2LastMousePositions.Count > 1)
                {
                    Point start = user2LastMousePositions.First().Location;
                    Point end = user2LastMousePositions.Last().Location;
                    user2Velocity = Velocity.FromCursorPositions(start, end);
                }
                else
                {
                    user2Velocity = new Velocity(0, 0);
                }
            }

            Refresh();

            //if using Polhemus
            /*if ((studyController.currentCondition == HaikuStudyCondition.Pens
                || studyController.currentCondition == HaikuStudyCondition.OnePens
                || studyController.currentCondition == HaikuStudyCondition.TwoPens)
                && Program.isDebug == false
                && polhemusController.tableController.isCalibrated == true)
            {
                Point windowLocation1 = polhemusController.tableLocationForStation(1);
                Point windowLocation2 = polhemusController.tableLocationForStation(2);

                if (studyController.currentCondition == HaikuStudyCondition.OnePens
                    || studyController.currentCondition == HaikuStudyCondition.Pens)
                {
                    if (windowLocation1.X >= 0 && windowLocation1.X <= Program.tableWidth && windowLocation1.Y >= 0 && windowLocation1.Y <= Program.tableHeight)
                        user1MouseLocation = windowLocation1;
                    sdgManager1.Mice[0].Location = user1MouseLocation;
                }
                if (studyController.currentCondition == HaikuStudyCondition.TwoPens
                    || studyController.currentCondition == HaikuStudyCondition.Pens)
                {
                    if (windowLocation2.X >= 0 && windowLocation2.X <= Program.tableWidth && windowLocation2.Y >= 0 && windowLocation2.Y <= Program.tableHeight)
                        user2MouseLocation = windowLocation2;
                    if (sdgManager1.Mice.Count > 1)
                        sdgManager1.Mice[1].Location = user2MouseLocation;
                }
                updateBoxLocations();
                //updateEmbodimentStuff();
            }*/

            if (Program.useVelocity)
            {
                if (studyController.areCrossing(user1MouseLocation, user2MouseLocation))
                {
                    if (!user1AtFault && !user2AtFault)
                    {
                        Direction user1Dir;
                        if (user1Velocity.Angle > -Math.PI / 2 && user1Velocity.Angle < Math.PI / 2)
                            user1Dir = Direction.Right;
                        else
                            user1Dir = Direction.Left;

                        Direction user2Dir;
                        if (user2Velocity.Angle > -Math.PI / 2 && user2Velocity.Angle < Math.PI / 2)
                            user2Dir = Direction.Right;
                        else
                            user2Dir = Direction.Left;

                        if (user1Velocity.Magnitude < 50 && user2Velocity.Magnitude >= 50)
                            user2AtFault = true;
                        else if (user2Velocity.Magnitude < 50 && user1Velocity.Magnitude >= 50)
                            user1AtFault = true;
                        else if (user1Velocity.Magnitude > 50 && user1Velocity.Magnitude > user2Velocity.Magnitude && user1Dir == user2Dir)
                            user1AtFault = true;
                        else if (user2Velocity.Magnitude > 50 && user2Velocity.Magnitude > user1Velocity.Magnitude && user1Dir == user2Dir)
                            user2AtFault = true;
                        else
                            user1AtFault = user2AtFault = true;

                        if (user1AtFault && !user2AtFault)
                            Console.WriteLine("User 1 at fault.");
                        else if (user2AtFault && !user1AtFault)
                            Console.WriteLine("User 2 at fault.");
                        else
                            Console.WriteLine("Both at fault.");
                    }
                }
                else
                {
                    user1AtFault = false;
                    user2AtFault = false;
                }
            }
            else
            {
                user1AtFault = true;
                user2AtFault = true;
            }

            blobOverlap = 0;
            user1ArmUser2PaperOcclusion = 0;
            user2ArmUser1PaperOcclusion = 0;
            if (Program.isDebug == false)
            {
                if (studyController.currentCondition.UsesBlobIntersection())
                {
                    Bitmap myMaskTable = null, theirMaskTable = null;
                    Rectangle myRect, theirRect;

                    if (playerID == 0)
                    {
                        myRect = HaikuStudyController.positionOneAreaRectangle;
                        theirRect = HaikuStudyController.positionTwoAreaRectangle;
                    }
                    else
                    {
                        myRect = HaikuStudyController.positionTwoAreaRectangle;
                        theirRect = HaikuStudyController.positionOneAreaRectangle;
                    }

                    myRect.Y = myRect.Y - Program.tableHeight + Program.usableHeight;
                    theirRect.Y = theirRect.Y - Program.tableHeight + Program.usableHeight;

                    if (showMyArm)
                    {
                        myMaskTable = new Bitmap(Program.tableWidth, Program.usableHeight, PixelFormat.Format24bppRgb);
                        using (Graphics g = Graphics.FromImage(myMaskTable))
                        {
                            g.Transform = kinectCalibration.Matrix;
                            g.TranslateTransform(0, Program.usableHeight - Program.tableHeight, MatrixOrder.Append);

                            g.DrawImage(myArmMask, myArmRect);
                        }

                        int occlusionArea = Utilities.MaskPaperOverlapArea(myMaskTable, theirRect);

                        if (playerID == 0)
                            user1ArmUser2PaperOcclusion = occlusionArea;
                        else if (playerID == 1)
                            user2ArmUser1PaperOcclusion = occlusionArea;
                    }

                    if (showTheirArm)
                    {
                        theirMaskTable = new Bitmap(Program.tableWidth, Program.usableHeight, PixelFormat.Format24bppRgb);
                        using (Graphics g = Graphics.FromImage(theirMaskTable))
                        {
                            g.Transform = theirCalibration;
                            g.TranslateTransform(0, Program.usableHeight - Program.tableHeight, MatrixOrder.Append);

                            g.DrawImage(theirArmMask, theirArmRect);
                        }

                        int occlusionArea = Utilities.MaskPaperOverlapArea(theirMaskTable, myRect);

                        if (playerID == 0)
                            user2ArmUser1PaperOcclusion = occlusionArea;
                        else if (playerID == 1)
                            user1ArmUser2PaperOcclusion = occlusionArea;
                    }

                    if (showMyArm && showTheirArm)
                        blobOverlap = Utilities.MaskOverlapArea(myMaskTable, theirMaskTable);
                }

                bool shouldVibrate = false;
                PointF? intersection = null;

                if (studyController.currentCondition.UsesVibration())
                {
                    if (studyController.currentCondition.UsesBlobIntersection())
                    {
                        if (blobOverlap > 0)
                            shouldVibrate = true;
                    }
                    else if (studyController.areCrossing(user1MouseLocation, user2MouseLocation, out intersection))
                    {
                        shouldVibrate = true;
                    }
                }

                if (studyController.currentCondition.UsesKinectFakeArms() && (!showMyArm || !showTheirArm))
                    shouldVibrate = false;

                /*if (studyController.areCrossing(user1MouseLocation, user2MouseLocation, out intersection) && studyController.isActuatePenalty == true
                    &&
                    (studyController.currentCondition == HaikuStudyCondition.LinesMouseVibrate
                    || studyController.currentCondition == HaikuStudyCondition.LinesBeltVibrate
                    || studyController.currentCondition == HaikuStudyCondition.PocketVibration
                    || studyController.currentCondition == HaikuStudyCondition.MouseVibration
                    || studyController.currentCondition == HaikuStudyCondition.KinectArmsVibration
                    || studyController.currentCondition.UsesVibration()))*/

                if (shouldVibrate)
                {
                    if (Program.useScaledVibration && intersection != null)
                    {
                        Point intersectionPoint = new Point((int)intersection.Value.X, (int)intersection.Value.Y);

                        if (playerID == 0 && user1AtFault)
                        {
                            double totalDist = Utilities.distanceBetweenPoints(user1Origin, user1MouseLocation);
                            double crossedDist = Utilities.distanceBetweenPoints(intersectionPoint, user1MouseLocation);

                            // Change smoothly from 50% vibration at just crossed to 100% vibration at 50% crossed.
                            double fractionCrossed = crossedDist / totalDist;
                            double amount = Math.Min(fractionCrossed + 0.5, 1);
                            PhidgetController.turnOnVibration(amount);
                        }
                        else if (playerID == 1 && user2AtFault)
                        {
                            double totalDist = Utilities.distanceBetweenPoints(user2Origin, user2MouseLocation);
                            double crossedDist = Utilities.distanceBetweenPoints(intersectionPoint, user2MouseLocation);

                            // Change smoothly from 50% vibration at just crossed to 100% vibration at 50% crossed.
                            double fractionCrossed = crossedDist / totalDist;
                            double amount = Math.Min(fractionCrossed + 0.5, 1);
                            PhidgetController.turnOnVibration(amount);
                        }
                    }
                    else // if ((playerID == 0 && user1AtFault) || (playerID == 1 && user2AtFault))
                    {
                        PhidgetController.turnOnVibration();
                    }
                }
                else if (studyController.currentCondition.UsesVibration())
                    PhidgetController.turnOffVibration();
            }

            //do logging
            if(doLogging == true)
            {
                bool isdragging1 = false;
                bool isdragging2 = false;
                if (boxBeingDraggedByUser1 != null)
                    isdragging1 = true;
                if (boxBeingDraggedByUser2 != null)
                    isdragging2 = true;
                studyController.logMouseLocations(user1MouseLocation, user2MouseLocation, isdragging1, isdragging2, areTheyBlocked);
            }
        }
示例#22
0
        protected void CheckBlockAhead()
        {
            var     length    = Length / 2;
            var     direction = Vector3.Normalize(Velocity * 1.00000101f);
            Vector3 position  = KnownPosition;
            int     count     = (int)(Math.Ceiling(Velocity.Length() / length) + 2);

            for (int i = 0; i < count; i++)
            {
                var distVec = direction * (float)length * i;
                BlockCoordinates blockPos = position + distVec;
                Block            block    = Level.GetBlock(blockPos);
                if (block.IsSolid)
                {
                    var yaw = (Math.Atan2(direction.X, direction.Z) * 180.0D / Math.PI) + 180;
                    //Log.Warn($"Will hit block {block} at angle of {yaw}");

                    Ray ray = new Ray(position, direction);
                    if (ray.Intersects(block.GetBoundingBox()).HasValue)
                    {
                        int face = IntersectSides(block.GetBoundingBox(), ray);

                        //Log.Warn($"Hit block {block} at angle of {yaw} on face {face}");
                        if (face == -1)
                        {
                            continue;
                        }
                        switch (face)
                        {
                        case 0:
                            Velocity *= new Vector3(1, 1, 0);
                            break;

                        case 1:
                            Velocity *= new Vector3(0, 1, 1);
                            break;

                        case 2:
                            Velocity *= new Vector3(1, 1, 0);
                            break;

                        case 3:
                            Velocity *= new Vector3(0, 1, 1);
                            break;

                        case 4:                                 // Under
                            Velocity *= new Vector3(1, 0, 1);
                            break;
                            //case 5:
                            //	float ff = 0.6f * 0.98f;
                            //	Velocity *= new Vector3(ff, 0.0f, ff);
                            //	break;
                        }
                        return;
                    }
                    else
                    {
                        //Log.Warn($"Hit block {block} at angle of {yaw} had no intersection (strange)");
                        Velocity *= new Vector3(0, 0, 0);
                    }
                }
            }
        }
示例#23
0
        //  Update position, check collisions, etc. and draw if particle still lives.
        //  Return false if particle dies/timeouts in this tick.
        public bool Draw(VRageRender.MyBillboard billboard)
        {
            if (Pivot != null)
            {
                if (PivotRotation != null)
                {
                    Matrix pivotRotationTransform =
                        Matrix.CreateRotationX(MathHelper.ToRadians(m_actualPivotRotation.X) * VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS) *
                        Matrix.CreateRotationY(MathHelper.ToRadians(m_actualPivotRotation.Y) * VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS) *
                        Matrix.CreateRotationZ(MathHelper.ToRadians(m_actualPivotRotation.Z) * VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS);

                    m_actualPivot = Vector3.TransformNormal(m_actualPivot, pivotRotationTransform);
                }

                m_actualPivot = Vector3D.TransformNormal(m_actualPivot, m_generation.GetEffect().WorldMatrix);
            }

            var actualPosition = m_actualPosition + m_actualPivot;

            MyTransparentGeometry.StartParticleProfilingBlock("Distance calculation");
            //  This time is scaled according to planned lifespan of the particle

            // Distance for sorting
            billboard.DistanceSquared = (float)Vector3D.DistanceSquared(MyTransparentGeometry.Camera.Translation, actualPosition);

            MyTransparentGeometry.EndParticleProfilingBlock();

            // If distance to camera is really small don't draw it.
            if (billboard.DistanceSquared <= 0.1f)
            {
                return(false);
            }

            MyTransparentGeometry.StartParticleProfilingBlock("Quad calculation");

            MyTransparentGeometry.StartParticleProfilingBlock("actualRadius");
            float actualRadius = 1;

            Radius.GetInterpolatedValue <float>(m_normalizedTime, out actualRadius);
            MyTransparentGeometry.EndParticleProfilingBlock();

            float actualAlphaCutout = 0;

            if (AlphaCutout != null)
            {
                MyTransparentGeometry.StartParticleProfilingBlock("AlphaCutout calculation");

                AlphaCutout.GetInterpolatedValue <float>(m_normalizedTime, out actualAlphaCutout);

                MyTransparentGeometry.EndParticleProfilingBlock();
            }

            billboard.ContainedBillboards.Clear();

            billboard.Near   = m_generation.GetEffect().Near;
            billboard.Lowres = m_generation.GetEffect().LowRes || VRageRender.MyRenderConstants.RenderQualityProfile.LowResParticles;
            billboard.CustomViewProjection = -1;
            billboard.ParentID             = -1;
            billboard.AlphaCutout          = actualAlphaCutout;
            billboard.UVOffset             = Vector2.Zero;
            billboard.UVSize = Vector2.One;



            float alpha = 1;


            Matrix  transform = Matrix.Identity;
            Vector3 normal    = Vector3.Forward;

            Vector3 actualVelocity = (Vector3)(m_actualPosition - m_previousPosition);

            float radiusBySpeed = m_generation.RadiusBySpeed;

            if (radiusBySpeed > 0)
            {
                float actualSpeed = actualVelocity.Length();
                actualRadius = Math.Max(actualRadius, actualRadius * m_generation.RadiusBySpeed * actualSpeed);
            }


            if (Type == MyParticleTypeEnum.Point)
            {
                MyTransparentGeometry.StartParticleProfilingBlock("GetBillboardQuadRotated");

                Vector2 actualRadiusV2 = new Vector2(actualRadius, actualRadius);

                if (Thickness > 0)
                {
                    actualRadiusV2.Y = Thickness;
                }

                if (m_generation.RotationReference == MyRotationReference.Camera)
                {
                    transform =
                        Matrix.CreateFromAxisAngle(MyTransparentGeometry.Camera.Right, m_actualAngle.X) *
                        Matrix.CreateFromAxisAngle(MyTransparentGeometry.Camera.Up, m_actualAngle.Y) *
                        Matrix.CreateFromAxisAngle(MyTransparentGeometry.Camera.Forward, m_actualAngle.Z);

                    GetBillboardQuadRotated(billboard, ref actualPosition, actualRadiusV2, ref transform, MyTransparentGeometry.Camera.Left, MyTransparentGeometry.Camera.Up);
                }
                else if (m_generation.RotationReference == MyRotationReference.Local)
                {
                    transform = Matrix.CreateFromAxisAngle(m_generation.GetEffect().WorldMatrix.Right, m_actualAngle.X) *
                                Matrix.CreateFromAxisAngle(m_generation.GetEffect().WorldMatrix.Up, m_actualAngle.Y) *
                                Matrix.CreateFromAxisAngle(m_generation.GetEffect().WorldMatrix.Forward, m_actualAngle.Z);

                    GetBillboardQuadRotated(billboard, ref actualPosition, actualRadiusV2, ref transform, m_generation.GetEffect().WorldMatrix.Left, m_generation.GetEffect().WorldMatrix.Up);
                }
                else if (m_generation.RotationReference == MyRotationReference.Velocity)
                {
                    if (actualVelocity.LengthSquared() < 0.00001f)
                    {
                        return(false);
                    }

                    Matrix velocityRef = Matrix.CreateFromDir(Vector3.Normalize(actualVelocity));

                    transform = Matrix.CreateFromAxisAngle(velocityRef.Right, m_actualAngle.X) *
                                Matrix.CreateFromAxisAngle(velocityRef.Up, m_actualAngle.Y) *
                                Matrix.CreateFromAxisAngle(velocityRef.Forward, m_actualAngle.Z);

                    GetBillboardQuadRotated(billboard, ref actualPosition, actualRadiusV2, ref transform, velocityRef.Left, velocityRef.Up);
                }
                else if (m_generation.RotationReference == MyRotationReference.VelocityAndCamera)
                {
                    if (actualVelocity.LengthSquared() < 0.0001f)
                    {
                        return(false);
                    }

                    Vector3 cameraToPoint = Vector3.Normalize(m_actualPosition - MyTransparentGeometry.Camera.Translation);
                    Vector3 velocityDir   = Vector3.Normalize(actualVelocity);

                    Vector3 sideVector = Vector3.Cross(cameraToPoint, velocityDir);
                    Vector3 upVector   = Vector3.Cross(sideVector, velocityDir);

                    Matrix velocityRef = Matrix.CreateWorld(m_actualPosition, velocityDir, upVector);

                    transform = Matrix.CreateFromAxisAngle(velocityRef.Right, m_actualAngle.X) *
                                Matrix.CreateFromAxisAngle(velocityRef.Up, m_actualAngle.Y) *
                                Matrix.CreateFromAxisAngle(velocityRef.Forward, m_actualAngle.Z);

                    GetBillboardQuadRotated(billboard, ref actualPosition, actualRadiusV2, ref transform, velocityRef.Left, velocityRef.Up);
                }
                else if (m_generation.RotationReference == MyRotationReference.LocalAndCamera)
                {
                    Vector3 cameraToPoint = Vector3.Normalize(m_actualPosition - MyTransparentGeometry.Camera.Translation);
                    Vector3 localDir      = m_generation.GetEffect().WorldMatrix.Forward;
                    float   dot           = cameraToPoint.Dot(localDir);
                    Matrix  velocityRef;
                    if (dot >= 0.9999f)
                    {
                        // TODO Petr: probably not correct, at least it does not produce NaN positions
                        velocityRef = Matrix.CreateTranslation(m_actualPosition);
                    }
                    else
                    {
                        Vector3 sideVector = Vector3.Cross(cameraToPoint, localDir);
                        Vector3 upVector   = Vector3.Cross(sideVector, localDir);

                        velocityRef = Matrix.CreateWorld(m_actualPosition, localDir, upVector);
                    }

                    transform = Matrix.CreateFromAxisAngle(velocityRef.Right, m_actualAngle.X) *
                                Matrix.CreateFromAxisAngle(velocityRef.Up, m_actualAngle.Y) *
                                Matrix.CreateFromAxisAngle(velocityRef.Forward, m_actualAngle.Z);

                    GetBillboardQuadRotated(billboard, ref actualPosition, actualRadiusV2, ref transform, velocityRef.Left, velocityRef.Up);
                }
                else
                {
                    System.Diagnostics.Debug.Fail("Unknown RotationReference enum");
                }

                MyTransparentGeometry.EndParticleProfilingBlock();
            }
            else if (Type == MyParticleTypeEnum.Line)
            {
                if (MyUtils.IsZero(Velocity.LengthSquared()))
                {
                    Velocity = MyUtils.GetRandomVector3Normalized();
                }

                MyQuadD quad = new MyQuadD();

                MyPolyLineD polyLine = new MyPolyLineD();
                //polyLine.LineDirectionNormalized = MyUtils.Normalize(Velocity);
                if (actualVelocity.LengthSquared() > 0)
                {
                    polyLine.LineDirectionNormalized = MyUtils.Normalize(actualVelocity);
                }
                else
                {
                    polyLine.LineDirectionNormalized = MyUtils.Normalize(Velocity);
                }

                if (m_actualAngle.Z != 0)
                {
                    polyLine.LineDirectionNormalized = Vector3.TransformNormal(polyLine.LineDirectionNormalized, Matrix.CreateRotationY(m_actualAngle.Z));
                }

                polyLine.Point0   = actualPosition;
                polyLine.Point1.X = actualPosition.X - polyLine.LineDirectionNormalized.X * actualRadius;
                polyLine.Point1.Y = actualPosition.Y - polyLine.LineDirectionNormalized.Y * actualRadius;
                polyLine.Point1.Z = actualPosition.Z - polyLine.LineDirectionNormalized.Z * actualRadius;

                if (m_actualAngle.LengthSquared() > 0)
                { //centerize
                    polyLine.Point0.X = polyLine.Point0.X - polyLine.LineDirectionNormalized.X * actualRadius * 0.5f;
                    polyLine.Point0.Y = polyLine.Point0.Y - polyLine.LineDirectionNormalized.Y * actualRadius * 0.5f;
                    polyLine.Point0.Z = polyLine.Point0.Z - polyLine.LineDirectionNormalized.Z * actualRadius * 0.5f;
                    polyLine.Point1.X = polyLine.Point1.X - polyLine.LineDirectionNormalized.X * actualRadius * 0.5f;
                    polyLine.Point1.Y = polyLine.Point1.Y - polyLine.LineDirectionNormalized.Y * actualRadius * 0.5f;
                    polyLine.Point1.Z = polyLine.Point1.Z - polyLine.LineDirectionNormalized.Z * actualRadius * 0.5f;
                }

                polyLine.Thickness = Thickness;
                var camPos = MyTransparentGeometry.Camera.Translation;
                MyUtils.GetPolyLineQuad(out quad, ref polyLine, camPos);

                transform.Forward = polyLine.LineDirectionNormalized;

                billboard.Position0 = quad.Point0;
                billboard.Position1 = quad.Point1;
                billboard.Position2 = quad.Point2;
                billboard.Position3 = quad.Point3;
            }
            else if (Type == MyParticleTypeEnum.Trail)
            {
                if (Quad.Point0 == Quad.Point2) //not moving particle
                {
                    return(false);
                }
                if (Quad.Point1 == Quad.Point3) //not moving particle was previous one
                {
                    return(false);
                }
                if (Quad.Point0 == Quad.Point3) //not moving particle was previous one
                {
                    return(false);
                }

                billboard.Position0 = Quad.Point0;
                billboard.Position1 = Quad.Point1;
                billboard.Position2 = Quad.Point2;
                billboard.Position3 = Quad.Point3;
            }
            else
            {
                throw new NotSupportedException(Type + " is not supported particle type");
            }

            if (this.m_generation.AlphaAnisotropic)
            {
                normal = Vector3.Normalize(Vector3.Cross(billboard.Position0 - billboard.Position1, billboard.Position0 - billboard.Position2));

                Vector3 forward = (billboard.Position0 + billboard.Position1 + billboard.Position2 + billboard.Position3) / 4 - MyTransparentGeometry.Camera.Translation;

                //Vector3 forward = MyTransparentGeometry.Camera.Forward;

                float angle = Math.Abs(Vector3.Dot(MyUtils.Normalize(forward), normal));


                float alphaCone = 1 - (float)Math.Pow(1 - angle, 4);
                alpha = alphaCone;
            }


            MyTransparentGeometry.EndParticleProfilingBlock();

            MyTransparentGeometry.StartParticleProfilingBlock("Material calculation");

            Vector4 color = Vector4.One;

            if (Color.GetKeysCount() > 0)
            {
                Color.GetInterpolatedValue <Vector4>(m_normalizedTime, out color);
            }

            if (m_arrayIndex != -1)
            {
                Vector3 arraySize = m_generation.ArraySize;
                if (arraySize.X > 0 && arraySize.Y > 0)
                {
                    int arrayOffset = m_generation.ArrayOffset;
                    int arrayModulo = m_generation.ArrayModulo == 0 ? (int)arraySize.X * (int)arraySize.Y : m_generation.ArrayModulo;

                    m_arrayIndex = m_arrayIndex % arrayModulo + arrayOffset;

                    float xDiv   = 1.0f / arraySize.X;
                    float yDiv   = 1.0f / arraySize.Y;
                    int   xIndex = m_arrayIndex % (int)arraySize.X;
                    int   yIndex = m_arrayIndex / (int)arraySize.X;

                    billboard.UVOffset = new Vector2(xDiv * xIndex, yDiv * yIndex);
                    billboard.UVSize   = new Vector2(xDiv, yDiv);
                }
            }


            var   material1         = MyTransparentMaterials.GetMaterial("ErrorMaterial");
            var   material2         = MyTransparentMaterials.GetMaterial("ErrorMaterial");
            float textureBlendRatio = 0;

            if ((Flags & ParticleFlags.BlendTextures) != 0)
            {
                float prevTime, nextTime, difference;
                Material.GetPreviousValue(m_normalizedTime, out material1, out prevTime);
                Material.GetNextValue(m_normalizedTime, out material2, out nextTime, out difference);

                if (prevTime != nextTime)
                {
                    textureBlendRatio = (m_normalizedTime - prevTime) * difference;
                }
            }
            else
            {
                Material.GetInterpolatedValue(m_normalizedTime, out material1);
            }

            MyTransparentGeometry.EndParticleProfilingBlock();

            //This gets 0.44ms for 2000 particles
            MyTransparentGeometry.StartParticleProfilingBlock("billboard.Start");

            if (material1 != null)
            {
                billboard.Material = material1.Name;
            }

            billboard.BlendMaterial     = material2.Name;
            billboard.BlendTextureRatio = textureBlendRatio;
            billboard.EnableColorize    = false;

            billboard.Color                     = color * alpha * m_generation.GetEffect().UserColorMultiplier;
            billboard.ColorIntensity            = ColorIntensity;
            billboard.SoftParticleDistanceScale = SoftParticleDistanceScale;

            MyTransparentGeometry.EndParticleProfilingBlock();

            return(true);
        }
示例#24
0
        private static void AddTyresInfo(R3ESharedData data, SimulatorDataSet simData)
        {
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontLeft.TyrePressure.ActualQuantity  = Pressure.FromKiloPascals(data.TirePressure.FrontLeft);
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontRight.TyrePressure.ActualQuantity = Pressure.FromKiloPascals(data.TirePressure.FrontRight);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearLeft.TyrePressure.ActualQuantity   = Pressure.FromKiloPascals(data.TirePressure.RearLeft);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearRight.TyrePressure.ActualQuantity  = Pressure.FromKiloPascals(data.TirePressure.RearRight);

            simData.PlayerInfo.CarInfo.WheelsInfo.FrontLeft.TyreWear.ActualWear  = 1 - data.TireWear.FrontLeft;
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontRight.TyreWear.ActualWear = 1 - data.TireWear.FrontRight;
            simData.PlayerInfo.CarInfo.WheelsInfo.RearLeft.TyreWear.ActualWear   = 1 - data.TireWear.RearLeft;
            simData.PlayerInfo.CarInfo.WheelsInfo.RearRight.TyreWear.ActualWear  = 1 - data.TireWear.RearRight;

            simData.PlayerInfo.CarInfo.WheelsInfo.FrontLeft.Rps  = -data.TireRps.FrontLeft;
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontRight.Rps = -data.TireRps.FrontRight;
            simData.PlayerInfo.CarInfo.WheelsInfo.RearLeft.Rps   = -data.TireRps.RearLeft;
            simData.PlayerInfo.CarInfo.WheelsInfo.RearRight.Rps  = -data.TireRps.RearRight;

            simData.PlayerInfo.CarInfo.WheelsInfo.FrontLeft.DirtLevel  = data.TireDirt.FrontLeft;
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontRight.DirtLevel = data.TireDirt.FrontRight;
            simData.PlayerInfo.CarInfo.WheelsInfo.RearLeft.DirtLevel   = data.TireDirt.RearLeft;
            simData.PlayerInfo.CarInfo.WheelsInfo.RearRight.DirtLevel  = data.TireDirt.RearRight;

            simData.PlayerInfo.CarInfo.WheelsInfo.FrontLeft.SuspensionTravel  = Distance.FromMeters(data.Player.SuspensionDeflection.FrontLeft);
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontRight.SuspensionTravel = Distance.FromMeters(data.Player.SuspensionDeflection.FrontRight);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearLeft.SuspensionTravel   = Distance.FromMeters(data.Player.SuspensionDeflection.RearLeft);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearRight.SuspensionTravel  = Distance.FromMeters(data.Player.SuspensionDeflection.RearRight);

            simData.PlayerInfo.CarInfo.WheelsInfo.FrontLeft.SuspensionVelocity  = Velocity.FromMs(data.Player.SuspensionVelocity.FrontLeft);
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontRight.SuspensionVelocity = Velocity.FromMs(data.Player.SuspensionVelocity.FrontRight);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearLeft.SuspensionVelocity   = Velocity.FromMs(data.Player.SuspensionVelocity.RearLeft);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearRight.SuspensionVelocity  = Velocity.FromMs(data.Player.SuspensionVelocity.RearRight);

            simData.PlayerInfo.CarInfo.WheelsInfo.FrontLeft.Camber  = Angle.GetFromRadians(data.Player.Camber.FrontLeft);
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontRight.Camber = Angle.GetFromRadians(data.Player.Camber.FrontRight);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearLeft.Camber   = Angle.GetFromRadians(data.Player.Camber.RearLeft);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearRight.Camber  = Angle.GetFromRadians(data.Player.Camber.RearRight);

            simData.PlayerInfo.CarInfo.WheelsInfo.FrontLeft.RideHeight  = Distance.FromMeters(data.Player.RideHeight.FrontLeft);
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontRight.RideHeight = Distance.FromMeters(data.Player.RideHeight.FrontRight);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearLeft.RideHeight   = Distance.FromMeters(data.Player.RideHeight.RearLeft);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearRight.RideHeight  = Distance.FromMeters(data.Player.RideHeight.RearRight);

            // Front Left Tyre Temps
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontLeft.CenterTyreTemp.IdealQuantity       = Temperature.FromCelsius(data.TireTemp.FrontLeft.OptimalTemp);
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontLeft.CenterTyreTemp.IdealQuantityWindow = Temperature.FromCelsius((data.TireTemp.FrontLeft.HotTemp - data.TireTemp.FrontLeft.OptimalTemp) * 0.5);
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontLeft.LeftTyreTemp.ActualQuantity        = Temperature.FromCelsius(data.TireTemp.FrontLeft.CurrentTemp.Left);
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontLeft.RightTyreTemp.ActualQuantity       = Temperature.FromCelsius(data.TireTemp.FrontLeft.CurrentTemp.Right);
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontLeft.CenterTyreTemp.ActualQuantity      = Temperature.FromCelsius(data.TireTemp.FrontLeft.CurrentTemp.Center);
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontLeft.TyreCoreTemperature.ActualQuantity = Temperature.FromCelsius((data.TireTemp.FrontLeft.CurrentTemp.Left + data.TireTemp.FrontLeft.CurrentTemp.Center + data.TireTemp.FrontLeft.CurrentTemp.Right) / 3);


            // Front Right Tyre Temps
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontRight.CenterTyreTemp.IdealQuantity       = Temperature.FromCelsius(data.TireTemp.FrontLeft.OptimalTemp);
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontRight.CenterTyreTemp.IdealQuantityWindow = Temperature.FromCelsius((data.TireTemp.FrontLeft.HotTemp - data.TireTemp.FrontLeft.OptimalTemp) * 0.5);
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontRight.LeftTyreTemp.ActualQuantity        = Temperature.FromCelsius(data.TireTemp.FrontRight.CurrentTemp.Left);
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontRight.RightTyreTemp.ActualQuantity       = Temperature.FromCelsius(data.TireTemp.FrontRight.CurrentTemp.Right);
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontRight.CenterTyreTemp.ActualQuantity      = Temperature.FromCelsius(data.TireTemp.FrontRight.CurrentTemp.Center);
            simData.PlayerInfo.CarInfo.WheelsInfo.FrontRight.TyreCoreTemperature.ActualQuantity = Temperature.FromCelsius((data.TireTemp.FrontRight.CurrentTemp.Left + data.TireTemp.FrontRight.CurrentTemp.Center + data.TireTemp.FrontRight.CurrentTemp.Right) / 3);


            // Rear Left Tyre Temps
            simData.PlayerInfo.CarInfo.WheelsInfo.RearLeft.CenterTyreTemp.IdealQuantity       = Temperature.FromCelsius(data.TireTemp.FrontLeft.OptimalTemp);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearLeft.CenterTyreTemp.IdealQuantityWindow = Temperature.FromCelsius((data.TireTemp.FrontLeft.HotTemp - data.TireTemp.FrontLeft.OptimalTemp) * 0.5);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearLeft.LeftTyreTemp.ActualQuantity        = Temperature.FromCelsius(data.TireTemp.RearLeft.CurrentTemp.Left);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearLeft.RightTyreTemp.ActualQuantity       = Temperature.FromCelsius(data.TireTemp.RearLeft.CurrentTemp.Right);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearLeft.CenterTyreTemp.ActualQuantity      = Temperature.FromCelsius(data.TireTemp.RearLeft.CurrentTemp.Center);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearLeft.TyreCoreTemperature.ActualQuantity = Temperature.FromCelsius((data.TireTemp.RearLeft.CurrentTemp.Left + data.TireTemp.RearLeft.CurrentTemp.Center + data.TireTemp.RearLeft.CurrentTemp.Right) / 3);

            // Rear Right Tyre Temps
            simData.PlayerInfo.CarInfo.WheelsInfo.RearRight.CenterTyreTemp.IdealQuantity       = Temperature.FromCelsius(data.TireTemp.FrontLeft.OptimalTemp);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearRight.CenterTyreTemp.IdealQuantityWindow = Temperature.FromCelsius((data.TireTemp.FrontLeft.HotTemp - data.TireTemp.FrontLeft.OptimalTemp) * 0.5);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearRight.LeftTyreTemp.ActualQuantity        = Temperature.FromCelsius(data.TireTemp.RearRight.CurrentTemp.Left);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearRight.RightTyreTemp.ActualQuantity       = Temperature.FromCelsius(data.TireTemp.RearRight.CurrentTemp.Right);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearRight.CenterTyreTemp.ActualQuantity      = Temperature.FromCelsius(data.TireTemp.RearRight.CurrentTemp.Center);
            simData.PlayerInfo.CarInfo.WheelsInfo.RearRight.TyreCoreTemperature.ActualQuantity = Temperature.FromCelsius((data.TireTemp.RearRight.CurrentTemp.Left + data.TireTemp.RearRight.CurrentTemp.Center + data.TireTemp.RearRight.CurrentTemp.Right) / 3);

            // Fuel System
            simData.PlayerInfo.CarInfo.FuelSystemInfo.FuelCapacity  = Volume.FromLiters(data.FuelCapacity);
            simData.PlayerInfo.CarInfo.FuelSystemInfo.FuelRemaining = Volume.FromLiters(data.FuelLeft);
            simData.PlayerInfo.CarInfo.FuelSystemInfo.FuelPressure  = Pressure.FromKiloPascals(data.FuelPressure);
        }
        void FillData(ref MyGPUEmitter emitter)
        {
            float time;
            MyAnimatedPropertyVector4 color;
            MyAnimatedPropertyFloat   radius;
            MyAnimatedPropertyFloat   colorIntensity;

            Color.GetKey(0, out time, out color);
            Radius.GetKey(0, out time, out radius);
            ColorIntensity.GetKey(0, out time, out colorIntensity);

            emitter.GID = m_renderId;
            m_currentParticlesPerSecond = GetParticlesPerSecond();
            emitter.ParticlesPerSecond  = m_show ? m_currentParticlesPerSecond : 0;

            float intensity;

            color.GetKey(0, out time, out emitter.Data.Color0);
            color.GetKey(1, out emitter.Data.ColorKey1, out emitter.Data.Color1);
            color.GetKey(2, out emitter.Data.ColorKey2, out emitter.Data.Color2);
            color.GetKey(3, out time, out emitter.Data.Color3);

            // unmultiply colors and factor by intensity
            colorIntensity.GetInterpolatedValue <float>(0, out intensity);
            emitter.Data.Color0.X *= intensity;
            emitter.Data.Color0.Y *= intensity;
            emitter.Data.Color0.Z *= intensity;
            emitter.Data.Color0   *= m_effect.UserColorMultiplier;
            colorIntensity.GetInterpolatedValue <float>(emitter.Data.ColorKey1, out intensity);
            emitter.Data.Color1.X *= intensity;
            emitter.Data.Color1.Y *= intensity;
            emitter.Data.Color1.Z *= intensity;
            emitter.Data.Color1   *= m_effect.UserColorMultiplier;
            colorIntensity.GetInterpolatedValue <float>(emitter.Data.ColorKey2, out intensity);
            emitter.Data.Color2.X *= intensity;
            emitter.Data.Color2.Y *= intensity;
            emitter.Data.Color2.Z *= intensity;
            emitter.Data.Color2   *= m_effect.UserColorMultiplier;
            colorIntensity.GetInterpolatedValue <float>(1.0f, out intensity);
            emitter.Data.Color3.X *= intensity;
            emitter.Data.Color3.Y *= intensity;
            emitter.Data.Color3.Z *= intensity;
            emitter.Data.Color3   *= m_effect.UserColorMultiplier;

            emitter.Data.ColorVar = ColorVar;
            if (emitter.Data.ColorVar > 1.0f)
            {
                emitter.Data.ColorVar = 1.0f;
            }
            else if (emitter.Data.ColorVar < 0)
            {
                emitter.Data.ColorVar = 0;
            }
            emitter.Data.HueVar = HueVar;
            if (emitter.Data.HueVar > 1.0f)
            {
                emitter.Data.HueVar = 1.0f;
            }
            else if (emitter.Data.HueVar < 0)
            {
                emitter.Data.HueVar = 0;
            }

            emitter.Data.Bounciness = Bounciness;

            MatrixD mat = CalculateWorldMatrix();

            emitter.Data.RotationMatrix = mat;
            emitter.Data.Direction      = Direction;
            Velocity.GetInterpolatedValue <float>(m_effect.GetElapsedTime(), out emitter.Data.Velocity);
            VelocityVar.GetInterpolatedValue <float>(m_effect.GetElapsedTime(), out emitter.Data.VelocityVar);
            float cone;

            DirectionCone.GetInterpolatedValue <float>(m_effect.GetElapsedTime(), out cone);
            emitter.Data.DirectionCone = MathHelper.ToRadians(cone);
            DirectionConeVar.GetInterpolatedValue <float>(m_effect.GetElapsedTime(), out cone);
            emitter.Data.DirectionConeVar = MathHelper.ToRadians(cone);

            emitter.Data.NumParticlesToEmitThisFrame = 0;

            emitter.Data.ParticleLifeSpan = Life;

            radius.GetKey(0, out time, out emitter.Data.ParticleSize0);
            radius.GetKey(1, out emitter.Data.ParticleSizeKeys1, out emitter.Data.ParticleSize1);
            radius.GetKey(2, out emitter.Data.ParticleSizeKeys2, out emitter.Data.ParticleSize2);
            radius.GetKey(3, out time, out emitter.Data.ParticleSize3);
            emitter.Data.ParticleSize0 *= m_effect.UserRadiusMultiplier;
            emitter.Data.ParticleSize1 *= m_effect.UserRadiusMultiplier;
            emitter.Data.ParticleSize2 *= m_effect.UserRadiusMultiplier;
            emitter.Data.ParticleSize3 *= m_effect.UserRadiusMultiplier;

            EmitterSize.GetInterpolatedValue <Vector3>(m_effect.GetElapsedTime(), out emitter.Data.EmitterSize);
            EmitterSizeMin.GetInterpolatedValue <float>(m_effect.GetElapsedTime(), out emitter.Data.EmitterSizeMin);
            emitter.Data.RotationVelocity    = RotationVelocity;
            emitter.Data.RotationVelocityVar = RotationVelocityVar;

            emitter.Data.Acceleration     = Acceleration;
            emitter.Data.Gravity          = m_effect.Gravity * Gravity;
            emitter.Data.StreakMultiplier = StreakMultiplier;

            GPUEmitterFlags flags = 0;

            flags |= Streaks ? GPUEmitterFlags.Streaks : 0;
            flags |= Collide ? GPUEmitterFlags.Collide : 0;
            flags |= SleepState ? GPUEmitterFlags.SleepState : 0;
            flags |= Light ? GPUEmitterFlags.Light : 0;
            flags |= VolumetricLight ? GPUEmitterFlags.VolumetricLight : 0;
            flags |= m_effect.IsSimulationPaused || MyParticlesManager.Paused ? GPUEmitterFlags.FreezeSimulate : 0;
            flags |= MyParticlesManager.Paused ? GPUEmitterFlags.FreezeEmit : 0;

            emitter.Data.Flags = flags;

            emitter.Data.SoftParticleDistanceScale = SoftParticleDistanceScale;
            emitter.Data.AnimationFrameTime        = AnimationFrameTime;
            emitter.Data.OITWeightFactor           = OITWeightFactor;

            emitter.Data.Scale = m_effect.GetEmitterScale();

            emitter.AtlasTexture     = (Material.GetValue <MyTransparentMaterial>()).Texture;
            emitter.AtlasDimension   = new Vector2I((int)ArraySize.GetValue <Vector3>().X, (int)ArraySize.GetValue <Vector3>().Y);
            emitter.AtlasFrameOffset = ArrayOffset;
            emitter.AtlasFrameModulo = ArrayModulo;
            emitter.WorldPosition    = mat.Translation;
        }
示例#26
0
        private bool InitializeParticle(Particle p)
        {
            Color4   color;
            Matrix32 transform;

            CalcInitialColorAndTransform(out color, out transform);
            float   emitterScaleAmount = 1;
            Vector2 emitterScale       = new Vector2();

            emitterScale.X = transform.U.Length;
            emitterScale.Y = transform.V.Length;
            float crossProduct = Vector2.CrossProduct(transform.U, transform.V);

            if (crossProduct < 0.0f)
            {
                emitterScale.Y = -emitterScale.Y;
            }
            emitterScaleAmount = (float)Math.Sqrt(Math.Abs(crossProduct));
            float        emitterAngle             = transform.U.Atan2Deg;
            NumericRange aspectRatioVariationPair = new NumericRange(0, Math.Max(0.0f, AspectRatio.Dispersion));
            float        zoom        = Zoom.NormalRandomNumber(Rng);
            float        aspectRatio = AspectRatio.Median *
                                       (1 + Math.Abs(aspectRatioVariationPair.NormalRandomNumber(Rng))) /
                                       (1 + Math.Abs(aspectRatioVariationPair.NormalRandomNumber(Rng)));

            p.TextureIndex        = 0.0f;
            p.Velocity            = Velocity.NormalRandomNumber(Rng) * emitterScaleAmount;
            p.ScaleInitial        = emitterScale * ApplyAspectRatio(zoom, aspectRatio);
            p.ScaleCurrent        = p.ScaleInitial;
            p.WindDirection       = WindDirection.UniformRandomNumber(Rng);
            p.WindAmount          = WindAmount.NormalRandomNumber(Rng) * emitterScaleAmount;
            p.GravityVelocity     = 0.0f;
            p.GravityAcceleration = 0.0f;
            p.GravityAmount       = GravityAmount.NormalRandomNumber(Rng) * emitterScaleAmount;
            p.GravityDirection    = GravityDirection.NormalRandomNumber(Rng);
            p.MagnetAmountInitial = MagnetAmount.NormalRandomNumber(Rng);
            p.Lifetime            = Math.Max(Lifetime.NormalRandomNumber(Rng), 0.1f);
            p.Age                 = 0.0f;
            p.AngularVelocity     = AngularVelocity.NormalRandomNumber(Rng);
            p.Angle               = Orientation.UniformRandomNumber(Rng) + emitterAngle;
            p.Spin                = Spin.NormalRandomNumber(Rng);
            p.ColorInitial        = color;
            p.ColorCurrent        = color;
            p.RandomRayDirection  = (new NumericRange(0, 360)).UniformRandomNumber(Rng);
            p.RandomSplineVertex0 = GenerateRandomMotionControlPoint(ref p.RandomRayDirection);
            p.RandomSplineVertex1 = Vector2.Zero;
            p.RandomSplineVertex2 = GenerateRandomMotionControlPoint(ref p.RandomRayDirection);
            p.RandomSplineVertex3 = GenerateRandomMotionControlPoint(ref p.RandomRayDirection);
            p.RandomMotionSpeed   = RandomMotionSpeed.NormalRandomNumber(Rng);
            p.RandomSplineOffset  = 0;
            Vector2 position;

            switch (Shape)
            {
            case EmitterShape.Point:
                position           = 0.5f * Size;
                p.RegularDirection = Direction.UniformRandomNumber(Rng) + emitterAngle - 90.0f;
                break;

            case EmitterShape.Line:
                position           = new Vector2(Rng.RandomFloat() * Size.X, Size.Y * 0.5f);
                p.RegularDirection = Direction.UniformRandomNumber(Rng) + emitterAngle - 90.0f;
                break;

            case EmitterShape.Ellipse:
                float   angle  = Rng.RandomFloat(0, 360);
                Vector2 sincos = Vector2.CosSinRough(angle * Mathf.DegToRad);
                position           = 0.5f * ((sincos + Vector2.One) * Size);
                p.RegularDirection = Direction.UniformRandomNumber(Rng) + emitterAngle - 90 + angle;
                break;

            case EmitterShape.Area:
                position.X         = Rng.RandomFloat() * Size.X;
                position.Y         = Rng.RandomFloat() * Size.Y;
                p.RegularDirection = Direction.UniformRandomNumber(Rng) + emitterAngle - 90.0f;
                break;

            case EmitterShape.Custom:
                position           = GetPointInCustomShape();
                p.RegularDirection = Direction.UniformRandomNumber(Rng) + emitterAngle - 90.0f;
                break;

            default:
                throw new Lime.Exception("Invalid particle emitter shape");
            }
            p.RegularPosition = transform.TransformVector(position);
            var modifiers = GetModifiers();

            if (modifiers.Count == 0)
            {
                return(false);
            }
            p.Modifier = modifiers[Rng.RandomInt(modifiers.Count)];
            var animationDuration = AnimationUtils.FramesToSeconds(p.Modifier.Animators.GetOverallDuration());

            p.AgeToAnimationTime = (float)(animationDuration / p.Lifetime);
            if (EmissionType == EmissionType.Inner)
            {
                p.RegularDirection += 180;
            }
            else if ((EmissionType & EmissionType.Inner) != 0)
            {
                if (Rng.RandomInt(2) == 0)
                {
                    p.RegularDirection += 180;
                }
            }
            else if (EmissionType == 0)
            {
                return(false);
            }
            p.FullDirection = p.RegularDirection;
            p.FullPosition  = p.RegularPosition;
            return(true);
        }
示例#27
0
 public void WriteVelocity(Velocity value)
 {
     WriteShort(value.X);
     WriteShort(value.Y);
     WriteShort(value.Z);
 }
示例#28
0
        public override void Tick()
        {
            ViewOffset = Vector3.Up * EyeHeight;

            UpdateBBox();

            ViewOffset += TraceOffset;

            RestoreGroundPos();

            if (Unstuck.TestAndFix())
            {
                return;
            }

            Swimming = Player.WaterLevel.Fraction > 0.6f;

            if (!Swimming)
            {
                Velocity -= new Vector3(0, 0, Gravity * 0.5f) * Time.Delta;
                Velocity += new Vector3(0, 0, BaseVelocity.z) * Time.Delta;

                BaseVelocity = BaseVelocity.WithZ(0);
            }

            if (Input.Pressed(InputButton.Jump))
            {
                CheckJumpButton();
            }

            bool bStartOnGround = GroundEntity != null;

            if (bStartOnGround)
            {
                Velocity = Velocity.WithZ(0);

                if (GroundEntity != null)
                {
                    ApplyFriction(GroundFriction * _surfaceFriction);
                }
            }

            WishVelocity = new Vector3(Input.Forward, Input.Left, 0);

            var inSpeed = WishVelocity.Length.Clamp(0, 1);

            WishVelocity *= Input.Rot;

            if (!Swimming)
            {
                WishVelocity = WishVelocity.WithZ(0);
            }

            WishVelocity  = WishVelocity.Normal * inSpeed;
            WishVelocity *= GetWishSpeed();

            Duck.PreTick();

            bool stayOnGround = false;

            OnPreTickMove();

            if (Swimming)
            {
                ApplyFriction(1);
                WaterMove();
            }
            else if (GroundEntity != null)
            {
                stayOnGround = true;
                WalkMove();
            }
            else
            {
                AirMove();
            }

            CategorizePosition(stayOnGround);

            if (!Swimming)
            {
                Velocity -= new Vector3(0, 0, Gravity * 0.5f) * Time.Delta;
            }

            if (GroundEntity != null)
            {
                Velocity = Velocity.WithZ(0);
            }

            SaveGroundPos();
        }
示例#29
0
        private void TryPlayerMove()
        {
            var timeLeft    = Time.Delta;
            var allFraction = 0.0f;

            var originalVelocity = Velocity;
            var primalVelocity   = Velocity;

            var numPlanes = 0;

            for (int bumpCount = 0; bumpCount < 4; bumpCount++)
            {
                if (Velocity.Length == 0.0f)
                {
                    break;
                }

                var end = Pos + Velocity * timeLeft;
                var pm  = TraceBBox(Pos, end);

                allFraction += pm.Fraction;

                if (pm.Fraction > DistEpsilon)
                {
                    Pos = pm.EndPos;
                    originalVelocity = Velocity;
                    numPlanes        = 0;
                }

                if (pm.Fraction == 1)
                {
                    break;
                }

                var probablyFloor = pm.Normal.z > GroundNormalZ;

                timeLeft -= timeLeft * pm.Fraction;

                if (numPlanes >= _planes.Length)
                {
                    Velocity = Vector3.Zero;
                    break;
                }

                _planes[numPlanes] = pm.Normal;
                numPlanes++;

                if (numPlanes == 1 && GroundEntity == null)
                {
                    var overbounce = 1.0f;

                    if (!probablyFloor)
                    {
                        overbounce = 1.0f + Bounce * (1.0f - _surfaceFriction);
                    }

                    originalVelocity = ClipVelocity(originalVelocity, _planes[0], overbounce);
                    Velocity         = originalVelocity;
                }
                else
                {
                    int i;

                    for (i = 0; i < numPlanes; i++)
                    {
                        Velocity = ClipVelocity(originalVelocity, _planes[i], 1);

                        int j;

                        for (j = 0; j < numPlanes; j++)
                        {
                            if (j == i)
                            {
                                continue;
                            }

                            if (Velocity.Dot(_planes[j]) < 0)
                            {
                                break;
                            }
                        }

                        if (j == numPlanes)
                        {
                            break;
                        }
                    }

                    if (i == numPlanes)
                    {
                        if (numPlanes != 2)
                        {
                            Velocity = Vector3.Zero;
                            break;
                        }

                        var direction = Vector3.Cross(_planes[0], _planes[1]).Normal;
                        var dot       = direction.Dot(Velocity);

                        Velocity = direction * dot;
                    }

                    if (Vector3.Dot(Velocity, primalVelocity) <= 0)
                    {
                        Velocity = Vector3.Zero;
                        break;
                    }
                }
            }

            if (allFraction == 0)
            {
                Velocity = Vector3.Zero;
            }
        }
示例#30
0
 public Moon(Position initialPosition, Velocity initialVelocity)
 {
     _position = initialPosition;
     _velocity = initialVelocity;
 }
示例#31
0
 /// <summary>
 /// Updates the state with new position and velocity
 /// </summary>
 static Func<BallState, BallState> SetPosAndVel(double x, double y, Velocity vx, Velocity vy) => state =>
     state.With(X: x, Y: y, VelX: vx, VelY: vy);
示例#32
0
            public override void Update(GameTime gameTime)
            {
                Gameplay g = Sender.Parent.Parent;

                #region Gestion de la gravité
                float vx = Velocity.X;
                float vy = Velocity.Y;

                if (!_onFloor)
                {
                    vy = GRAVITY;
                }

                // Dans l'eau
                if (Position.Y > g.WaterLevel)
                {
                    Velocity.Normalize();
                    if (Position.Y > g.WaterLevel + g.WaterHeight)
                    {
                        Die(false);
                    }
                }
                #endregion

                #region Limitations de la vélocité
                vx       = MathHelper.Clamp(vx, -SPEED_MAX, SPEED_MAX);
                vy       = MathHelper.Clamp(vy, -SPEED_MAX, SPEED_MAX);
                Velocity = new Vector2(vx, vy);
                #endregion

                #region Récupération de l'ancienne position en 3 points en bas (Gauche / Centre / Droite) pour vérifier les collisions
                Vector2 previousPosMiddle = new Vector2(BoundingBox.Location.X, BoundingBox.Size.Y);
                Vector2 previousPosLeft   = new Vector2(BoundingBox.Left, BoundingBox.Bottom);
                Vector2 previousPosRight  = new Vector2(BoundingBox.Right, BoundingBox.Bottom);
                #endregion

                base.Update(gameTime);

                #region Collision avec le sol
                Vector2 newPosLeft   = new Vector2(Position.X - ImgBox.Value.Width / 2, Position.Y);
                Vector2 newPosMiddle = Position;
                Vector2 newPosRight  = new Vector2(Position.X + ImgBox.Value.Width / 2, Position.Y);

                if (g.IsSolid(newPosLeft, previousPosLeft) ||
                    g.IsSolid(newPosMiddle, previousPosMiddle) ||
                    g.IsSolid(newPosRight, previousPosRight))
                {
                    _onFloor = true;

                    // Récupère l'altitude en Y à position.X -20 et +20 afin d'en déterminer l'angle à partir d'un vecteur tracé entre ces deux points.
                    Vector2 center = g.FindHighestPoint(Position, 0);
                    Vector2 before = g.FindHighestPoint(Position, -BoundingBox.Width / 2);
                    Vector2 after  = g.FindHighestPoint(Position, BoundingBox.Width / 2);
                    Angle     = (float)utils.MathAngle(after - before);
                    Position += center;
                }
                else
                {
                    _onFloor = false;
                }
                RefreshBoundingBox();
                #endregion
            }
        public void ExtractVelocityFromInput(KeySample __keyDown, Velocity value)
        {


            value.AngularVelocity = 0;
            value.LinearVelocityX = 0;
            value.LinearVelocityY = 0;



            if (__keyDown != null)
            {
                #region alt
                Func<Keys, Keys, bool> alt =
                    (k1, k2) =>
                    {
                        
                        if (__keyDown[Keys.Alt, Keys.ControlKey])
                        {
                            return __keyDown[k2];
                        }
                        return __keyDown[k1];
                    };
                #endregion

                var k = new
                {
                    up = __keyDown[Keys.Up],
                    down = __keyDown[Keys.Down],

                    left = alt(Keys.Left, Keys.A),
                    right = alt(Keys.Right, Keys.D),

                    strafeleft = alt(Keys.A, Keys.Left),
                    straferight = alt(Keys.D, Keys.Right),
                };


                if (k.up)
                {
                    // we have reasone to keep walking

                    value.LinearVelocityY = 1;
                }

                if (k.down)
                {
                    // we have reasone to keep walking
                    // go slow backwards
                    value.LinearVelocityY = -0.5;

                }


                if (k.left)
                {
                    // we have reasone to keep walking

                    value.AngularVelocity = -1;

                }

                if (k.right)
                {
                    // we have reasone to keep walking

                    value.AngularVelocity = 1;

                }

                if (k.strafeleft)
                {
                    // we have reasone to keep walking

                    value.LinearVelocityX = -1;

                }

                if (k.straferight)
                {
                    // we have reasone to keep walking

                    value.LinearVelocityX = 1;

                }
            }


        }
        public void ApplyVelocity()
        {
            // this is now

            {
                var current = this.body;
                //var v = velocity.AngularVelocity * 10;         current.SetAngularVelocity(v);


                current.ApplyAngularImpulse(
                    velocity.AngularVelocity
                      * this.CurrentInput.forcex
                    * ApplyVelocityElapse.ElapsedMilliseconds
                    * 0.01
                    * (1 - (this.body.GetLinearVelocity().Length() / this.speed).Min(0.9) * 0.5)
                );



                var vx = Math.Cos(current.GetAngle()) * velocity.LinearVelocityY * this.speed * this.CurrentInput.forcey
                    + Math.Cos(current.GetAngle() + Math.PI / 2) * velocity.LinearVelocityX * this.speed;
                var vy = Math.Sin(current.GetAngle()) * velocity.LinearVelocityY * this.speed * this.CurrentInput.forcey
                        + Math.Sin(current.GetAngle() + Math.PI / 2) * velocity.LinearVelocityX * this.speed;


                this.visual.currentvisual.alpha = 1.0;

                #region RemoteGameReference
                if (RemoteGameReference != null)
                    if (vx == 0)
                        if (vy == 0)
                            //if (v == 0)
                            {
                                // not moving anymore in network mode
                                // far enough to be out of sync?

                                if (karmabody.GetLinearVelocity().Length() == 0)
                                    if (this.KarmaInput0.All(k => k.value == 0))
                                    {

                                        this.body.SetAngle(
                                             karmabody.GetAngle()
                                         );


                                        var gap = new __vec2(
                                            (float)this.karmabody.GetPosition().x - (float)this.body.GetPosition().x,
                                            (float)this.karmabody.GetPosition().y - (float)this.body.GetPosition().y
                                        );

                                        // tolerate lesser distance?
                                        if (gap.GetLength() > 0.5)
                                        {
                                            //this.body.SetPositionAndAngle(
                                            //    new b2Vec2(
                                            //        this.karmabody.GetPosition().x,
                                            //        this.karmabody.GetPosition().y
                                            //    ),
                                            //    this.karmabody.GetAngle()
                                            //);

                                            // show we are in the wrong place!
                                            this.visual.currentvisual.alpha = 0.3;


                                            // look at where we should be instead
                                            this.body.SetAngle(
                                                gap.GetRotation()
                                            );

                                            // and walk there!
                                            vx = Math.Cos(current.GetAngle()) * 0.5 * this.speed
                                               + Math.Cos(current.GetAngle() + Math.PI / 2) * 0 * this.speed;
                                            vy = Math.Sin(current.GetAngle()) * 0.5 * this.speed
                                                   + Math.Sin(current.GetAngle() + Math.PI / 2) * 0 * this.speed;
                                        }
                                    }

                            }
                #endregion

       
                current.SetLinearVelocity(
                    new b2Vec2(
                     vx, vy
                    )
                );

            }

            // what about our karma body?
            if (this.KarmaInput0.Count > 0)
            {
                var _karma__keyDown = this.KarmaInput0.Peek();

                var _karma_velocity = new Velocity();


                ExtractVelocityFromInput(_karma__keyDown, _karma_velocity);

                var current = this.karmabody;
                //var v = _karma_velocity.AngularVelocity * 10;
                //current.SetAngularVelocity(v);

                current.ApplyAngularImpulse(
                    _karma_velocity.AngularVelocity
                    * ApplyVelocityElapse.ElapsedMilliseconds
                   * 0.01
                    * (1 - (current.GetLinearVelocity().Length() / this.speed).Min(0.9) * 0.5)
                );


                var vx = Math.Cos(current.GetAngle()) * _karma_velocity.LinearVelocityY * this.speed
                                   + Math.Cos(current.GetAngle() + Math.PI / 2) * _karma_velocity.LinearVelocityX * this.speed;
                var vy = Math.Sin(current.GetAngle()) * _karma_velocity.LinearVelocityY * this.speed
                        + Math.Sin(current.GetAngle() + Math.PI / 2) * _karma_velocity.LinearVelocityX * this.speed;


                current.SetActive(
                     _karma__keyDown.BodyIsActive
                 );

                current.SetLinearVelocity(
                    new b2Vec2(
                     vx, vy
                    )
                );

                if (_karma__keyDown.fixup)
                {
                    var fixupmultiplier = 0.90;

                    current.SetAngle(
                        // meab me in scotty,
                         _karma__keyDown.angle + (current.GetAngle() - _karma__keyDown.angle) * fixupmultiplier

                    );



                    var gap = new __vec2(
                        (float)this.karmabody.GetPosition().x - (float)_karma__keyDown.x,
                        (float)this.karmabody.GetPosition().y - (float)_karma__keyDown.y
                    );

                    if (gap.GetLength() > 0.1)
                    {
                        current.SetLinearVelocity(
                             new b2Vec2(
                              vx - gap.x * 2.0,
                              vy - gap.y * 2.0
                             )
                         );
                    }
                }
            }
            ApplyVelocityElapse.Restart();
        }
示例#35
0
 public int KineticEnergy() => Velocity.Energy();
示例#36
0
        private async Task TestCantGoThroughWalls(Direction d, CliTestHarness app, SpaceTimePanel stPanel)
        {
            SpacialAwareness.OnNudge.SubscribeForLifetime((ev) => Assert.Fail("Nudging not allowed"), app);
            var st   = stPanel.SpaceTime;
            var wall = st.Add(new SpacialElement()
            {
                BackgroundColor = RGB.DarkRed
            });
            ILocationF movingObjectLocation;
            float      movementAngle;
            float      expected;
            Func <SpacialElement, float> actual;

            if (d == Direction.Right)
            {
                movingObjectLocation = LocationF.Create((int)(st.Width * .25f), st.Height * .5f - .5f);
                movementAngle        = 0;
                wall.ResizeTo(.1f, st.Height);
                wall.MoveTo((int)(st.Width * .75f), 0);

                expected = wall.Left;
                actual   = m => m.Right();
            }
            else if (d == Direction.Left)
            {
                movingObjectLocation = LocationF.Create((int)(st.Width * .75f), st.Height * .5f - .5f);
                movementAngle        = 180;
                wall.ResizeTo(.1f, st.Height);
                wall.MoveTo((int)(st.Width * .25f) - .1f, 0);

                expected = wall.Right();
                actual   = m => m.Left;
            }
            else if (d == Direction.Up)
            {
                movingObjectLocation = LocationF.Create(st.Width * .5f - .5f, (int)(st.Height * .75f));
                movementAngle        = 270;
                wall.ResizeTo(st.Width, .1f);
                wall.MoveTo(0, (int)(st.Height * .25f) - .1f);

                expected = wall.Bottom();
                actual   = m => m.Top;
            }
            else if (d == Direction.Down)
            {
                movingObjectLocation = LocationF.Create(st.Width * .5f - .5f, (int)(st.Height * .25f));
                movementAngle        = 90;
                wall.ResizeTo(st.Width, .1f);
                wall.MoveTo(0, (int)(st.Height * .75f));

                expected = wall.Top;
                actual   = m => m.Bottom();
            }
            else
            {
                throw new NotSupportedException();
            }

            for (var speed = 5; speed < 1000; speed *= 2)
            {
                Console.WriteLine($"Speed: {speed}");
                var movingObject = st.Add(new SpacialElement(1, 1, movingObjectLocation.Left, movingObjectLocation.Top)
                {
                    BackgroundColor = RGB.Blue
                });
                var v = new Velocity(movingObject);
                await st.DelayAsync(500);

                v.Angle = movementAngle;
                v.Speed = speed;
                await st.DelayAsync(20000);

                PhysicsTest.AssertClose(expected, actual(movingObject), .2f);
                Console.WriteLine($"Wall.Left == {expected}, movingObject.Right() == {actual(movingObject)}");
                movingObject.Lifetime.Dispose();
            }
        }
示例#37
0
        protected override void OnLoad(EventArgs e)
        {
            Velocity.Init();
            VelocityContext = new VelocityContext();
            Item currentItem;
            Item scriptItem = null;
            var  scriptId   = WebUtil.SafeEncode(WebUtil.GetQueryString("scriptId"));
            var  scriptDb   = WebUtil.SafeEncode(WebUtil.GetQueryString("scriptDb", ApplicationSettings.ScriptLibraryDb));

            if (!string.IsNullOrEmpty(scriptId))
            {
                scriptItem = Factory.GetDatabase(scriptDb).GetItem(scriptId);
            }

            if (scriptItem == null)
            {
                if (Context.Item.IsPowerShellScript())
                {
                    scriptItem = Context.Item;
                }
                else
                {
                    VelocityOutput.Text = "Could not resolve PowerShell script or no script item specified.";
                    return;
                }
            }

            var script = scriptItem["script"];

            var id = WebUtil.SafeEncode(WebUtil.GetQueryString("id"));

            if (!string.IsNullOrEmpty(id))
            {
                var db =
                    WebUtil.SafeEncode(WebUtil.GetQueryString("db",
                                                              WebUtil.GetQueryString("database", (Context.ContentDatabase ?? Context.Database).Name)));
                var la =
                    WebUtil.SafeEncode(WebUtil.GetQueryString("la",
                                                              WebUtil.GetQueryString("language", (Context.ContentDatabase ?? Context.Database).Name)));
                var vs =
                    WebUtil.SafeEncode(WebUtil.GetQueryString("vs",
                                                              WebUtil.GetQueryString("version", Version.Latest.Number.ToString())));
#pragma warning disable 618
                currentItem = Factory.GetDatabase(db)
                              .GetItem(new ID(id), LanguageManager.GetLanguage(la), new Version(vs));
#pragma warning restore 618
            }
            else
            {
                currentItem = Context.Item;
            }

            using (var scriptSession = ScriptSessionManager.NewSession(ApplicationNames.RemoteAutomation, false))
            {
                scriptSession.SetItemLocationContext(currentItem);
                scriptSession.ExecuteScriptPart(script);

                // add output
                var output = new List <string>();

                if (scriptSession.Output.Count > 0)
                {
                    output.Add(
                        scriptSession.Output
                        .Select(p => p.Terminated ? p.Text + "\n" : p.Text)
                        .Aggregate((current, next) => current + next)
                        );
                }
                VelocityContext.Put("scriptOutput", output);

                // add variables
                List <string> variableNames = new List <string>();
                foreach (var variable in scriptSession.Variables)
                {
                    VelocityContext.Put(variable.Name, variable.Value);
                    variableNames.Add(variable.Name);
                }

                VelocityContext.Put("variableNames", variableNames);

                StringWriter result = new StringWriter();
                try
                {
                    Velocity.Evaluate(VelocityContext, result, "PowerShell Script",
                                      scriptItem["VelocityTemplate"]);
                }
                catch (ParseErrorException ex)
                {
                    PowerShellLog.Error($"Error parsing template for the {currentItem.Paths.Path} item.", ex);
                }
                VelocityOutput.Text = result.GetStringBuilder().ToString();
            }
            //litResult.
        }
示例#38
0
        protected override EnvBumper.Action GetAction()
        {
            //Pos
            //Velocity
            //enemies[0].Pos
            //enemies[0].Velocity

            Vector2 dist = enemies[0].Pos - Pos;


            float myAngle = (float)Math.Atan2(dist.Y, dist.X);

            float distToCenter = Pos.Length();

            float targetToCenter = EnvBumper.RADIUS * 0.5f;

            myAngle  = (float)Math.Atan2(-Pos.Y, -Pos.X);
            myAngle += MathHelper.PiOver2 * 0.25f;

            float angleToCenter = (float)Math.Atan2(-Pos.Y, -Pos.X);
            float angleOrtho    = angleToCenter + MathHelper.PiOver2;


            float lerp = Velocity.Length() * 6f;

            lerp    = Math.Min(1, lerp);
            lerp    = 1 - lerp;
            myAngle = angleToCenter + MathHelper.PiOver2 * lerp;


            //Vector2 predictedPos = Pos + Velocity * Math.Min(

            //float a = Velocity.X;
            //float b = Velocity.Y;
            //float x = Pos.X;
            //float y = Pos.Y;
            //float r = EnvBumper.RADIUS;
            //float t = (float)Math.Sqrt(a * a * (r * r - y * y) + 2 * a * b * x * y + b * b * (r * r - x * x) + a * x + b * y) / (a * a + b * b);
            //Console.WriteLine(t);

            if (frames > 60 * 3)
            {
                Vector2 target = enemies[0].Pos + enemies[0].Velocity * Math.Min(10, enemies[0].Velocity.Length() * 10f);

                dist = target - Pos;

                myAngle = (float)Math.Atan2(dist.Y, dist.X);
            }


            if (distToCenter > EnvBumper.RADIUS * 0.6f)
            {
                myAngle = angleToCenter;
            }
            else if (Velocity.Length() > 0.2f)
            {
                myAngle = (float)Math.Atan2(-Velocity.Y, -Velocity.X);
            }

            frames++;

            return(new EnvBumper.Action()
            {
                angle = myAngle,
                accelerate = true
            });
        }
示例#39
0
 public static Duration ExpectedDuration(INode a, INode b, Velocity maximumVelocity)
 => Distance.BeweenPositions(a.Position, b.Position) / maximumVelocity;
示例#40
0
 private static string FormatSpeed(Velocity speed)
 {
     return(speed.Knots().ToString("#### Kts"));
 }
示例#41
0
 private void Initialize()
 {
     pos = new Position( 0.0f, 0.0f, 0.0f );
     dir = new Direction( 0.0f, 0.0f, 0.0f );
     vel = new Velocity( 0.0f, 0.0f, 0.0f );
     acl = new Accel( 0.0f, 0.0f, 0.0f );
 }
示例#42
0
 public void ComputeSteadyState()
 {
     Vector3 _ = Velocity.ComputeSteadyState(_r, _sourcePanel);
 }
示例#43
0
 // Use this for initialization
 void Start()
 {
     velocity = transform.root.GetComponentInChildren<Velocity>();
     normalPoint = new GameObject();
     normalPoint.name = "Reference Point";
     normalPoint.SetActive(false);
 }
        public void Reset(TimeStep step, int count, Contact[] contacts, Position[] positions, Velocity[] velocities, bool warmstarting = Settings.EnableWarmstarting)
        {
            _step = step;
            _count = count;
            _positions = positions;
            _velocities = velocities;
            _contacts = contacts;

            // grow the array
            if (_velocityConstraints == null || _velocityConstraints.Length < count)
            {
                _velocityConstraints = new ContactVelocityConstraint[count * 2];
                _positionConstraints = new ContactPositionConstraint[count * 2];

                for (int i = 0; i < _velocityConstraints.Length; i++)
                {
                    _velocityConstraints[i] = new ContactVelocityConstraint();
                }

                for (int i = 0; i < _positionConstraints.Length; i++)
                {
                    _positionConstraints[i] = new ContactPositionConstraint();
                }
            }

            // Initialize position independent portions of the constraints.
            for (int i = 0; i < _count; ++i)
            {
                Contact contact = contacts[i];

                Fixture fixtureA = contact.FixtureA;
                Fixture fixtureB = contact.FixtureB;
                Shape shapeA = fixtureA.Shape;
                Shape shapeB = fixtureB.Shape;
                float radiusA = shapeA.Radius;
                float radiusB = shapeB.Radius;
                Body bodyA = fixtureA.Body;
                Body bodyB = fixtureB.Body;
                Manifold manifold = contact.Manifold;

                int pointCount = manifold.PointCount;
                Debug.Assert(pointCount > 0);

                ContactVelocityConstraint vc = _velocityConstraints[i];
                vc.friction = contact.Friction;
                vc.restitution = contact.Restitution;
                vc.tangentSpeed = contact.TangentSpeed;
                vc.indexA = bodyA.IslandIndex;
                vc.indexB = bodyB.IslandIndex;
                vc.invMassA = bodyA._invMass;
                vc.invMassB = bodyB._invMass;
                vc.invIA = bodyA._invI;
                vc.invIB = bodyB._invI;
                vc.contactIndex = i;
                vc.pointCount = pointCount;
                vc.K.SetZero();
                vc.normalMass.SetZero();

                ContactPositionConstraint pc = _positionConstraints[i];
                pc.indexA = bodyA.IslandIndex;
                pc.indexB = bodyB.IslandIndex;
                pc.invMassA = bodyA._invMass;
                pc.invMassB = bodyB._invMass;
                pc.localCenterA = bodyA._sweep.LocalCenter;
                pc.localCenterB = bodyB._sweep.LocalCenter;
                pc.invIA = bodyA._invI;
                pc.invIB = bodyB._invI;
                pc.localNormal = manifold.LocalNormal;
                pc.localPoint = manifold.LocalPoint;
                pc.pointCount = pointCount;
                pc.radiusA = radiusA;
                pc.radiusB = radiusB;
                pc.type = manifold.Type;

                for (int j = 0; j < pointCount; ++j)
                {
                    ManifoldPoint cp = manifold.Points[j];
                    VelocityConstraintPoint vcp = vc.points[j];

                    if (Settings.EnableWarmstarting)
                    {
                        vcp.normalImpulse = _step.dtRatio * cp.NormalImpulse;
                        vcp.tangentImpulse = _step.dtRatio * cp.TangentImpulse;
                    }
                    else
                    {
                        vcp.normalImpulse = 0.0f;
                        vcp.tangentImpulse = 0.0f;
                    }

                    vcp.rA = Vector2.Zero;
                    vcp.rB = Vector2.Zero;
                    vcp.normalMass = 0.0f;
                    vcp.tangentMass = 0.0f;
                    vcp.velocityBias = 0.0f;

                    pc.localPoints[j] = cp.LocalPoint;
                }
            }
        }
示例#45
0
 public Cursor()
 {
     X = Y = 0;
     V = new Velocity();
 }
        protected void NarrowPhase(Rigidbody rb1, Rigidbody rb2)
        {
#if DEBUG_COLLISIONS
            f_checkStates[CalcRBID(rb1, rb2)] = CheckState.NarrowCheck;
            ++m_narrowChecks;
#endif

            // If none of them are triggers, that means that the collision shall be resolved
            // Well, they cannot be resolved here already; the data has to be remembered until the end of the resolutions
            if (!rb1.ColliderData.IsTrigger && !rb2.ColliderData.IsTrigger)
            {
                // TODO; Implement the other collisions

                if (rb1.ColliderData.Collider2D is AABB)
                {
                    if (rb2.ColliderData.Collider2D is AABB)
                    {
                        // this should not be possible is this example
                    }
                    else
                    {
                        // AABB - Circle
                    }
                }
                else
                {
                    if (rb2.ColliderData.Collider2D is AABB)
                    {
                        // Circle - AABB
                    }
                    else
                    {
                        // Circle - Circle
                        CollisionDataRB cd = Intersections.CollisionCircleCircle((Circle)rb1.ColliderData.Collider2D, (Circle)rb2.ColliderData.Collider2D, rb1, rb2);
                        if (cd.DidCollide)
                        {
                            //UnityEngine.Debug.Log(Name + ": " + (rb1.ID / 4) + " - " + (rb2.ID / 4));
                            m_collisionsThisFrame[CalcRBID(rb1, rb2)] = cd;
                            m_collisionsLastFrame.Remove(CalcRBID(rb1, rb2));
#if DEBUG_COLLISIONS
                            f_checkStates[CalcRBID(rb1, rb2)] = CheckState.Collision;
                            ++m_collisions;
#endif

                            //TESTING
                            // this is so bad, that I only keep it here, to not think it would be nice
                            // As stated above, THIS SHOULD NOT HAPPEN HERE!!!!!
                            // Also, this now triggers a collision although the collision is considered as not happening
                            Velocity v1 = rb1.DynamicData.Velocity;
                            Velocity v2 = rb2.DynamicData.Velocity;

                            //if (Velocity.Angle(v1, v2) < new Angle(90)) {
                            if (!m_collisionsLastFrame.ContainsKey(CalcRBID(rb1, rb2)))
                            {
                                Mass m1 = rb1.ObjectData.Mass;
                                Mass m2 = rb2.ObjectData.Mass;

                                rb1.DynamicData = new DynamicData((v1 * (m1 - m2) + (2 * m2 * v2)) / (m1 + m2), Acceleration.zero);
                                rb2.DynamicData = new DynamicData((v2 * (m2 - m1) + (2 * m1 * v1)) / (m2 + m1), Acceleration.zero);
                            }
                            //TESTING END
                        }
                    }
                }

                // pass collision to the event
            }
            else     // this means not both are colliders, so I only fire a trigger event on both (if touching)
            // In a trigger, we only care, whether they are touching or not
            // TODO I can already call the trigger functions here

            {
                if (rb1.ColliderData.Collider2D is AABB)
                {
                    if (rb2.ColliderData.Collider2D is AABB)
                    {
                        // this should not be possible in this example
                        if (Intersections.DoIntersectAABBAABB((AABB)rb1.ColliderData.Collider2D, (AABB)rb2.ColliderData.Collider2D, rb1.GameObject.Transform, rb2.GameObject.Transform))
                        {
                            // call triggers for 1 and send 2
                            // call triggers for 2 and send 1

                            m_triggersThisFrame.Add(CalcRBID(rb1, rb2));
                            m_triggersLastFrame.Remove(CalcRBID(rb1, rb2));
#if DEBUG_COLLISIONS
                            f_checkStates[CalcRBID(rb1, rb2)] = CheckState.Trigger;
                            ++m_triggers;
#endif
                        }
                    }
                    else
                    {
                        // AABB - Circle
                        if (Intersections.DoIntersectAABBCircle((AABB)rb1.ColliderData.Collider2D, (Circle)rb2.ColliderData.Collider2D, rb1.GameObject.Transform, rb2.GameObject.Transform))
                        {
                            // call triggers for 1 and send 2
                            // call triggers for 2 and send 1

                            m_triggersThisFrame.Add(CalcRBID(rb1, rb2));
                            m_triggersLastFrame.Remove(CalcRBID(rb1, rb2));
#if DEBUG_COLLISIONS
                            f_checkStates[CalcRBID(rb1, rb2)] = CheckState.Trigger;
                            ++m_triggers;
#endif
                        }
                    }
                }
                else
                {
                    if (rb2.ColliderData.Collider2D is AABB)
                    {
                        // Circle - AABB
                        if (Intersections.DoIntersectAABBCircle((AABB)rb2.ColliderData.Collider2D, (Circle)rb1.ColliderData.Collider2D, rb2.GameObject.Transform, rb1.GameObject.Transform))
                        {
                            // call triggers for 1 and send 2
                            // call triggers for 2 and send 1
                            m_triggersThisFrame.Add(CalcRBID(rb1, rb2));
                            m_triggersLastFrame.Remove(CalcRBID(rb1, rb2));
#if DEBUG_COLLISIONS
                            f_checkStates[CalcRBID(rb1, rb2)] = CheckState.Trigger;
                            ++m_triggers;
#endif
                        }
                    }
                    else
                    {
                        // Circle - Circle
                        if (Intersections.DoIntersectCircleCircle((Circle)rb1.ColliderData.Collider2D, (Circle)rb2.ColliderData.Collider2D, rb1.GameObject.Transform, rb2.GameObject.Transform))
                        {
                            // call triggers for 1 and send 2
                            // call triggers for 2 and send 1
                            m_triggersThisFrame.Add(CalcRBID(rb1, rb2));
                            m_triggersLastFrame.Remove(CalcRBID(rb1, rb2));
#if DEBUG_COLLISIONS
                            f_checkStates[CalcRBID(rb1, rb2)] = CheckState.Trigger;
                            ++m_triggers;
#endif
                        }
                    }
                }

                // TODO only check if they are touching + calling trigger functions after that if any
                // pass collider to the event
            }
        }
示例#47
0
        private void InsertNode(INode current, IEdge via, INode goal, Duration costSoFar, Velocity maximumVelocity)
        {
            this.PathReconstructor.SetCameFrom(current, via);

            var node = new PathFinderNode(current, costSoFar, ExpectedDuration(current, goal, maximumVelocity));

            this.Interesting.Insert(node);
            this.Nodes[current] = node;
        }
示例#48
0
        public override void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera)
        {
            BoundingBox bounds = chunks.Bounds;

            bounds.Max.Y += 50;

            if (!IsSleeping && (Velocity).Length() < 0.15f)
            {
                SleepTimer.Update(gameTime);
                if (SleepTimer.HasTriggered)
                {
                    applyGravityThisFrame = false;
                    Velocity  *= 0.0f;
                    IsSleeping = true;
                }
            }
            else
            {
                SleepTimer.Reset();
                IsSleeping = false;
            }

            if (!IsSleeping || overrideSleepThisFrame)
            {
                if (overrideSleepThisFrame)
                {
                    overrideSleepThisFrame = false;
                }

                float dt = (float)(gameTime.ElapsedGameTime.TotalSeconds);


                if (MathFunctions.HasNan(Velocity))
                {
                    Velocity = Vector3.Zero;
                }

                MoveY(dt);
                MoveX(dt);
                MoveZ(dt);
                HandleCollisions(chunks, dt);

                Matrix transform = LocalTransform;
                if (bounds.Contains(LocalTransform.Translation + Velocity * dt) != ContainmentType.Contains)
                {
                    transform.Translation = LocalTransform.Translation - 0.1f * Velocity * dt;
                    Velocity = new Vector3(Velocity.X * -0.9f, Velocity.Y, Velocity.Z * -0.9f);
                }


                if (LocalTransform.Translation.Z < -10 || bounds.Contains(GetBoundingBox()) == ContainmentType.Disjoint)
                {
                    Die();
                }


                if (Orientation == OrientMode.Physics)
                {
                    Matrix dA = Matrix.Identity;
                    dA *= Matrix.CreateRotationX(AngularVelocity.X * dt);
                    dA *= Matrix.CreateRotationY(AngularVelocity.Y * dt);
                    dA *= Matrix.CreateRotationZ(AngularVelocity.Z * dt);

                    transform = dA * transform;
                }
                else if (Orientation != OrientMode.Fixed)
                {
                    if (Velocity.Length() > 0.4f)
                    {
                        if (Orientation == OrientMode.LookAt)
                        {
                            Matrix newTransform =
                                Matrix.Invert(Matrix.CreateLookAt(Position, Position + Velocity, Vector3.Down));
                            newTransform.Translation = transform.Translation;
                            transform = newTransform;
                        }
                        else if (Orientation == OrientMode.RotateY)
                        {
                            Rotation = (float)Math.Atan2(Velocity.X, -Velocity.Z);
                            Quaternion newRotation = Quaternion.CreateFromRotationMatrix(Matrix.CreateRotationY(Rotation));
                            Quaternion oldRotation = Quaternion.CreateFromRotationMatrix(LocalTransform);
                            Quaternion finalRot    = Quaternion.Slerp(oldRotation, newRotation, 0.1f);
                            finalRot.Normalize();
                            Matrix newTransform = Matrix.CreateFromQuaternion(finalRot);
                            newTransform.Translation = transform.Translation;
                            newTransform.Right.Normalize();
                            newTransform.Up.Normalize();
                            newTransform.Forward.Normalize();
                            newTransform.M14 = 0;
                            newTransform.M24 = 0;
                            newTransform.M34 = 0;
                            newTransform.M44 = 1;
                            transform        = newTransform;
                        }
                    }
                }

                transform.Translation = ClampToBounds(transform.Translation);
                LocalTransform        = transform;

                if (Math.Abs(Velocity.Y) < 0.1f)
                {
                    Velocity = new Vector3(Velocity.X * Friction, Velocity.Y, Velocity.Z * Friction);
                }

                if (applyGravityThisFrame)
                {
                    ApplyForce(Gravity, dt);
                }
                else
                {
                    applyGravityThisFrame = true;
                }

                Velocity        *= LinearDamping;
                AngularVelocity *= AngularDamping;
                UpdateBoundingBox();
            }
            CheckLiquids(chunks, (float)gameTime.ElapsedGameTime.TotalSeconds);
            Velocity         = (PreviousVelocity * 0.1f + Velocity * 0.9f);
            PreviousVelocity = Velocity;
            PreviousPosition = Position;
            base.Update(gameTime, chunks, camera);
        }
示例#49
0
        protected override EnvBumper.Action GetAction()
        {
            //Pos
            //Velocity
            //enemies[0].Pos
            //enemies[0].Velocity

            Vector2 dist = enemies[0].Pos - Pos;


            float myAngle = (float)Math.Atan2(dist.Y, dist.X);

            float distToCenter = Pos.Length();

            float targetToCenter = EnvBumper.RADIUS * 0.5f;

            myAngle  = (float)Math.Atan2(-Pos.Y, -Pos.X);
            myAngle += MathHelper.PiOver2 * 0.25f;

            float angleToCenter = (float)Math.Atan2(-Pos.Y, -Pos.X);
            float angleOrtho    = angleToCenter + MathHelper.PiOver2;


            float lerp = Velocity.Length() * 6f;

            lerp    = Math.Min(1, lerp);
            lerp    = 1 - lerp;
            myAngle = angleToCenter - MathHelper.PiOver2 * lerp;


            Vector2 predictedPos = Predict(Pos, Velocity);

            //float a = Velocity.X;
            //float b = Velocity.Y;
            //float x = Pos.X;
            //float y = Pos.Y;
            //float r = EnvBumper.RADIUS;
            //float t = (float)Math.Sqrt(a * a * (r * r - y * y) + 2 * a * b * x * y + b * b * (r * r - x * x) + a * x + b * y) / (a * a + b * b);
            //Console.WriteLine(t);

            //if (frames > 60 * 5)
            {
                if (goAway <= 0)
                {
                    Vector2 target = Predict(enemies[0].Pos, enemies[0].Velocity);// enemies[0].Pos + enemies[0].Velocity * Math.Min(200, enemies[0].Velocity.Length() * 80f);

                    dist = target - predictedPos;

                    myAngle = (float)Math.Atan2(dist.Y, dist.X);

                    float angleFromCenterToEnemy;

                    Vector2 myGoal   = enemies[0].Pos * 0.5f;
                    Vector2 goalDist = myGoal - predictedPos;
                    angleFromCenterToEnemy = (float)Math.Atan2(goalDist.Y, goalDist.X);
                    float angleDist = Calculate.AngleDistance(myAngle, angleFromCenterToEnemy);
                    myAngle += angleDist * 0.25f;
                    float vChange = Vector2.Distance(lastVelocity, Velocity);
                    Console.WriteLine(vChange);
                    if (vChange > 0.1f && Vector2.Dot(Velocity, dist) < 0)
                    {
                        //goAway = 30;
                    }
                }
                else
                {
                    // myAngle = (float)Math.Atan2(-dist.Y, -dist.X);
                    goAway--;
                }
            }


            if (distToCenter > EnvBumper.RADIUS * 0.6f)
            {
                myAngle = angleToCenter;
            }
            else if (Velocity.Length() > 0.2f)
            {
                myAngle = (float)Math.Atan2(-Velocity.Y, -Velocity.X);
            }

            frames++;

            lastVelocity = Velocity;
            return(new EnvBumper.Action()
            {
                angle = myAngle,
                accelerate = true
            });
        }
示例#50
0
        public SubMap(byte[,] processedFullSizeMapDataForPathFinding, byte[,] processedFullSizeMapDataForExploration, int[,] islandProcessedMapDataForPathFinding, int islandId)
        {
            var startTime = DateTime.Now;

            this.IslandId = islandId;
            this.mapDataForExploration = processedFullSizeMapDataForExploration.Clone() as byte[, ];

            EraseNonIslandData(this.mapDataForExploration, islandProcessedMapDataForPathFinding, islandId);

            //var nodeA = new Node(new Position(1, 1));
            //var nodeB = new Node(new Position(2, 2));
            //nodeA.Connect(nodeB,2)

            int reducedWidth        = processedFullSizeMapDataForPathFinding.GetLength(0) / PathfindingConsts.myPathfindingGridSize;
            int reducedHeight       = processedFullSizeMapDataForPathFinding.GetLength(1) / PathfindingConsts.myPathfindingGridSize;
            var gridSize            = new GridSize(columns: reducedWidth, rows: reducedHeight);
            var cellSize            = new Size(Distance.FromMeters(PathfindingConsts.myPathfindingGridSize), Distance.FromMeters(PathfindingConsts.myPathfindingGridSize));
            var traversalVelocity   = Velocity.FromKilometersPerHour(100);
            var startTimeGridCreate = DateTime.Now;

            Grid = Grid.CreateGridWithLateralAndDiagonalConnections(gridSize, cellSize, traversalVelocity);
            Console.WriteLine($"Creating grid took: {DateTime.Now.Subtract(startTimeGridCreate).TotalMilliseconds} milliseconds");

            //Parallel.For(0, reducedWidth, x =>
            // {

            var startTimeGridPrep = DateTime.Now;

            for (int x = 0; x < reducedWidth; x++)
            {
                for (int y = 0; y < reducedHeight; y++)
                {
                    int xAdjusted = x * PathfindingConsts.myPathfindingGridSize;
                    int yAdjusted = y * PathfindingConsts.myPathfindingGridSize;

                    if (processedFullSizeMapDataForPathFinding[xAdjusted, yAdjusted] == 0 || islandProcessedMapDataForPathFinding[xAdjusted, yAdjusted] != islandId)
                    {
                        // Grid.RemoveDiagonalConnectionsIntersectingWithNode(new GridPosition(x, y));
                        Grid.DisconnectNode(new GridPosition(x, y));
                    }
                    //if (processedFullSizeMapDataForPathFinding[xAdjusted, yAdjusted] != 0 && islandProcessedMapDataForPathFinding[xAdjusted, yAdjusted] != islandId)
                    //{
                    //    Grid.RemoveDiagonalConnectionsIntersectingWithNode(new GridPosition(x, y));
                    //    Grid.DisconnectNode(new GridPosition(x, y));
                    //}
                }
            }
            Console.WriteLine($"Prepping grid took: {DateTime.Now.Subtract(startTimeGridPrep).TotalMilliseconds} milliseconds");

            //});

            //for (int x = 0; x < reducedWidth; x++)
            //{
            //    for (int y = 0; y < reducedHeight; y++)
            //    {
            //        int xAdjusted = x * PathfindingConsts.myPathfindingGridSize;
            //        int yAdjusted = y * PathfindingConsts.myPathfindingGridSize;

            //        if (processedFullSizeMapDataForPathFinding[xAdjusted, yAdjusted] == 0)
            //        {
            //            // Grid.RemoveDiagonalConnectionsIntersectingWithNode(new GridPosition(x, y));
            //            Grid.DisconnectNode(new GridPosition(x, y));
            //        }
            //        if (processedFullSizeMapDataForPathFinding[xAdjusted, yAdjusted] != 0 && islandProcessedMapDataForPathFinding[xAdjusted, yAdjusted] != islandId)
            //        {
            //            //Grid.RemoveDiagonalConnectionsIntersectingWithNode(new GridPosition(x, y));
            //            Grid.DisconnectNode(new GridPosition(x, y));
            //        }
            //    }
            //}
            var startTimeExplorationPrep = DateTime.Now;

            Exploration = new Exploration(mapDataForExploration);
            Console.WriteLine($"Prepping exploration took: {DateTime.Now.Subtract(startTimeExplorationPrep).TotalMilliseconds} milliseconds");


            Console.WriteLine($"Creating submap took: {DateTime.Now.Subtract(startTime).TotalMilliseconds} milliseconds");
        }
        public void ApplyVelocity()
        {
            if (this.visual.Altitude != 0)
                if (AutomaticTouchdown)
                    if (this.driverseat.driver == null)
                    {
                        this.VerticalVelocity = -0.4;

                        // reset

                        this.AngularVelocity = 0;
                        this.LinearVelocityX = 0;
                        this.LinearVelocityY = 0;
                    }

            var dx = Context.gametime.ElapsedMilliseconds - ApplyVelocityElapsed;
            ApplyVelocityElapsed = Context.gametime.ElapsedMilliseconds;


            {
                var current = this.body;
                //var v = this.AngularVelocity * 10;
                //current.SetAngularVelocity(v);



                current.ApplyAngularImpulse(
                    this.AngularVelocity
                     * this.CurrentInput.forcex
                    * 0.4
                    * (1 - (this.body.GetLinearVelocity().Length() / this.speed).Min(0.9) * 0.5)
                );


                var vx = Math.Cos(current.GetAngle()) * this.LinearVelocityY * this.speed * this.CurrentInput.forcey
                        + Math.Cos(current.GetAngle() + Math.PI / 2) * this.LinearVelocityX * this.speed * this.CurrentInput.forcex;
                var vy = Math.Sin(current.GetAngle()) * this.LinearVelocityY * this.speed * this.CurrentInput.forcey
                        + Math.Sin(current.GetAngle() + Math.PI / 2) * this.LinearVelocityX * this.speed * this.CurrentInput.forcex;




                #region RemoteGameReference
                if (RemoteGameReference != null)
                    if (vx == 0)
                        if (vy == 0)
                        //if (v == 0)
                        {
                            // not moving anymore in network mode
                            // far enough to be out of sync?

                            //if (karmabody.GetAngularVelocity() == 0)
                            if (body.GetLinearVelocity().Length() == 0)
                                if (this.KarmaInput0.All(k => k.value == 0))
                                {




                                    var gap = new __vec2(
                                        (float)this.groundkarma_body.GetPosition().x - (float)this.body.GetPosition().x,
                                        (float)this.groundkarma_body.GetPosition().y - (float)this.body.GetPosition().y
                                    );

                                    // tolerate lesser distance?

                                    var da0 = this.groundkarma_body.GetAngle() - this.body.GetAngle();
                                    var da360 = (this.groundkarma_body.GetAngle() + 360.DegreesToRadians()) - this.body.GetAngle();

                                    if (da0 < da360)
                                    {
                                        this.body.SetAngle(
                                               this.body.GetAngle() + da0 * 0.2
                                        );
                                    }
                                    else
                                    {
                                        this.body.SetAngle(
                                               this.body.GetAngle() + da360 * 0.2
                                        );
                                    }


                                    this.body.SetPosition(
                                        new b2Vec2(
                                            this.body.GetPosition().x + gap.x * 0.1,
                                            this.body.GetPosition().y + gap.y * 0.1
                                        )
                                    );
                                }

                        }
                #endregion







                this.body.SetLinearVelocity(
                    new b2Vec2(
                     vx, vy


                    )
                );

                // attempt to course correct if near 90 degree angles!

                //if (this.AngularVelocity == 0)
                //{
                //    var fixupmultiplier = 0.90;

                //    var fixai = (current.GetAngle().RadiansToDegrees() / 4.0);

                //    if (AngularVelocitySign > 0)
                //        fixai = Math.Ceiling(fixai);
                //    else
                //        fixai = Math.Floor(fixai);

                //    var fixaf = (fixai * 16).DegreesToRadians();


                //    // like a magnet
                //    current.SetAngle(
                //        // meab me in scotty
                //            fixaf + (current.GetAngle() - fixaf) * fixupmultiplier

                //    );
                //}
                //else
                //{
                //    AngularVelocitySign = Math.Sign(this.AngularVelocity);
                //}
            }


            this.visual.Altitude =
                (this.visual.Altitude + 0.005 * dx * this.VerticalVelocity).Max(0).Min(1);


            // what about our karma body?
            if (this.KarmaInput0.Count > 0)
            {
                var _karma__keyDown = this.KarmaInput0.Peek();

                var _karma_velocity = new Velocity();


                ExtractVelocityFromInput(_karma__keyDown, _karma_velocity);

                var current = this.groundkarma_body;
                //var v = _karma_velocity.AngularVelocity * 10;
                //current.SetAngularVelocity(v);


                current.ApplyAngularImpulse(
                    this.AngularVelocity * 0.6 * (1 - (current.GetLinearVelocity().Length() / this.speed).Min(0.9) * 0.5)
                );


                var vx = Math.Cos(current.GetAngle()) * _karma_velocity.LinearVelocityY * this.speed
                                   + Math.Cos(current.GetAngle() + Math.PI / 2) * _karma_velocity.LinearVelocityX * this.speed;
                var vy = Math.Sin(current.GetAngle()) * _karma_velocity.LinearVelocityY * this.speed
                        + Math.Sin(current.GetAngle() + Math.PI / 2) * _karma_velocity.LinearVelocityX * this.speed;

                current.SetActive(
                    _karma__keyDown.BodyIsActive
                );

                current.SetLinearVelocity(
                    new b2Vec2(
                     vx, vy
                    )
                );

                if (_karma__keyDown.fixup)
                {
                    var fixupmultiplier = 0.90;

                    // like a magnet
                    current.SetPositionAndAngle(
                        new b2Vec2(
                            _karma__keyDown.x + (current.GetPosition().x - _karma__keyDown.x) * fixupmultiplier,
                            _karma__keyDown.y + (current.GetPosition().y - _karma__keyDown.y) * fixupmultiplier
                        ),
                        // meab me in scotty
                            _karma__keyDown.angle + (current.GetAngle() - _karma__keyDown.angle) * fixupmultiplier

                    );
                }
            }
        }
示例#52
0
 void UpdateEnemyVisionGrid(IEnumerable <UnitCalculation> enemyUnits)
 {
     EnemyVisionGrid = Grid.CreateGridWithLateralAndDiagonalConnections(WalkGrid.GridSize, new Size(Distance.FromMeters(1), Distance.FromMeters(1)), Velocity.FromMetersPerSecond(1));
     foreach (var enemy in enemyUnits)
     {
         var nodes = GetNodesInRange(enemy.Unit.Pos, 11, EnemyVisionGrid.Columns, EnemyVisionGrid.Rows); // TODO: get sight range of every unit, // TODO: units on low ground can't see high ground
         foreach (var node in nodes)
         {
             EnemyVisionGrid.DisconnectNode(node);
         }
     }
 }
示例#53
0
 //public AccObject(float start_time, Velocity acc, float duration)
 //{
 //    this.start_time = start_time;
 //    this.acc = acc;
 //    this.duration = duration;
 //}
 public AccObject(float start_time, float speed, float direction, float duration)
 {
     this.start_time = start_time;
     this.acc = new Velocity(speed, direction);
     this.duration = duration;
 }
示例#54
0
 public static void calculate_movement(Velocity vel)
 {
     VelocityHandler.update_particles(vel.vx, vel.vy, vel.vz, _size);
 }
示例#55
0
 public static ITween Linear(Velocity velocity)
 {
     return(new EasingVelocityTween(LinearFunction, velocity));
 }
示例#56
0
        public void UpdateLocation(GameTime gameTime)
        {
            if (UnitState != UnitState.dead)
            {
                ExtraRotation = Matrix.CreateRotationZ(MathHelper.ToRadians(extraRotationZ));
                float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
                if (elapsedTime != 0)
                {
                    thrust += impulse / elapsedTime;
                }
                if (Mass != 0)
                {
                    #region 计算摩擦力
                    Vector3 frictionDirection = Vector3.Zero;
                    Vector3 acceleration      = Vector3.Zero;
                    Vector3 friction          = Vector3.Zero;
                    float   totalFiction;
                    if (!ignoreNormalFiction)
                    {
                        totalFiction = addictionalFictionForce + FrictionForce;
                    }
                    else
                    {
                        totalFiction = addictionalFictionForce;
                    }
                    if (Velocity.Length() != 0)
                    {
                        if (Velocity.Length() * Mass <= totalFiction * elapsedTime)
                        {
                            frictionDirection = (Vector3.Normalize(Velocity)) * (-1);
                            if (elapsedTime > 0)
                            {
                                friction = (Velocity.Length() * Mass) / elapsedTime * frictionDirection;
                            }
                        }
                        else
                        {
                            frictionDirection = (Vector3.Normalize(Velocity)) * (-1);
                            friction          = totalFiction * frictionDirection;
                        }
                    }
                    #endregion

                    acceleration = (thrust + friction) / Mass;//计算加速度
                    Velocity    += acceleration * elapsedTime;


                    Position += Velocity * elapsedTime;
                }

                if (thrust != Vector3.Zero)
                {
                    UpdateModel(gameTime, MoveState.Moving);
                }
                else
                {
                    UpdateModel(gameTime, MoveState.NotMoving);
                }
            }
            impulse = Vector3.Zero;
            thrust  = Vector3.Zero;

            addictionalFictionForce = 0;
            ignoreNormalFiction     = false;
        }
        public void ExtractVelocityFromInput(KeySample __keyDown, Velocity value)
        {


            value.AngularVelocity = 0;
            value.LinearVelocityX = 0;
            value.LinearVelocityY = 0;



            if (__keyDown != null)
            {
                #region alt
                Func<Keys, Keys, bool> alt =
                    (k1, k2) =>
                    {
                        if (__keyDown[Keys.Alt])
                        {
                            return __keyDown[k2];
                        }
                        return __keyDown[k1];
                    };
                #endregion

                // script: error JSC1000: ActionScript : unable to emit br.s at 'FlashHeatZeeker.UnitPedControl.Library.PhysicalPed.ExtractVelocityFromInput'#004c: invalid br opcode
                var k = new
                {
                    up = __keyDown[Keys.Up],
                    down = __keyDown[Keys.Down],

                    left = alt(Keys.Left, Keys.A),
                    right = alt(Keys.Right, Keys.D),

                    strafeleft = alt(Keys.A, Keys.Left),
                    straferight = alt(Keys.D, Keys.Right),
                };

                if (k.up)
                {
                    // we have reasone to keep walking

                    value.LinearVelocityY = 1;
                }

                if (k.down)
                {
                    // we have reasone to keep walking
                    // go slow backwards
                    value.LinearVelocityY = -0.5;

                }

                if (k.left)
                {
                    // we have reasone to keep walking

                    value.AngularVelocity = -1;

                }

                if (k.right)
                {
                    // we have reasone to keep walking

                    value.AngularVelocity = 1;

                }
                if (k.strafeleft)
                {
                    // we have reasone to keep walking

                    value.LinearVelocityX = -1;

                }

                if (k.straferight)
                {
                    // we have reasone to keep walking

                    value.LinearVelocityX = 1;

                }
            }


        }
示例#58
0
        public override void OnTick()
        {
            //base.OnTick();

            if (KnownPosition.Y <= 0 ||
                (Velocity.Length() <= 0 && DespawnOnImpact) ||
                (Velocity.Length() <= 0 && !DespawnOnImpact && Ttl <= 0))
            {
                if (DespawnOnImpact || (!DespawnOnImpact && Ttl <= 0))
                {
                    DespawnEntity();
                    return;
                }
                else
                {
                    IsCritical = false;
                }
                return;
            }

            Ttl--;

            if (KnownPosition.Y <= 0 || Velocity.Length() <= 0)
            {
                return;
            }

            Entity entityCollided = CheckEntityCollide(KnownPosition, Velocity);

            bool collided = false;

            if (entityCollided != null)
            {
                double speed  = Math.Sqrt(Velocity.X * Velocity.X + Velocity.Y * Velocity.Y + Velocity.Z * Velocity.Z);
                double damage = Math.Ceiling(speed * Damage);
                if (IsCritical)
                {
                    damage += Level.Random.Next((int)(damage / 2 + 2));

                    McpeAnimate animate = McpeAnimate.CreateObject();
                    animate.runtimeEntityId = entityCollided.EntityId;
                    animate.actionId        = 4;
                    Level.RelayBroadcast(animate);
                }

                if (PowerLevel > 0)
                {
                    damage = damage + ((PowerLevel + 1) * 0.25);
                }

                Player player = entityCollided as Player;

                if (player != null)
                {
                    damage = player.DamageCalculator.CalculatePlayerDamage(this, player, null, damage, DamageCause.Projectile);
                    player.LastAttackTarget = entityCollided;
                }

                entityCollided.HealthManager.TakeHit(this, (int)damage, DamageCause.Projectile);
                entityCollided.HealthManager.LastDamageSource = Shooter;

                DespawnEntity();
                return;
            }
            else
            {
                var velocity2 = Velocity;
                velocity2 *= (float)(1.0d - Drag);
                velocity2 -= new Vector3(0, (float)Gravity, 0);
                double distance = velocity2.Length();
                velocity2 = Vector3.Normalize(velocity2) / 2;

                for (int i = 0; i < Math.Ceiling(distance) * 2; i++)
                {
                    Vector3 nextPos = KnownPosition.ToVector3();
                    nextPos.X += (float)velocity2.X * i;
                    nextPos.Y += (float)velocity2.Y * i;
                    nextPos.Z += (float)velocity2.Z * i;

                    Block block = Level.GetBlock(nextPos);
                    collided = block.IsSolid && block.GetBoundingBox().Contains(nextPos);
                    if (collided)
                    {
                        SetIntersectLocation(block.GetBoundingBox(), KnownPosition.ToVector3());
                        break;
                    }
                }
            }

            if (collided)
            {
                Velocity = Vector3.Zero;
            }
            else
            {
                KnownPosition.X += (float)Velocity.X;
                KnownPosition.Y += (float)Velocity.Y;
                KnownPosition.Z += (float)Velocity.Z;

                Velocity *= (float)(1.0 - Drag);
                Velocity -= new Vector3(0, (float)Gravity, 0);

                KnownPosition.Yaw   = (float)Velocity.GetYaw();
                KnownPosition.Pitch = (float)Velocity.GetPitch();
            }

            // For debugging of flight-path
            if (BroadcastMovement)
            {
                //LastUpdatedTime = DateTime.UtcNow;

                BroadcastMoveAndMotion();
            }
        }
        public void ApplyVelocity()
        {

            {
                var current = this.body;
                //var v = this.AngularVelocity * 10;
                //current.SetAngularVelocity(v);

                current.ApplyAngularImpulse(
                   this.AngularVelocity * AngularVelocityMultiplier
                   * this.CurrentInput.forcex
                   * ApplyVelocityElapse.ElapsedMilliseconds
                   * 1.0
                   * (1 - (this.body.GetLinearVelocity().Length() / this.speed).Min(0.9) * 0.5)
               );


                var vx = Math.Cos(current.GetAngle()) * this.LinearVelocityY * this.speed * this.CurrentInput.forcey
                        + Math.Cos(current.GetAngle() + Math.PI / 2) * this.LinearVelocityX * this.speed;
                var vy = Math.Sin(current.GetAngle()) * this.LinearVelocityY * this.speed * this.CurrentInput.forcey
                        + Math.Sin(current.GetAngle() + Math.PI / 2) * this.LinearVelocityX * this.speed;





                this.visual.currentvisual.alpha = 1.0;

                #region RemoteGameReference
                if (RemoteGameReference != null)
                    if (vx == 0)
                        if (vy == 0)
                        //if (v == 0)
                        {
                            // not moving anymore in network mode
                            // far enough to be out of sync?

                            //if (karmabody.GetAngularVelocity() == 0)
                            if (karmabody.GetLinearVelocity().Length() == 0)
                                if (this.KarmaInput0.All(k => k.value == 0))
                                {




                                    var gap = new __vec2(
                                        (float)this.karmabody.GetPosition().x - (float)this.body.GetPosition().x,
                                        (float)this.karmabody.GetPosition().y - (float)this.body.GetPosition().y
                                    );

                                    // tolerate lesser distance?

                                    var CloseEnough = gap.GetLength() < 1.2;
                                    var TooFar = gap.GetLength() > 5;

                                    if (CloseEnough)
                                    {
                                        ApplyVelocityMoveToLocation = false;
                                    }

                                    if (TooFar || ApplyVelocityMoveToLocation)
                                    {
                                        //this.body.SetPositionAndAngle(
                                        //    new b2Vec2(
                                        //        this.karmabody.GetPosition().x,
                                        //        this.karmabody.GetPosition().y
                                        //    ),
                                        //    this.karmabody.GetAngle()
                                        //);

                                        // show we are in the wrong place!
                                        this.visual.currentvisual.alpha = 0.3;


                                        // look at where we should be instead
                                        this.body.SetAngle(
                                            gap.GetRotation()
                                        );

                                        // and walk there!
                                        vx = Math.Cos(current.GetAngle()) * 0.5 * this.speed
                                           + Math.Cos(current.GetAngle() + Math.PI / 2) * 0 * this.speed;
                                        vy = Math.Sin(current.GetAngle()) * 0.5 * this.speed
                                               + Math.Sin(current.GetAngle() + Math.PI / 2) * 0 * this.speed;

                                        ApplyVelocityMoveToLocation = true;
                                    }
                                    else
                                    {
                                        var da0 = this.karmabody.GetAngle() - this.body.GetAngle();
                                        var da360 = (this.karmabody.GetAngle() + 360.DegreesToRadians()) - this.body.GetAngle();

                                        if (da0 < da360)
                                        {
                                            this.body.SetAngle(
                                                   this.body.GetAngle() + da0 * 0.2
                                            );
                                        }
                                        else
                                        {
                                            this.body.SetAngle(
                                                   this.body.GetAngle() + da360 * 0.2
                                            );
                                        }

                                        if (CloseEnough)
                                        {

                                        }
                                        else
                                        {
                                            this.body.SetPosition(
                                                new b2Vec2(
                                                    this.body.GetPosition().x + gap.x * 0.3,
                                                    this.body.GetPosition().y + gap.y * 0.3
                                                )
                                            );
                                        }
                                    }
                                }

                        }
                #endregion


                current.SetLinearVelocity(
                    new b2Vec2(
                     vx, vy


                    )
                );
            }


            // what about our karma body?
            if (this.KarmaInput0.Count > 0)
            {
                var _karma__keyDown = this.KarmaInput0.Peek();

                var _karma_velocity = new Velocity();


                ExtractVelocityFromInput(_karma__keyDown, _karma_velocity);

                var current = this.karmabody;
                //var v = _karma_velocity.AngularVelocity * 10;
                //current.SetAngularVelocity(v);

                this.karmabody.ApplyAngularImpulse(
                    _karma_velocity.AngularVelocity
                    * ApplyVelocityElapse.ElapsedMilliseconds
                    * 0.5
                    * (1 - (this.karmabody.GetLinearVelocity().Length() / this.speed).Min(0.9) * 0.25)
                );


                var vx = Math.Cos(current.GetAngle()) * _karma_velocity.LinearVelocityY * this.speed
                                   + Math.Cos(current.GetAngle() + Math.PI / 2) * _karma_velocity.LinearVelocityX * this.speed;
                var vy = Math.Sin(current.GetAngle()) * _karma_velocity.LinearVelocityY * this.speed
                        + Math.Sin(current.GetAngle() + Math.PI / 2) * _karma_velocity.LinearVelocityX * this.speed;

                current.SetLinearVelocity(
                    new b2Vec2(
                     vx, vy
                    )
                );

                if (_karma__keyDown.fixup)
                {
                    var fixupmultiplier = 0.90;
                    // like a magnet
                    current.SetPositionAndAngle(
                        new b2Vec2(
                            _karma__keyDown.x + (current.GetPosition().x - _karma__keyDown.x) * fixupmultiplier,
                            _karma__keyDown.y + (current.GetPosition().y - _karma__keyDown.y) * fixupmultiplier
                        ),
                        // meab me in scotty
                            _karma__keyDown.angle + (current.GetAngle() - _karma__keyDown.angle) * fixupmultiplier

                    );
                }
            }


            this.damagebody.SetPositionAndAngle(
               new b2Vec2(this.body.GetPosition().x, this.body.GetPosition().y), this.body.GetAngle()
             );

            ApplyVelocityElapse.Restart();
        }
示例#60
0
        /// <summary>
        /// Runs the test.
        /// </summary>
        public virtual void RunTest()
        {
            VelocityContext context = new VelocityContext();

            AssureResultsDirectoryExists(TemplateTest.RESULT_DIR);

            /*
             *  get the template and the output
             */

            /*
             *  Chinese and spanish
             */

            Template template = Velocity.GetTemplate(GetFileName(null, "encodingtest", TemplateTest.TMPL_FILE_EXT), "UTF-8");

            FileStream fos =
                new FileStream(GetFileName(TemplateTest.RESULT_DIR, "encodingtest", TemplateTest.RESULT_FILE_EXT), FileMode.Create);

            StreamWriter writer = new StreamWriter(fos);

            template.Merge(context, writer);
            writer.Flush();
            writer.Close();

            if (
                !IsMatch(TemplateTest.RESULT_DIR, TemplateTest.COMPARE_DIR, "encodingtest", TemplateTest.RESULT_FILE_EXT,
                         TemplateTest.CMP_FILE_EXT))
            {
                Assert.Fail("Output 1 incorrect.");
            }

            /*
             *  a 'high-byte' chinese example from Michael Zhou
             */

            template = Velocity.GetTemplate(GetFileName(null, "encodingtest2", TemplateTest.TMPL_FILE_EXT), "UTF-8");

            fos =
                new FileStream(GetFileName(TemplateTest.RESULT_DIR, "encodingtest2", TemplateTest.RESULT_FILE_EXT), FileMode.Create);

            writer = new StreamWriter(fos);

            template.Merge(context, writer);
            writer.Flush();
            writer.Close();

            if (
                !IsMatch(TemplateTest.RESULT_DIR, TemplateTest.COMPARE_DIR, "encodingtest2", TemplateTest.RESULT_FILE_EXT,
                         TemplateTest.CMP_FILE_EXT))
            {
                Assert.Fail("Output 2 incorrect.");
            }

            /*
             *  a 'high-byte' chinese from Ilkka
             */

            template = Velocity.GetTemplate(GetFileName(null, "encodingtest3", TemplateTest.TMPL_FILE_EXT), "GB18030");
            //GBK=936?

            fos =
                new FileStream(GetFileName(TemplateTest.RESULT_DIR, "encodingtest3", TemplateTest.RESULT_FILE_EXT), FileMode.Create);

            writer = new StreamWriter(fos, Encoding.GetEncoding("GB18030"));

            template.Merge(context, writer);
            writer.Flush();
            writer.Close();

            if (
                !IsMatch(TemplateTest.RESULT_DIR, TemplateTest.COMPARE_DIR, "encodingtest3", TemplateTest.RESULT_FILE_EXT,
                         TemplateTest.CMP_FILE_EXT))
            {
                Assert.Fail("Output 3 incorrect.");
            }

            /*
             *  Russian example from Vitaly Repetenko
             */

            template = Velocity.GetTemplate(GetFileName(null, "encodingtest_KOI8-R", TemplateTest.TMPL_FILE_EXT), "KOI8-R");
            fos      =
                new FileStream(GetFileName(TemplateTest.RESULT_DIR, "encodingtest_KOI8-R", TemplateTest.RESULT_FILE_EXT),
                               FileMode.Create);
            writer = new StreamWriter(fos, Encoding.GetEncoding("KOI8-R"));

            template.Merge(context, writer);
            writer.Flush();
            writer.Close();

            if (
                !IsMatch(TemplateTest.RESULT_DIR, TemplateTest.COMPARE_DIR, "encodingtest_KOI8-R", TemplateTest.RESULT_FILE_EXT,
                         TemplateTest.CMP_FILE_EXT))
            {
                Assert.Fail("Output 4 incorrect.");
            }


            /*
             *  ISO-8859-1 example from Mike Bridge
             */

            template =
                Velocity.GetTemplate(GetFileName(null, "encodingtest_ISO-8859-1", TemplateTest.TMPL_FILE_EXT), "ISO-8859-1");
            fos =
                new FileStream(GetFileName(TemplateTest.RESULT_DIR, "encodingtest_ISO-8859-1", TemplateTest.RESULT_FILE_EXT),
                               FileMode.Create);
            writer = new StreamWriter(fos, Encoding.GetEncoding("ISO-8859-1"));

            template.Merge(context, writer);
            writer.Flush();
            writer.Close();

            if (
                !IsMatch(TemplateTest.RESULT_DIR, TemplateTest.COMPARE_DIR, "encodingtest_ISO-8859-1", TemplateTest.RESULT_FILE_EXT,
                         TemplateTest.CMP_FILE_EXT))
            {
                Assert.Fail("Output 5 incorrect.");
            }
        }