Ejemplo n.º 1
1
 public static void writeVertex(XmlWriter writer, Vector2D vert)
 {
     writer.WriteStartElement("vertex");
     writer.WriteAttributeString("x", vert.x.ToString());
     writer.WriteAttributeString("y", vert.y.ToString());
     writer.WriteEndElement();
 }
Ejemplo n.º 2
0
		private void AdvanceTouchTick(MockTouch touch, State state, Vector2D position,
			TouchFlickTrigger trigger)
		{
			touch.SetTouchState(0, state, position);
			AdvanceTimeAndUpdateEntities();
			touch.Update(new[] { trigger });
		}
Ejemplo n.º 3
0
		private void ButtonClick(Vector2D position)
		{
			if (userStats.DrawArea.Contains(position))
				ClickUserStatButton();
			else if (topLocation.DrawArea.Contains(position))
				ClickTopLocationButton();
		}
Ejemplo n.º 4
0
 public static void ContainsInclusive(Vector2D[] vertexes, ref Vector2D point, out ContainmentType result)
 {
     if (vertexes == null) { throw new ArgumentNullException("vertexes"); }
     if (vertexes.Length < 3) { throw new ArgumentOutOfRangeException("vertexes"); }
     int count = 0;    // the crossing count
     Vector2D v1 = vertexes[vertexes.Length - 1];
     Vector2D v2;
     for (int index = 0; index < vertexes.Length; index++, v1 = v2)
     {
         v2 = vertexes[index];
         if (((v1.Y <= point.Y) ^ (v2.Y <= point.Y)) ||
             (v1.Y == point.Y) || (v2.Y == point.Y))
         {
             Scalar xIntersection = (v1.X + ((point.Y - v1.Y) / (v2.Y - v1.Y)) * (v2.X - v1.X));
             if (point.X < xIntersection) // P.X < intersect
             {
                 ++count;
             }
             else if (xIntersection == point.X)
             {
                 result = ContainmentType.Contains;
                 return;
             }
         }
     }
     result = ((count & 1) != 0) ? (ContainmentType.Contains) : (ContainmentType.Disjoint); //true if odd.
 }
Ejemplo n.º 5
0
		public Logo Create()
		{
			Randomizer random = Randomizer.Current;
			Size size = new Size(random.Get(0.02f, 0.08f));
			var halfWidth = size.Width / 2f;
			var doubleWidth = size.Width * 2f;
			Rectangle view = screen.Viewport;
			Vector2D position = new Vector2D(random.Get(doubleWidth, view.Width - doubleWidth), view.Bottom - size.Height / 2);
			float direction = position.X > 0.5f ? -1 : 1;
			if (random.Get(1, 100) >= 30) direction *= -1;
			float r = direction > 0
				? random.Get(0, view.Width - position.X - doubleWidth)
				: random.Get(0, position.X - doubleWidth);
			var h = random.Get(0.3f, view.Height - 0.05f);
			var angle = Math.Atan((4 * h) / r);
			if (angle == 0)
				angle = 1.57079f;
			var v0 = Math.Sqrt(r * MovingSprite.Gravity / Math.Sin(2 * angle));
			var v_x = (float)(v0 * Math.Cos(angle));
			var v_y = (float)(v0 * Math.Sin(angle));
			v_x *= direction;
			var data = new SimplePhysics.Data()
			{
				Gravity = new Vector2D(0f, MovingSprite.Gravity),
				Velocity = new Vector2D(v_x, -v_y),
				RotationSpeed = random.Get(10, 50) * direction
			};
			return new Logo("DeltaEngineLogo", Color.GetRandomBrightColor(), position, size, data);
		}
		public DefaultTowerSelectionPanelForTesting(Vector2D position, Game game)
		{
			towerPanel = new Scene();
			clickedPosition = position;
			this.game = game;
			DisplayTowerSelectionPanel();
		}
Ejemplo n.º 7
0
        public static void Build(string dot, string outputpath, bool open)
        {
            Vector2D pagesize;
            var nodes = Node.GetNodes(dot, out pagesize);
            var links = Link.GetLinks(dot, nodes);

            PDFDocument doc = new PDFDocument();
            var page = doc.Pages.Add(new Page(pagesize));

            var space = new Vector1D(0.15, UnitsOfMeasure.Centimeters);

            for (int i = 0; i < links.Length; i++)
            {
                var link = links[i];

                var allTo = links.Where(x => x.To == link.To).ToList();
                var allFrom = links.Where(x => x.From == link.From).ToList();

                var p1 = new Vector2D(link.From.Center.X, link.From.GateRect.Bottom);
                var p3 = new Vector2D(link.To.Center.X, link.To.BoxRect.Top);

                p1.X += allFrom.IndexOf(link) * space - ((allFrom.Count - 1) * space) / 2;

                page.Objects.Add(new Connector(p1, p3 - p1, link.From.Center.X));
            }

            for (int i = 0; i < nodes.Length; i++)
                page.Objects.AddRange(HandleNode(nodes[i]));

            doc.Create(outputpath, open);
        }
		private void SetTouchState(State state, Vector2D position)
		{
			if (touch == null)
				return; //ncrunch: no coverage
			touch.SetTouchState(0, state, position);
			AdvanceTimeAndUpdateEntities();
		}
Ejemplo n.º 9
0
		/// <summary>
		/// Finds the distance of a specified point from the line segment and the
		/// closest point on the segment to the specified point.
		/// </summary>
		/// <param name="p">The test point.</param>
		/// <param name="closestPt">Closest point on the segment to c.</param>
		/// <returns>Returns the distance from p to the closest point on the segment.</returns>
		public double Distance(Point2D p, Point2D closestPt)
		{
			if (closestPt == null)
				closestPt = new Point2D();

			// Construct vector v (AB) and w (AP)
			var v = new Vector2D(A, B);
			var w = new Vector2D(A, p);

			// Numerator of the component of w onto v. If <= 0 then A
			// is the closest point. By separating into the numerator
			// and denominator of the component we avoid a division unless
			// it is necessary.
			double n = w.Dot(v);
			if (n <= 0.0f)
			{
				closestPt.Set(A);
				return w.Norm();
			}

			// Get the denominator of the component. If the component >= 1
			// (d <= n) then point B is the closest point
			double d = v.Dot(v);
			if (d <= n)
			{
				closestPt.Set(B);
				return new Vector2D(B, p).Norm();
			}

			// Closest point is along the segment. The point is the projection of
			// w onto v.
			closestPt.Set(v.Mult(n / d));
			closestPt.Add(A);
			return new Vector2D(closestPt, p).Norm();
		}
Ejemplo n.º 10
0
        public override void MouseDown(Vector2D mouseDownPos, EnumMouseButton button)
        {
            if (mesh == null)
                return;
            base.MouseDown(mouseDownPos, button);

        }
Ejemplo n.º 11
0
 public VectorText(string text, Vector2D position)
     : base(Rectangle.FromCenter(position, new Size(0.05f)))
 {
     Add(new Data(text));
     Start<ProcessText>();
     OnDraw<Render>();
 }
Ejemplo n.º 12
0
       public override void MouseMove(Vector2D mouseMovePos, EnumMouseButton button)
       {
           base.MouseMove(mouseMovePos,button);

           switch (ParameterCurve.Instance.currentCurve)
           {
               case EnumCurveComplex.FourPointBezier :
                   curve = ParameterCurve.Instance.CreateFourBezierCurve(mesh);
                   break;
               case EnumCurveComplex.ThreePointBezier:
                   curve = ParameterCurve.Instance.CreateThreeBezierCurve(mesh);
                   break;
               case EnumCurveComplex.NPointBezier:
                   curve = ParameterCurve.Instance.CreateNBezierCurve(mesh);
                   break;
               case EnumCurveComplex.FourPointBSpline:
                   curve = ParameterCurve.Instance.CreateFourPointBSplineCurve(mesh);
                   break;
               case EnumCurveComplex.NPointBSpline:
                   curve = ParameterCurve.Instance.CreateNBsplineCurve(mesh);
                   break;
               case EnumCurveComplex.NURBS:
                   curve = ParameterCurve.Instance.CreateNURBS(mesh);
                   break;
               case EnumCurveComplex.NURBSCicle:
                   curve = ParameterCurve.Instance.CreateNURBSCicle(mesh);
                   break;
               case EnumCurveComplex.NURBSEllipse:
                   curve = ParameterCurve.Instance.CreateNURBSEllipse(mesh);
                   break;
           }
          
       }
Ejemplo n.º 13
0
        public static MassInfo FromPolygon(Vector2D[] vertexes, Scalar mass)
        {
            if (vertexes == null) { throw new ArgumentNullException("vertexes"); }
            if (vertexes.Length == 0) { throw new ArgumentOutOfRangeException("vertexes"); }

            if (vertexes.Length == 1) { return new MassInfo(mass, 0); }

            Scalar denom = 0.0f;
            Scalar numer = 0.0f;

            for (int j = vertexes.Length - 1, i = 0; i < vertexes.Length; j = i, i++)
            {
                Scalar a, b, c;
                Vector2D P0 = vertexes[j];
                Vector2D P1 = vertexes[i];
                Vector2D.Dot(ref P1, ref P1, out a);
                Vector2D.Dot(ref P1, ref P0, out b);
                Vector2D.Dot(ref P0, ref P0, out c);
                a += b + c;
                Vector2D.ZCross(ref P0, ref P1, out b);
                b = MathHelper.Abs(b);
                denom += (b * a);
                numer += b;
            }
            return new MassInfo(mass, (mass * denom) / (numer * 6));
        }
Ejemplo n.º 14
0
		private void SetNewCenter(Vector2D newCenter)
		{
			Center = newCenter;
			var newLetterArea = DrawArea;
			newLetterArea.Left += Dimension * 0.05f;
			currentFontText.DrawArea = newLetterArea;
		}
Ejemplo n.º 15
0
        public override void MouseUp(Vector2D mouseUpPos, EnumMouseButton button)
        {
            //if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
            //{
            //    if (button == EnumMouseButton.Left)
            //    {
            //        if ((Control.ModifierKeys & Keys.Shift) != Keys.Shift)
            //        {
            //            NonManifoldMesh m =mesh;
            //            int n = m.VertexCount;
            //            for (int i = 0; i < n; i++)
            //            {
            //                m.VertexFlag[i] = (byte)0;
            //            }
            //        }
            //        SelectRandomPoint();
            //    }
            //}

            //if ((Control.ModifierKeys & Keys.Alt) == Keys.Alt)
            //{ 
            //        NonManifoldMesh m = mesh;
            //        int n =  m.VertexCount;
            //        for (int i = 0; i < n; i++)
            //        {
            //            m.VertexFlag[i] = (byte)0;
            //        }
              
            //}
            //base.MouseUp(mouseUpPos,button);

          
       
        }
Ejemplo n.º 16
0
        public override void Collition(Particles particles, double elapsedTime)
        {
            if (particles == null)
                return;
            if (particles.Enabled == false)
                return;
            double distance = 0;
            foreach (particle p in particles.particles)
            {
                distance = (p.Position.X - Position.X) * (p.Position.X - Position.X) +
                    (p.Position.Y - Position.Y) * (p.Position.Y - Position.Y);
                //如果进入范围以内则触发碰撞器
                if (distance < radius_pow)
                {
                    Vector2D vct = new Vector2D((p.Position.X - Position.X ),
                        (p.Position.Y - Position.Y)).GetNormalize();
                    double dx = elapsedTime * speed * vct.X;
                    double dy = elapsedTime * speed * vct.Y;
                    double tx = p.Position.X + dx;
                    double ty = p.Position.Y + dy;
                    p.Position.X = tx;
                    p.Position.Y = ty;
                }

            }
        }
Ejemplo n.º 17
0
        public TriangleTest(Vector3D a, Vector3D b, Vector3D c)
        {
            this.A = a;
            this.B = b;
            this.C = c;

            Vector2D sa;
            Vector2D sb;
            Vector2D sc;

            sa = new Vector2D(1, 5);
            sb = new Vector2D(2, 3);
            sc = new Vector2D(4, 2);

            this.sA = sa;
            this.sB = sb;
            this.sC = sc;

            triVertices.Add(A);
            triVertices.Add(B);
            triVertices.Add(C);

            AB = (A - B).Length();
            BC = (B - C).Length();
            AC = (C - A).Length();

            lengthOfTheEdge.Add(AB);
            lengthOfTheEdge.Add(BC);
            lengthOfTheEdge.Add(AC);
            lengthOfTheEdge.Sort();

        }
Ejemplo n.º 18
0
		internal Vector2D FromScreenPositionToScreenSpace(Vector2D position)
		{
			var screenPoint = ToSysPoint(position);
			if (WindowHandleIsValidIntPtr())
				NativeMethods.ScreenToClient(window.Handle, ref screenPoint); //ncrunch: no coverage
			return ScreenSpace.Current.FromPixelSpace(FromSysPoint(screenPoint));
		}
Ejemplo n.º 19
0
 public void Add()
 {
     Vector2D a = new Vector2D(1, 2);
     Vector2D b = new Vector2D(3, 1);
     Assert.That(a + b, Is.EqualTo(new Vector2D(4, 3)));
     Assert.That(a + new Vector2D(2, 2), Is.EqualTo(new Vector2D(3, 4)));
 }
Ejemplo n.º 20
0
 public void DotProduct()
 {
     Vector2D a = new Vector2D(1, 0);
     Vector2D b = new Vector2D(0, 1);
     Assert.That(Vector2D.DotProduct(a, b), Is.EqualTo(0));
     Assert.That(Vector2D.DotProduct(a, a), Is.EqualTo(1));
 }
Ejemplo n.º 21
0
 public override Scalar GetDistance(Vector2D vector)
 {
     Vector2D.Subtract(ref vector, ref vertexes[0], out vector);
     Scalar result;
     Vector2D.GetMagnitude(ref vector, out result);
     return result;
 }
Ejemplo n.º 22
0
		public void CheckForSlicing(Vector2D start, Vector2D end)
		{
			if (!sideStatus.HasFlag(Sides.Top) && CheckIfLineIntersectsLine(start, end, DrawArea.TopLeft, DrawArea.TopRight)) sideStatus |= Sides.Top;
			if (!sideStatus.HasFlag(Sides.Left) && CheckIfLineIntersectsLine(start, end, DrawArea.TopLeft, DrawArea.BottomLeft)) sideStatus |= Sides.Left;
			if (!sideStatus.HasFlag(Sides.Bottom) && CheckIfLineIntersectsLine(start, end, DrawArea.BottomLeft, DrawArea.BottomRight)) sideStatus |= Sides.Bottom;
			if (!sideStatus.HasFlag(Sides.Right) && CheckIfLineIntersectsLine(start, end, DrawArea.TopRight, DrawArea.BottomRight)) sideStatus |= Sides.Right;
		}
Ejemplo n.º 23
0
        public TransformState(int id, Vector2D value)
        {
            Blobs = new Spread<Blob>();
            PBlobs = new Spread<Blob>();

            Reset(id, value);
        }
Ejemplo n.º 24
0
		private static void SellTower(Vector2D point)
		{
			var level = (GameLevel)Level.Current;
			if (level == null)
				return;
			level.SellTower(GameLevelExtensions.GetGridPosition(point));
		}
Ejemplo n.º 25
0
		public override void PerformAttack(AvatarAttack attack, Vector2D position)
		{
			if (attack == AvatarAttack.PiggyBankCoinMinefield)
				SpawnCoinMinefield();
			else if (attack == AvatarAttack.PiggyBankPayDay)
				BuffAllCreepsToDropMoreGold();
		}
		public Correspondence(int BoardIndex, Vector3D World, Vector2D Projection, DateTime Timestamp)
		{
			this.BoardIndex = BoardIndex;
			this.World = World;
			this.Projection = Projection;
			this.Timestamp = Timestamp;
		}
Ejemplo n.º 27
0
		public MockTouch()
		{
			IsAvailable = true;
			positions = new Vector2D[2];
			positions[0] = Vector2D.Half;
			TouchStates = new State[MaxNumberOfTouchIndices];
		}
Ejemplo n.º 28
0
 public Ball(Vector2D position, Vector2D size, string id)
     : base(5, 0.3, false)
 {
     initPosition = position;
     this.Id = id;
     friction = 0.020F;
 }
Ejemplo n.º 29
0
 private static void CreateFontTexts(Vector2D[] centers, Size size)
 {
     new FontText(Font.Default, "Up", Rectangle.FromCenter(centers[0], size));
     new FontText(Font.Default, "Down", Rectangle.FromCenter(centers[1], size));
     new FontText(Font.Default, "Left", Rectangle.FromCenter(centers[2], size));
     new FontText(Font.Default, "Right", Rectangle.FromCenter(centers[3], size));
 }
Ejemplo n.º 30
0
        public void StopTransformation()
        {
            Blobs.SliceCount = 0;
            PDelta = new Vector2D();

            Phase = TransformPhase.Idle;
        }
Ejemplo n.º 31
0
        public override Vector2D Calculate()
        {
            Vector2D steeringForce = sB.Calculate() + aB.Calculate() + cB.Calculate();

            return(steeringForce.SetMagnitude(ME.MaxSpeed));
        }
Ejemplo n.º 32
0
 public static Vector2D ApplyInvertedTransform(this Vector2D v, Matrix m)
 {
     return((!m * v.ToMatrix()).ToVector2D());
 }
Ejemplo n.º 33
0
 public Stone?this[Vector2D position]
 {
     get => board[position];
Ejemplo n.º 34
0
 public Snake(Vector2D pos, char icon, ConsoleColor color, string name) : base(icon, color, pos)
 {
     Name = name;
 }
Ejemplo n.º 35
0
 // This returns the distance from given coordinates
 public float DistanceTo(Vector2D p)
 {
     return(Vector2D.Distance(p, pos));
 }
Ejemplo n.º 36
0
 public Position2D(Vector2D posVec, string name = "Pos2D") : this(posVec.X, posVec.Y, name)
 {
 }
Ejemplo n.º 37
0
 // This checks if the given point is inside the sector polygon
 // See: http://paulbourke.net/geometry/polygonmesh/index.html#insidepoly
 public bool Intersect(Vector2D p)
 {
     return(Intersect(p, true));
 }
Ejemplo n.º 38
0
 public static Vector2D Round(this Vector2D v)
 {
     return(new Vector2D((float)System.Math.Round(v.X), (float)System.Math.Round(v.Y)));
 }
Ejemplo n.º 39
0
 public static Vector2D Floor(this Vector2D v)
 {
     return(new Vector2D((float)System.Math.Floor(v.X), (float)System.Math.Floor(v.Y)));
 }
Ejemplo n.º 40
0
 public static Vector2D PixelSnap(this Vector2D v)
 {
     return(new Vector2D(((float)System.Math.Floor(v.X)) + 0.5f, ((float)System.Math.Floor(v.Y)) + 0.5f));
 }
Ejemplo n.º 41
0
 public static double GetValue(this IMyModule module, Vector2D pos)
 {
     return(module.GetValue(pos.X, pos.Y));
 }
Ejemplo n.º 42
0
        void DrawEdge(Graphics g, Edge item, PointF p1, PointF p2, bool selected)
        {
            string distance = GetDistance(Point.Round(p1), Point.Round(p2)).ToString();

            p1.X += NODE_RADIUS;
            p1.Y += NODE_RADIUS;
            p2.X += NODE_RADIUS;
            p2.Y += NODE_RADIUS;

            Vector2D v1 = new Vector2D(p1.X - p2.X, p1.Y - p2.Y);

            if (v1.Length - NODE_RADIUS > 0)
            {
                v1.Contract(NODE_RADIUS);
                p1.X = p2.X + v1.X;
                p1.Y = p2.Y + v1.Y;
            }
            Vector2D v = new Vector2D(p2.X - p1.X, p2.Y - p1.Y);

            if (v.Length - NODE_RADIUS > 0)
            {
                v.Contract(NODE_RADIUS);
                p2.X = p1.X + v.X;
                p2.Y = p1.Y + v.Y;
            }
            if (!IsUndirectedGraph && item.IsUndirected)
            {
                _penEdge.StartCap = LineCap.ArrowAnchor;
            }
            else
            {
                _penEdge.StartCap = LineCap.NoAnchor;
            }

            if (item.IsRemoving)
            {
                Pen p = new Pen(Color.Red, 4);
                g.DrawLine(p, p1, p2);
            }
            else
            {
                if (_path != null && (_path.Contains(new Point(item.Start, item.End)) || _path.Contains(new Point(item.End, item.Start))))
                {
                    Pen p = (Pen)_penEdge.Clone();
                    p.Color     = Color.Green;
                    p.DashStyle = DashStyle.Dash;
                    g.DrawLine(p, p1, p2);
                }
                else if (selected)
                {
                    var hPen = (Pen)_penEdge.Clone();
                    hPen.Color = Color.Red;
                    g.DrawLine(hPen, p1, p2);
                }
                else
                {
                    g.DrawLine(_penEdge, p1, p2);
                }
            }


            // draw distance
            SizeF  size = g.MeasureString(distance, this.Font);
            PointF pp   = p1;

            pp.X += p2.X;
            pp.Y += p2.Y;
            pp.X /= 2;
            pp.Y /= 2;
            pp.X -= size.Width / 2;
            pp.Y -= size.Height / 2;
            g.FillEllipse(Brushes.Yellow, pp.X - 5, pp.Y - 5, size.Width + 10, size.Height + 5);
            g.DrawString(distance.ToString(), this.Font, Brushes.Blue, pp);
        }
Ejemplo n.º 43
0
 /// <summary>
 /// Updates the commandControl's stored turret direction
 /// </summary>
 public void UpdateTDir(Vector2D angle)
 {
     angle.Normalize();
     commandControl.tDirection = angle;
 }
Ejemplo n.º 44
0
 /// <summary>
 /// Gets the full size of the given window including its borders.
 /// </summary>
 /// <param name="window">The window to get size information from.</param>
 /// <returns>The full size of the window (including both content area and borders)</returns>
 public static Vector2D <int> GetFullSize(this IWindow window) => Vector2D.Add(window.Size, window.BorderSize.Size);
Ejemplo n.º 45
0
 public ITile GetFloorAt(Vector2D pos)
 {
     return(GetAllFloorIn(new RectangleF(pos.X, pos.Y, 2f, 2f)).FirstOrDefault());
 }
Ejemplo n.º 46
0
            protected void DrawArrowHeadSeg(ref List <Segment> segments, Vector2D pt, Vector2D director)
            {
                director.Normalize();
                Vector2D normal = new Vector2D(-director.Y, director.X);

                double angleRad    = GlobalCotationProperties.ArrowHeadAngle * Math.PI / 180.0;
                double arrowLength = GlobalCotationProperties.ArrowLength;

                segments.Add(new Segment(pt - arrowLength * (Math.Cos(angleRad) * director + Math.Sin(angleRad) * normal), pt));
                segments.Add(new Segment(pt - arrowLength * (Math.Cos(angleRad) * director - Math.Sin(angleRad) * normal), pt));
            }
Ejemplo n.º 47
0
 protected void DrawArrowHead(Pic.Factory2D.PicGraphics graphics, Vector2D pt, double angle)
 {
     DrawArrowHead(graphics, pt, new Vector2D(Math.Cos(angle * Math.PI / 180.0), Math.Sin(angle * Math.PI / 180.0)));
 }
Ejemplo n.º 48
0
        //mxd
        public bool Setup(SectorLevel level, Effect3DFloor extrafloor, bool innerside)
        {
            Sector   s = level.sector;
            Vector2D texscale;

            this.innerside = innerside;             //mxd

            base.Setup(level, extrafloor);

            // Fetch ZDoom fields
            double   rotate = Angle2D.DegToRad(s.Fields.GetValue("rotationceiling", 0.0));
            Vector2D offset = new Vector2D(s.Fields.GetValue("xpanningceiling", 0.0),
                                           s.Fields.GetValue("ypanningceiling", 0.0));
            Vector2D scale = new Vector2D(s.Fields.GetValue("xscaleceiling", 1.0),
                                          s.Fields.GetValue("yscaleceiling", 1.0));

            //Load ceiling texture
            if (s.LongCeilTexture != MapSet.EmptyLongName)
            {
                base.Texture = General.Map.Data.GetFlatImage(s.LongCeilTexture);
                if (base.Texture == null || base.Texture is UnknownImage)
                {
                    base.Texture         = General.Map.Data.UnknownTexture3D;
                    setuponloadedtexture = s.LongCeilTexture;
                }
                else if (!base.Texture.IsImageLoaded)
                {
                    setuponloadedtexture = s.LongCeilTexture;
                }
            }
            else
            {
                // Use missing texture
                base.Texture         = General.Map.Data.MissingTexture3D;
                setuponloadedtexture = 0;
            }

            // Determine texture scale
            if (base.Texture.IsImageLoaded)
            {
                texscale = new Vector2D(1.0f / base.Texture.ScaledWidth, 1.0f / base.Texture.ScaledHeight);
            }
            else
            {
                texscale = new Vector2D(1.0f / 64.0f, 1.0f / 64.0f);
            }

            // Determine brightness
            byte       alpha = (byte)General.Clamp(level.alpha, 0, 255);
            int        color = PixelColor.FromInt(level.color).WithAlpha(alpha).ToInt();
            int        targetbrightness;
            SectorData sd = mode.GetSectorData(this.Sector.Sector);

            if (extrafloor != null && !extrafloor.VavoomType && !level.disablelighting)
            {
                //mxd. Top extrafloor level should calculate fogdensity from the brightness of the level above it
                if (!innerside)
                {
                    targetbrightness = 0;
                    for (int i = 0; i < sd.LightLevels.Count - 1; i++)
                    {
                        if (sd.LightLevels[i] == level)
                        {
                            targetbrightness = sd.LightLevels[i + 1].brightnessbelow;
                            break;
                        }
                    }
                }
                //mxd. Inner extrafloor ceilings must be colored using control sector's color and brightness
                else
                {
                    targetbrightness = level.brightnessbelow;
                    for (int i = 0; i < sd.LightLevels.Count; i++)
                    {
                        if (sd.LightLevels[i] == level)
                        {
                            if (i > 0)
                            {
                                color = PixelColor.FromInt(sd.LightLevels[i - 1].color).WithAlpha(alpha).ToInt();
                            }
                            break;
                        }
                    }
                }
            }
            else
            {
                targetbrightness = level.brightnessbelow;
            }

            // [ZZ] Apply Doom 64 lighting here (for extrafloor)
            if (extrafloor != null)
            {
                color = PixelColor.Modulate(PixelColor.FromInt(color), extrafloor.ColorCeiling).WithAlpha(alpha).ToInt();
            }

            //mxd. Determine fog density
            fogfactor = CalculateFogFactor(targetbrightness);

            // Make vertices
            ReadOnlyCollection <Vector2D> triverts = Sector.Sector.Triangles.Vertices;

            WorldVertex[] verts = new WorldVertex[triverts.Count];
            for (int i = 0; i < triverts.Count; i++)
            {
                // Color shading
                verts[i].c = color;                 //mxd

                // Vertex coordinates
                verts[i].x = (float)triverts[i].x;
                verts[i].y = (float)triverts[i].y;
                verts[i].z = (float)level.plane.GetZ(triverts[i]);

                // Texture coordinates
                Vector2D pos = triverts[i];
                pos        = pos.GetRotated(rotate);
                pos.y      = -pos.y;
                pos        = (pos + offset) * scale * texscale;
                verts[i].u = (float)pos.x;
                verts[i].v = (float)pos.y;
            }

            // The sector triangulation created clockwise triangles that
            // are right up for the floor. For the ceiling we must flip
            // the triangles upside down.
            if (extrafloor == null || extrafloor.VavoomType || innerside)
            {
                SwapTriangleVertices(verts);
            }

            // Determine render pass
            if (extrafloor != null)
            {
                if (extrafloor.Sloped3dFloor)                //mxd
                {
                    this.RenderPass = RenderPass.Mask;
                }
                else if (extrafloor.RenderAdditive)                //mxd
                {
                    this.RenderPass = RenderPass.Additive;
                }
                else if ((level.alpha < 255) || Texture.IsTranslucent)
                {
                    this.RenderPass = RenderPass.Alpha;
                }
                else
                {
                    this.RenderPass = RenderPass.Mask;
                }
            }
            else
            {
                this.RenderPass = RenderPass.Solid;
            }

            //mxd. Update sky render flag
            bool isrenderedassky = renderassky;

            renderassky = (level.sector.CeilTexture == General.Map.Config.SkyFlatName);
            if (isrenderedassky != renderassky && Sector.Sides != null)
            {
                // Upper sidedef geometry may need updating...
                foreach (Sidedef side in level.sector.Sidedefs)
                {
                    VisualSidedefParts parts = Sector.GetSidedefParts(side);

                    // Upper side can exist in either our, or the neightbouring sector, right?
                    if (parts.upper != null && parts.upper.Triangles > 0)
                    {
                        parts.upper.UpdateSkyRenderFlag();
                    }
                    else if (side.Other != null && side.Other.Sector != null && side.Other.Sector.CeilTexture == General.Map.Config.SkyFlatName)
                    {
                        // Update upper side of the neightbouring sector
                        BaseVisualSector other = (BaseVisualSector)mode.GetVisualSector(side.Other.Sector);
                        if (other != null && other.Sides != null)
                        {
                            parts = other.GetSidedefParts(side.Other);
                            if (parts.upper != null && parts.upper.Triangles > 0)
                            {
                                parts.upper.UpdateSkyRenderFlag();
                            }
                        }
                    }
                }
            }

            // Apply vertices
            base.SetVertices(verts);
            return(verts.Length > 0);
        }
Ejemplo n.º 49
0
 public QuadTreeElement(T data, Vector2D topRight, Vector2D bottomLeft)
 {
     this.Data       = data;
     this.TopRight   = topRight;
     this.BottomLeft = bottomLeft;
 }
Ejemplo n.º 50
0
            protected void DrawArrowHead(Pic.Factory2D.PicGraphics graphics, Vector2D pt, Vector2D director)
            {
                director.Normalize();
                Vector2D normal = new Vector2D(-director.Y, director.X);

                double angleRad    = GlobalCotationProperties.ArrowHeadAngle * Math.PI / 180.0;
                double arrowLength = graphics.DX_inv(GlobalCotationProperties.ArrowLength);

                // lower part of arrow head
                graphics.DrawLine(LineType
                                  , pt - arrowLength * (Math.Cos(angleRad) * director + Math.Sin(angleRad) * normal)
                                  , pt);
                // upper part of arrow head
                graphics.DrawLine(LineType
                                  , pt - arrowLength * (Math.Cos(angleRad) * director - Math.Sin(angleRad) * normal)
                                  , pt);
            }
Ejemplo n.º 51
0
        public override void Render <TSurface, TSource>(ScreenRenderer <TSurface, TSource> r)
        {
            foreach (PlayerAnimation player in WatchedComponents)
            {
                Renderable renderable = player.Owner.Components.Get <Renderable>();

                Vector2D[] srcOffsets = new Vector2D[5];
                srcOffsets[Legs]   = new Vector2D(0, Origins[Legs]);
                srcOffsets[Torso]  = new Vector2D(0, Origins[Torso]);
                srcOffsets[Head]   = new Vector2D(0, Origins[Head]);
                srcOffsets[Woofer] = new Vector2D(0, Origins[Woofer]);
                srcOffsets[Arms]   = new Vector2D(0, Origins[Arms]);

                Vector2D[] destOffsets = new Vector2D[5];
                destOffsets[Legs] = destOffsets[Torso] = destOffsets[Head] = destOffsets[Woofer] = destOffsets[Arms] = Vector2D.Empty;

                if (!player.Initialized)
                {
                    renderable.Sprites = new List <Sprite>()
                    {
                        new Sprite(player.SpritesheetName, Destination, new Rectangle(srcOffsets[Legs], 32, 32)),
                        new Sprite(player.SpritesheetName, Destination, new Rectangle(srcOffsets[Torso], 32, 32)),
                        new Sprite(player.SpritesheetName, Destination, new Rectangle(srcOffsets[Head], 32, 32)),
                        new Sprite("woofer", Destination, new Rectangle(srcOffsets[Woofer], 0, 0)),
                        new Sprite(player.SpritesheetName, Destination, new Rectangle(srcOffsets[Arms], 32, 32))
                    };
                    player.Initialized = true;
                }


                Physical physical = player.Owner.Components.Get <Physical>();
                PlayerMovementComponent movement    = player.Owner.Components.Get <PlayerMovementComponent>();
                PlayerOrientation       orientation = player.Owner.Components.Get <PlayerOrientation>();
                if (physical == null || movement == null || orientation == null)
                {
                    continue;
                }
                PulseAbility pulse = player.Owner.Components.Get <PulseAbility>();

                bool handsFree = pulse == null;

                if (orientation.Unit.X > 0 || player.LastLookedRight)
                {
                    for (int i = Legs; i <= Arms; i++)
                    {
                        srcOffsets[i] += OrientationOffset;
                    }
                }

                bool forceLook = handsFree && !movement.OnGround;

                if (orientation.Unit.Y >= Math.Sin(Math.PI / 9))
                {
                    if (!forceLook)
                    {
                        srcOffsets[Head].X += 32;
                    }
                    srcOffsets[Woofer].X += 32;
                    if (!handsFree)
                    {
                        srcOffsets[Arms].X += 32;
                    }
                    if (orientation.Unit.Y >= Math.Sin(2 * Math.PI / 6))
                    {
                        srcOffsets[Woofer].X += 32;
                        if (!handsFree)
                        {
                            srcOffsets[Arms].X += 32;
                        }
                    }
                }
                else if (orientation.Unit.Y <= Math.Sin(-Math.PI / 9))
                {
                    if (!forceLook)
                    {
                        srcOffsets[Head].X += 64;
                    }
                    srcOffsets[Woofer].X += 96;
                    if (!handsFree)
                    {
                        srcOffsets[Arms].X += 96;
                    }
                    if (orientation.Unit.Y <= Math.Sin(-2 * Math.PI / 6))
                    {
                        srcOffsets[Woofer].X += 32;
                        destOffsets[Woofer]  += new Vector2D(0, -3); //Offset woofer down since it goes out of the spritesheet grid
                        if (!handsFree)
                        {
                            srcOffsets[Arms].X += 32;
                        }
                    }
                }

                if (forceLook)
                {
                    srcOffsets[Head].X += physical.Velocity.Y <= 0 ? 64 : 32;
                }

                if (orientation.Unit.X != 0)
                {
                    player.LastLookedRight = orientation.Unit.X > 0;
                }

                if (pulse != null)
                {
                    srcOffsets[Woofer].Y  = 256;
                    srcOffsets[Woofer].Y -= 32 * Math.Round(pulse.EnergyMeter / 20);
                    if (pulse.EnergyMeter == 0 && player.WooferBlinkingTime >= 0.375)
                    {
                        srcOffsets[Woofer].Y += 32;
                    }
                }

                if (handsFree)
                {
                    srcOffsets[Arms].Y += 32;
                }

                if (!movement.OnGround || Math.Abs(physical.Velocity.X) <= 1e-2) /*player.WalkAnimationProgress = 0;*/ } {
Ejemplo n.º 52
0
        public static void ServerSpawnMinions(
            ICharacter characterBoss,
            Vector2D characterBossCenterPosition,
            IProtoCharacterMob protoMinion,
            List <ICharacter> minionsList,
            double spawnCheckDistanceSqr,
            ServerBossDamageTracker bossDamageTracker,
            double minionsPerPlayer,
            int minionsTotalMin,
            int minionsTotalMax,
            int?minionsSpawnPerIterationLimit,
            double baseMinionsNumber,
            double spawnNoObstaclesCircleRadius,
            double spawnDistanceMin,
            double spawnDistanceMax)
        {
            // calculate how many minions required
            var minionsRequired = baseMinionsNumber;

            using var tempListCharacters = Api.Shared.GetTempList <ICharacter>();
            Api.Server.World.GetScopedByPlayers(characterBoss, tempListCharacters);

            foreach (var playerCharacter in tempListCharacters.AsList())
            {
                if (playerCharacter.ProtoGameObject is PlayerCharacterSpectator)
                {
                    continue;
                }

                if (playerCharacter.Position.DistanceSquaredTo(characterBossCenterPosition)
                    <= spawnCheckDistanceSqr)
                {
                    minionsRequired += minionsPerPlayer;
                }
            }

            minionsRequired = MathHelper.Clamp(minionsRequired,
                                               minionsTotalMin,
                                               minionsTotalMax);

            if (minionsSpawnPerIterationLimit.HasValue)
            {
                minionsRequired = Math.Min(minionsRequired, minionsSpawnPerIterationLimit.Value);
            }

            ServerProcessMinions(characterBoss,
                                 protoMinion,
                                 minionsList,
                                 out var spawnedMinionsCount,
                                 despawnDistanceSqr: spawnCheckDistanceSqr);

            //Logger.Dev($"Minions required: {minionsRequired} minions have: {minionsHave}");
            minionsRequired -= spawnedMinionsCount;
            if (minionsRequired <= 0)
            {
                return;
            }

            // spawn minions
            var attemptsRemains = 300;
            var physicsSpace    = characterBoss.PhysicsBody.PhysicsSpace;

            while (minionsRequired > 0)
            {
                attemptsRemains--;
                if (attemptsRemains <= 0)
                {
                    // attempts exceeded
                    return;
                }

                var spawnDistance = spawnDistanceMin
                                    + RandomHelper.NextDouble() * (spawnDistanceMax - spawnDistanceMin);
                var angle         = RandomHelper.NextDouble() * MathConstants.DoublePI;
                var spawnPosition = new Vector2D(
                    characterBossCenterPosition.X + spawnDistance * Math.Cos(angle),
                    characterBossCenterPosition.Y + spawnDistance * Math.Sin(angle));
                if (ServerTrySpawnMinion(spawnPosition) is { } spawnedMinion)
                {
                    // spawned successfully!
                    minionsRequired--;
                    minionsList.Add(spawnedMinion);
                }
            }

            ICharacter ServerTrySpawnMinion(Vector2D spawnPosition)
            {
                if (physicsSpace.TestCircle(spawnPosition,
                                            spawnNoObstaclesCircleRadius,
                                            CollisionGroups.Default,
                                            sendDebugEvent: true).EnumerateAndDispose().Any())
                {
                    // obstacles nearby
                    return(null);
                }

                var spawnedCharacter = Api.Server.Characters.SpawnCharacter(protoMinion, spawnPosition);

                if (spawnedCharacter is null)
                {
                    return(null);
                }

                // write this boss' damage tracker into the minion character
                // so any damage dealt to it will be counted in the winners ranking
                var privateState = spawnedCharacter.GetPrivateState <ICharacterPrivateStateWithBossDamageTracker>();

                privateState.DamageTracker = bossDamageTracker;

                // start spawn animation
                if (spawnedCharacter.ProtoGameObject is IProtoCharacterMob protoCharacterMob)
                {
                    protoCharacterMob.ServerSetSpawnState(spawnedCharacter,
                                                          MobSpawnState.Spawning);
                }

                return(spawnedCharacter);
            }
        }
Ejemplo n.º 53
0
 public Ellipse(Vector2D center, float radiusX, float radiusY, Color color)
     : this(Rectangle.FromCenter(center, new Size(2 * radiusX, 2 * radiusY)), color)
 {
 }
Ejemplo n.º 54
0
        public override bool Update(Vector2D mouseS, IMapManager currentMap)
        {
            if (currentMap == null)
            {
                return(false);
            }

            spriteToDraw = GetDirectionalSprite(pManager.CurrentBaseSprite);

            mouseScreen = mouseS;
            mouseWorld  = new Vector2D(mouseScreen.X + ClientWindowData.Singleton.ScreenOrigin.X,
                                       mouseScreen.Y + ClientWindowData.Singleton.ScreenOrigin.Y);

            var spriteRectWorld = new RectangleF(mouseWorld.X - (spriteToDraw.Width / 2f),
                                                 mouseWorld.Y - (spriteToDraw.Height / 2f), spriteToDraw.Width,
                                                 spriteToDraw.Height);

            currentTile = currentMap.GetFloorAt(mouseWorld);

            //if (currentMap.IsSolidTile(mouseWorld)) validPosition = false;

            if (pManager.CurrentPermission.Range > 0)
            {
                if (
                    (pManager.PlayerManager.ControlledEntity.GetComponent <TransformComponent>(ComponentFamily.Transform)
                     .Position - mouseWorld).Length > pManager.CurrentPermission.Range)
                {
                    return(false);
                }
            }

            if (currentTile != null)
            {
                if (pManager.CurrentPermission.IsTile)
                {
                    mouseWorld = (currentTile.Position +
                                  new Vector2D(currentMap.GetTileSpacing() / 2f, currentMap.GetTileSpacing() / 2f));
                    mouseScreen = new Vector2D(mouseWorld.X - ClientWindowData.Singleton.ScreenOrigin.X,
                                               mouseWorld.Y - ClientWindowData.Singleton.ScreenOrigin.Y);
                }
                else
                {
                    mouseWorld = (currentTile.Position +
                                  new Vector2D(currentMap.GetTileSpacing() / 2f, currentMap.GetTileSpacing() / 2f)) +
                                 new Vector2D(pManager.CurrentTemplate.PlacementOffset.Key,
                                              pManager.CurrentTemplate.PlacementOffset.Value);
                    mouseScreen = new Vector2D(mouseWorld.X - ClientWindowData.Singleton.ScreenOrigin.X,
                                               mouseWorld.Y - ClientWindowData.Singleton.ScreenOrigin.Y);

                    spriteRectWorld = new RectangleF(mouseWorld.X - (spriteToDraw.Width / 2f),
                                                     mouseWorld.Y - (spriteToDraw.Height / 2f), spriteToDraw.Width,
                                                     spriteToDraw.Height);
                    if (pManager.CollisionManager.IsColliding(spriteRectWorld))
                    {
                        return(false);
                    }
                    //Since walls also have collisions, this means we can't place objects on walls with this mode.
                }
            }

            return(true);
        }
Ejemplo n.º 55
0
 public ITile GetTypeAt(Type type, Vector2D pos)
 {
     ITile[] tiles = GetAllTilesAt(pos);
     return(tiles.FirstOrDefault(x => x.GetType() == type));
 }
        /// <summary>
        /// 查找一个封闭的区域
        /// </summary>
        private void FindClosestLines(List <Line2D> readyLines, List <Line2D> huntLines, bool IsLargeRegion, ref List <Line2D> resultLines, Vector2D startP, Line2D nextLine = null)
        {
            List <Line2D> rpointlines = new List <Line2D>();

            //获取当前关联的所有其他线
            foreach (var item in huntLines)
            {
                Line2D matrixLine = Line2D.Create(startP, OtherPointOfLine(item, startP));
                rpointlines.Add(matrixLine);
            }

            Line2D searchline = nextLine;

            //假如需要查找的线不存在,则查询对应的线段
            if (nextLine == null)
            {
                // 查找一个最水平的线,那么这个线为从左开始,切方向向右的线段对key的角度进行降序排列,Key的Direction.Y越小,说明越水平
                searchline = (from sl in rpointlines orderby Math.Asin(sl.Direction.Y) select sl).FirstOrDefault();
            }
            else
            {
                //对key值的内容参数进行降序排列
                if (IsLargeRegion)
                {
                    searchline = (from dic in rpointlines orderby(-searchline.Direction).AngleFrom(dic.Direction) descending select dic).FirstOrDefault();
                }
                else
                {
                    searchline = (from dic in rpointlines orderby(-searchline.Direction).AngleFrom(dic.Direction) select dic).FirstOrDefault();
                }
            }


            //查找当前线中,是否已经存在,假如存在,则说明已经闭合,直接退出当前的递归操作
            if (!HasLookin(resultLines, searchline))
            {
                //闭合后,则查找线的另外一个点
                Vector2D OtherPoint = this.OtherPointOfLine(searchline, startP);

                //在当前的集合中,再查找相关联的所有的线
                List <Line2D> nhuntLiness = this.GetHuntLines(OtherPoint, readyLines, searchline);

                //没有形成闭合,但是已经找不到和当前点相关的墙体,说无法形成闭合
                if (nhuntLiness.Count > 0)
                {
                    //说明还可以继续查找
                    resultLines.Add(searchline);

                    //继续进行查找
                    this.FindClosestLines(readyLines, nhuntLiness, IsLargeRegion, ref resultLines, OtherPoint, searchline);
                }
                else
                {
                    //假如线还没有查找完成,则当前线已经没有下一个线了,说明当前线是无效的线
                    if (readyLines.Count > 0)
                    {
                        //移除这个线,并且从其他的线中,重新查找闭合的线
                        this.RemoveLine(readyLines, searchline);
                        this.RemoveLine(huntLines, searchline);

                        if (huntLines.Count > 0)
                        {
                            //移除一个捕获线,从当前结束点重新开始查找
                            this.FindClosestLines(readyLines, huntLines, IsLargeRegion, ref resultLines, startP, nextLine);
                        }
                        else
                        {
                            resultLines = null;
                            return;
                        }
                    }
                    else
                    {
                        resultLines = null;
                        return;
                    }
                }
            }
        }
Ejemplo n.º 57
0
        public override void Input()
        {
            if (!ModalActive)
            {
                return;
            }
            IInputMap inputMap = Woofer.Controller.InputManager.ActiveInputMap;

            if (Outline == null)
            {
                Outline = new EntityOutline(Owner, 0);
                Owner.Events.InvokeEvent(new BeginOverlay(Outline));
            }

            Vector2D movement = inputMap.Movement;

            if (movement.Magnitude > 1e-5 && Editor.MoveTimeframe.Execute())
            {
                if (movement.Y > 0)
                {
                    if (SelectedIndex - 1 >= -1)
                    {
                        SelectedIndex--;
                    }
                }
                else if (movement.Y < 0)
                {
                    if (SelectedIndex + 1 < Owner.Entities.Count)
                    {
                        SelectedIndex++;
                    }
                }
                if (movement.Y != 0)
                {
                    RemoveTimer = 0;
                }
            }

            if (inputMap.Jump.Consume())
            {
                if (SelectedIndex == -1)
                {
                    Owner.Events.InvokeEvent(new StartEnumSelectEvent("Add Entity", new List <string>()
                    {
                        BLANK_ENTITY, FROM_PREFABS
                    }, CreateEntity, null));
                    Owner.Events.InvokeEvent(new ForceModalChangeEvent("enum_select", null));
                    ModalActive  = false;
                    ModalVisible = false;
                }
                else
                {
                    Owner.Events.InvokeEvent(new EntitySelectEvent(Owner.Entities.ToList()[SelectedIndex], null));
                    Owner.Events.InvokeEvent(new ForceModalChangeEvent("entity_view", null));
                    ModalActive  = false;
                    ModalVisible = false;
                }
            }

            if (RemoveTimer > 0)
            {
                RemoveTimer--;
            }
            if (inputMap.Pulse.Pressed && SelectedIndex >= 0)
            {
                RemoveTimer += 2 + RemoveSpeed;
                if (RemoveTimer / 25 > 3)
                {
                    Owner.Entities.Remove(Owner.Entities.ElementAt(SelectedIndex).Id);
                    RemoveTimer = 0;
                    RemoveSpeed++;
                }
            }
            else
            {
                RemoveTimer = 0;
                RemoveSpeed = 0;
            }

            Outline.Id = 0;
            if (SelectedIndex >= 0 && SelectedIndex < Owner.Entities.Count)
            {
                Outline.Id = Owner.Entities.ToList()[SelectedIndex].Id;
            }
            if (SelectedIndex < StartOffset)
            {
                StartOffset = SelectedIndex;
            }
            if (SelectedIndex > StartOffset + AmountVisible)
            {
                StartOffset = SelectedIndex - AmountVisible;
            }
        }
Ejemplo n.º 58
0
 public ITile GetTypeAt(string type, Vector2D pos)
 {
     return(GetTypeAt(Type.GetType("ClientServices.Tiles." + type, false), pos));
 }
Ejemplo n.º 59
0
 /// <summary>
 /// Creates a new bounding box.
 /// </summary>
 /// <param name="min">Minimal coordinates.</param>
 /// <param name="max">Maximal coordinates.</param>
 public BoundingBox2D(Vector2D min, Vector2D max)
 {
     Min = min;
     Max = max;
 }
Ejemplo n.º 60
0
 public ITile[] GetAllTilesAt(Vector2D pos)
 {
     return(GetAllTilesIn(new RectangleF(pos.X, pos.Y, 2f, 2f)));
 }