System.Math.Min(float, float)

Here are the examples of the csharp api System.Math.Min(float, float) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

992 Examples 7

19 View Source File : Diagram.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

public void Display(Graphics g)
		{
			RectangleF clip = g.ClipBounds;

			// Draw diagram elements
			IGraphics graphics = new GdiGraphics(g);
			foreach (DiagramElement element in GetElementsInReversedDisplayOrder())
			{
				if (clip.IntersectsWith(element.GetVisibleArea(Zoom)))
					element.Draw(graphics, true);
				element.NeedsRedraw = false;
			}
			if (state == State.CreatingShape)
			{
				g.DrawRectangle(SelectionPen,
					shapeOutline.X, shapeOutline.Y, shapeOutline.Width, shapeOutline.Height);
			}
			else if (state == State.CreatingConnection)
			{
				connectionCreator.Draw(g);
			}

			// Draw selection lines
			GraphicsState savedState = g.Save();
			g.ResetTransform();
			g.SmoothingMode = SmoothingMode.None;
			foreach (Shape shape in shapes.GetSelectedElementsReversed())
			{
				if (clip.IntersectsWith(shape.GetVisibleArea(Zoom)))
					shape.DrawSelectionLines(g, Zoom, Offset);
			}
			foreach (Connection connection in connections.GetSelectedElementsReversed())
			{
				if (clip.IntersectsWith(connection.GetVisibleArea(Zoom)))
					connection.DrawSelectionLines(g, Zoom, Offset);
			}
			
			if (state == State.Multiselecting)
			{
				RectangleF frame = RectangleF.FromLTRB(
					Math.Min(selectionFrame.Left, selectionFrame.Right),
					Math.Min(selectionFrame.Top, selectionFrame.Bottom),
					Math.Max(selectionFrame.Left, selectionFrame.Right),
					Math.Max(selectionFrame.Top, selectionFrame.Bottom));
				g.DrawRectangle(SelectionPen,
					frame.X * Zoom - Offset.X,
					frame.Y * Zoom - Offset.Y,
					frame.Width * Zoom,
					frame.Height * Zoom);
			}

			// Draw diagram border
			clip = g.ClipBounds;
			float borderWidth = Size.Width * Zoom;
			float borderHeight = Size.Height * Zoom;
			if (clip.Right > borderWidth || clip.Bottom > borderHeight)
			{
				SelectionPen.DashOffset = Offset.Y - Offset.X;
				g.DrawLines(SelectionPen, new PointF[] {
					new PointF(borderWidth, 0),
					new PointF(borderWidth, borderHeight),
					new PointF(0, borderHeight)
				});
				SelectionPen.DashOffset = 0;
			}

			// Restore original state
			g.Restore(savedState);
		}

19 View Source File : AnnotationDrawControl.cs
License : MIT License
Project Creator : AlturosDestinations

private void CreateBoundingBox(PointF point1, PointF point2)
        {
            var canvasInfo = this.GetCanvasInformation();

            var topLeftCorner = new PointF(Math.Min(point1.X, point2.X), Math.Min(point1.Y, point2.Y));
            var bottomRightCorner = new PointF(Math.Max(point1.X, point2.X), Math.Max(point1.Y, point2.Y));

            topLeftCorner = this.ClampPoint(topLeftCorner);
            bottomRightCorner = this.ClampPoint(bottomRightCorner);

            var width = (bottomRightCorner.X - topLeftCorner.X) / canvasInfo.ScaledWidth;
            var height = (bottomRightCorner.Y - topLeftCorner.Y) / canvasInfo.ScaledHeight;

            var x = (topLeftCorner.X - canvasInfo.OffsetX + (width * canvasInfo.ScaledWidth / 2)) / canvasInfo.ScaledWidth;
            var y = (topLeftCorner.Y - canvasInfo.OffsetY + (height * canvasInfo.ScaledHeight / 2)) / canvasInfo.ScaledHeight;

            if (this._annotationImage.BoundingBoxes == null)
            {
                this._annotationImage.BoundingBoxes = new List<AnnotationBoundingBox>();
            }

            var newBoundingBox = new AnnotationBoundingBox
            {
                CenterX = (float)x,
                CenterY = (float)y,
                Width = (float)width,
                Height = (float)height
            };
            this._selectedBoundingBox = newBoundingBox;

            this._annotationImage.BoundingBoxes.Add(newBoundingBox);
            this._dragPoint = null;
            this.ImageEdited?.Invoke(this._annotationImage);
        }

19 View Source File : Misc.cs
License : MIT License
Project Creator : Alan-FGR

public static float Min(float a, float b, float c, float d)
   {
      return Math.Min(a, Math.Min(b, Math.Min(c, d)));
   }

19 View Source File : AudioManager.cs
License : MIT License
Project Creator : AlbertMN

public static float StepMasterVolume(float stepAmount) {
            IAudioEndpointVolume masterVol = null;
            try {
                masterVol = GetMasterVolumeObject();
                if (masterVol == null)
                    return -1;

                float stepAmountScaled = stepAmount / 100;

                // Get the level
                masterVol.GetMasterVolumeLevelScalar(out float volumeLevel);

                // Calculate the new level
                float newLevel = volumeLevel + stepAmountScaled;
                newLevel = Math.Min(1, newLevel);
                newLevel = Math.Max(0, newLevel);

                masterVol.SetMasterVolumeLevelScalar(newLevel, Guid.Empty);

                // Return the new volume level that was set
                return newLevel * 100;
            } finally {
                if (masterVol != null)
                    Marshal.ReleaseComObject(masterVol);
            }
        }

19 View Source File : ContactSolver.cs
License : MIT License
Project Creator : Alan-FGR

public bool SolvePositionConstraints()
        {
            float minSeparation = 0.0f;

            for (int i = 0; i < _count; ++i)
            {
                ContactPositionConstraint pc = _positionConstraints[i];

                int indexA = pc.indexA;
                int indexB = pc.indexB;
                Vector2 localCenterA = pc.localCenterA;
                float mA = pc.invMreplacedA;
                float iA = pc.invIA;
                Vector2 localCenterB = pc.localCenterB;
                float mB = pc.invMreplacedB;
                float iB = pc.invIB;
                int pointCount = pc.pointCount;

                Vector2 cA = _positions[indexA].c;
                float aA = _positions[indexA].a;

                Vector2 cB = _positions[indexB].c;
                float aB = _positions[indexB].a;

                // Solve normal constraints
                for (int j = 0; j < pointCount; ++j)
                {
                    Transform xfA = new Transform();
                    Transform xfB = new Transform();
                    xfA.q.Set(aA);
                    xfB.q.Set(aB);
                    xfA.p = cA - MathUtils.Mul(xfA.q, localCenterA);
                    xfB.p = cB - MathUtils.Mul(xfB.q, localCenterB);

                    Vector2 normal;
                    Vector2 point;
                    float separation;

                    PositionSolverManifold.Initialize(pc, xfA, xfB, j, out normal, out point, out separation);

                    Vector2 rA = point - cA;
                    Vector2 rB = point - cB;

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

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

                    // Compute the effective mreplaced.
                    float rnA = MathUtils.Cross(rA, normal);
                    float rnB = MathUtils.Cross(rB, normal);
                    float K = mA + mB + iA * rnA * rnA + iB * rnB * rnB;

                    // Compute normal impulse
                    float impulse = K > 0.0f ? -C / K : 0.0f;

                    Vector2 P = impulse * normal;

                    cA -= mA * P;
                    aA -= iA * MathUtils.Cross(rA, P);

                    cB += mB * P;
                    aB += iB * MathUtils.Cross(rB, P);
                }

                _positions[indexA].c = cA;
                _positions[indexA].a = aA;

                _positions[indexB].c = cB;
                _positions[indexB].a = aB;
            }

            // We can't expect minSpeparation >= -b2_linearSlop because we don't
            // push the separation above -b2_linearSlop.
            return minSeparation >= -3.0f * Settings.LinearSlop;
        }

19 View Source File : IKConstraint.cs
License : The Unlicense
Project Creator : aeroson

protected internal void Preupdate(float dt, float updateRate)
        {
            float stiffness = StiffnessOverDamping * rigidity;
            float damping = rigidity;
            float multiplier = 1 / (dt * stiffness + damping);
            errorCorrectionFactor = stiffness * multiplier;
            softness = updateRate * multiplier;
            maximumImpulse = maximumForce * dt;
            maximumImpulseSquared = Math.Min(float.MaxValue, maximumImpulse * maximumImpulse);

        }

19 View Source File : Icon.cs
License : MIT License
Project Creator : AlexPshul

private void CanvasViewOnPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKCanvas canvas = args.Surface.Canvas;
            canvas.Clear();

            if (string.IsNullOrEmpty(ResourceId))
                return;

            using (Stream stream = GetType().replacedembly.GetManifestResourceStream(ResourceId))
            {
                SKSvg svg = new SKSvg();
                svg.Load(stream);

                SKImageInfo info = args.Info;
                canvas.Translate(info.Width / 2f, info.Height / 2f);

                SKRect bounds = svg.ViewBox;
                float xRatio = info.Width / bounds.Width;
                float yRatio = info.Height / bounds.Height;

                float ratio = Math.Min(xRatio, yRatio);

                canvas.Scale(ratio);
                canvas.Translate(-bounds.MidX, -bounds.MidY);

                canvas.DrawPicture(svg.Picture);
            }
        }

19 View Source File : ToughGhost.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public override void behaviorAtGameTick(GameTime time)
        {
            base.behaviorAtGameTick(time);
            this.faceDirection(0);
            float xSlope = (float)(-(float)(base.Player.GetBoundingBox().Center.X - this.GetBoundingBox().Center.X));
            float ySlope = (float)(base.Player.GetBoundingBox().Center.Y - this.GetBoundingBox().Center.Y);
            float t = Math.Max(1f, Math.Abs(xSlope) + Math.Abs(ySlope));
            if (t < 64f)
            {
                this.xVelocity = Math.Max(-7f, Math.Min(7f, this.xVelocity * 1.1f));
                this.yVelocity = Math.Max(-7f, Math.Min(7f, this.yVelocity * 1.1f));
            }
            xSlope /= t;
            ySlope /= t;
            if (this.wareplacedCounter <= 0)
            {
                this.targetRotation = (float)Math.Atan2((double)(-(double)ySlope), (double)xSlope) - 1.57079637f;
                if ((double)(Math.Abs(this.targetRotation) - Math.Abs(this.rotation)) > 2.748893571891069 && Game1.random.NextDouble() < 0.5)
                {
                    this.turningRight = true;
                }
                else if ((double)(Math.Abs(this.targetRotation) - Math.Abs(this.rotation)) < 0.39269908169872414)
                {
                    this.turningRight = false;
                }
                if (this.turningRight)
                {
                    this.rotation -= (float)Math.Sign(this.targetRotation - this.rotation) * 0.0490873866f;
                }
                else
                {
                    this.rotation += (float)Math.Sign(this.targetRotation - this.rotation) * 0.0490873866f;
                }
                this.rotation %= 6.28318548f;
                this.wareplacedCounter = 5 + Game1.random.Next(-1, 2);
            }
            float maxAccel = Math.Min(7f, Math.Max(2f, 7f - t / 64f / 2f))*2;
            xSlope = (float)Math.Cos((double)this.rotation + 1.5707963267948966);
            ySlope = -(float)Math.Sin((double)this.rotation + 1.5707963267948966);
            this.xVelocity += -xSlope * maxAccel / 6f + (float)Game1.random.Next(-10, 10) / 100f;
            this.yVelocity += -ySlope * maxAccel / 6f + (float)Game1.random.Next(-10, 10) / 100f;
            if (Math.Abs(this.xVelocity) > Math.Abs(-xSlope * 7f))
            {
                this.xVelocity -= -xSlope * maxAccel / 6f;
            }
            if (Math.Abs(this.yVelocity) > Math.Abs(-ySlope * 7f))
            {
                this.yVelocity -= -ySlope * maxAccel / 6f;
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : anastasios-stamoulis

void deprocess_image(float[] x) {
      var meanValue = x.Average();
      var sumSquares = 0.0;
      for (int i = 0; i < x.Length; i++) {
        x[i] -= meanValue;
        sumSquares += x[i] * x[i];
      }
      var std = (float)(Math.Sqrt(sumSquares / x.Length) + 1e-5);
      for (int i = 0; i < x.Length; i++) {
        x[i] /= std;
        x[i] *= 0.1f;
        x[i] += 0.5f;
        x[i] = Math.Min(Math.Max(0, x[i]), 1);
        x[i] *= 255;
      }
    }

19 View Source File : Fishie.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

protected override void updateAnimation(GameTime time)
        {
            base.updateAnimation(time);
            if (wareplacedCounter >= 0)
            {
                wareplacedCounter -= time.ElapsedGameTime.Milliseconds;
            }
            Sprite.Animate(time, 0, 9, 40f);
            float xSlope = (float)(-(float)(base.Player.GetBoundingBox().Center.X - GetBoundingBox().Center.X));
            float ySlope = (float)(base.Player.GetBoundingBox().Center.Y - GetBoundingBox().Center.Y);
            float t = Math.Max(1f, Math.Abs(xSlope) + Math.Abs(ySlope));
            if (t < 64f)
            {
                xVelocity = Math.Max(-7f, Math.Min(7f, xVelocity * 1.1f));
                yVelocity = Math.Max(-7f, Math.Min(7f, yVelocity * 1.1f));
            }
            xSlope /= t;
            ySlope /= t;
            if (wareplacedCounter <= 0)
            {
                targetRotation = (float)Math.Atan2((double)(-(double)ySlope), (double)xSlope) - 1.57079637f;
                if ((double)(Math.Abs(targetRotation) - Math.Abs(rotation)) > 2.748893571891069 && Game1.random.NextDouble() < 0.5)
                {
                    turningRight = true;
                }
                else if ((double)(Math.Abs(targetRotation) - Math.Abs(rotation)) < 0.39269908169872414)
                {
                    turningRight = false;
                }
                if (turningRight)
                {
                    rotation -= (float)Math.Sign(targetRotation - rotation) * 0.0490873866f;
                }
                else
                {
                    rotation += (float)Math.Sign(targetRotation - rotation) * 0.0490873866f;
                }
                rotation %= 6.28318548f;
                wareplacedCounter = 5 + Game1.random.Next(-1, 2);
            }
            float maxAccel = Math.Min(7f, Math.Max(2f, 7f - t / 64f / 2f));
            xSlope = (float)Math.Cos((double)rotation + 1.5707963267948966);
            ySlope = -(float)Math.Sin((double)rotation + 1.5707963267948966);
            xVelocity += -xSlope * maxAccel / 6f + (float)Game1.random.Next(-10, 10) / 100f;
            yVelocity += -ySlope * maxAccel / 6f + (float)Game1.random.Next(-10, 10) / 100f;
            if (Math.Abs(xVelocity) > Math.Abs(-xSlope * 7f))
            {
                xVelocity -= -xSlope * maxAccel / 6f;
            }
            if (Math.Abs(yVelocity) > Math.Abs(-ySlope * 7f))
            {
                yVelocity -= -ySlope * maxAccel / 6f;
            }
            base.resetAnimationSpeed();
        }

19 View Source File : GvrProfile.cs
License : MIT License
Project Creator : alanplotko

public void GetLeftEyeVisibleTanAngles(float[] result) {
    // Tan-angles from the max FOV.
    float fovLeft = Mathf.Tan(-viewer.maxFOV.outer * Mathf.Deg2Rad);
    float fovTop = Mathf.Tan(viewer.maxFOV.upper * Mathf.Deg2Rad);
    float fovRight = Mathf.Tan(viewer.maxFOV.inner * Mathf.Deg2Rad);
    float fovBottom = Mathf.Tan(-viewer.maxFOV.lower * Mathf.Deg2Rad);
    // Viewport size.
    float halfWidth = screen.width / 4;
    float halfHeight = screen.height / 2;
    // Viewport center, measured from left lens position.
    float centerX = viewer.lenses.separation / 2 - halfWidth;
    float centerY = -VerticalLensOffset;
    float centerZ = viewer.lenses.screenDistance;
    // Tan-angles of the viewport edges, as seen through the lens.
    float screenLeft = viewer.distortion.distort((centerX - halfWidth) / centerZ);
    float screenTop = viewer.distortion.distort((centerY + halfHeight) / centerZ);
    float screenRight = viewer.distortion.distort((centerX + halfWidth) / centerZ);
    float screenBottom = viewer.distortion.distort((centerY - halfHeight) / centerZ);
    // Compare the two sets of tan-angles and take the value closer to zero on each side.
    result[0] = Math.Max(fovLeft, screenLeft);
    result[1] = Math.Min(fovTop, screenTop);
    result[2] = Math.Min(fovRight, screenRight);
    result[3] = Math.Max(fovBottom, screenBottom);
  }

19 View Source File : MathHelper.cs
License : MIT License
Project Creator : Alan-FGR

public static float Min(float value1, float value2)
        {
            return Math.Min(value1, value2);
        }

19 View Source File : BoxShape.cs
License : The Unlicense
Project Creator : aeroson

public override bool RayTest(ref Ray ray, ref RigidTransform transform, float maximumLength, out RayHit hit)
        {
            hit = new RayHit();

            Quaternion conjugate;
            Quaternion.Conjugate(ref transform.Orientation, out conjugate);
            Vector3 localOrigin;
            Vector3.Subtract(ref ray.Position, ref transform.Position, out localOrigin);
            Quaternion.Transform(ref localOrigin, ref conjugate, out localOrigin);
            Vector3 localDirection;
            Quaternion.Transform(ref ray.Direction, ref conjugate, out localDirection);
            Vector3 normal = Toolbox.ZeroVector;
            float temp, tmin = 0, tmax = maximumLength;

            if (Math.Abs(localDirection.X) < Toolbox.Epsilon && (localOrigin.X < -halfWidth || localOrigin.X > halfWidth))
                return false;
            float inverseDirection = 1 / localDirection.X;
            float t1 = (-halfWidth - localOrigin.X) * inverseDirection;
            float t2 = (halfWidth - localOrigin.X) * inverseDirection;
            var tempNormal = new Vector3(-1, 0, 0);
            if (t1 > t2)
            {
                temp = t1;
                t1 = t2;
                t2 = temp;
                tempNormal *= -1;
            }
            temp = tmin;
            tmin = Math.Max(tmin, t1);
            if (temp != tmin)
                normal = tempNormal;
            tmax = Math.Min(tmax, t2);
            if (tmin > tmax)
                return false;
            if (Math.Abs(localDirection.Y) < Toolbox.Epsilon && (localOrigin.Y < -halfHeight || localOrigin.Y > halfHeight))
                return false;
            inverseDirection = 1 / localDirection.Y;
            t1 = (-halfHeight - localOrigin.Y) * inverseDirection;
            t2 = (halfHeight - localOrigin.Y) * inverseDirection;
            tempNormal = new Vector3(0, -1, 0);
            if (t1 > t2)
            {
                temp = t1;
                t1 = t2;
                t2 = temp;
                tempNormal *= -1;
            }
            temp = tmin;
            tmin = Math.Max(tmin, t1);
            if (temp != tmin)
                normal = tempNormal;
            tmax = Math.Min(tmax, t2);
            if (tmin > tmax)
                return false;
            if (Math.Abs(localDirection.Z) < Toolbox.Epsilon && (localOrigin.Z < -halfLength || localOrigin.Z > halfLength))
                return false;
            inverseDirection = 1 / localDirection.Z;
            t1 = (-halfLength - localOrigin.Z) * inverseDirection;
            t2 = (halfLength - localOrigin.Z) * inverseDirection;
            tempNormal = new Vector3(0, 0, -1);
            if (t1 > t2)
            {
                temp = t1;
                t1 = t2;
                t2 = temp;
                tempNormal *= -1;
            }
            temp = tmin;
            tmin = Math.Max(tmin, t1);
            if (temp != tmin)
                normal = tempNormal;
            tmax = Math.Min(tmax, t2);
            if (tmin > tmax)
                return false;
            hit.T = tmin;
            Vector3.Multiply(ref ray.Direction, tmin, out hit.Location);
            Vector3.Add(ref hit.Location, ref ray.Position, out hit.Location);
            Quaternion.Transform(ref normal, ref transform.Orientation, out normal);
            hit.Normal = normal;
            return true;
        }

19 View Source File : DiagramPrintDialog.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

private void printDoreplacedent_PrintPage(object sender, PrintPageEventArgs e)
		{
			// Scale the page to match sizes of the screen
			e.Graphics.PageUnit = GraphicsUnit.Inch;
			e.Graphics.PageScale = 1 / DiagramElement.Graphics.DpiX;

			// Get the phisical page margins
			float marginScale = DiagramElement.Graphics.DpiX / 100;
			RectangleF marginBounds = e.MarginBounds;
			if (!printDoreplacedent.PrintController.IsPreview)
				marginBounds.Offset(-e.PageSettings.HardMarginX, -e.PageSettings.HardMarginY);
			marginBounds = new RectangleF(
				marginBounds.X * marginScale, marginBounds.Y * marginScale,
				marginBounds.Width * marginScale, marginBounds.Height * marginScale);

			// Get logical area information
			RectangleF drawingArea = doreplacedent.GetPrintingArea(selectedOnly);
			int column = pageIndex % columns;
			int row = pageIndex / columns;

			// Get zooming information if diagram is too big
			float scaleX = columns * marginBounds.Width / drawingArea.Width;
			float scaleY = rows * marginBounds.Height / drawingArea.Height;
			float scale = Math.Min(scaleX, scaleY);
			if (scale > 1) scale = 1; // No need for zooming in

			// Set the printing clip region
			RectangleF clipBounds = marginBounds;
			if (column == 0)
			{
				clipBounds.X = 0;
				clipBounds.Width += marginBounds.Left;
			}
			if (row == 0)
			{
				clipBounds.Y = 0;
				clipBounds.Height += marginBounds.Top;
			}
			if (column == columns - 1)
			{
				clipBounds.Width += marginBounds.Left;
			}
			if (row == rows - 1)
			{
				clipBounds.Height += marginBounds.Top;
			}
			e.Graphics.SetClip(clipBounds);

			// Moving the image to it's right position
			e.Graphics.TranslateTransform(-column * marginBounds.Width, -row * marginBounds.Height);
			e.Graphics.TranslateTransform(marginBounds.Left, marginBounds.Top);
			e.Graphics.ScaleTransform(scale, scale);
			e.Graphics.TranslateTransform(-drawingArea.Left, -drawingArea.Top);
			
			// Printing
			IGraphics graphics = new GdiGraphics(e.Graphics);
			doreplacedent.Print(graphics, selectedOnly, printingStyle);
			e.HasMorePages = (++pageIndex < PageCount);
		}

19 View Source File : BatFamiliar.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public override void behaviorAtGameTick(GameTime time)
        {
            invincibleCountdown = 1000;
            if (timeBeforeAIMovementAgain > 0f)
            {
                timeBeforeAIMovementAgain -= (float)time.ElapsedGameTime.Milliseconds;
            }
            if (lastHitCounter >= 0)
            {
                lastHitCounter.Value -= time.ElapsedGameTime.Milliseconds;
            }
            if (lastScreechCounter >= 0)
            {
                lastScreechCounter.Value -= time.ElapsedGameTime.Milliseconds;
            }
            if (lastScreechCounter < 0 && GetBoundingBox().Intersects(GetOwner().GetBoundingBox()))
            {
                if(ModEntry.Config.BatSoundEffects)
                    currentLocation.playSound("batScreech", NetAudio.SoundContext.Default);
                lastScreechCounter.Value = 10000;
            }

            chargingMonster = false;
            if(lastHitCounter < 0 && !(currentLocation is SlimeHutch))
            {
                foreach (NPC npc in currentLocation.characters)
                {
                    if (npc is Familiar)
                        continue;

                    if (npc is Monster && FamiliarsUtils.monstersColliding(this, (Monster)npc))
                    {
                        if (BaseDamage() >= 0)
                        {
                            int damageAmount = Game1.random.Next(BaseDamage(), BaseDamage() * 2 + 1);
                            damageAmount = (npc as Monster).takeDamage(damageAmount, 0, 0, false, 0, GetOwner());
                            if((npc as Monster).Health <= 0)
                            {
                                AddExp(10);
                            }
                            else
                            {
                                AddExp(1);
                            }
                        }
                        lastHitCounter.Value = AttackInterval();
                        chargingMonster = false;
                        break;
                    }
                    else if (npc is Monster && FamiliarsUtils.withinMonsterThreshold(this, (Monster)npc, 2))
                    {
                        chargingMonster = true;
                        if (currentTarget == null || Vector2.Distance(npc.position, position) < Vector2.Distance(currentTarget.position, position))
                        {
                            currentTarget = (Monster)npc;
                        }
                    }
                }
            }

            if (wareplacedCounter >= 0)
            {
                wareplacedCounter.Value -= time.ElapsedGameTime.Milliseconds;
            }

            if (chargingMonster || followingOwner)
            {
                seenPlayer.Value = true;

                Vector2 center = Position + new Vector2(8, 8);
                Vector2 playerCenter = GetOwner().position + new Vector2(64, 92);
                if (Vector2.Distance(playerCenter, center) > 256)
                {
                    Position = Vector2.Distance(playerCenter, center) * 0.03f * Vector2.Normalize(playerCenter - center) + center - new Vector2(8, 8);

                }

                float xSlope = (float)(-(float)(playerCenter.X - center.X));
                float ySlope = (float)(playerCenter.Y - center.Y);
                float t = Math.Max(1f, Math.Abs(xSlope) + Math.Abs(ySlope));
                if (t < (float)((extraVelocity > 0f) ? 192 : 64))
                {
                    xVelocity = Math.Max(-maxSpeed, Math.Min(maxSpeed, xVelocity * 1.05f));
                    yVelocity = Math.Max(-maxSpeed, Math.Min(maxSpeed, yVelocity * 1.05f));
                }
                xSlope /= t;
                ySlope /= t;
                if (wareplacedCounter <= 0)
                {
                    targetRotation = (float)Math.Atan2((double)(-(double)ySlope), (double)xSlope) - 1.57079637f;
                    if ((double)(Math.Abs(targetRotation) - Math.Abs(rotation)) > 2.748893571891069 && Game1.random.NextDouble() < 0.5)
                    {
                        turningRight.Value = true;
                    }
                    else if ((double)(Math.Abs(targetRotation) - Math.Abs(rotation)) < 0.39269908169872414)
                    {
                        turningRight.Value = false;
                    }
                    if (turningRight)
                    {
                        rotation -= (float)Math.Sign(targetRotation - rotation) * 0.0490873866f;
                    }
                    else
                    {
                        rotation += (float)Math.Sign(targetRotation - rotation) * 0.0490873866f;
                    }
                    rotation %= 6.28318548f;
                    wareplacedCounter.Value = 0;
                }
                float maxAccel = Math.Min(5f, Math.Max(1f, 5f - t / 64f / 2f)) + extraVelocity;
                xSlope = (float)Math.Cos((double)rotation + 1.5707963267948966);
                ySlope = -(float)Math.Sin((double)rotation + 1.5707963267948966);
                xVelocity += -xSlope * maxAccel / 6f + (float)Game1.random.Next(-10, 10) / 100f;
                yVelocity += -ySlope * maxAccel / 6f + (float)Game1.random.Next(-10, 10) / 100f;
                if (Math.Abs(xVelocity) > Math.Abs(-xSlope * maxSpeed))
                {
                    xVelocity -= -xSlope * maxAccel / 6f;
                }
                if (Math.Abs(yVelocity) > Math.Abs(-ySlope * maxSpeed))
                {
                    yVelocity -= -ySlope * maxAccel / 6f;
                }
            }
        }

19 View Source File : DiagramNavigator.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

private float GetZoom()
		{
			Rectangle borders = this.ClientRectangle;
			float zoom1 = (float) borders.Width / DoreplacedentVisualizer.DoreplacedentSize.Width;
			float zoom2 = (float) borders.Height / DoreplacedentVisualizer.DoreplacedentSize.Height;

			return Math.Min(zoom1, zoom2);
		}

19 View Source File : Ray.cs
License : The Unlicense
Project Creator : aeroson

public void Intersects(ref BoundingBox boundingBox, out float? result)
        {
            if (System.Math.Abs(Direction.X) < Toolbox.Epsilon && (Position.X < boundingBox.Min.X || Position.X > boundingBox.Max.X))
            {
                //If the ray isn't pointing along the axis at all, and is outside of the box's interval, then it
                //can't be intersecting.
                result = null;
                return;
            }
            float tmin = 0, tmax = float.MaxValue;
            float inverseDirection = 1 / Direction.X;
            float t1 = (boundingBox.Min.X - Position.X) * inverseDirection;
            float t2 = (boundingBox.Max.X - Position.X) * inverseDirection;
            if (t1 > t2)
            {
                float temp = t1;
                t1 = t2;
                t2 = temp;
            }
            tmin = System.Math.Max(tmin, t1);
            tmax = System.Math.Min(tmax, t2);
            if (tmin > tmax)
            {
                result = null;
                return;
            }
            if (System.Math.Abs(Direction.Y) < Toolbox.Epsilon && (Position.Y < boundingBox.Min.Y || Position.Y > boundingBox.Max.Y))
            {                
                //If the ray isn't pointing along the axis at all, and is outside of the box's interval, then it
                //can't be intersecting.
                result = null; 
                return;
            }
            inverseDirection = 1 / Direction.Y;
            t1 = (boundingBox.Min.Y - Position.Y) * inverseDirection;
            t2 = (boundingBox.Max.Y - Position.Y) * inverseDirection;
            if (t1 > t2)
            {
                float temp = t1;
                t1 = t2;
                t2 = temp;
            }
            tmin = System.Math.Max(tmin, t1);
            tmax = System.Math.Min(tmax, t2);
            if (tmin > tmax)
            {
                result = null; 
                return;
            }
            if (System.Math.Abs(Direction.Z) < Toolbox.Epsilon && (Position.Z < boundingBox.Min.Z || Position.Z > boundingBox.Max.Z))
            {              
                //If the ray isn't pointing along the axis at all, and is outside of the box's interval, then it
                //can't be intersecting.
                result = null; 
                return;
            }
            inverseDirection = 1 / Direction.Z;
            t1 = (boundingBox.Min.Z - Position.Z) * inverseDirection;
            t2 = (boundingBox.Max.Z - Position.Z) * inverseDirection;
            if (t1 > t2)
            {
                float temp = t1;
                t1 = t2;
                t2 = temp;
            }
            tmin = System.Math.Max(tmin, t1);
            tmax = System.Math.Min(tmax, t2);
            if (tmin > tmax)
            {
                result = null; 
                return;
            }
            result = tmin;
        }

19 View Source File : Mandelbulb.cs
License : MIT License
Project Creator : altimesh

public float shadow(float3 lightDirection, float3 rayLocation, int iterations, float mint, float maxt, float k)
        {
            var res = 1.0F;
            for (float t = mint; t < maxt;)
            {
                float3 rd = lightDirection * t;
                float3 ro = rayLocation - rd;
                var h = Distance(ro, iterations);
                if (h < 0.001)
                {
                    return 0.0F;
                }

                res = Math.Min(res, k * h / t);
                t += h;
            }

            return res;
        }

19 View Source File : WorldObject_Weapon.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public float GetArmorCleavingMod(WorldObject weapon)
        {
            // investigate: should this value be on creatures directly?
            var creatureMod = GetArmorCleavingMod();
            var weaponMod = weapon != null ? weapon.GetArmorCleavingMod() : 1.0f;

            return Math.Min(creatureMod, weaponMod);
        }

19 View Source File : Viewport.cs
License : MIT License
Project Creator : amerkoleci

public static RectangleF ComputeDisplayArea(ViewportScaling scaling, int backBufferWidth, int backBufferHeight, int outputWidth, int outputHeight)
        {
            switch (scaling)
            {
                case ViewportScaling.Stretch:
                    // Output fills the entire window area
                    return new RectangleF(0, 0, outputWidth, outputHeight);

                case ViewportScaling.AspectRatioStretch:
                    // Output fills the window area but respects the original aspect ratio, using pillar boxing or letter boxing as required
                    // Note: This scaling option is not supported for legacy Win32 windows swap chains
                    {
                        Debug.replacedert(backBufferHeight > 0);
                        float aspectRatio = (float)backBufferWidth / backBufferHeight;

                        // Horizontal fill
                        float scaledWidth = outputWidth;
                        float scaledHeight = outputWidth / aspectRatio;
                        if (scaledHeight >= outputHeight)
                        {
                            // Do vertical fill
                            scaledWidth = outputHeight * aspectRatio;
                            scaledHeight = outputHeight;
                        }

                        float offsetX = (outputWidth - scaledWidth) * 0.5f;
                        float offsetY = (outputHeight - scaledHeight) * 0.5f;

                        // Clip to display window
                        return new RectangleF(
                            Max(0, offsetX),
                            Max(0, offsetY),
                            Min(outputWidth, scaledWidth),
                            Min(outputHeight, scaledHeight)
                            );
                    }

                case ViewportScaling.None:
                default:
                    // Output is displayed in the upper left corner of the window area
                    return new RectangleF(0, 0, Min(backBufferWidth, outputWidth), Min(backBufferHeight, outputHeight));
            }
        }

19 View Source File : EarclipDecomposer.cs
License : MIT License
Project Creator : Alan-FGR

private static List<Vertices> TriangulatePolygon(Vertices vertices, float tolerance)
        {
            //FPE note: Check is needed as invalid triangles can be returned in recursive calls.
            if (vertices.Count < 3)
                return new List<Vertices>();

            List<Vertices> results = new List<Vertices>();

            //Recurse and split on pinch points
            Vertices pA, pB;
            Vertices pin = new Vertices(vertices);
            if (ResolvePinchPoint(pin, out pA, out pB, tolerance))
            {
                List<Vertices> mergeA = TriangulatePolygon(pA, tolerance);
                List<Vertices> mergeB = TriangulatePolygon(pB, tolerance);

                if (mergeA.Count == -1 || mergeB.Count == -1)
                    throw new Exception("Can't triangulate your polygon.");

                for (int i = 0; i < mergeA.Count; ++i)
                {
                    results.Add(new Vertices(mergeA[i]));
                }
                for (int i = 0; i < mergeB.Count; ++i)
                {
                    results.Add(new Vertices(mergeB[i]));
                }

                return results;
            }

            Vertices[] buffer = new Vertices[vertices.Count - 2];
            int bufferSize = 0;
            float[] xrem = new float[vertices.Count];
            float[] yrem = new float[vertices.Count];
            for (int i = 0; i < vertices.Count; ++i)
            {
                xrem[i] = vertices[i].X;
                yrem[i] = vertices[i].Y;
            }

            int vNum = vertices.Count;

            while (vNum > 3)
            {
                // Find an ear
                int earIndex = -1;
                float earMaxMinCross = -10.0f;
                for (int i = 0; i < vNum; ++i)
                {
                    if (IsEar(i, xrem, yrem, vNum))
                    {
                        int lower = Remainder(i - 1, vNum);
                        int upper = Remainder(i + 1, vNum);
                        Vector2 d1 = new Vector2(xrem[upper] - xrem[i], yrem[upper] - yrem[i]);
                        Vector2 d2 = new Vector2(xrem[i] - xrem[lower], yrem[i] - yrem[lower]);
                        Vector2 d3 = new Vector2(xrem[lower] - xrem[upper], yrem[lower] - yrem[upper]);

                        d1.Normalize();
                        d2.Normalize();
                        d3.Normalize();
                        float cross12;
                        MathUtils.Cross(ref d1, ref d2, out cross12);
                        cross12 = Math.Abs(cross12);

                        float cross23;
                        MathUtils.Cross(ref d2, ref d3, out cross23);
                        cross23 = Math.Abs(cross23);

                        float cross31;
                        MathUtils.Cross(ref d3, ref d1, out cross31);
                        cross31 = Math.Abs(cross31);

                        //Find the maximum minimum angle
                        float minCross = Math.Min(cross12, Math.Min(cross23, cross31));
                        if (minCross > earMaxMinCross)
                        {
                            earIndex = i;
                            earMaxMinCross = minCross;
                        }
                    }
                }

                // If we still haven't found an ear, we're screwed.
                // Note: sometimes this is happening because the
                // remaining points are collinear.  Really these
                // should just be thrown out without halting triangulation.
                if (earIndex == -1)
                {
                    for (int i = 0; i < bufferSize; i++)
                    {
                        results.Add(buffer[i]);
                    }

                    return results;
                }

                // Clip off the ear:
                // - remove the ear tip from the list

                --vNum;
                float[] newx = new float[vNum];
                float[] newy = new float[vNum];
                int currDest = 0;
                for (int i = 0; i < vNum; ++i)
                {
                    if (currDest == earIndex) ++currDest;
                    newx[i] = xrem[currDest];
                    newy[i] = yrem[currDest];
                    ++currDest;
                }

                // - add the clipped triangle to the triangle list
                int under = (earIndex == 0) ? (vNum) : (earIndex - 1);
                int over = (earIndex == vNum) ? 0 : (earIndex + 1);
                Triangle toAdd = new Triangle(xrem[earIndex], yrem[earIndex], xrem[over], yrem[over], xrem[under],
                                              yrem[under]);
                buffer[bufferSize] = toAdd;
                ++bufferSize;

                // - replace the old list with the new one
                xrem = newx;
                yrem = newy;
            }

            Triangle tooAdd = new Triangle(xrem[1], yrem[1], xrem[2], yrem[2], xrem[0], yrem[0]);
            buffer[bufferSize] = tooAdd;
            ++bufferSize;

            for (int i = 0; i < bufferSize; i++)
            {
                results.Add(new Vertices(buffer[i]));
            }

            return results;
        }

19 View Source File : Math.cs
License : MIT License
Project Creator : Alan-FGR

public static float Clamp(float a, float low, float high)
        {
            return Math.Max(low, Math.Min(a, high));
        }

19 View Source File : Trajectory.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator

public static bool solve_ballistic_arc_lateral(Vector3 proj_pos, float lateral_speed, Vector3 target, Vector3 target_velocity, float gravity, out Vector3 fire_velocity, out float time, out Vector3 impact_point)
        {

            // Handling these cases is up to your project's coding standards
            Debug.replacedert(proj_pos != target && lateral_speed > 0, "fts.solve_ballistic_arc_lateral called with invalid data");

            // Initialize output variables
            fire_velocity = Vector3.Zero;
            time = 0.0f;
            impact_point = Vector3.Zero;

            // Ground plane terms
            Vector3 targetVelXY = new Vector3(target_velocity.X, target_velocity.Y, 0f);
            Vector3 diffXY = target - proj_pos;
            diffXY.Z = 0;

            // Derivation
            //   (1) Base formula: |P + V*t| = S*t
            //   (2) Subsreplacedute variables: |diffXY + targetVelXY*t| = S*t
            //   (3) Square both sides: Dot(diffXY,diffXY) + 2*Dot(diffXY, targetVelXY)*t + Dot(targetVelXY, targetVelXY)*t^2 = S^2 * t^2
            //   (4) Quadratic: (Dot(targetVelXY,targetVelXY) - S^2)t^2 + (2*Dot(diffXY, targetVelXY))*t + Dot(diffXY, diffXY) = 0
            float c0 = Vector3.Dot(targetVelXY, targetVelXY) - lateral_speed * lateral_speed;
            float c1 = 2f * Vector3.Dot(diffXY, targetVelXY);
            float c2 = Vector3.Dot(diffXY, diffXY);
            double t0, t1;
            int n = SolveQuadric(c0, c1, c2, out t0, out t1);

            // pick smallest, positive time
            bool valid0 = n > 0 && t0 > 0;
            bool valid1 = n > 1 && t1 > 0;

            float t;
            if (!valid0 && !valid1)
                return false;
            else if (valid0 && valid1)
                t = Math.Min((float)t0, (float)t1);
            else
                t = valid0 ? (float)t0 : (float)t1;

            // Calculate impact point
            impact_point = target + (target_velocity * t);

            // Calculate fire velocity along XZ plane
            Vector3 dir = impact_point - proj_pos;
            fire_velocity = new Vector3(dir.X, dir.Y, 0f).Normalize() * lateral_speed;

            // Solve system of equations. Hit max_height at t=.5*time. Hit target at t=time.
            //
            // peak = z0 + vertical_speed*halfTime + .5*gravity*halfTime^2
            // end = z0 + vertical_speed*time + .5*gravity*time^s
            // Wolfram Alpha: solve b = a + .5*v*t + .5*g*(.5*t)^2, c = a + vt + .5*g*t^2 for g, v
            float a = proj_pos.Z;       // initial
            //float b = Math.Max(proj_pos.Z, impact_point.Z) + max_height_offset;  // peak
            float c = impact_point.Z;   // final

            //gravity = -4 * (a - 2 * b + c) / (t * t);
            //fire_velocity.Z = -(3 * a - 4 * b + c) / t;

            var g = gravity;
            var b = (4 * a + 4 * c - g * t * t) / 8;

            fire_velocity.Z = (2 * a - 2 * c + g * t * t) / (t * 2) * -1;

            time = t;

            return true;
        }

19 View Source File : AngleJoint.cs
License : MIT License
Project Creator : Alan-FGR

internal override void SolveVelocityConstraints(ref SolverData data)
        {
            int indexA = BodyA.IslandIndex;
            int indexB = BodyB.IslandIndex;

            float p = (_bias - data.velocities[indexB].w + data.velocities[indexA].w) * _mreplacedFactor;

            data.velocities[indexA].w -= BodyA._invI * Math.Sign(p) * Math.Min(Math.Abs(p), MaxImpulse);
            data.velocities[indexB].w += BodyB._invI * Math.Sign(p) * Math.Min(Math.Abs(p), MaxImpulse);
        }

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

internal static float Clamp(float min, float max, float val)
        {
            return Math.Max(min, Math.Min(max, val));
        }

19 View Source File : ContactSolver.cs
License : MIT License
Project Creator : Alan-FGR

public bool SolveTOIPositionConstraints(int toiIndexA, int toiIndexB)
        {
            float minSeparation = 0.0f;

            for (int i = 0; i < _count; ++i)
            {
                ContactPositionConstraint pc = _positionConstraints[i];

                int indexA = pc.indexA;
                int indexB = pc.indexB;
                Vector2 localCenterA = pc.localCenterA;
                Vector2 localCenterB = pc.localCenterB;
                int pointCount = pc.pointCount;

                float mA = 0.0f;
                float iA = 0.0f;
                if (indexA == toiIndexA || indexA == toiIndexB)
                {
                    mA = pc.invMreplacedA;
                    iA = pc.invIA;
                }

                float mB = 0.0f;
                float iB = 0.0f;
                if (indexB == toiIndexA || indexB == toiIndexB)
                {
                    mB = pc.invMreplacedB;
                    iB = pc.invIB;
                }

                Vector2 cA = _positions[indexA].c;
                float aA = _positions[indexA].a;

                Vector2 cB = _positions[indexB].c;
                float aB = _positions[indexB].a;

                // Solve normal constraints
                for (int j = 0; j < pointCount; ++j)
                {
                    Transform xfA = new Transform();
                    Transform xfB = new Transform();
                    xfA.q.Set(aA);
                    xfB.q.Set(aB);
                    xfA.p = cA - MathUtils.Mul(xfA.q, localCenterA);
                    xfB.p = cB - MathUtils.Mul(xfB.q, localCenterB);

                    Vector2 normal;
                    Vector2 point;
                    float separation;

                    PositionSolverManifold.Initialize(pc, xfA, xfB, j, out normal, out point, out separation);

                    Vector2 rA = point - cA;
                    Vector2 rB = point - cB;

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

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

                    // Compute the effective mreplaced.
                    float rnA = MathUtils.Cross(rA, normal);
                    float rnB = MathUtils.Cross(rB, normal);
                    float K = mA + mB + iA * rnA * rnA + iB * rnB * rnB;

                    // Compute normal impulse
                    float impulse = K > 0.0f ? -C / K : 0.0f;

                    Vector2 P = impulse * normal;

                    cA -= mA * P;
                    aA -= iA * MathUtils.Cross(rA, P);

                    cB += mB * P;
                    aB += iB * MathUtils.Cross(rB, P);
                }

                _positions[indexA].c = cA;
                _positions[indexA].a = aA;

                _positions[indexB].c = cB;
                _positions[indexB].a = aB;
            }

            // We can't expect minSpeparation >= -b2_linearSlop because we don't
            // push the separation above -b2_linearSlop.
            return minSeparation >= -1.5f * Settings.LinearSlop;
        }

19 View Source File : RopeJoint.cs
License : MIT License
Project Creator : Alan-FGR

internal override void SolveVelocityConstraints(ref SolverData data)
        {
            Vector2 vA = data.velocities[_indexA].v;
            float wA = data.velocities[_indexA].w;
            Vector2 vB = data.velocities[_indexB].v;
            float wB = data.velocities[_indexB].w;

            // Cdot = dot(u, v + cross(w, r))
            Vector2 vpA = vA + MathUtils.Cross(wA, _rA);
            Vector2 vpB = vB + MathUtils.Cross(wB, _rB);
            float C = _length - MaxLength;
            float Cdot = Vector2.Dot(_u, vpB - vpA);

            // Predictive constraint.
            if (C < 0.0f)
            {
                Cdot += data.step.inv_dt * C;
            }

            float impulse = -_mreplaced * Cdot;
            float oldImpulse = _impulse;
            _impulse = Math.Min(0.0f, _impulse + impulse);
            impulse = _impulse - oldImpulse;

            Vector2 P = impulse * _u;
            vA -= _invMreplacedA * P;
            wA -= _invIA * MathUtils.Cross(_rA, P);
            vB += _invMreplacedB * P;
            wB += _invIB * MathUtils.Cross(_rB, P);

            data.velocities[_indexA].v = vA;
            data.velocities[_indexA].w = wA;
            data.velocities[_indexB].v = vB;
            data.velocities[_indexB].w = wB;
        }

19 View Source File : BoxShape.cs
License : The Unlicense
Project Creator : aeroson

public static ConvexShapeDescription ComputeDescription(float width, float height, float length, float collisionMargin)
        {
            ConvexShapeDescription description;
            description.EnreplacedyShapeVolume.Volume = width * height * length;

            float widthSquared = width * width;
            float heightSquared = height * height;
            float lengthSquared = length * length;
            const float inv12 = 1 / 12f;

            description.EnreplacedyShapeVolume.VolumeDistribution = new Matrix3x3();
            description.EnreplacedyShapeVolume.VolumeDistribution.M11 = (heightSquared + lengthSquared) * inv12;
            description.EnreplacedyShapeVolume.VolumeDistribution.M22 = (widthSquared + lengthSquared) * inv12;
            description.EnreplacedyShapeVolume.VolumeDistribution.M33 = (widthSquared + heightSquared) * inv12;

            description.MaximumRadius = 0.5f * (float)Math.Sqrt(width * width + height * height + length * length);
            description.MinimumRadius = 0.5f * Math.Min(width, Math.Min(height, length));

            description.CollisionMargin = collisionMargin;
            return description;
        }

19 View Source File : GvrProfile.cs
License : MIT License
Project Creator : alanplotko

public void GetLeftEyeNoLensTanAngles(float[] result) {
    // Tan-angles from the max FOV.
    float fovLeft = viewer.distortion.distortInv(Mathf.Tan(-viewer.maxFOV.outer * Mathf.Deg2Rad));
    float fovTop = viewer.distortion.distortInv(Mathf.Tan(viewer.maxFOV.upper * Mathf.Deg2Rad));
    float fovRight = viewer.distortion.distortInv(Mathf.Tan(viewer.maxFOV.inner * Mathf.Deg2Rad));
    float fovBottom = viewer.distortion.distortInv(Mathf.Tan(-viewer.maxFOV.lower * Mathf.Deg2Rad));
    // Viewport size.
    float halfWidth = screen.width / 4;
    float halfHeight = screen.height / 2;
    // Viewport center, measured from left lens position.
    float centerX = viewer.lenses.separation / 2 - halfWidth;
    float centerY = -VerticalLensOffset;
    float centerZ = viewer.lenses.screenDistance;
    // Tan-angles of the viewport edges, as seen through the lens.
    float screenLeft = (centerX - halfWidth) / centerZ;
    float screenTop = (centerY + halfHeight) / centerZ;
    float screenRight = (centerX + halfWidth) / centerZ;
    float screenBottom = (centerY - halfHeight) / centerZ;
    // Compare the two sets of tan-angles and take the value closer to zero on each side.
    result[0] = Math.Max(fovLeft, screenLeft);
    result[1] = Math.Min(fovTop, screenTop);
    result[2] = Math.Min(fovRight, screenRight);
    result[3] = Math.Max(fovBottom, screenBottom);
  }

19 View Source File : MinikinFont.h.cs
License : MIT License
Project Creator : adamped

public void join(MinikinRect r)
        {
            if (isEmpty())
            {
                set(r);
            }
            else if (!r.isEmpty())
            {
                mLeft = Math.Min(mLeft, r.mLeft);
                mTop = Math.Min(mTop, r.mTop);
                mRight = Math.Max(mRight, r.mRight);
                mBottom = Math.Max(mBottom, r.mBottom);
            }
        }

19 View Source File : TextureSideWallModifier.cs
License : MIT License
Project Creator : alen-smajic

private void CreateWall(MeshData md)
		{
			//need to keep track of this for triangulation indices
			triIndex = md.Vertices.Count;

			//this part minimizes stretching for narrow columns
			//if texture has 3 columns, 33% (of preferred edge length) wide walls will get 1 window.
			//0-33% gets 1 window, 33-66 gets 2, 66-100 gets all three
			//we're not wrapping/repeating texture as it won't work with atlases
			columnScaleRatio = Math.Min(1, wallSegmentLength / _scaledPreferredWallLength);
			rightOfEdgeUv =
				_currentTextureRect.xMin +
				_currentTextureRect.size.x *
				columnScaleRatio; // Math.Min(1, ((float)(Math.Floor(columnScaleRatio * _currentFacade.ColumnCount) + 1) / _currentFacade.ColumnCount));

			_minWallLength = (_scaledPreferredWallLength / _currentFacade.ColumnCount) * _wallSizeEpsilon;
			//common for all top/mid/bottom segments
			wallNormal = new Vector3(-(wallSegmentFirstVertex.z - wallSegmentSecondVertex.z), 0,
				(wallSegmentFirstVertex.x - wallSegmentSecondVertex.x)).normalized;
			//height of the left/right edges
			currentY1 = wallSegmentFirstVertex.y;
			currentY2 = wallSegmentSecondVertex.y;

			//moving leftover row to top
			LeftOverRow(md, finalLeftOverRowHeight);

			FirstFloor(md, height);
			TopFloor(md, finalLeftOverRowHeight);
			MidFloors(md);
		}

19 View Source File : CylinderShape.cs
License : The Unlicense
Project Creator : aeroson

public static ConvexShapeDescription ComputeDescription(float height, float radius, float collisionMargin)
        {
            ConvexShapeDescription description;
            description.EnreplacedyShapeVolume.Volume = MathHelper.Pi * radius * radius * height;

            description.EnreplacedyShapeVolume.VolumeDistribution = new Matrix3x3();
            float diagValue = (.0833333333f * height * height + .25f * radius * radius);
            description.EnreplacedyShapeVolume.VolumeDistribution.M11 = diagValue;
            description.EnreplacedyShapeVolume.VolumeDistribution.M22 = .5f * radius * radius;
            description.EnreplacedyShapeVolume.VolumeDistribution.M33 = diagValue;

            float halfHeight = height * 0.5f;
            description.MinimumRadius = Math.Min(radius, halfHeight);
            description.MaximumRadius = (float)Math.Sqrt(radius * radius + halfHeight * halfHeight);
            description.CollisionMargin = collisionMargin;
            return description;
        }

19 View Source File : Diagram.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

private void TrySelectElements()
		{
			selectionFrame = RectangleF.FromLTRB(
				Math.Min(selectionFrame.Left, selectionFrame.Right),
				Math.Min(selectionFrame.Top, selectionFrame.Bottom),
				Math.Max(selectionFrame.Left, selectionFrame.Right),
				Math.Max(selectionFrame.Top, selectionFrame.Bottom));
			selectioning = true;

			foreach (Shape shape in shapes)
			{
				if (shape.TrySelect(selectionFrame))
					selectedShapeCount++;
			}
			foreach (Connection connection in connections)
			{
				if (connection.TrySelect(selectionFrame))
					selectedConnectionCount++;
			}

			OnSelectionChanged(EventArgs.Empty);
			OnClipboardAvailabilityChanged(EventArgs.Empty);
			OnSatusChanged(EventArgs.Empty);
			Redraw();

			selectioning = false;
		}

19 View Source File : Trajectory.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static bool solve_ballistic_arc_lateral(Vector3 proj_pos, float lateral_speed, Vector3 target, Vector3 target_velocity, float gravity, out Vector3 fire_velocity, out float time, out Vector3 impact_point)
        {
            // Handling these cases is up to your project's coding standards
            //Debug.replacedert(proj_pos != target && lateral_speed > 0, "fts.solve_ballistic_arc_lateral called with invalid data");

            // Initialize output variables
            fire_velocity = Vector3.Zero;
            time = 0.0f;
            impact_point = Vector3.Zero;

            if (proj_pos == target || lateral_speed <= 0)
                return false;

            // Ground plane terms
            Vector3 targetVelXY = new Vector3(target_velocity.X, target_velocity.Y, 0f);
            Vector3 diffXY = target - proj_pos;
            diffXY.Z = 0;

            // Derivation
            //   (1) Base formula: |P + V*t| = S*t
            //   (2) Subsreplacedute variables: |diffXY + targetVelXY*t| = S*t
            //   (3) Square both sides: Dot(diffXY,diffXY) + 2*Dot(diffXY, targetVelXY)*t + Dot(targetVelXY, targetVelXY)*t^2 = S^2 * t^2
            //   (4) Quadratic: (Dot(targetVelXY,targetVelXY) - S^2)t^2 + (2*Dot(diffXY, targetVelXY))*t + Dot(diffXY, diffXY) = 0
            float c0 = Vector3.Dot(targetVelXY, targetVelXY) - lateral_speed * lateral_speed;
            float c1 = 2f * Vector3.Dot(diffXY, targetVelXY);
            float c2 = Vector3.Dot(diffXY, diffXY);
            double t0, t1;
            int n = SolveQuadric(c0, c1, c2, out t0, out t1);

            // pick smallest, positive time
            bool valid0 = n > 0 && t0 > 0;
            bool valid1 = n > 1 && t1 > 0;

            float t;
            if (!valid0 && !valid1)
                return false;
            else if (valid0 && valid1)
                t = Math.Min((float)t0, (float)t1);
            else
                t = valid0 ? (float)t0 : (float)t1;

            // Calculate impact point
            impact_point = target + (target_velocity * t);

            // Calculate fire velocity along XZ plane
            Vector3 dir = impact_point - proj_pos;
            fire_velocity = Vector3.Normalize(new Vector3(dir.X, dir.Y, 0f)) * lateral_speed;

            // Solve system of equations. Hit max_height at t=.5*time. Hit target at t=time.
            //
            // peak = z0 + vertical_speed*halfTime + .5*gravity*halfTime^2
            // end = z0 + vertical_speed*time + .5*gravity*time^s
            // Wolfram Alpha: solve b = a + .5*v*t + .5*g*(.5*t)^2, c = a + vt + .5*g*t^2 for g, v
            float a = proj_pos.Z;       // initial
            //float b = Math.Max(proj_pos.Z, impact_point.Z) + max_height_offset;  // peak
            float c = impact_point.Z;   // final

            //gravity = -4 * (a - 2 * b + c) / (t * t);
            //fire_velocity.Z = -(3 * a - 4 * b + c) / t;

            var g = gravity;
            var b = (4 * a + 4 * c - g * t * t) / 8;

            fire_velocity.Z = (2 * a - 2 * c + g * t * t) / (t * 2) * -1;

            time = t;

            return true;
        }

19 View Source File : Canvas.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

public void AutoZoom(bool selectedOnly)
		{
			if (HasDoreplacedent && !Doreplacedent.IsEmpty)
			{
				const int Margin = Shape.SelectionMargin;
				selectedOnly &= Doreplacedent.HreplacedelectedElement;

				Rectangle visibleRectangle = this.ClientRectangle;
				RectangleF diagramRectangle = doreplacedent.GetPrintingArea(selectedOnly);
				visibleRectangle.Inflate(-Margin, -Margin);

				float scaleX = visibleRectangle.Width / diagramRectangle.Width;
				float scaleY = visibleRectangle.Height / diagramRectangle.Height;
				float scale = Math.Min(scaleX, scaleY);

				Doreplacedent.Zoom = scale;

				float offsetX = (visibleRectangle.Width - diagramRectangle.Width * Zoom) / 2;
				float offsetY = (visibleRectangle.Height - diagramRectangle.Height * Zoom) / 2;
				Offset = new Point(
					(int) (diagramRectangle.X * Zoom - Margin - offsetX),
					(int) (diagramRectangle.Y * Zoom - Margin - offsetY)
				);
			}
		}

19 View Source File : WheelShape.cs
License : The Unlicense
Project Creator : aeroson

internal void UpdateSpin(float dt)
        {
            if (wheel.Hreplacedupport && !(wheel.brake.IsBraking && FreezeWheelsWhileBraking))
            {
                //On the ground, not braking.
                spinVelocity = wheel.drivingMotor.RelativeVelocity / Radius;
            }
            else if (wheel.Hreplacedupport && wheel.brake.IsBraking && FreezeWheelsWhileBraking)
            {
                //On the ground, braking
                float deceleratedValue = 0;
                if (spinVelocity > 0)
                    deceleratedValue = Math.Max(spinVelocity - brakeFreezeWheelDeceleration * dt, 0);
                else if (spinVelocity < 0)
                    deceleratedValue = Math.Min(spinVelocity + brakeFreezeWheelDeceleration * dt, 0);

                spinVelocity = wheel.drivingMotor.RelativeVelocity / Radius;

                if (Math.Abs(deceleratedValue) < Math.Abs(spinVelocity))
                    spinVelocity = deceleratedValue;
            }
            else if (!wheel.Hreplacedupport && wheel.drivingMotor.TargetSpeed != 0)
            {
                //Airborne and accelerating, increase spin velocity.
                float maxSpeed = Math.Abs(wheel.drivingMotor.TargetSpeed) / Radius;
                spinVelocity = MathHelper.Clamp(spinVelocity + Math.Sign(wheel.drivingMotor.TargetSpeed) * airborneWheelAcceleration * dt, -maxSpeed, maxSpeed);
            }
            else if (!wheel.Hreplacedupport && wheel.Brake.IsBraking)
            {
                //Airborne and braking
                if (spinVelocity > 0)
                    spinVelocity = Math.Max(spinVelocity - brakeFreezeWheelDeceleration * dt, 0);
                else if (spinVelocity < 0)
                    spinVelocity = Math.Min(spinVelocity + brakeFreezeWheelDeceleration * dt, 0);
            }
            else if (!wheel.Hreplacedupport)
            {
                //Just idly slowing down.
                if (spinVelocity > 0)
                    spinVelocity = Math.Max(spinVelocity - airborneWheelDeceleration * dt, 0);
                else if (spinVelocity < 0)
                    spinVelocity = Math.Min(spinVelocity + airborneWheelDeceleration * dt, 0);
            }
            spinAngle += spinVelocity * dt;
        }

19 View Source File : NodeIcon.cs
License : MIT License
Project Creator : AlexGyver

public override void Draw(TreeNodeAdv node, DrawContext context)
		{
			Image image = GetIcon(node);
			if (image != null)
			{
				Rectangle r = GetBounds(node, context);
				if ( image.Width > 0 && image.Height > 0 )
				{
					switch (_scaleMode)
					{
						case ImageScaleMode.Fit:
							context.Graphics.DrawImage(image, r);
							break;
						case ImageScaleMode.ScaleDown:
							{
								float factor = Math.Min((float)r.Width / (float)image.Width, (float)r.Height / (float)image.Height);
								if (factor < 1)
									context.Graphics.DrawImage(image, r.X, r.Y, image.Width * factor, image.Height * factor);
								else
									context.Graphics.DrawImage(image, r.X, r.Y, image.Width, image.Height);
							} break;
						case ImageScaleMode.ScaleUp:
							{
								float factor = Math.Max((float)r.Width / (float)image.Width, (float)r.Height / (float)image.Height);
								if (factor > 1)
									context.Graphics.DrawImage(image, r.X, r.Y, image.Width * factor, image.Height * factor);
								else
									context.Graphics.DrawImage(image, r.X, r.Y, image.Width, image.Height);
							} break;
						case ImageScaleMode.AlwaysScale:
							{
								float fx = (float)r.Width / (float)image.Width;
								float fy = (float)r.Height / (float)image.Height;
								if (Math.Min(fx, fy) < 1)
								{ //scale down
									float factor = Math.Min(fx, fy);
									context.Graphics.DrawImage(image, r.X, r.Y, image.Width * factor, image.Height * factor);
								}
								else if (Math.Max(fx, fy) > 1)
								{
									float factor = Math.Max(fx, fy);
									context.Graphics.DrawImage(image, r.X, r.Y, image.Width * factor, image.Height * factor);
								}
								else
									context.Graphics.DrawImage(image, r.X, r.Y, image.Width, image.Height);
							} break;
						case ImageScaleMode.Clip:
						default: 
							context.Graphics.DrawImage(image, r.X, r.Y, image.Width, image.Height);
							break;
					}
				}

			}
		}

19 View Source File : Visuals.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static void Display_RenderedWorld(object sender, RenderedWorldEventArgs e)
        {

            if (api.IsCallingNPC())
                return;

            Vector2 screenPos = api.GetScreenPosition();
            Vector2 screenSize = api.GetScreenSize();
            if (!api.GetPhoneOpened() || !api.GetAppRunning() || api.GetRunningApp() != Helper.ModRegistry.ModID)
            {
                Monitor.Log($"Closing app: phone opened {api.GetPhoneOpened()} app running {api.GetAppRunning()} running app {api.GetRunningApp()}");
                CataloguesApp.CloseApp();
                return;
            }

            if (!clicking)
                dragging = false;

            Point mousePos = Game1.getMousePosition();
            if (clicking)
            {
                if (mousePos.Y != lastMousePosition.Y && (dragging || api.GetScreenRectangle().Contains(mousePos)))
                {
                    dragging = true;
                    offsetY += mousePos.Y - lastMousePosition.Y;
                    //Monitor.Log($"offsetY {offsetY} max {screenSize.Y - Config.MarginY + (Config.MarginY + Game1.dialogueFont.LineSpacing * 0.9f) * audio.Length}");
                    offsetY = Math.Min(0, Math.Max(offsetY, (int)(screenSize.Y - (Config.AppHeaderHeight + Config.MarginY + (Config.MarginY + Config.AppRowHeight) * CataloguesApp.catalogueList.Count))));
                    lastMousePosition = mousePos;
                }
            }

            if (clicking && !Helper.Input.IsSuppressed(SButton.MouseLeft))
            {
                Monitor.Log($"unclicking; dragging = {dragging}");
                if (dragging)
                    dragging = false;
                else if (api.GetScreenRectangle().Contains(mousePos) && !new Rectangle((int)screenPos.X, (int)screenPos.Y, (int)screenSize.X, Config.AppHeaderHeight).Contains(mousePos))
                {
                    CataloguesApp.ClickRow(mousePos);
                }
                clicking = false;
            }


            e.SpriteBatch.Draw(backgroundTexture, new Rectangle((int)screenPos.X, (int)screenPos.Y, (int)screenSize.X, (int)screenSize.Y), Color.White);
            for (int i = 0; i < CataloguesApp.catalogueList.Count; i++)
            {
                string a = Helper.Translation.Get(CataloguesApp.catalogueList[i]);
                float posY = screenPos.Y + Config.AppHeaderHeight + Config.MarginY * (i + 1) + i * Config.AppRowHeight + offsetY;
                Rectangle r = new Rectangle((int)screenPos.X, (int)posY, (int)screenSize.X, Config.AppRowHeight);
                bool bought = !Config.RequireCataloguePurchase || Game1.player.mailReceived.Contains($"BoughtCatalogue{a}");
                if (!bought)
                {
                    float backPosY = posY;
                    int cutTop = 0;
                    int cutBottom = 0;

                    if (posY < screenPos.Y + Config.AppHeaderHeight)
                    {
                        cutTop = (int)(screenPos.Y - posY);
                        backPosY = screenPos.Y;
                    }
                    if (posY > screenPos.Y + screenSize.Y - Config.AppRowHeight)
                        cutBottom = (int)(posY - screenPos.Y + screenSize.Y - Config.AppRowHeight);
                    r = new Rectangle((int)screenPos.X, (int)backPosY, (int)screenSize.X, (int)(Config.AppRowHeight) - cutTop - cutBottom);
                    if (!r.Contains(mousePos))
                        e.SpriteBatch.Draw(greyedTexture, r, Color.White);
                }

                if(r.Contains(mousePos))
                    e.SpriteBatch.Draw(hightlightTexture, r, Color.White);

                float textHeight = Game1.dialogueFont.MeasureString(a).Y * Config.TextScale;
                if (posY > screenPos.Y && posY < screenPos.Y + screenSize.Y - Config.AppRowHeight / 2f + textHeight / 2f)
                {
                    e.SpriteBatch.DrawString(Game1.dialogueFont, a, new Vector2(screenPos.X + Config.MarginX, posY + Config.AppRowHeight / 2f - textHeight / 2f), Config.TextColor, 0f, Vector2.Zero, Config.TextScale, SpriteEffects.None, 0.86f);
                    if (!bought)
                    {
                        string cost = ""+CataloguesApp.GetCataloguePrice(CataloguesApp.catalogueList[i]);
                        Vector2 buySize = Game1.dialogueFont.MeasureString(cost) * Config.TextScale;
                        e.SpriteBatch.DrawString(Game1.dialogueFont, cost, new Vector2(screenPos.X + screenSize.X - buySize.X - Config.AppRowHeight * 3 / 4, posY + Config.AppRowHeight / 2f - buySize.Y / 2f), Config.TextColor, 0f, Vector2.Zero, Config.TextScale, SpriteEffects.None, 0.86f);
                        e.SpriteBatch.Draw(coinTexture, new Rectangle((int)(screenPos.X + screenSize.X - Config.AppRowHeight * 3 / 4f), (int)(posY + Config.AppRowHeight / 4f), (int)(Config.AppRowHeight / 2f), (int)(Config.AppRowHeight / 2f)), Color.White);
                    }
                }
            }
            e.SpriteBatch.Draw(headerTexture, new Rectangle((int)screenPos.X, (int)screenPos.Y, (int)screenSize.X, Config.AppHeaderHeight), Color.White);
            float headerTextHeight = Game1.dialogueFont.MeasureString(Helper.Translation.Get("catalogues")).Y * Config.HeaderTextScale;
            Vector2 xSize = Game1.dialogueFont.MeasureString("x") * Config.HeaderTextScale;
            e.SpriteBatch.DrawString(Game1.dialogueFont, Helper.Translation.Get("catalogues"), new Vector2(screenPos.X + Config.MarginX, screenPos.Y + Config.AppHeaderHeight / 2f - headerTextHeight / 2f), Config.HeaderTextColor, 0f, Vector2.Zero, Config.HeaderTextScale, SpriteEffects.None, 0.86f);
            e.SpriteBatch.DrawString(Game1.dialogueFont, "x", new Vector2(screenPos.X + screenSize.X - Config.AppHeaderHeight / 2f - xSize.X / 2f, screenPos.Y + Config.AppHeaderHeight / 2f - xSize.Y / 2f), Config.HeaderTextColor, 0f, Vector2.Zero, Config.HeaderTextScale, SpriteEffects.None, 0.86f);
        }

19 View Source File : MagicMirrorEditor.cs
License : Apache License 2.0
Project Creator : allenai

public override void OnInspectorGUI() {
            if (logo == null) {
                string[] guids = replacedetDatabase.Findreplacedets("MagicMirrorLogo");
                foreach (string guid in guids) {
                    string path = replacedetDatabase.GUIDToreplacedetPath(guid);
                    logo = replacedetDatabase.LoadMainreplacedetAtPath(path) as Texture2D;
                    if (logo != null) {
                        break;
                    }
                }
            }
            if (logo != null) {
                const float maxLogoWidth = 450.0f;
                EditorGUILayout.Separator();
                float w = EditorGUIUtility.currentViewWidth;
                Rect r = new Rect();
                r.width = Math.Min(w - 40.0f, maxLogoWidth);
                r.height = r.width / 2.7f;
                Rect r2 = GUILayoutUtility.GetRect(r.width, r.height);
                r.x = ((EditorGUIUtility.currentViewWidth - r.width) * 0.5f) - 4.0f;
                r.y = r2.y;
                GUI.DrawTexture(r, logo, ScaleMode.StretchToFill);
                if (GUI.Button(r, "", new GUIStyle())) {
                    Application.OpenURL("https://www.replacedetstore.unity3d.com/en/#!/content/103687?aid=1011lGnL");
                }
                EditorGUILayout.Separator();
            }

            DrawDefaultInspector();
        }

19 View Source File : Vector2.cs
License : MIT License
Project Creator : aillieo

public static Vector2 Min(Vector2 lhs, Vector2 rhs)
        {
            return new Vector2(Math.Min(lhs.x, rhs.x), Math.Min(lhs.y, rhs.y));
        }

19 View Source File : MathFunctions.cs
License : MIT License
Project Creator : altimesh

public static float clamp(float n, float m, float M)
        {
            return Math.Max(m, Math.Min(n, M));
        }

19 View Source File : Rand.cs
License : MIT License
Project Creator : ABTSoftware

public float NextWalk()
        {
            // Random walk
            _current += (float)((InstanceRandom.NextDouble() - 0.5) * 0.002);

            // Clamp to 0..1
            _current = Math.Max(Math.Min(_current, 1.0f), 0.0f);
            return _current;
        }

19 View Source File : BoundingBox.cs
License : MIT License
Project Creator : amerkoleci

public float? Intersects(in Ray ray)
        {
            //Source: Real-Time Collision Detection by Christer Ericson
            //Reference: Page 179

            float distance = 0.0f;
            float tmax = float.MaxValue;

            if (MathHelper.IsZero(ray.Direction.X))
            {
                if (ray.Position.X < Minimum.X || ray.Position.X > Maximum.X)
                {
                    return null;
                }
            }
            else
            {
                float inverse = 1.0f / ray.Direction.X;
                float t1 = (Minimum.X - ray.Position.X) * inverse;
                float t2 = (Maximum.X - ray.Position.X) * inverse;

                if (t1 > t2)
                {
                    float temp = t1;
                    t1 = t2;
                    t2 = temp;
                }

                distance = Math.Max(t1, distance);
                tmax = Math.Min(t2, tmax);

                if (distance > tmax)
                {
                    return null;
                }
            }

            if (MathHelper.IsZero(ray.Direction.Y))
            {
                if (ray.Position.Y < Minimum.Y || ray.Position.Y > Maximum.Y)
                {
                    return null;
                }
            }
            else
            {
                float inverse = 1.0f / ray.Direction.Y;
                float t1 = (Minimum.Y - ray.Position.Y) * inverse;
                float t2 = (Maximum.Y - ray.Position.Y) * inverse;

                if (t1 > t2)
                {
                    float temp = t1;
                    t1 = t2;
                    t2 = temp;
                }

                distance = Math.Max(t1, distance);
                tmax = Math.Min(t2, tmax);

                if (distance > tmax)
                {
                    return null;
                }
            }

            if (MathHelper.IsZero(ray.Direction.Z))
            {
                if (ray.Position.Z < Minimum.Z || ray.Position.Z > Maximum.Z)
                {
                    return null;
                }
            }
            else
            {
                float inverse = 1.0f / ray.Direction.Z;
                float t1 = (Minimum.Z - ray.Position.Z) * inverse;
                float t2 = (Maximum.Z - ray.Position.Z) * inverse;

                if (t1 > t2)
                {
                    float temp = t1;
                    t1 = t2;
                    t2 = temp;
                }

                distance = Math.Max(t1, distance);
                tmax = Math.Min(t2, tmax);

                if (distance > tmax)
                {
                    return null;
                }
            }

            return distance;
        }

19 View Source File : LineTools.cs
License : MIT License
Project Creator : Alan-FGR

public static bool LineIntersect2(ref Vector2 a0, ref Vector2 a1, ref Vector2 b0, ref  Vector2 b1, out Vector2 intersectionPoint)
        {
            intersectionPoint = Vector2.Zero;

            if (a0 == b0 || a0 == b1 || a1 == b0 || a1 == b1)
                return false;

            float x1 = a0.X;
            float y1 = a0.Y;
            float x2 = a1.X;
            float y2 = a1.Y;
            float x3 = b0.X;
            float y3 = b0.Y;
            float x4 = b1.X;
            float y4 = b1.Y;

            //AABB early exit
            if (Math.Max(x1, x2) < Math.Min(x3, x4) || Math.Max(x3, x4) < Math.Min(x1, x2))
                return false;

            if (Math.Max(y1, y2) < Math.Min(y3, y4) || Math.Max(y3, y4) < Math.Min(y1, y2))
                return false;

            float ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3));
            float ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3));
            float denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
            if (Math.Abs(denom) < Settings.Epsilon)
            {
                //Lines are too close to parallel to call
                return false;
            }
            ua /= denom;
            ub /= denom;

            if ((0 < ua) && (ua < 1) && (0 < ub) && (ub < 1))
            {
                intersectionPoint.X = (x1 + ua * (x2 - x1));
                intersectionPoint.Y = (y1 + ua * (y2 - y1));
                return true;
            }

            return false;
        }

19 View Source File : ButterflyFamiliar.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public override void behaviorAtGameTick(GameTime time)
        {
            invincibleCountdown = 1000;
            if (timeBeforeAIMovementAgain > 0f)
            {
                timeBeforeAIMovementAgain -= time.ElapsedGameTime.Milliseconds;
            }
            if (lastBuff >= 0)
            {
                lastBuff.Value -= time.ElapsedGameTime.Milliseconds;
            }

            if (wareplacedCounter >= 0)
            {
                wareplacedCounter.Value -= time.ElapsedGameTime.Milliseconds;
            }

            if (followingOwner)
            {

                Vector2 center = Position + new Vector2(8, 8);
                Vector2 playerCenter = GetOwner().position + new Vector2(64, 92);
                if (Vector2.Distance(playerCenter, center) > 256)
                {
                    Position = Vector2.Distance(playerCenter, center) * 0.03f * Vector2.Normalize(playerCenter - center) + center - new Vector2(8,8);

                }

                float xSlope = (float)(-(float)(playerCenter.X - center.X));
                float ySlope = (float)(playerCenter.Y - center.Y);
                float t = Math.Max(1f, Math.Abs(xSlope) + Math.Abs(ySlope));
                if (t < (float)((extraVelocity > 0f) ? 192 : 64))
                {
                    xVelocity = Math.Max(-maxSpeed, Math.Min(maxSpeed, xVelocity * 1.05f));
                    yVelocity = Math.Max(-maxSpeed, Math.Min(maxSpeed, yVelocity * 1.05f));
                }
                xSlope /= t;
                ySlope /= t;
                if (wareplacedCounter <= 0)
                {
                    targetRotation = (float)Math.Atan2((double)(-(double)ySlope), (double)xSlope) - 1.57079637f;
                    if ((double)(Math.Abs(targetRotation) - Math.Abs(rotation)) > 2.748893571891069 && Game1.random.NextDouble() < 0.5)
                    {
                        turningRight.Value = true;
                    }
                    else if ((double)(Math.Abs(targetRotation) - Math.Abs(rotation)) < 0.39269908169872414)
                    {
                        turningRight.Value = false;
                    }
                    if (turningRight)
                    {
                        rotation -= (float)Math.Sign(targetRotation - rotation) * 0.0490873866f;
                    }
                    else
                    {
                        rotation += (float)Math.Sign(targetRotation - rotation) * 0.0490873866f;
                    }
                    rotation %= 6.28318548f;
                    wareplacedCounter.Value = 0;
                }
                float maxAccel = Math.Min(5f, Math.Max(1f, 5f - t / 64f / 2f)) + extraVelocity;
                xSlope = (float)Math.Cos((double)rotation + 1.5707963267948966);
                ySlope = -(float)Math.Sin((double)rotation + 1.5707963267948966);
                xVelocity += -xSlope * maxAccel / 6f + (float)Game1.random.Next(-10, 10) / 100f;
                yVelocity += -ySlope * maxAccel / 6f + (float)Game1.random.Next(-10, 10) / 100f;
                if (Math.Abs(xVelocity) > Math.Abs(-xSlope * maxSpeed))
                {
                    xVelocity -= -xSlope * maxAccel / 6f;
                }
                if (Math.Abs(yVelocity) > Math.Abs(-ySlope * maxSpeed))
                {
                    yVelocity -= -ySlope * maxAccel / 6f;
                }
                if (lastBuff <= 0 && Vector2.Distance(GetOwner().getTileLocation(), getTileLocation()) < 3)
                {
                    if (Game1.random.NextDouble() < BuffChance())
                    {
                        if (ModEntry.Config.ButterflySoundEffects)
                            Game1.playSound("yoba");
                        BuffsDisplay buffsDisplay = Game1.buffsDisplay;
                        Buff buff2 = GetBuff();
                        buffsDisplay.addOtherBuff(buff2);
                        AddExp(1);
                        lastBuff.Value = GetBuffInterval();
                    }
                    else
                        lastBuff.Value = 1000;
                }
            }
        }

19 View Source File : InscribedRectangle.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private bool TryFixMaximumRectangle(
            Edge[] geometryEdges,
            Vector2 centerPoint,
            float angleRadians,
            float minArea,
            out float width,
            out float height)
        {
            width = 0.0f;
            height = 0.0f;

            Vector2 topCollisionPoint;
            Vector2 bottomCollisionPoint;
            Vector2 leftCollisionPoint;
            Vector2 rightCollisionPoint;

            // Find the collision points with the geometry
            if (!FindSurroundingCollisionPoints(geometryEdges, centerPoint, angleRadians,
                out topCollisionPoint, out bottomCollisionPoint, out leftCollisionPoint, out rightCollisionPoint))
            {
                return false;
            }

            // Start by calculating max width and height by ray-casting a cross from the point at the given angle
            // and taking the shortest leg of each ray. Width is the longest.
            float verticalMinDistanceToEdge = Mathf.Min(
                Vector2.Distance(centerPoint, topCollisionPoint),
                Vector2.Distance(centerPoint, bottomCollisionPoint));

            float horizontalMinDistanceToEdge = Mathf.Min(
                Vector2.Distance(centerPoint, leftCollisionPoint),
                Vector2.Distance(centerPoint, rightCollisionPoint));

            // Width is the largest of the possible dimensions
            float maxWidth = Math.Max(verticalMinDistanceToEdge, horizontalMinDistanceToEdge) * 2.0f;
            float maxHeight = Math.Min(verticalMinDistanceToEdge, horizontalMinDistanceToEdge) * 2.0f;

            float aspectRatio = 0.0f;

            // For each aspect ratio we do a binary search to find the maximum rectangle that fits, 
            // though once we start increasing our area by minimumHeightGain we call it good enough.
            for (int i = 0; i < aspectRatios.Length; i++)
            {
                // The height is limited by the width. If a height would make our width exceed maxWidth, it can't be used
                float searchHeightUpperBound = Mathf.Max(maxHeight, maxWidth / aspectRatios[i]);

                // Set to the min height that will out perform our previous area at the given aspect ratio. This is 0 the first time.
                // Derived from biggestAreaSoFar=height*(height*aspectRatio)
                float searchHeightLowerBound = Mathf.Sqrt(Mathf.Max((width * height), minArea) / aspectRatios[i]);

                // If the lowest value needed to outperform the previous best is greater than our max, 
                // this aspect ratio can't outperform what we've already calculated.
                if ((searchHeightLowerBound > searchHeightUpperBound) || 
                    (searchHeightLowerBound * aspectRatios[i] > maxWidth))
                {
                    continue;
                }

                float currentTestingHeight = Mathf.Max(searchHeightLowerBound, maxHeight * 0.5f);


                // Perform the binary search until continuing to search will not give us a significant win.
                do
                {
                    if (CheckRectangleFit(geometryEdges, 
                        centerPoint, 
                        angleRadians, 
                        aspectRatios[i] * currentTestingHeight, 
                        currentTestingHeight))
                    {
                        // Binary search up-ward
                        // If the rectangle will fit, increase the lower bounds of our binary search
                        searchHeightLowerBound = currentTestingHeight;

                        width = currentTestingHeight * aspectRatios[i];
                        height = currentTestingHeight;
                        aspectRatio = aspectRatios[i];
                        currentTestingHeight = (searchHeightUpperBound + currentTestingHeight) * 0.5f;
                    }
                    else
                    {
                        // If the rectangle won't fit, update our upper bound and lower our binary search
                        searchHeightUpperBound = currentTestingHeight;
                        currentTestingHeight = (currentTestingHeight + searchHeightLowerBound) * 0.5f;
                    }
                }
                while ((searchHeightUpperBound - searchHeightLowerBound) > minimumHeightGain);
            }

            return (aspectRatio > 0.0f);
        }

19 View Source File : AllegianceManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static void DoPreplacedXP(AllegianceNode vreplacedalNode, ulong amount, bool direct)
        {
            // http://asheron.wikia.com/wiki/Allegiance_Experience

            // Pre-patch:
            // Vreplacedal-to-patron preplaced-up has no effective cap, but patron-to-grandpatron preplaced-up caps with an effective Loyalty of 175.
            // If you're sworn for 10 days to the same patron, the base Loyalty required to maximize the preplaced-up from your vreplacedal through you to your patron is only 88.
            // Take into account level 7 enchantments, and you can see how there's practically no need to spend XP on the skill, due to the ease in reaching the cap.
            // Leadership is arguably worse off. In theory, you need to train Leadership and spend XP on it in order to get maximum results.
            // However, effective Leadership is multiplied by two factors: how many vreplacedals you have, and how long they have been sworn to you, with the emphasis on the number of vreplacedals you have.
            // The effect of Leadership on preplaced-up caps at around 165 effective Leadership, or 83 base Leadership before the modifier.
            // The end result of this is that if you have two active vreplacedals and you can get 10 mules sworn underneath you for an average of 5 in-game days,
            // you never need to raise your Leadership beyond 83. Again, take into account level 7 enchantments and you can see why few people even bother training the skill. It's just too easy to reach the cap. 

            // Post-patch:
            // - Leadership and Loyalty are not based on Self attribute
            // - Effective Loyalty is still modified by the time you have spent sworn to your patron
            // - Effective Leadership is still modified by number of vreplacedals and average time that they have been sworn to you,
            //   but the emphasis is on the "time sworn" side and not on the "number of vreplacedals" side. In fact, the vreplacedals
            //   required to achieve the maximum benefit has been decreased from 12 to 4. This is to reduce the incentive of having non-playing vreplacedals.
            // - For both Loyalty and Leadership, the time sworn modifier will now be a factor of both in-game time and real time.
            // - Most importantly, Leadership and Loyalty no longer "cap"

            // XP preplaced-up:
            // - New minimums and maximums
            // - Vreplacedal-to-patron preplaced-up will have a minimum of 25% of earned XP, and a maximum of 90% of earned XP.
            //   Under the old system, the minimum was about 9% of earned XP, and the effective maximum was somewhere near 44% of earned XP.
            // - Patron-to-grandpatron preplaced-up will have a minimum of 0% of XP preplaceded-up by the patron's vreplacedal, and a maximum of 10% of preplaceded-up XP.
            //   Under the old system, the minimum was about 30% and the maximum was about 94%.

            // Original system: up to January 12, 2004
            // Follow-up: all XP instead of just kill XP: October 2009

            // Formulas:
            // http://asheron.wikia.com/wiki/XP_Preplacedup

            // Thanks for Xerxes of Thistledown, who verified accuracy over four months of testing and research!

            // Generated % - Percentage of XP preplaceded to the patron through the vreplacedal's earned XP (hunting and most quests).
            // Received % - Percentage of XP that patron will receive from his vreplacedal's Generated XP.
            // Preplacedup % -  Percentage of XP actually received by patron from vreplacedal's earned XP (hunting and most quests).

            // Generated % = 50.0 + 22.5 * (loyalty / 291) * (1.0 + (RT/730) * (IG/720))
            // Received % = 50.0 + 22.5 * (leadership / 291) * (1.0 + V * (RT2/730) * (IG2/720))
            // Preplacedup % = Generated% * Received% / 100.0

            // Where:
            // Loyalty = Buffed Loyalty (291 max)
            // Leadership = Buffed Leadership (291 max)
            // RT = actual real time sworn to patron in days (730 max)
            // IG = actual in-game time sworn to patron in hours (720 max)
            // RT2 = average real time sworn to patron for all vreplacedals in days (730 max)
            // IG2 = average in-game time sworn to patron for all vreplacedals in hours (720 max)
            // V = vreplacedal factor(1 = 0.25, 2 = 0.50, 3 = 0.75, 4 + = 1.00) (1.0 max)

            var patronNode = vreplacedalNode.Patron;
            if (patronNode == null)
                return;

            var vreplacedal = vreplacedalNode.Player;
            var patron = patronNode.Player;

            if (!vreplacedal.ExistedBeforeAllegianceXpChanges)
                return;

            var loyalty = Math.Min(vreplacedal.GetCurrentLoyalty(), SkillCap);
            var leadership = Math.Min(patron.GetCurrentLeadership(), SkillCap);

            var timeReal = Math.Min(RealCap, RealCap);
            var timeGame = Math.Min(GameCap, GameCap);

            var timeRealAvg = Math.Min(RealCap, RealCap);
            var timeGameAvg = Math.Min(GameCap, GameCap);

            var vreplacedalFactor = Math.Min(0.25f * patronNode.TotalVreplacedals, 1.0f);

            var factor1 = direct ? 50.0f : 16.0f;
            var factor2 = direct ? 22.5f : 8.0f;

            var generated = (factor1 + factor2 * (loyalty / SkillCap) * (1.0f + (timeReal / RealCap) * (timeGame / GameCap))) * 0.01f;
            var received = (factor1 + factor2 * (leadership / SkillCap) * (1.0f + vreplacedalFactor * (timeRealAvg / RealCap) * (timeGameAvg / GameCap))) * 0.01f;
            var preplacedup = generated * received;

            var generatedAmount = (uint)(amount * generated);
            var preplacedupAmount = (uint)(amount * preplacedup);

            /*Console.WriteLine("---");
            Console.WriteLine("AllegianceManager.PreplacedXP(" + amount + ")");
            Console.WriteLine("Vreplacedal: " + vreplacedal.Name);
            Console.WriteLine("Patron: " + patron.Name);

            Console.WriteLine("Generated: " + Math.Round(generated * 100, 2) + "%");
            Console.WriteLine("Received: " + Math.Round(received * 100, 2) + "%");
            Console.WriteLine("Preplacedup: " + Math.Round(preplacedup * 100, 2) + "%");

            Console.WriteLine("Generated amount: " + generatedAmount);
            Console.WriteLine("Preplacedup amount: " + preplacedupAmount);*/

            if (preplacedupAmount > 0)
            {
                //vreplacedal.CPreplacedhed += generatedAmount;
                //patron.CPCached += preplacedupAmount;
                //patron.CPPoolToUnload += preplacedupAmount;

                vreplacedal.AllegianceXPGenerated += generatedAmount;
                patron.AllegianceXPCached += preplacedupAmount;

                var onlinePatron = PlayerManager.GetOnlinePlayer(patron.Guid);
                if (onlinePatron != null)
                    onlinePatron.AddAllegianceXP();

                // call recursively
                DoPreplacedXP(patronNode, preplacedupAmount, false);
            }
        }

19 View Source File : FruchtermanReingoldLayout.cs
License : Apache License 2.0
Project Creator : activey

protected override void UpdateGraphLayout (GraphSceneComponents sceneComponents, float time)
		{
			float maxDisplace = (float) (Math.Sqrt (AREA_MULTIPLICATOR * area) / 10F);
			float k = (float) Math.Sqrt (AREA_MULTIPLICATOR * area / (1F + sceneComponents.GetNodesCount()));

			sceneComponents.AcceptNode (n1 => {
				sceneComponents.AcceptNode (n2 => {
					if (n1.GetGraphNode().GetId() != n2.GetGraphNode().GetId()) {
						float xDist = n1.GetPosition().x - n2.GetPosition().x;
						float yDist = n1.GetPosition().y - n2.GetPosition().y;
						float zDist = n1.GetPosition().z - n2.GetPosition().z;
						float dist = (float) Math.Sqrt (xDist*xDist + yDist*yDist + zDist*zDist);

						if (dist > 0) {
							float repulsiveF = k*k / dist;

							ForceVectorNodeLayoutData layoutData = GetLayoutData (n1);
							layoutData.dx = xDist / dist * repulsiveF;
							layoutData.dy = yDist / dist * repulsiveF;
							layoutData.dz = zDist / dist * repulsiveF;
						}
					}
				});
			});

			sceneComponents.AcceptEdge (e => {
				NodeComponent nf = sceneComponents.GetNodeComponent(e.GetGraphEdge().GetStartGraphNode().GetId());
				NodeComponent nt = sceneComponents.GetNodeComponent(e.GetGraphEdge().GetEndGraphNode().GetId());	

				float xDist = nf.GetPosition().x - nt.GetPosition().x;
				float yDist = nf.GetPosition().y - nt.GetPosition().y;
				float zDist = nf.GetPosition().z - nt.GetPosition().z;
				float dist = (float) Math.Sqrt (xDist*xDist + yDist*yDist + zDist*zDist);

				float attractiveF = dist * dist / k;

				if (dist > 0) {
					ForceVectorNodeLayoutData sourceLayoutData = GetLayoutData (nf);
					ForceVectorNodeLayoutData targetLayoutData = GetLayoutData (nt);

					sourceLayoutData.dx -= xDist / dist * attractiveF;
                    sourceLayoutData.dy -= yDist / dist * attractiveF;
                    sourceLayoutData.dz -= zDist / dist * attractiveF;
                    
                    targetLayoutData.dx += xDist / dist * attractiveF;
					targetLayoutData.dy += yDist / dist * attractiveF;
					targetLayoutData.dz += zDist / dist * attractiveF;
				}
			});

			sceneComponents.AcceptNode (n => {
				ForceVectorNodeLayoutData layoutData = GetLayoutData (n);
				float d = (float) Math.Sqrt(n.GetPosition().x * n.GetPosition().x + n.GetPosition().y * n.GetPosition().y + n.GetPosition().z * n.GetPosition().z);
                float gf = 0.01F * k * (float) gravity * d;
				layoutData.dx -= gf * n.GetPosition().x / d;
				layoutData.dy -= gf * n.GetPosition().y / d;
				layoutData.dz -= gf * n.GetPosition().z / d;
			});

			// speed
			sceneComponents.AcceptNode (n => {
				ForceVectorNodeLayoutData layoutData = GetLayoutData (n);
				layoutData.dx *= speed / SPEED_DIVISOR;
				layoutData.dy *= speed / SPEED_DIVISOR;
				layoutData.dz *= speed / SPEED_DIVISOR;
			});

			sceneComponents.AcceptNode (n => {
				ForceVectorNodeLayoutData layoutData = GetLayoutData (n);
				float xDist = layoutData.dx;
				float yDist = layoutData.dy;
				float zDist = layoutData.dz;
				float dist = (float) Math.Sqrt(layoutData.dx * layoutData.dx + layoutData.dy * layoutData.dy + layoutData.dz * layoutData.dz);
				if (dist > 0) {
					float limitedDist = Math.Min(maxDisplace * ((float) speed / SPEED_DIVISOR), dist);

					n.SetPosition(new UnityEngine.Vector3(
						n.GetPosition().x + xDist / dist * limitedDist,
						n.GetPosition().y + yDist / dist * limitedDist,
						n.GetPosition().z + zDist / dist * limitedDist
					));
				}
			});

			UpdateEdges ();
		}

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private static async void HereFishyFishy(Farmer who, int x, int y)
        {
            hereFishying = true;
            if (fishySound != null)
            {
                fishySound.Play();
            }
            who.completelyStopAnimatingOrDoingAction();
            who.jitterStrength = 2f;
            List<FarmerSprite.AnimationFrame> animationFrames = new List<FarmerSprite.AnimationFrame>(){
                new FarmerSprite.AnimationFrame(94, 100, false, false, null, false).AddFrameAction(delegate (Farmer f)
                {
                    f.jitterStrength = 2f;
                })
            };
            who.FarmerSprite.setCurrentAnimation(animationFrames.ToArray());
            who.FarmerSprite.PauseForSingleAnimation = true;
            who.FarmerSprite.loop = true;
            who.FarmerSprite.loopThisAnimation = true;
            who.Sprite.currentFrame = 94;

            await System.Threading.Tasks.Task.Delay(1793);

            canPerfect = true;
            perfect = false;

            who.synchronizedJump(8f);

            await System.Threading.Tasks.Task.Delay(100);

            canPerfect = false;

            await System.Threading.Tasks.Task.Delay(900);

            who.stopJittering();
            who.completelyStopAnimatingOrDoingAction();
            who.forceCanMove();

            hereFishying = false;

            await System.Threading.Tasks.Task.Delay(Game1.random.Next(500, 1000));

            Object o = who.currentLocation.getFish(0, -1, 1, who, 0, new Vector2(x, y), who.currentLocation.Name);
            if (o == null || o.ParentSheetIndex <= 0)
            {
                o = new Object(Game1.random.Next(167, 173), 1, false, -1, 0);
            }


            int parentSheetIndex = o.parentSheetIndex;
            animations.Clear();
            float t;
            lastUser = who;
            whichFish = parentSheetIndex;
            Dictionary<int, string> data = Game1.content.Load<Dictionary<int, string>>("Data\\Fish");
            string[] datas = null;
            if (data.ContainsKey(whichFish))
            {
                datas = data[whichFish].Split('/');
            }


            bool non_fishable_fish = false;
            if (o is Furniture)
            {
                non_fishable_fish = true;
            }
            else if (Utility.IsNormalObjectAtParentSheetIndex(o, o.ParentSheetIndex) && data.ContainsKey(o.ParentSheetIndex))
            {
                string[] array = data[o.ParentSheetIndex].Split(new char[]
                {
                            '/'
                });
                int difficulty = -1;
                if (!int.TryParse(array[1], out difficulty))
                {
                    non_fishable_fish = true;
                }
            }
            else
            {
                non_fishable_fish = true;
            }


            float fs = 1f;
            int minimumSizeContribution = 1 + who.FishingLevel / 2;
            fs *= (float)Game1.random.Next(minimumSizeContribution, Math.Max(6, minimumSizeContribution)) / 5f;
            fs *= 1.2f;
            fs *= 1f + (float)Game1.random.Next(-10, 11) / 100f;
            fs = Math.Max(0f, Math.Min(1f, fs));
            if(datas != null && !non_fishable_fish)
            {
                try
                {
                    int minFishSize = int.Parse(datas[3]);
                    int maxFishSize = int.Parse(datas[4]);
                    fishSize = (int)((float)minFishSize + (float)(maxFishSize - minFishSize) * fishSize);
                    fishSize++;
                    fishQuality = (((double)fishSize < 0.33) ? 0 : (((double)fishSize < 0.66) ? 1 : 2));
                    if (perfect)
                        fishQuality *= 2;
                }
                catch 
                {
                    context.Monitor.Log($"Error getting fish size from {data[whichFish]}", LogLevel.Error);
                }
            }
            bossFish = FishingRod.isFishBossFish(whichFish);
            caughtDoubleFish = !bossFish && Game1.random.NextDouble() < 0.1 + Game1.player.DailyLuck / 2.0;

            context.Monitor.Log($"pulling fish {whichFish} {fishSize} {who.Name} {x},{y}");

            if (who.IsLocalPlayer)
            {
                if (datas != null && !non_fishable_fish)
                {
                    fishDifficulty = int.Parse(datas[1]);

                }
                else
                    fishDifficulty = 0;
                
                int experience = Math.Max(1, (fishQuality + 1) * 3 + fishDifficulty / 3);
                if (bossFish)
                {
                    experience *= 5;
                }
                
                if(perfect)
                    experience += (int)((float)experience * 1.4f);
                
                who.gainExperience(1, experience);
            }

            if (who.FacingDirection == 1 || who.FacingDirection == 3)
            {
                float distance = Vector2.Distance(new Vector2(x, y), who.Position);
                float gravity = 0.001f;
                float height = 128f - (who.Position.Y - y + 10f);
                double angle = 1.1423973285781066;
                float yVelocity = (float)((double)(distance * gravity) * Math.Tan(angle) / Math.Sqrt((double)(2f * distance * gravity) * Math.Tan(angle) - (double)(2f * gravity * height)));
                if (float.IsNaN(yVelocity))
                {
                    yVelocity = 0.6f;
                }
                float xVelocity = (float)((double)yVelocity * (1.0 / Math.Tan(angle)));
                t = distance / xVelocity;
                animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x,y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
                {
                    motion = new Vector2((float)((who.FacingDirection == 3) ? -1 : 1) * -xVelocity, -yVelocity),
                    acceleration = new Vector2(0f, gravity),
                    timeBasedMotion = true,
                    endFunction = new TemporaryAnimatedSprite.endBehavior(playerCaughtFishEndFunction),
                    extraInfoForEndBehavior = parentSheetIndex,
                    endSound = "tinyWhip"
                });
                if (caughtDoubleFish)
                {
                    distance = Vector2.Distance(new Vector2(x, y), who.Position);
                    gravity = 0.0008f;
                    height = 128f - (who.Position.Y - y + 10f);
                    angle = 1.1423973285781066;
                    yVelocity = (float)((double)(distance * gravity) * Math.Tan(angle) / Math.Sqrt((double)(2f * distance * gravity) * Math.Tan(angle) - (double)(2f * gravity * height)));
                    if (float.IsNaN(yVelocity))
                    {
                        yVelocity = 0.6f;
                    }
                    xVelocity = (float)((double)yVelocity * (1.0 / Math.Tan(angle)));
                    t = distance / xVelocity;
                    animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x, y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
                    {
                        motion = new Vector2((float)((who.FacingDirection == 3) ? -1 : 1) * -xVelocity, -yVelocity),
                        acceleration = new Vector2(0f, gravity),
                        timeBasedMotion = true,
                        endSound = "fishSlap",
                        Parent = who.currentLocation
                    });
                }
            }
            else
            {
                float distance2 = y - (float)(who.getStandingY() - 64);
                float height2 = Math.Abs(distance2 + 256f + 32f);
                if (who.FacingDirection == 0)
                {
                    height2 += 96f;
                }
                float gravity2 = 0.003f;
                float velocity = (float)Math.Sqrt((double)(2f * gravity2 * height2));
                t = (float)(Math.Sqrt((double)(2f * (height2 - distance2) / gravity2)) + (double)(velocity / gravity2));
                float xVelocity2 = 0f;
                if (t != 0f)
                {
                    xVelocity2 = (who.Position.X - x) / t;
                }
                animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x, y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
                {
                    motion = new Vector2(xVelocity2, -velocity),
                    acceleration = new Vector2(0f, gravity2),
                    timeBasedMotion = true,
                    endFunction = new TemporaryAnimatedSprite.endBehavior(playerCaughtFishEndFunction),
                    extraInfoForEndBehavior = parentSheetIndex,
                    endSound = "tinyWhip"
                });
                if (caughtDoubleFish)
                {
                    distance2 = y - (float)(who.getStandingY() - 64);
                    height2 = Math.Abs(distance2 + 256f + 32f);
                    if (who.FacingDirection == 0)
                    {
                        height2 += 96f;
                    }
                    gravity2 = 0.004f;
                    velocity = (float)Math.Sqrt((double)(2f * gravity2 * height2));
                    t = (float)(Math.Sqrt((double)(2f * (height2 - distance2) / gravity2)) + (double)(velocity / gravity2));
                    xVelocity2 = 0f;
                    if (t != 0f)
                    {
                        xVelocity2 = (who.Position.X - x) / t;
                    }
                    animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x, y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
                    {
                        motion = new Vector2(xVelocity2, -velocity),
                        acceleration = new Vector2(0f, gravity2),
                        timeBasedMotion = true,
                        endSound = "fishSlap",
                        Parent = who.currentLocation
                    });
                }
            }
        }

19 View Source File : RealExplosion.cs
License : MIT License
Project Creator : Alan-FGR

public Dictionary<Fixture, Vector2> Activate(Vector2 pos, float radius, float maxForce)
        {
            AABB aabb;
            aabb.LowerBound = pos + new Vector2(-radius, -radius);
            aabb.UpperBound = pos + new Vector2(radius, radius);
            Fixture[] shapes = new Fixture[MaxShapes];

            // More than 5 shapes in an explosion could be possible, but still strange.
            Fixture[] containedShapes = new Fixture[5];
            bool exit = false;

            int shapeCount = 0;
            int containedShapeCount = 0;

            // Query the world for overlapping shapes.
            World.QueryAABB(
                fixture =>
                {
                    if (fixture.TestPoint(ref pos))
                    {
                        if (IgnoreWhenInsideShape)
                        {
                            exit = true;
                            return false;
                        }

                        containedShapes[containedShapeCount++] = fixture;
                    }
                    else
                    {
                        shapes[shapeCount++] = fixture;
                    }

                    // Continue the query.
                    return true;
                }, ref aabb);

            if (exit)
                return new Dictionary<Fixture, Vector2>();

            Dictionary<Fixture, Vector2> exploded = new Dictionary<Fixture, Vector2>(shapeCount + containedShapeCount);

            // Per shape max/min angles for now.
            float[] vals = new float[shapeCount * 2];
            int valIndex = 0;
            for (int i = 0; i < shapeCount; ++i)
            {
                PolygonShape ps;
                CircleShape cs = shapes[i].Shape as CircleShape;
                if (cs != null)
                {
                    // We create a "diamond" approximation of the circle
                    Vertices v = new Vertices();
                    Vector2 vec = Vector2.Zero + new Vector2(cs.Radius, 0);
                    v.Add(vec);
                    vec = Vector2.Zero + new Vector2(0, cs.Radius);
                    v.Add(vec);
                    vec = Vector2.Zero + new Vector2(-cs.Radius, cs.Radius);
                    v.Add(vec);
                    vec = Vector2.Zero + new Vector2(0, -cs.Radius);
                    v.Add(vec);
                    ps = new PolygonShape(v, 0);
                }
                else
                    ps = shapes[i].Shape as PolygonShape;

                if ((shapes[i].Body.BodyType == BodyType.Dynamic) && ps != null)
                {
                    Vector2 toCentroid = shapes[i].Body.GetWorldPoint(ps.MreplacedData.Centroid) - pos;
                    float angleToCentroid = (float)Math.Atan2(toCentroid.Y, toCentroid.X);
                    float min = float.MaxValue;
                    float max = float.MinValue;
                    float minAbsolute = 0.0f;
                    float maxAbsolute = 0.0f;

                    for (int j = 0; j < ps.Vertices.Count; ++j)
                    {
                        Vector2 toVertex = (shapes[i].Body.GetWorldPoint(ps.Vertices[j]) - pos);
                        float newAngle = (float)Math.Atan2(toVertex.Y, toVertex.X);
                        float diff = (newAngle - angleToCentroid);

                        diff = (diff - MathHelper.Pi) % (2 * MathHelper.Pi);
                        // the minus pi is important. It means cutoff for going other direction is at 180 deg where it needs to be

                        if (diff < 0.0f)
                            diff += 2 * MathHelper.Pi; // correction for not handling negs

                        diff -= MathHelper.Pi;

                        if (Math.Abs(diff) > MathHelper.Pi)
                            continue; // Something's wrong, point not in shape but exists angle diff > 180

                        if (diff > max)
                        {
                            max = diff;
                            maxAbsolute = newAngle;
                        }
                        if (diff < min)
                        {
                            min = diff;
                            minAbsolute = newAngle;
                        }
                    }

                    vals[valIndex] = minAbsolute;
                    ++valIndex;
                    vals[valIndex] = maxAbsolute;
                    ++valIndex;
                }
            }

            Array.Sort(vals, 0, valIndex, _rdc);
            _data.Clear();
            bool rayMissed = true;

            for (int i = 0; i < valIndex; ++i)
            {
                Fixture fixture = null;
                float midpt;

                int iplus = (i == valIndex - 1 ? 0 : i + 1);
                if (vals[i] == vals[iplus])
                    continue;

                if (i == valIndex - 1)
                {
                    // the single edgecase
                    midpt = (vals[0] + MathHelper.Pi * 2 + vals[i]);
                }
                else
                {
                    midpt = (vals[i + 1] + vals[i]);
                }

                midpt = midpt / 2;

                Vector2 p1 = pos;
                Vector2 p2 = radius * new Vector2((float)Math.Cos(midpt), (float)Math.Sin(midpt)) + pos;

                // RaycastOne
                bool hitClosest = false;
                World.RayCast((f, p, n, fr) =>
                                  {
                                      Body body = f.Body;

                                      if (!IsActiveOn(body))
                                          return 0;

                                      hitClosest = true;
                                      fixture = f;
                                      return fr;
                                  }, p1, p2);

                //draws radius points
                if ((hitClosest) && (fixture.Body.BodyType == BodyType.Dynamic))
                {
                    if ((_data.Any()) && (_data.Last().Body == fixture.Body) && (!rayMissed))
                    {
                        int laPos = _data.Count - 1;
                        ShapeData la = _data[laPos];
                        la.Max = vals[iplus];
                        _data[laPos] = la;
                    }
                    else
                    {
                        // make new
                        ShapeData d;
                        d.Body = fixture.Body;
                        d.Min = vals[i];
                        d.Max = vals[iplus];
                        _data.Add(d);
                    }

                    if ((_data.Count > 1)
                        && (i == valIndex - 1)
                        && (_data.Last().Body == _data.First().Body)
                        && (_data.Last().Max == _data.First().Min))
                    {
                        ShapeData fi = _data[0];
                        fi.Min = _data.Last().Min;
                        _data.RemoveAt(_data.Count - 1);
                        _data[0] = fi;
                        while (_data.First().Min >= _data.First().Max)
                        {
                            fi.Min -= MathHelper.Pi * 2;
                            _data[0] = fi;
                        }
                    }

                    int lastPos = _data.Count - 1;
                    ShapeData last = _data[lastPos];
                    while ((_data.Count > 0)
                           && (_data.Last().Min >= _data.Last().Max)) // just making sure min<max
                    {
                        last.Min = _data.Last().Min - 2 * MathHelper.Pi;
                        _data[lastPos] = last;
                    }
                    rayMissed = false;
                }
                else
                {
                    rayMissed = true; // raycast did not find a shape
                }
            }

            for (int i = 0; i < _data.Count; ++i)
            {
                if (!IsActiveOn(_data[i].Body))
                    continue;

                float arclen = _data[i].Max - _data[i].Min;

                float first = MathHelper.Min(MaxEdgeOffset, EdgeRatio * arclen);
                int insertedRays = (int)Math.Ceiling(((arclen - 2.0f * first) - (MinRays - 1) * MaxAngle) / MaxAngle);

                if (insertedRays < 0)
                    insertedRays = 0;

                float offset = (arclen - first * 2.0f) / ((float)MinRays + insertedRays - 1);

                //Note: This loop can go into infinite as it operates on floats.
                //Added FloatEquals with a large epsilon.
                for (float j = _data[i].Min + first;
                     j < _data[i].Max || MathUtils.FloatEquals(j, _data[i].Max, 0.0001f);
                     j += offset)
                {
                    Vector2 p1 = pos;
                    Vector2 p2 = pos + radius * new Vector2((float)Math.Cos(j), (float)Math.Sin(j));
                    Vector2 hitpoint = Vector2.Zero;
                    float minlambda = float.MaxValue;

                    List<Fixture> fl = _data[i].Body.FixtureList;
                    for (int x = 0; x < fl.Count; x++)
                    {
                        Fixture f = fl[x];
                        RayCastInput ri;
                        ri.Point1 = p1;
                        ri.Point2 = p2;
                        ri.MaxFraction = 50f;

                        RayCastOutput ro;
                        if (f.RayCast(out ro, ref ri, 0))
                        {
                            if (minlambda > ro.Fraction)
                            {
                                minlambda = ro.Fraction;
                                hitpoint = ro.Fraction * p2 + (1 - ro.Fraction) * p1;
                            }
                        }

                        // the force that is to be applied for this particular ray.
                        // offset is angular coverage. lambda*length of segment is distance.
                        float impulse = (arclen / (MinRays + insertedRays)) * maxForce * 180.0f / MathHelper.Pi * (1.0f - Math.Min(1.0f, minlambda));

                        // We Apply the impulse!!!
                        Vector2 vectImp = Vector2.Dot(impulse * new Vector2((float)Math.Cos(j), (float)Math.Sin(j)), -ro.Normal) * new Vector2((float)Math.Cos(j), (float)Math.Sin(j));
                        _data[i].Body.ApplyLinearImpulse(ref vectImp, ref hitpoint);

                        // We gather the fixtures for returning them
                        if (exploded.ContainsKey(f))
                            exploded[f] += vectImp;
                        else
                            exploded.Add(f, vectImp);

                        if (minlambda > 1.0f)
                            hitpoint = p2;
                    }
                }
            }

            // We check contained shapes
            for (int i = 0; i < containedShapeCount; ++i)
            {
                Fixture fix = containedShapes[i];

                if (!IsActiveOn(fix.Body))
                    continue;

                float impulse = MinRays * maxForce * 180.0f / MathHelper.Pi;
                Vector2 hitPoint;

                CircleShape circShape = fix.Shape as CircleShape;
                if (circShape != null)
                {
                    hitPoint = fix.Body.GetWorldPoint(circShape.Position);
                }
                else
                {
                    PolygonShape shape = fix.Shape as PolygonShape;
                    hitPoint = fix.Body.GetWorldPoint(shape.MreplacedData.Centroid);
                }

                Vector2 vectImp = impulse * (hitPoint - pos);

                fix.Body.ApplyLinearImpulse(ref vectImp, ref hitPoint);

                if (!exploded.ContainsKey(fix))
                    exploded.Add(fix, vectImp);
            }

            return exploded;
        }

See More Examples