Ejemplo n.º 1
0
        private static long calculateMainCableLength(Point[] locations)
        {
            long largestXCoordinate = locations.Max(location => location.X);
            long smallestXCoordinate = locations.Min(location => location.X);

            return largestXCoordinate - smallestXCoordinate;
        }
Ejemplo n.º 2
0
        public void TestMethod1()
        {
            int nBuildings = 3;

            Point[] buildings = new Point[nBuildings];

            //buildings[0] = new Point(-5,-3);
            //buildings[1] = new Point(-9, 2);
            //buildings[2] = new Point(3, -4);

            buildings[0] = new Point(1, 2);
            buildings[1] = new Point(0, 0);
            buildings[2] = new Point(2, 2);

            int widthDistance = buildings.Max(_ => _.X) - buildings.Min(_ => _.X);

            var average = buildings.Average(_ => _.Y);

            var yPos = (long) buildings.Select(p => new Tuple<int, double>(p.Y, Math.Abs(p.Y - average))).OrderBy(_ => _.Item2).First().Item1;
            var dist = buildings.Select(p => Math.Abs((p.Y - yPos))).Sum();

             var totalDistance = (long)widthDistance + dist;

            Assert.AreEqual(4,totalDistance);
        }
Ejemplo n.º 3
0
        public void Tag(T attributes, Point location, Point size)
        {
            var min      = location.Max(Point.Zero);
            var max      = (location + size).Min(MapSize);
            var drawSize = max - min;

            for (int i = 0; i < drawSize.X * drawSize.Y; i++)
            {
                var x = min.X + (i % drawSize.X);
                var y = min.Y + (i / drawSize.X);
                AttributeMap[x, y] = attributes;
            }
        }
    public void rotate()
    {
        var matrix = new Matrix();

        matrix.RotateAt(theAngle, center);
        gw.Transform = matrix;
        // Get the 4 corner points of myRect2.
        Point p1 = new Point(myRect2.X, myRect2.Y),
              p2 = new Point(myRect2.X + myRect2.Width, myRect2.Y),
              p3 = new Point(myRect2.X, myRect2.Y + myRect2.Height),
              p4 = new Point(myRect2.X + myRect2.Width, myRect2.Y + myRect2.Height);

        Point[] pts = new Point[] { p1, p2, p3, p4 };
        // Rotate the 4 points.
        gw.Transform.TransformPoints(pts);
        // Update rotatedRect2 with those rotated points.
        rotatedRect2.X      = pts.Min(pt => pt.X);
        rotatedRect2.Y      = pts.Min(pt => pt.Y);
        rotatedRect2.Width  = pts.Max(pt => pt.X) - pts.Min(pt => pt.X);
        rotatedRect2.Height = pts.Max(pt => pt.Y) - pts.Min(pt => pt.Y);
        drawstuff();
    }
Ejemplo n.º 5
0
 protected override void SetEndLocation(Point end, Keys modifiers, Point location)
 {
     if (!lastPoint)
     {
         AddPoint(end);
         lastPoint = true;
     }
     else
     {
         points [points.Count - 1] = Point.Max(Point.Empty, end);
         ApplyPoints(points);
     }
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Creates a polygon shape from the specified points.
 /// </summary>
 /// <param name="points">The points.</param>
 public Polygon(Point[] points)
 {
     // Set the location.
     this.location = points.Min();
     // Set the size.
     this.size = new Size(points.Max().Subtract(this.location));
     // Set the points.
     this.points = new Point[points.Length];
     for (int index = 0; index < points.Length; index++)
     {
         this.points[index] = points[index].Subtract(this.location);
     }
 }
Ejemplo n.º 7
0
        public void Fill(int tile, Point location, Point size)
        {
            var min      = location.Max(Point.Zero);
            var max      = (location + size).Min(MapSize);
            var drawSize = max - min;

            for (int i = 0; i < drawSize.X * drawSize.Y; i++)
            {
                var x = min.X + (i % drawSize.X);
                var y = min.Y + (i / drawSize.X);
                Map[x, y] = tile;
            }
        }
Ejemplo n.º 8
0
        public void Fill(Texture texture, Point location, Point size)
        {
            var from = location.Max(Point.Zero);
            var to   = (location + size).Min(Size);
            var area = to - from;

            for (int i = 0; i < area.X * area.Y; i++)
            {
                var x = location.X + (i % area.X);
                var y = location.Y + (i / area.X);

                Map[x, y] = new Tile(texture);
            }
        }
Ejemplo n.º 9
0
        public void DrawPath(Color color, int width, Point[] points)
        {
            // todo: handle points.Length <= 1

            var relativePoints = new Point[points.Length];

            for (int i = 0; i < relativePoints.Length; i++)
            {
                var point = points[i];
                relativePoints[i] = new Point(point.X + offset.X, point.Y + offset.Y);
            }

            if (color.IsFullyOpaque())
            {
                DrawOpaquePathGDI(color, width, relativePoints);
                return;
            }

            int minX = relativePoints.Min(p => p.X) - width;
            int minY = relativePoints.Min(p => p.Y) - width;
            int maxX = relativePoints.Max(p => p.X) + width;
            int maxY = relativePoints.Max(p => p.Y) + width;

            for (int i = 0; i < relativePoints.Length; i++)
            {
                var point = relativePoints[i];
                relativePoints[i] = new Point(point.X - minX, point.Y - minY);
            }

            WithTransparentCanvas
            (
                new Rectangle(minX, minY, maxX - minX + 1, maxY - minY + 1),
                color.A, true,
                canvas => canvas.DrawOpaquePathGDI(color, width, relativePoints)
            );
        }
Ejemplo n.º 10
0
        public void Fill(
            TileSet tileSet,
            Animation animation,
            Point location,
            Point size)
        {
            var from = location.Max(Point.Zero);
            var to   = (location + size).Min(Size);
            var area = to - from;

            animation.Loop     = true;
            animation.MaxLoops = 0;

            for (int i = 0; i < area.X * area.Y; i++)
            {
                var x = location.X + (i % area.X);
                var y = location.Y + (i / area.X);

                Map[x, y] = new Tile(tileSet, animation);
            }
        }
Ejemplo n.º 11
0
 public override void OnMouseMove(MouseEventArgs e)
 {
     if (moving)
     {
         switch (e.Buttons)
         {
         case MouseButtons.Primary:
             if (movingPoint != null)
             {
                 var updates = new List <Rectangle> ();
                 RemoveDrawing(updates);
                 this.Command.Points [movingPoint.Value] = Point.Max(Point.Empty, (Point)e.Location);
                 ApplyDrawing(updates);
                 Handler.FlushCommands(updates);
                 e.Handled = true;
             }
             break;
         }
     }
     else
     {
         base.OnMouseMove(e);
     }
 }
Ejemplo n.º 12
0
        public override void OnMouseDown(MouseEventArgs e)
        {
            switch (e.Buttons)
            {
            case MouseButtons.Primary:
                var updates = new List <Rectangle> ();
                ApplyInvertedDrawing(updates);
                point = null;
                if (Document.RipImage != null)
                {
                    var command = Document.Create <Commands.PutImage>();
                    command.Point = Point.Max(Point.Empty, (Point)e.Location);
                    Handler.AddCommand(command, updates);
                }
                Handler.FlushCommands(updates);

                e.Handled = true;
                break;

            default:
                base.OnMouseDown(e);
                break;
            }
        }
Ejemplo n.º 13
0
        private IEnumerable<Shape> _addSeriesAsPolyline(Point[] points, Brush color, double storkeThickness,
            bool animate = true)
        {
            if (points.Length < 2) return Enumerable.Empty<Shape>();
            var addedFigures = new List<Shape>();

            var l = 0d;
            for (var i = 1; i < points.Length; i++)
            {
                var p1 = points[i - 1];
                var p2 = points[i];
                l += Math.Sqrt(
                    Math.Pow(Math.Abs(p1.X - p2.X), 2) +
                    Math.Pow(Math.Abs(p1.Y - p2.Y), 2)
                    );
            }

            var f = points.First();
            var p = points.Where(x => x != f);
            var g = new PathGeometry
            {
                Figures = new PathFigureCollection(new List<PathFigure>
                {
                    new PathFigure
                    {
                        StartPoint = f,
                        Segments = new PathSegmentCollection(
                            p.Select(x => new LineSegment {Point = new Point(x.X, x.Y)}))
                    }
                })
            };

            var path = new Path
            {
                Stroke = color,
                StrokeThickness = storkeThickness,
                Data = g,
                StrokeEndLineCap = PenLineCap.Round,
                StrokeStartLineCap = PenLineCap.Round,
                StrokeDashOffset = l,
                StrokeDashArray = new DoubleCollection { l, l },
                ClipToBounds = true
            };

            var sp = points.ToList();
            sp.Add(new Point(points.Max(x => x.X), ToPlotArea(Chart.Min.Y, AxisTags.Y)));

            Chart.Canvas.Children.Add(path);
            addedFigures.Add(path);

            var draw = new DoubleAnimationUsingKeyFrames
            {
                BeginTime = TimeSpan.FromSeconds(0),
                KeyFrames = new DoubleKeyFrameCollection
                {
                    new SplineDoubleKeyFrame
                    {
                        KeyTime = TimeSpan.FromMilliseconds(1),
                        Value = l
                    },
                    new SplineDoubleKeyFrame
                    {
                        KeyTime = TimeSpan.FromMilliseconds(750),
                        Value = 0
                    }
                }
            };
            Storyboard.SetTarget(draw, path);
            Storyboard.SetTargetProperty(draw, new PropertyPath(Shape.StrokeDashOffsetProperty));
            var sbDraw = new Storyboard();
            sbDraw.Children.Add(draw);
            var animated = false;
            if (!Chart.DisableAnimation)
            {
                if (animate)
                {
                    sbDraw.Begin();
                    animated = true;
                }
            }
            if (!animated) path.StrokeDashOffset = 0;
            return addedFigures;
        }
Ejemplo n.º 14
0
		private IEnumerable<Shape> _addSerieAsBezier(Point[] points, bool animate = true)
		{
            if (points.Length < 2) return Enumerable.Empty<Shape>();
			var addedFigures = new List<Shape>();

			Point[] cp1, cp2;
			BezierSpline.GetCurveControlPoints(points, out cp1, out cp2);

			var lines = new PathSegmentCollection();
			var areaLines = new PathSegmentCollection {new LineSegment(points[0], true)};
			var l = 0d;
			for (var i = 0; i < cp1.Length; ++i)
			{
				lines.Add(new BezierSegment(cp1[i], cp2[i], points[i + 1], true));
				areaLines.Add(new BezierSegment(cp1[i], cp2[i], points[i + 1], true));
				//it would be awesome to use a better formula to calculate bezier lenght
				l += Math.Sqrt(
				               Math.Pow(Math.Abs(cp1[i].X - cp2[i].X), 2) +
				               Math.Pow(Math.Abs(cp1[i].Y - cp2[i].Y), 2));
				l += Math.Sqrt(
				               Math.Pow(Math.Abs(cp2[i].X - points[i + 1].X), 2) +
				               Math.Pow(Math.Abs(cp2[i].Y - points[i + 1].Y), 2));
			}
			//aprox factor, it was calculated by aproximation.
			//the more line is curved, the more it fails.
			l = l * .65;
			areaLines.Add(new LineSegment(new Point(points.Max(x => x.X), ToPlotArea(Chart.Min.Y, AxisTags.Y)), true));
			var f = new PathFigure(points[0], lines, false);
			var fa = new PathFigure(new Point(points.Min(x => x.X), ToPlotArea(Chart.Min.Y, AxisTags.Y)), areaLines, false);
			var g = new PathGeometry(new[] {f});
			var ga = new PathGeometry(new[] {fa});

		    var path = new Path
		    {
		        Stroke = Stroke,
		        StrokeThickness = StrokeThickness,
		        Data = g,
		        StrokeEndLineCap = PenLineCap.Round,
		        StrokeStartLineCap = PenLineCap.Round,
		        StrokeDashOffset = l,
		        StrokeDashArray = new DoubleCollection {l, l},
		        ClipToBounds = true
		    };
		    var patha = new Path
		    {
		        StrokeThickness = 0,
		        Data = ga,
		        Fill = Fill,
		        ClipToBounds = true
		    };

			Chart.Canvas.Children.Add(path);
			addedFigures.Add(path);
            
		    Chart.Canvas.Children.Add(patha);
		    addedFigures.Add(patha);

		    var draw = new DoubleAnimationUsingKeyFrames
		    {
		        BeginTime = TimeSpan.FromSeconds(0),
		        KeyFrames = new DoubleKeyFrameCollection
		        {
		            new SplineDoubleKeyFrame
		            {
		                KeyTime = TimeSpan.FromMilliseconds(1),
		                Value = l
		            },
		            new SplineDoubleKeyFrame
		            {
		                KeyTime = TimeSpan.FromMilliseconds(750),
		                Value = 0
		            }
		        }
		    };

			Storyboard.SetTarget(draw, path);
			Storyboard.SetTargetProperty(draw, new PropertyPath(Shape.StrokeDashOffsetProperty));
			var sbDraw = new Storyboard();
			sbDraw.Children.Add(draw);
			var animated = false;
			if (!Chart.DisableAnimation)
			{
				if (animate)
				{
					sbDraw.Begin();
					animated = true;
				}
			}
			if (!animated) path.StrokeDashOffset = 0;
			return addedFigures;
		}
Ejemplo n.º 15
0
 protected override void SetPosition(Rectangle rect)
 {
     rect.TopLeft           = Point.Max(Point.Empty, rect.TopLeft);
     rect.InnerBottomRight  = Point.Max(Point.Empty, rect.InnerBottomRight);
     this.Command.Rectangle = rect;
 }
Ejemplo n.º 16
0
        private void captureImageGrabberEvent(object sender, EventArgs e)
        {
            try
            {
                Mat m = new Mat();
                videoCapture.Retrieve(m);

                imgInput = m.ToImage <Bgr, Byte>();
                var imgGray = imgInput.Convert <Gray, byte>().Clone(); //Конвертируем в оттенки серого

                imgGray._EqualizeHist();                               // выравниваем ярксоть (только для черно-белого изображения)

                //imgGray.SmoothGaussian(4);
                imgGray._SmoothGaussian(1);                                                                                                           //гауусовский фильтр

                VectorOfRect faces = new VectorOfRect(faceFrontalDetector.DetectMultiScale(imgGray, 1.1, 3, new Size(100, 100), new Size(300, 300))); //находим все лица
                if (faces.Size > 0)
                {
                    Rectangle[] facesRect = faces.ToArray();// приводим вектор к фигуре
                    //facesRect[0]

                    Array.Sort(facesRect, new Comparison <Rectangle>(CompareShapes));  //сортировка по высоте

                    VectorOfVectorOfPointF landmarks = new VectorOfVectorOfPointF();

                    bool success = facemark.Fit(imgGray, faces, landmarks);//находим точки лица


                    double k = (double)faces[0].Width / imgGray.Width;

                    double s = (matrixCam * avarageFaceSize) / k;


                    PointF[] h = landmarks[0].ToArray();//преобразовываем в массив точек

                    //var point = h.Select(p => new Point(Convert.ToInt32(p.X), Convert.ToInt32(p.Y)));

                    Point[] rightEye = new Point[6];
                    rightEye[0].X = Convert.ToInt32(Math.Round(h[36].X));
                    rightEye[0].Y = Convert.ToInt32(Math.Round(h[36].Y));
                    rightEye[1].X = Convert.ToInt32(Math.Round(h[37].X));
                    rightEye[1].Y = Convert.ToInt32(Math.Round(h[37].Y));
                    rightEye[2].X = Convert.ToInt32(Math.Round(h[38].X));
                    rightEye[2].Y = Convert.ToInt32(Math.Round(h[38].Y));
                    rightEye[3].X = Convert.ToInt32(Math.Round(h[39].X));
                    rightEye[3].Y = Convert.ToInt32(Math.Round(h[39].Y));
                    rightEye[4].X = Convert.ToInt32(Math.Round(h[40].X));
                    rightEye[4].Y = Convert.ToInt32(Math.Round(h[40].Y));
                    rightEye[5].X = Convert.ToInt32(Math.Round(h[41].X));
                    rightEye[5].Y = Convert.ToInt32(Math.Round(h[41].Y));

                    var rightEyeMinimalPoint = rightEye.First(x => x.Y == rightEye.Max(y => y.Y));
                    var rightEyeMaximalPoint = rightEye.First(x => x.Y == rightEye.Min(y => y.Y));

                    Point[] leftEye = new Point[6];
                    leftEye[0].X = Convert.ToInt32(Math.Round(h[42].X));
                    leftEye[0].Y = Convert.ToInt32(Math.Round(h[42].Y));
                    leftEye[1].X = Convert.ToInt32(Math.Round(h[43].X));
                    leftEye[1].Y = Convert.ToInt32(Math.Round(h[43].Y));
                    leftEye[2].X = Convert.ToInt32(Math.Round(h[44].X));
                    leftEye[2].Y = Convert.ToInt32(Math.Round(h[44].Y));
                    leftEye[3].X = Convert.ToInt32(Math.Round(h[45].X));
                    leftEye[3].Y = Convert.ToInt32(Math.Round(h[45].Y));
                    leftEye[4].X = Convert.ToInt32(Math.Round(h[46].X));
                    leftEye[4].Y = Convert.ToInt32(Math.Round(h[46].Y));
                    leftEye[5].X = Convert.ToInt32(Math.Round(h[47].X));
                    leftEye[5].Y = Convert.ToInt32(Math.Round(h[47].Y));

                    var leftEyeMinimalPoint = leftEye.First(x => x.Y == leftEye.Max(y => y.Y));
                    var leftEyeMaximalPoint = leftEye.First(x => x.Y == leftEye.Min(y => y.Y));


                    imgInput.DrawPolyline(leftEye, true, new Bgr(Color.Blue), 1);
                    imgInput.DrawPolyline(rightEye, true, new Bgr(Color.Blue), 1);


                    ////for (int i = 0; i < h.Length; ++i)
                    ////{
                    ////    mas[i].X = Convert.ToInt32(Math.Round(h[i].X));
                    ////    mas[i].Y = Convert.ToInt32(Math.Round(h[i].Y));
                    ////}



                    //imgInput.Draw(h[37], new Bgr(Color.Blue), 2);


                    //imgInput.Draw(new CircleF(mas[41], 10), new Bgr(Color.Gray), 1);


                    //imgInput.DrawPolyline(mas, true, new Bgr(Color.Blue), 2);

                    //////if (success)
                    //////{
                    //////    facesRect = faces.ToArray();
                    //////    for (int i = 0; i < facesRect.Length; i++)
                    //////    {
                    //////        imgInput.Draw(facesRect[0], new Bgr(Color.Blue), 2);
                    //////        FaceInvoke.DrawFacemarks(imgInput, landmarks[i], new Bgr(Color.Blue).MCvScalar);

                    //////    }
                    //////    //return imgInput;
                    //////}
                    //return null;

                    //int cropHeight = (int)Math.Round(facesRect[0].Height * 0.5, 0);

                    //Rectangle eyesAreaRec = new Rectangle(facesRect[0].X, (int)Math.Round(facesRect[0].Y * 1.4), facesRect[0].Width, cropHeight);


                    //for (int i = 0; i < facesRect.Length; i++)
                    //{
                    //    imgInput.Draw(facesRect[0], new Bgr(Color.Blue), 2);
                    //    //FaceInvoke.DrawFacemarks(imgInput, landmarks[i], new Bgr(Color.Blue).MCvScalar);

                    //}

                    //imgInput.Draw(eyesAreaRec, new Bgr(Color.Blue), 2);

                    Invoke(new Action(() =>
                    {
                        if (faces.Size > 0)
                        {
                            faceSizePixelEdit.Text   = faces[0].Size.Height.ToString();
                            camLengthEdit.Text       = s.ToString();
                            arcScaleComponent1.Value = faces[0].Size.Height;

                            if (rightEyeMaximalPoint.Y > 0 && rightEyeMinimalPoint.Y > 0)
                            {
                                rightEyeEdit.Text = Convert.ToString(rightEyeMinimalPoint.Y - rightEyeMaximalPoint.Y);
                            }
                        }
                    }));
                    //faceSizePixelEdit.Text = Convert.ToString(k);
                    //Writelabel(0);
                    generalBox.Image = imgInput;
                }
                else if (faces.Size == 0)
                {
                    //faces = new VectorOfRect(faceProfilDetector.DetectMultiScale(imgGray));
                    generalBox.Image = imgInput;
                }



                //VectorOfRect faces = new VectorOfRect(faceDetector.DetectMultiScale(grayImage));
                //VectorOfVectorOfPointF landmarks = new VectorOfVectorOfPointF();


                //bool success = facemark.Fit(grayImage, faces, landmarks);
                //PointF[][] f = landmarks.ToArrayOfArray();
                //if (success)
                //{
                //    Rectangle[] facesRect = faces.ToArray();
                //    for (int i = 0; i < facesRect.Length; i++)
                //    {
                //        imgInput.Draw(facesRect[0], new Bgr(Color.Blue), 2);
                //        FaceInvoke.DrawFacemarks(imgInput, landmarks[i], new Bgr(Color.Blue).MCvScalar);

                //    }
                //    return imgInput;
                //}
                //return null;

                //if (faces.Length > 0)
                //    faceSizePixelEdit.Text = Convert.ToString(faces[0].Size.Height * faces[0].Size.Width);
                //faceSizePixelEdit.Text = faces[0].Size.Height.ToString();
                //videoCapture.Pause();

                //videoCapture.Start();
                //////var imgGray = imgInput.Convert<Gray, byte>().Clone();
                //////Rectangle[] faces = classifierFace.DetectMultiScale(imgGray, 1.1, 4);
                //////foreach (var face in faces)
                //////{
                //////    imgInput.Draw(face, new Bgr(0, 0, 255), 2);

                //////    imgGray.ROI = face;
                //////    Rectangle[] eyes = classifierEye.DetectMultiScale(imgGray, 1.1, 4);
                //////    foreach (var eye in eyes)
                //////    {
                //////        var ec = eye;
                //////        ec.X += face.X;
                //////        ec.Y += face.Y;
                //////        imgInput.Draw(ec, new Bgr(0, 255, 0), 2);
                //////    }
                //////}


                Thread.Sleep(1);

                //imageInput =
                //pictureBox1.Image = m.ToImage<Bgr, byte>().Bitmap;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.InnerException.Message);
            }
        }
Ejemplo n.º 17
0
 protected override void SetEndLocation(Point end, Keys modifiers, Point location)
 {
     this.Command.End = Point.Max(Point.Empty, end);
 }
Ejemplo n.º 18
0
        private void imageGraberCapture(object sender, EventArgs e)
        {
            try
            {
                #region Получение кадра и массива лиц

                Mat m = new Mat();

                videoCapture.Retrieve(m);
                Image <Bgr, Byte> inputImage = m.ToImage <Bgr, Byte>();
                var imgGray = inputImage.Convert <Gray, Byte>().Clone();                                                           //Конвертируем в оттенки серого
                imgGray._EqualizeHist();                                                                                           //выравниваем яркость
                imgGray._SmoothGaussian(1);                                                                                        //убираем шумы

                VectorOfRect faces = new VectorOfRect(faceFrontalDetector.DetectMultiScale(imgGray, 1.05, 5, new Size(120, 120))); //находим все лица

                #endregion



                if (faces.Size > 0)
                {
                    Rectangle[] facesRect = faces.ToArray(); // приводим вектор к фигуре

                    facesRect.OrderBy(ob => ob.Height);      //сортировка по высоте

                    VectorOfVectorOfPointF landmarks = new VectorOfVectorOfPointF();

                    bool success = facemark.Fit(imgGray, faces, landmarks); //находим точки лица


                    #region Анализ расстояния до пользователя

                    double k = ((double)faces[0].Height) / imgGray.Height;

                    currentDistance = (2.5 * avarageFaceSize) / k;

                    #endregion

                    #region Анализ яркости

                    imageBrightList = FrameBright(imgGray.Clone(), facesRect[0]);

                    if ((imageBrightList[1] - imageBrightList[0]) > 55)
                    {
                        currentBright = 10;
                    }
                    else if ((imageBrightList[1] - imageBrightList[0]) > 45 && (imageBrightList[1] - imageBrightList[0]) < 55)
                    {
                        currentBright = 20;
                    }
                    else if ((imageBrightList[1] - imageBrightList[0]) > 35 && (imageBrightList[1] - imageBrightList[0]) < 45)
                    {
                        currentBright = 35;
                    }
                    else if ((imageBrightList[1] - imageBrightList[0]) > 25 && (imageBrightList[1] - imageBrightList[0]) < 35)
                    {
                        currentBright = 50;
                    }
                    else if ((imageBrightList[1] - imageBrightList[0]) > 15 && (imageBrightList[1] - imageBrightList[0]) < 25)
                    {
                        currentBright = 70;
                    }
                    else if ((imageBrightList[1] - imageBrightList[0]) > 10 && (imageBrightList[1] - imageBrightList[0]) < 15)
                    {
                        currentBright = 85;
                    }
                    else if ((imageBrightList[1] - imageBrightList[0]) > 5 && (imageBrightList[1] - imageBrightList[0]) < 10)
                    {
                        currentBright = 95;
                    }

                    //currentBright = (int)(((100.0/255)*imageBrightList[0]) + 0.5);

                    #endregion


                    #region Глазной анализатор

                    PointF[] h = landmarks[0].ToArray();//преобразовываем в массив точек

                    Point[] rightEye = new Point[6];
                    rightEye[0].X = Convert.ToInt32(Math.Round(h[36].X));
                    rightEye[0].Y = Convert.ToInt32(Math.Round(h[36].Y));
                    rightEye[1].X = Convert.ToInt32(Math.Round(h[37].X));
                    rightEye[1].Y = Convert.ToInt32(Math.Round(h[37].Y));
                    rightEye[2].X = Convert.ToInt32(Math.Round(h[38].X));
                    rightEye[2].Y = Convert.ToInt32(Math.Round(h[38].Y));
                    rightEye[3].X = Convert.ToInt32(Math.Round(h[39].X));
                    rightEye[3].Y = Convert.ToInt32(Math.Round(h[39].Y));
                    rightEye[4].X = Convert.ToInt32(Math.Round(h[40].X));
                    rightEye[4].Y = Convert.ToInt32(Math.Round(h[40].Y));
                    rightEye[5].X = Convert.ToInt32(Math.Round(h[41].X));
                    rightEye[5].Y = Convert.ToInt32(Math.Round(h[41].Y));

                    var rightEyeMinimalPoint = rightEye.First(x => x.Y == rightEye.Max(y => y.Y));
                    var rightEyeMaximalPoint = rightEye.First(x => x.Y == rightEye.Min(y => y.Y));

                    Point[] leftEye = new Point[6];
                    leftEye[0].X = Convert.ToInt32(Math.Round(h[42].X));
                    leftEye[0].Y = Convert.ToInt32(Math.Round(h[42].Y));
                    leftEye[1].X = Convert.ToInt32(Math.Round(h[43].X));
                    leftEye[1].Y = Convert.ToInt32(Math.Round(h[43].Y));
                    leftEye[2].X = Convert.ToInt32(Math.Round(h[44].X));
                    leftEye[2].Y = Convert.ToInt32(Math.Round(h[44].Y));
                    leftEye[3].X = Convert.ToInt32(Math.Round(h[45].X));
                    leftEye[3].Y = Convert.ToInt32(Math.Round(h[45].Y));
                    leftEye[4].X = Convert.ToInt32(Math.Round(h[46].X));
                    leftEye[4].Y = Convert.ToInt32(Math.Round(h[46].Y));
                    leftEye[5].X = Convert.ToInt32(Math.Round(h[47].X));
                    leftEye[5].Y = Convert.ToInt32(Math.Round(h[47].Y));

                    var leftEyeMinimalPoint = leftEye.First(x => x.Y == leftEye.Max(y => y.Y));
                    var leftEyeMaximalPoint = leftEye.First(x => x.Y == leftEye.Min(y => y.Y));



                    if (rightEyeMaximalPoint.Y > 0 && rightEyeMinimalPoint.Y > 0 && leftEyeMaximalPoint.Y > 0 && leftEyeMinimalPoint.Y > 0)
                    {
                        double bufer;


                        inputImage.DrawPolyline(leftEye, true, new Bgr(Color.Red), 2);
                        inputImage.DrawPolyline(rightEye, true, new Bgr(Color.Red), 2);

                        bufer = rightEyeMinimalPoint.Y - rightEyeMaximalPoint.Y;

                        double kk = ((double)bufer) / imgGray.Height;

                        curentRightEye = (currentDistance * kk) / 2.5; //в сантиметрах



                        if (curentRightEye > heightOpenRightEye)
                        {
                            curentRightEye = heightOpenRightEye;
                        }
                        else if (curentRightEye < heightCloseRightEye * chit)
                        {
                            curentRightEye = heightCloseRightEye;
                            blink++;
                            clipCounter++;
                        }



                        curentLeftEye = curentRightEye;
                    }
                    else
                    {
                        curentLeftEye  = heightCloseRightEye;
                        curentRightEye = heightCloseRightEye;
                    }


                    double?buffer = ((100 / (heightOpenLeftEye - heightCloseLeftEye)) * (curentRightEye - heightCloseLeftEye));

                    #endregion

                    Invoke(new Action(() =>
                    {
                        if (faces.Size > 0)
                        {
                            //brightGaugComponent.Value = (float)60;
                            distanceGaugComponent.Value = (float)currentDistance;

                            //график света
                            linearScaleMarkerComponent3.Value   = (float)currentBright;
                            linearScaleRangeBarComponent2.Value = (float)currentBright;

                            //lengthEdit.Text = test.ToString();
                            //faceSizeEdit.Text = curentRightEye.ToString();

                            //график глаза
                            linearScaleRangeBarComponent3.Value = (float)buffer;
                            linearScaleMarkerComponent4.Value   = (float)buffer;
                            //linearScaleRangeBarComponent1.Value = 60;
                        }
                    }));

                    inputImage.Draw(faces[0], new Bgr(Color.Green), 1);

                    generalTabBox.Image = inputImage;
                }
                else if (faces.Size == 0)
                {
                    //faces = new VectorOfRect(faceProfilDetector.DetectMultiScale(imgGray));
                    generalTabBox.Image = inputImage;
                }

                Thread.Sleep(1);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.InnerException.Message);
            }
        }
Ejemplo n.º 19
0
        private void MoveVertices()
        {
            if (_visualizationAlgorithm != VisualizationAlgorithm.ChargesAndSprings)
            {
                return;
            }

            _animationTimer.Stop();

            if (!IsAnimationSuspended)
            {
                var coordsDeltas = new Point[_vertices.Count];

                // Считаем действующие на вершины силы
                for (var i = 0; i < _vertices.Count; ++i)
                {
                    var vi     = _vertices[i];
                    var fx     = 0.0;
                    var fy     = 0.0;
                    var deltaI = new Point(0.0, 0.0);
                    for (var j = 0; j < _vertices.Count; ++j)
                    {
                        if (j == i)
                        {
                            continue;
                        }
                        var vj = _vertices[j];

                        var distanceIj = Distance(vi, vj);

                        var ex = (vi.ModelX - vj.ModelX) / distanceIj;
                        var ey = (vi.ModelY - vj.ModelY) / distanceIj;
                        fx += G * ex / Math.Pow(distanceIj, 2);
                        fy += G * ey / Math.Pow(distanceIj, 2);

                        if (this[vi, vj] != null || this[vj, vi] != null)
                        {
                            fx -= K * (distanceIj - L) * ex;
                            fy -= K * (distanceIj - L) * ey;
                        }
                        else
                        {
                            fx -= K * (distanceIj - L) * ex / 2;
                            fy -= K * (distanceIj - L) * ey / 2;
                        }

                        deltaI.X += fx * TICK_INTERVAL;
                        deltaI.Y += fy * TICK_INTERVAL;
                    }
                    coordsDeltas[i] = deltaI;
                }

                var newPositions = new Point[_vertices.Count];
                for (var i = 0; i < _vertices.Count; ++i)
                {
                    var vi     = _vertices[i];
                    var deltaI = coordsDeltas[i];
                    newPositions[i].X = vi.ModelX + deltaI.X;
                    newPositions[i].Y = vi.ModelY + deltaI.Y;
                }

                var scaleFactor = GetScaleFactor();

                // Подравниваем, чтобы картинка оставалась в центре
                var minX = newPositions.Min(p => p.X) * scaleFactor;
                var minY = newPositions.Min(p => p.Y) * scaleFactor;
                var maxX = newPositions.Max(p => p.X) * scaleFactor;
                var maxY = newPositions.Max(p => p.Y) * scaleFactor;

                var graphCenter  = new Point((maxX + minX) / 2, (maxY + minY) / 2);
                var layoutCenter = new Point(LayoutRoot.ActualWidth / 2, LayoutRoot.ActualHeight / 2);

                var deltaX = layoutCenter.X - graphCenter.X;
                var deltaY = layoutCenter.Y - graphCenter.Y;

                for (var i = 0; i < newPositions.Length; ++i)
                {
                    newPositions[i].X += deltaX / scaleFactor;
                    newPositions[i].Y += deltaY / scaleFactor;
                }

                // Запускаем анимацию
                for (var i = 0; i < _vertices.Count; ++i)
                {
                    var vi = _vertices[i];
                    if (vi.Equals(CapturedVertex))
                    {
                        continue;
                    }
                    var targetPositionI = newPositions[i];

                    var xiAnimation = SilverlightHelper
                                      .GetStoryboard(vi, "ModelX", targetPositionI.X, ANIMATION_INTERVAL, null);
                    var yiAnimation = SilverlightHelper
                                      .GetStoryboard(vi, "ModelY", targetPositionI.Y, ANIMATION_INTERVAL, null);
                    var scaleAnimation = SilverlightHelper
                                         .GetStoryboard(vi, "ScaleFactor", scaleFactor, ANIMATION_INTERVAL, null);

                    xiAnimation.Begin();
                    yiAnimation.Begin();
                    scaleAnimation.Begin();
                }
            }
            _animationTimer.Start();
        }
Ejemplo n.º 20
0
 protected override void SetPosition(Rectangle rect)
 {
     Command.Point  = Point.Max(Point.Empty, rect.Center);
     Command.Radius = rect.Size / 2;
 }
Ejemplo n.º 21
0
        private void rebuildSwapchain()
        {
            var sCaps = VkKhr.PhysicalDeviceExtensions.GetSurfaceCapabilitiesKhr(_vkPhysicalDevice, Surface);

            // Calculate the size of the images
            if (sCaps.CurrentExtent.Width != Int32.MaxValue)             // We have to use the given size
            {
                Extent = sCaps.CurrentExtent;
            }
            else             // We can choose an extent, but we will just make it the size of the window
            {
                Extent = Point.Max(sCaps.MinImageExtent, Point.Min(sCaps.MaxImageExtent, _window.Size));
            }

            // Calculate the number of images
            int imCount = sCaps.MinImageCount + 1;

            if (sCaps.MaxImageCount != 0)
            {
                imCount = Math.Min(imCount, sCaps.MaxImageCount);
            }
            _syncObjects.MaxInflightFrames = (uint)Math.Min(imCount, MAX_INFLIGHT_FRAMES);

            // Create the swapchain
            var oldSwapChain = _swapChain;

            VkKhr.SwapchainCreateInfoKhr cInfo = new VkKhr.SwapchainCreateInfoKhr(
                Surface,
                _surfaceFormat.Format,
                Extent,
                minImageCount: imCount,
                imageColorSpace: _surfaceFormat.ColorSpace,
                imageUsage: Vk.ImageUsages.ColorAttachment | Vk.ImageUsages.TransferDst,
                presentMode: _presentMode,
                oldSwapchain: oldSwapChain
                );
            _swapChain = VkKhr.DeviceExtensions.CreateSwapchainKhr(_vkDevice, cInfo);

            // Destroy the old swapchain
            oldSwapChain?.Dispose();

            // Get the new swapchain images
            var imgs = _swapChain.GetImages();

            _swapChainImages = new SwapchainImage[imgs.Length];
            imgs.ForEach((img, idx) => {
                Vk.ImageViewCreateInfo vInfo = new Vk.ImageViewCreateInfo(
                    _surfaceFormat.Format,
                    DEFAULT_SUBRESOURCE_RANGE,
                    viewType: Vk.ImageViewType.Image2D,
                    components: default
                    );
                var view = img.CreateView(vInfo);
                _swapChainImages[idx] = new SwapchainImage {
                    Image           = img, View = view,
                    TransferBarrier = new Vk.ImageMemoryBarrier(
                        img,
                        new Vk.ImageSubresourceRange(Vk.ImageAspects.Color, 0, 1, 0, 1),
                        Vk.Accesses.ColorAttachmentRead,
                        Vk.Accesses.TransferWrite,
                        Vk.ImageLayout.PresentSrcKhr,
                        Vk.ImageLayout.TransferDstOptimal
                        ),
                    PresentBarrier = new Vk.ImageMemoryBarrier(
                        img,
                        new Vk.ImageSubresourceRange(Vk.ImageAspects.Color, 0, 1, 0, 1),
                        Vk.Accesses.TransferWrite,
                        Vk.Accesses.ColorAttachmentRead,
                        Vk.ImageLayout.TransferDstOptimal,
                        Vk.ImageLayout.PresentSrcKhr
                        )
                };
            });

            // Perform the initial layout transitions to present mode
            _commandBuffer.Begin(ONE_TIME_SUBMIT);
            var imb = new Vk.ImageMemoryBarrier(null, new Vk.ImageSubresourceRange(Vk.ImageAspects.Color, 0, 1, 0, 1),
                                                Vk.Accesses.TransferWrite, Vk.Accesses.ColorAttachmentRead, Vk.ImageLayout.Undefined, Vk.ImageLayout.PresentSrcKhr);

            _commandBuffer.CmdPipelineBarrier(Vk.PipelineStages.AllCommands, Vk.PipelineStages.AllCommands,
                                              imageMemoryBarriers: _swapChainImages.Select(sci => { imb.Image = sci.Image; return(imb); }).ToArray());
            _commandBuffer.End();
            _presentQueue.Submit(new Vk.SubmitInfo(commandBuffers: new[] { _commandBuffer }), _blitFence);
            _blitFence.Wait();             // Do not reset

            // Report
            LDEBUG($"Presentation swapchain rebuilt @ {Extent} " +
                   $"(F:{_surfaceFormat.Format}:{_surfaceFormat.ColorSpace==VkKhr.ColorSpaceKhr.SRgbNonlinear} I:{_swapChainImages.Length}:{_syncObjects.MaxInflightFrames}).");
            Dirty = false;
        }
Ejemplo n.º 22
0
        private static double BuildTerrainSprtRadius(Point[] points)
        {
            // Get the average min distance between the points
            List<Tuple<int, int, double>> distances = new List<Tuple<int, int, double>>();

            for (int outer = 0; outer < points.Length - 1; outer++)
            {
                for (int inner = outer + 1; inner < points.Length; inner++)
                {
                    double distance = (points[outer] - points[inner]).LengthSquared;

                    distances.Add(Tuple.Create(outer, inner, distance));
                }
            }

            double avgDist;
            if (distances.Count == 0)
            {
                avgDist = points[0].ToVector().Length;
                if (Math1D.IsNearZero(avgDist))
                {
                    avgDist = .1;
                }
            }
            else
            {
                avgDist = Enumerable.Range(0, points.Length).
                    Select(o => distances.
                        Where(p => p.Item1 == o || p.Item2 == o).       // get the disances that mention this index
                        Min(p => p.Item3)).     // only keep the smallest of those distances
                    Average();      // get the average of all the mins

                avgDist = Math.Sqrt(avgDist);
            }

            // Get the distance of the farthest out neuron
            double maxDist = points.Max(o => o.ToVector().LengthSquared);
            maxDist = Math.Sqrt(maxDist);

            // Radius of the extra points will be the avg distance beyond that max
            return maxDist + avgDist;
        }
Ejemplo n.º 23
0
 public void MaxReturnsTheMaximumOfTwoPoints(
     double expectedRow, double expectedColumn, double rowA, double columnA, double rowB, double columnB)
 {
     Assert.Equal(new Point(expectedRow, expectedColumn), Point.Max(new Point(rowA, columnA), new Point(rowB, columnB)));
 }
Ejemplo n.º 24
0
 void AddPoint(Point point)
 {
     points.Add(Point.Max(Point.Empty, point));
     ApplyPoints(points);
 }
Ejemplo n.º 25
0
        public void SetSelectionCenter(Point e)
        {
            var r = new Rectangle();
            var s = this.CurrentSelectionLocation;
            var w = s.Width / 2;
            var h = s.Height / 2;
            var p = e.Max(new Point(w, h)).Min(new Point(this.CurrentCanvasSize.X - w, this.CurrentCanvasSize.Y - h));

            r.Left = p.X - w;
            r.Top = p.Y - h;
            r.Width = s.Width;
            r.Height = s.Height;

            SetSelectionLocation(r);

            if (SelectionCenterChanged != null)
                SelectionCenterChanged(p);
        }
Ejemplo n.º 26
0
        public static void CustomizeMultiPolygon(this IFixture fixture)
        {
            fixture.Customize <Polygon>(customization =>
                                        customization.FromFactory(generator =>
            {
                var polygonCount = generator.Next(1, 4);
                var polygons     = new NetTopologySuite.Geometries.Polygon[polygonCount];
                for (var polygonIndex = 0; polygonIndex < polygonCount; polygonIndex++)
                {
                    var offsetX = 10.0 * polygonIndex;
                    var offsetY = 10.0 * polygonIndex;

                    var shell = new NetTopologySuite.Geometries.LinearRing(
                        new []
                    {
                        new NetTopologySuite.Geometries.Point(offsetX, offsetY).Coordinate,
                        new NetTopologySuite.Geometries.Point(offsetX, offsetY + 5.0).Coordinate,
                        new NetTopologySuite.Geometries.Point(offsetX + 5.0, offsetY + 5.0).Coordinate,
                        new NetTopologySuite.Geometries.Point(offsetX + 5.0, offsetY).Coordinate,
                        new NetTopologySuite.Geometries.Point(offsetX, offsetY).Coordinate
                    });

                    var holes = new[]     // points are enumerated counter clock wise
                    {
                        new NetTopologySuite.Geometries.LinearRing(
                            new[]
                        {
                            new NetTopologySuite.Geometries.Point(offsetX + 1.0, offsetY + 2.0).Coordinate,
                            new NetTopologySuite.Geometries.Point(offsetX + 2.0, offsetY + 2.0).Coordinate,
                            new NetTopologySuite.Geometries.Point(offsetX + 2.0, offsetY + 3.0).Coordinate,
                            new NetTopologySuite.Geometries.Point(offsetX + 1.0, offsetY + 3.0).Coordinate,
                            new NetTopologySuite.Geometries.Point(offsetX + 1.0, offsetY + 2.0).Coordinate
                        }),
                        new NetTopologySuite.Geometries.LinearRing(
                            new[]
                        {
                            new NetTopologySuite.Geometries.Point(offsetX + 3.0, offsetY + 1.0).Coordinate,
                            new NetTopologySuite.Geometries.Point(offsetX + 4.0, offsetY + 1.0).Coordinate,
                            new NetTopologySuite.Geometries.Point(offsetX + 4.0, offsetY + 2.0).Coordinate,
                            new NetTopologySuite.Geometries.Point(offsetX + 3.0, offsetY + 2.0).Coordinate,
                            new NetTopologySuite.Geometries.Point(offsetX + 3.0, offsetY + 1.0).Coordinate
                        })
                    };
                    polygons[polygonIndex] = new NetTopologySuite.Geometries.Polygon(shell, holes);
                }

                var linearRings = polygons
                                  .SelectMany(polygon => new[] { polygon.Shell }.Concat(polygon.Holes))
                                  .ToArray();
                var parts  = new int[linearRings.Length];
                var points = new Point[polygons.Sum(polygon => polygon.Shell.NumPoints + polygon.Holes.Sum(hole => hole.NumPoints))];
                var offset = 0;
                for (var ringIndex = 0; ringIndex < linearRings.Length; ringIndex++)
                {
                    var linearRing   = linearRings[ringIndex];
                    parts[ringIndex] = offset;
                    for (var pointIndex = 0; pointIndex < linearRing.NumPoints; pointIndex++)
                    {
                        var point = linearRing.GetPointN(pointIndex);
                        points[offset + pointIndex] = new Point(point.X, point.Y);
                    }
                    offset += linearRing.NumPoints;
                }

                var boundingBox = new BoundingBox2D(
                    points.Min(p => p.X),
                    points.Min(p => p.Y),
                    points.Max(p => p.X),
                    points.Max(p => p.Y)
                    );
                return(new Polygon(boundingBox, parts, points));
            }).OmitAutoProperties()
                                        );
        }
Ejemplo n.º 27
0
        public static Bitmap ToBitmap(Point[] sequence)
        {
            if (sequence.Length == 0)
                return null;

            int xmax = (int)sequence.Max(x => x.X);
            int xmin = (int)sequence.Min(x => x.X);

            int ymax = (int)sequence.Max(x => x.Y);
            int ymin = (int)sequence.Min(x => x.Y);

            int width = xmax - xmin;
            int height = ymax - ymin;

            Bitmap bmp = new Bitmap(width + 16, height + 16);

            Graphics g = Graphics.FromImage(bmp);

            for (int i = 1; i < sequence.Length; i++)
            {
                int x = (int)sequence[i].X - xmin;
                int y = (int)sequence[i].Y - ymin;
                int p = (int)Accord.Math.Tools.Scale(0, sequence.Length, 0, 255, i);

                int prevX = (int)sequence[i - 1].X - xmin;
                int prevY = (int)sequence[i - 1].Y - ymin;

                using (Brush brush = new SolidBrush(Color.FromArgb(255 - p, 0, p)))
                using (Pen pen = new Pen(brush, 16))
                {
                    pen.StartCap = LineCap.Round;
                    pen.EndCap = LineCap.Round;
                    g.DrawLine(pen, prevX, prevY, x, y);
                }
            }

            return bmp;
        }
Ejemplo n.º 28
0
        public void MaxReturnsMaxOfXYOrZ()
        {
            var a = new Point(1, -2, 3);

            Point.Max(a).Should().Be(3);
        }
Ejemplo n.º 29
0
        private IEnumerable<Shape> _addSerieAsBezier(Point[] points, bool animate = true)
        {
            if (points.Length < 2) return Enumerable.Empty<Shape>();
            var addedFigures = new List<Shape>();

            Point[] cp1, cp2;
            BezierSpline.GetCurveControlPoints(points, out cp1, out cp2);

            var lines = new PathSegmentCollection();
            var areaLines = new PathSegmentCollection { new LineSegment(points[0], true) };
            var l = 0d;
            for (var i = 0; i < cp1.Length; ++i)
            {
                lines.Add(new BezierSegment(cp1[i], cp2[i], points[i + 1], true));
                areaLines.Add(new BezierSegment(cp1[i], cp2[i], points[i + 1], true));
                l += GetBezierLength(new [] { points[i], cp1[i], cp2[i], points[i + 1] });
            }
            l *= 1.05;
            l /= StrokeThickness;
            var lastP = Chart.Invert
                ? new Point(ToDrawMargin(Chart.Min.X, AxisTags.X), points.Min(x => x.Y))
                : new Point(points.Max(x => x.X), ToDrawMargin(Chart.Min.Y, AxisTags.Y));
            areaLines.Add(new LineSegment(lastP, true));
            var f = new PathFigure(points[0], lines, false);
            var aOrigin = Chart.Invert
                ? new Point(ToDrawMargin(Chart.Min.X, AxisTags.X), points.Max(x => x.Y))
                : new Point(points.Min(x => x.X), ToDrawMargin(Chart.Min.Y, AxisTags.Y));
            var fa = new PathFigure(aOrigin, areaLines, false);
            var g = new PathGeometry(new[] { f });
            var ga = new PathGeometry(new[] { fa });

            var path = new Path
            {
                Stroke = Stroke,
                StrokeThickness = StrokeThickness,
                Data = g,
                StrokeEndLineCap = PenLineCap.Round,
                StrokeStartLineCap = PenLineCap.Round,
                StrokeDashOffset = l,
                StrokeDashArray = new DoubleCollection { l, l },
                ClipToBounds = true
            };
            var patha = new Path
            {
                StrokeThickness = 0,
                Data = ga,
                Fill = Fill,
                ClipToBounds = true
            };

            Chart.DrawMargin.Children.Add(path);
            addedFigures.Add(path);

            Chart.DrawMargin.Children.Add(patha);
            addedFigures.Add(patha);

            var draw = new DoubleAnimationUsingKeyFrames
            {
                BeginTime = TimeSpan.FromSeconds(0),
                KeyFrames = new DoubleKeyFrameCollection
                {
                    new SplineDoubleKeyFrame
                    {
                        KeyTime = TimeSpan.FromMilliseconds(1),
                        Value = l
                    },
                    new SplineDoubleKeyFrame
                    {
                        KeyTime = TimeSpan.FromMilliseconds(750),
                        Value = 0
                    }
                }
            };

            Storyboard.SetTarget(draw, path);
            Storyboard.SetTargetProperty(draw, new PropertyPath(Shape.StrokeDashOffsetProperty));
            var sbDraw = new Storyboard();
            sbDraw.Children.Add(draw);
            var animated = false;
            if (!Chart.DisableAnimation)
            {
                if (animate)
                {
                    sbDraw.Begin();
                    animated = true;
                }
            }
            if (!animated) path.StrokeDashOffset = 0;
            return addedFigures;
        }
Ejemplo n.º 30
0
 protected override void SetStartLocation(Point start, Keys modifiers, Point location)
 {
     this.Command.Start = Point.Max(Point.Empty, start);
 }
Ejemplo n.º 31
0
 sealed protected override void SetPosition(Rectangle rect)
 {
     middlePoint = Point.Max(Point.Empty, rect.Center);
     radius      = rect.Size / 2;
     SetCenter(middlePoint, rect);
 }
Ejemplo n.º 32
0
        public void GenerateRamp(Map map, Point start, Point end, float halfWidth, float radius)
        {
            var random = RandomOffsetSeed.HasValue ? new Random(RandomOffsetSeed.Value) : null;

            var   primaryAxisVector = (end - start);
            float length            = primaryAxisVector.VectorLength();

            Coordinates startCoordinates = map.PositionToCoordinates(start);
            Coordinates endCoordinates   = map.PositionToCoordinates(end);

            byte startHeight      = map.HeightMap[startCoordinates.X, startCoordinates.Y];
            byte endHeight        = map.HeightMap[endCoordinates.X, endCoordinates.Y];
            int  heightDifference = endHeight - startHeight;

            float halfLength = length / 2f;

            var normal          = new Point(primaryAxisVector.Y, -primaryAxisVector.X) / length;;
            var halfWidthVector = normal * (halfWidth + radius);
            var center          = start + (primaryAxisVector / 2);

            var v = primaryAxisVector / length * radius;

            Point[] corners = new Point[]
            {
                start - v + halfWidthVector,
                start - v - halfWidthVector,
                end + v + halfWidthVector,
                end + v - halfWidthVector
            };

            var primaryAxis   = new Line(start, end);
            var secondaryAxis = new Line(center + halfWidthVector, center - halfWidthVector);

            var min = map.PositionToCoordinates(new Point(corners.Min(p => p.X), corners.Min(p => p.Y)));
            var max = map.PositionToCoordinates(new Point(corners.Max(p => p.X), corners.Max(p => p.Y)));

            Grid <byte> heights = new Grid <byte>(max.X - min.X, max.Y - min.Y);

            for (int x = 0; x < heights.Width; x++)
            {
                for (int y = 0; y < heights.Height; y++)
                {
                    var coordinates = new Coordinates(min.X + x, min.Y + y);

                    if (!CheckCoordinates(coordinates, map.HeightMap))
                    {
                        continue;
                    }

                    var point = map.CoordinatesToPosition(coordinates);
                    var pointOnPrimaryAxis   = primaryAxis.NearestPointOnLine(point);
                    var pointOnSecondaryAxis = secondaryAxis.NearestPointOnLine(point);

                    var nx = point - pointOnPrimaryAxis;
                    var ny = point - pointOnSecondaryAxis;

                    float dx = nx.VectorLength();
                    float dy = ny.VectorLength();

                    byte height;

                    if (dx <= halfWidth && dy <= halfLength)
                    {
                        height = (byte)(startHeight + (heightDifference * (pointOnPrimaryAxis - start).VectorLength() / length));
                    }
                    else
                    {
                        Point pointOnBorder = center;
                        if (dx > 0f)
                        {
                            pointOnBorder += (nx / dx) * System.Math.Min(dx, halfWidth);
                        }
                        if (dy > 0f)
                        {
                            pointOnBorder += (ny / dy) * System.Math.Min(dy, halfLength);
                        }

                        var borderToTarget       = point - pointOnBorder;
                        var borderToTargetLength = borderToTarget.VectorLength();

                        if (borderToTargetLength > radius)
                        {
                            height = (byte)map.HeightMap[coordinates.X, coordinates.Y];
                        }
                        else
                        {
                            var target            = pointOnBorder + (borderToTarget / borderToTargetLength * radius);
                            var targetCoordinates = map.PositionToCoordinates(target);

                            height = (byte)(startHeight + (heightDifference * (pointOnPrimaryAxis - start).VectorLength() / length));
                            byte targetHeight = map.HeightMap[targetCoordinates.X, targetCoordinates.Y];

                            float weight = borderToTargetLength / radius;
                            if (RandomOffsetSeed.HasValue)
                            {
                                weight *= 1f + (random.Next(6) - 3) * 0.01f;
                            }
                            weight = (float)((System.Math.Tanh(((weight * 2) - 1) * piOverTwo) + range) / (2 * range));
                            height = (byte)(height + (targetHeight - height) * weight);
                        }
                    }

                    heights[x, y] = height;
                }
            }

            for (int x = 0; x < heights.Width; x++)
            {
                for (int y = 0; y < heights.Height; y++)
                {
                    map.HeightMap[min.X + x, min.Y + y] = heights[x, y];
                    //map.Tiles[min.X + x, min.Y + y].Impassable = true;
                }
            }
        }