Example #1
0
        public void PointsCompareFalse()
        {
            MyPoint P1 = new MyPoint(1, 1);
            MyPoint P2 = new MyPoint(2, 2);

            Assert.AreEqual(P1 == P2, false);
        }
Example #2
0
        public void PointsCompareTrue()
        {
            MyPoint P1 = new MyPoint(10, 10);
            MyPoint P2 = new MyPoint(10, 10);

            Assert.AreEqual(P1 == P2, true);
        }
  private static int InterfaceInvocation() {

    // Return values 1 - 15
    int ret;

    IPoint p = new MyPoint();
    if (!InterfaceInvocation1(p)) return 1;
    if (!InterfaceInvocation2(p)) return 2;
    if (!InterfaceInvocation3(p)) return 3;
    if (!InterfaceInvocation4(p)) return 4;
    if (!InterfaceInvocation5(p)) return 5;

    IPoint1 point1 = new MyPoint2();

    if (!InterfaceInvocation6(point1)) return 6;
    if (!InterfaceInvocation7(point1)) return 7;
    if (!InterfaceInvocation8(point1)) return 8;
    if (!InterfaceInvocation9(point1)) return 9;
    if (!InterfaceInvocation10(point1)) return 10;

    IPoint9 point9 = (IPoint9)point1;

    if (!InterfaceInvocation11(point9)) return 11;
    if (!InterfaceInvocation12(point9)) return 12;
    if (!InterfaceInvocation13(point9)) return 13;
    if (!InterfaceInvocation14(point9)) return 14;
    if (!InterfaceInvocation15(point9)) return 15;


    if (!InterfaceInvocation16()) return 16;

    return 0;
  }
Example #4
0
 public static void Main()
 {
     MyPoint p = new MyPoint(2,3);
     Console.Write("My Point: ");
     PrintPoint(p);
     Console.ReadLine();
 }
 public bool IsCollinear(MyPoint c)
 {
     if (IsVert)
     {
         return c.X == aPoint.X;
     }
     else
     {
         return rise * (c.X - aPoint.X) == run * (c.Y - aPoint.Y);
     }
 }
	public static int Main ()
	{
		int h;
		if (Foo (a : h = 9, t : 3) != 9)
			return 1;
		
		if (h != 9)
			return 2;
		
		if (Bar (a : 1, s : "x", c : '2') != "1x2")
			return 3;
		
		if (Bar (s : "x") != "1x3")
			return 4;
		
		int i = 1;
		if (Test (a: i++, b: i++) != 17)
			return 5;
		
		if (i != 3)
			return 6;
		
		i = 1;
		if (Test (b: i++, a: i++) != 13)
			return 7;
		
		A a = new A ();
		i = 5;
		a [i:i++]++;
		
		if (a.id != 1)
			return 8;
		
		if (i != 6)
			return 9;
		
		MyPoint mp = new MyPoint (y : -1, x : 5);
		if (mp.Y != -1)
			return 10;
		
		Console.WriteLine ("ok");
		return 0;
	}
        public void DrawBoards()
        {
            MyPoint edgeLeftUp;
            MyPoint edgeRightDown;

            for (int i = 0; i < global.BoardList.Count(); i++)
            {
                //global.Verschnittoptimierung.display.;
                using (Graphics g = global.Verschnittoptimierung.display.CreateGraphics())
            {
                using (Pen pen = new Pen(Color.Black, 2))
                {

                        edgeLeftUp = new MyPoint(global.BoardList[i].edgeLeftUp.x, global.BoardList[i].edgeLeftUp.y);
                        edgeRightDown = new MyPoint(global.BoardList[i].edgeRightDown.x, global.BoardList[i].edgeRightDown.y);

                        // resize not used
                        // edgeLeftUp = Resize(edgeLeftUp);
                        // edgeRightDown = Resize(edgeRightDown);

                        //global.Verschnittoptimierung.Output.Text = Convert.ToString(global.Verschnittoptimierung.display.Height);

                        Brush brush = new SolidBrush(Color.AliceBlue);
                        g.TranslateTransform(global.Verschnittoptimierung.display.AutoScrollPosition.X, global.Verschnittoptimierung.display.AutoScrollPosition.Y);

                        g.DrawRectangle(pen, edgeLeftUp.x, edgeLeftUp.y,
                            edgeRightDown.x - edgeLeftUp.x,
                            edgeRightDown.y - edgeLeftUp.y);

                        g.FillRectangle(brush, edgeLeftUp.x, edgeLeftUp.y,
                            edgeRightDown.x - edgeLeftUp.x,
                            edgeRightDown.y - edgeLeftUp.y);
                    }
                }
            }
        }
Example #8
0
 public Rect()
 {
     this.edgeLeftUp = new MyPoint();
     this.edgeRightDown = new MyPoint();
 }
Example #9
0
 public MyLocation(MyPoint point, int speed, Direction dir)
 {
     this.Point = point;
     this.speed = speed;
     this.Dir   = dir;
 }
 public bool Equals(MyPoint p)
 {
     return p.X == this.X && p.Y == this.Y;
 }
 public LineParams(MyPoint a, MyPoint b)
 {
     aPoint = a;
     rise = b.Y - a.Y;
     run = b.X - a.X;
 }
Example #12
0
        /// <summary>
        /// Функция рассчета расстояния от точки до прямой, задаваемой двумя точками
        /// </summary>
        private static void PerpendicularDistance(MyPoint point, MyPoint start, MyPoint end, out long numerator,
            out long denominator)
        {
            Multiplications += 5;
            Additions += 6;

            var deltaX = end.X - start.X;
            var deltaY = end.Y - start.Y;
            var num = deltaX*(start.Y - point.Y) - (start.X - point.X)*deltaY;
            numerator = num*num;
            denominator = deltaX*deltaX + deltaY*deltaY;
        }
 /// <summary>
 /// data  - is the data you wnat to decrypt
 /// point - is the point is the basis where you are goint to put the data in the pixel
 /// OddX   OddY    Store
 ///   0     0        A
 ///   0     1        R
 ///   1     0        G
 ///   1     1        B
 /// </summary>
 /// <param name="data"></param>
 /// <param name="point"></param>
 /// <returns></returns>
 private Color generateColorFromData(int data,MyPoint point)
 {
     int[] pixel = new int[PIXEL_DATA_SIZE];
     bool evenX = (point.X % 2) == 0;
     bool evenY = (point.Y % 2) == 0;
     pixel[0] = (evenX && evenY) ? data : random.Next() % byte.MaxValue;
     pixel[1] = (evenX && !evenY) ? data : random.Next() % byte.MaxValue;
     pixel[2] = (!evenX && evenY) ? data : random.Next() % byte.MaxValue;
     pixel[3] = (!evenX && !evenY) ? data : random.Next() % byte.MaxValue;
     return Color.FromArgb(pixel[0], pixel[1], pixel[2], pixel[3]);
 }
Example #14
0
 public Rectangle(MyPoint centerPoint, float sideOne, float sideTwo) : base(centerPoint)
 {
     this.SideOne = sideOne;
     this.SideTwo = sideTwo;
 }
Example #15
0
 private void Move(MyPoint delta)
 {
     Position += delta / NodesCanvas.Scale.Value;
 }
Example #16
0
        public static CircleModel Ellipse2Model(Ellipse line, AttributeModel atModel)
        {
            CircleModel dbModel = new CircleModel();

            dbModel.Center = Point3d2Pointf(line.Center);
            //dbModel.MajorAxis= line.MajorRadius;
            //dbModel.MinorAxis = line.MinorRadius;
            MyPoint spt    = new MyPoint(line.StartPoint.X, line.StartPoint.Y);
            MyPoint ept    = new MyPoint(line.EndPoint.X, line.EndPoint.Y);
            MyPoint center = new MyPoint(dbModel.Center.X, dbModel.Center.Y);

            double length = line.RadiusRatio * (line.MinorRadius + line.MajorRadius);

            dbModel.pointList = MethodCommand.GetArcPoints(line, length);

            dbModel.Color = line.ColorIndex == 256 ? MethodCommand.GetLayerColorByID(line.LayerId) : System.Drawing.ColorTranslator.ToHtml(line.Color.ColorValue);
            foreach (AttributeItemModel item in atModel.attributeItems)
            {
                string attValue = "";

                switch (item.AtItemType)
                {
                case AttributeItemType.Area:
                    attValue = line.Area.ToString();
                    break;

                case AttributeItemType.TxtHeight:

                    break;

                case AttributeItemType.Color:
                    attValue = dbModel.Color;
                    break;

                case AttributeItemType.Content:

                    break;

                case AttributeItemType.LayerName:
                    attValue = line.Layer;
                    break;

                case AttributeItemType.LineScale:
                    attValue = line.LinetypeScale.ToString();
                    break;

                case AttributeItemType.LineType:
                    attValue = GetLayerLineTypeByID(line);
                    break;

                case AttributeItemType.Overallwidth:
                    break;

                case AttributeItemType.TotalArea:

                    break;
                }
                if (!string.IsNullOrEmpty(attValue))
                {
                    item.AtValue = attValue;
                    dbModel.attItemList.Add(item);
                }
            }
            return(dbModel);
        }
Example #17
0
        public static PolyLineModel Polyline2Model(Autodesk.AutoCAD.DatabaseServices.Polyline polyLine, AttributeModel atModel)
        {
            PolyLineModel polylineModel = new PolyLineModel();

            polylineModel.individualName   = "";
            polylineModel.individualFactor = "";
            polylineModel.individualCode   = "";
            polylineModel.individualStage  = "";

            // 增加个体编码、个体要素、个体名称
            System.Data.DataTable tb = Method.AutoGenerateNumMethod.GetAllPolylineNumsEx(polyLine);
            if (tb.Rows != null && tb.Rows.Count > 0)
            {
                foreach (System.Data.DataRow row in tb.Rows)
                {
                    if ((string)row["多段线id"] == polyLine.Id.Handle.Value.ToString())
                    {
                        polylineModel.individualName   = (string)row["个体名称"];
                        polylineModel.individualFactor = (string)row["个体要素"];
                        polylineModel.individualCode   = (string)row["个体编码"];
                        polylineModel.individualStage  = (string)row["个体阶段"];
                    }
                }
            }
            polylineModel.Area     = polyLine.Area;
            polylineModel.Closed   = polyLine.Closed;
            polylineModel.Color    = polyLine.ColorIndex == 256 ? MethodCommand.GetLayerColorByID(polyLine.LayerId) : System.Drawing.ColorTranslator.ToHtml(polyLine.Color.ColorValue);
            polylineModel.Vertices = new System.Collections.ArrayList();
            int vn = polyLine.NumberOfVertices;  //lwp已知的多段线

            for (int i = 0; i < vn; i++)
            {
                Point2d     pt = polyLine.GetPoint2dAt(i);
                SegmentType st = polyLine.GetSegmentType(i);
                if (st == SegmentType.Arc)
                {
                    ArcModel      arc = new ArcModel();
                    CircularArc2d cir = polyLine.GetArcSegment2dAt(i);
                    //  arc.Center = new System.Drawing.PointF((float)cir.Center.X,(float)cir.Center.Y);
                    arc.Center     = Point2d2Pointf(cir.Center);
                    arc.Radius     = cir.Radius;
                    arc.Startangel = cir.StartAngle;
                    arc.EndAngel   = cir.EndAngle;
                    //  arc.StartPoint = new System.Drawing.PointF((float)cir.StartPoint.X, (float)cir.StartPoint.Y);
                    if (cir.HasStartPoint)
                    {
                        arc.StartPoint = Point2d2Pointf(cir.StartPoint);
                    }
                    //  arc.EndPoint = new System.Drawing.PointF((float)cir.EndPoint.X, (float)cir.EndPoint.Y);
                    if (cir.HasEndPoint)
                    {
                        arc.EndPoint = Point2d2Pointf(cir.EndPoint);
                    }


                    MyPoint spt    = new MyPoint(arc.StartPoint.X, arc.StartPoint.Y);
                    MyPoint ept    = new MyPoint(arc.EndPoint.X, arc.EndPoint.Y);
                    MyPoint center = new MyPoint(arc.Center.X, arc.Center.Y);
                    arc.Color = polylineModel.Color;
                    // arc.pointList = MethodCommand.GetRoationPoint(spt, ept, center, arc.Startangel,arc.EndAngel,cir.IsClockWise);
                    arc.pointList = MethodCommand.GetArcPointsByPoint2d(cir.GetSamplePoints(20));
                    //arc.pointList = MethodCommand.GetArcPoints(arc.Center,arc.Startangel,arc.EndAngel,arc.Radius);
                    //  arc.pointList.Insert(0, arc.StartPoint);
                    //   arc.pointList.Add(arc.EndPoint);
                    foreach (AttributeItemModel item in atModel.attributeItems)
                    {
                        string attValue = "";

                        switch (item.AtItemType)
                        {
                        case AttributeItemType.Area:
                            attValue = polyLine.Area.ToString();
                            break;

                        case AttributeItemType.TxtHeight:

                            break;

                        case AttributeItemType.Color:
                            attValue = polylineModel.Color;
                            break;

                        case AttributeItemType.Content:

                            break;

                        case AttributeItemType.LayerName:
                            attValue = polyLine.Layer;
                            break;

                        case AttributeItemType.LineScale:
                            attValue = polyLine.LinetypeScale.ToString();
                            break;

                        case AttributeItemType.LineType:
                            attValue = GetLayerLineTypeByID(polyLine);
                            break;

                        case AttributeItemType.Overallwidth:
                            attValue = polyLine.ConstantWidth.ToString();
                            break;

                        case AttributeItemType.TotalArea:

                            break;
                        }
                        if (!string.IsNullOrEmpty(attValue))
                        {
                            item.AtValue = attValue;
                            arc.attItemList.Add(item);
                        }
                    }
                    polylineModel.Vertices.Add(arc);
                }
                else if (st == SegmentType.Line)
                {
                    LineModel     line   = new LineModel();
                    LineSegment2d lineSe = polyLine.GetLineSegment2dAt(i);
                    if (lineSe.HasStartPoint)
                    {
                        line.StartPoint = Point2d2Pointf(lineSe.StartPoint);
                    }
                    if (lineSe.HasEndPoint)
                    {
                        line.EndPoint = Point2d2Pointf(lineSe.EndPoint);
                    }
                    if (line.StartPoint.X == line.EndPoint.X && line.StartPoint.Y == line.EndPoint.Y)
                    {
                        line.Angle  = 0;
                        line.Length = 0;
                    }
                    else if (line.StartPoint.X == line.EndPoint.X)
                    {
                        line.Angle = 90;
                    }
                    line.Color = polylineModel.Color;
                    foreach (AttributeItemModel item in atModel.attributeItems)
                    {
                        string attValue = "";

                        switch (item.AtItemType)
                        {
                        case AttributeItemType.Area:
                            attValue = polyLine.Area.ToString();
                            break;

                        case AttributeItemType.TxtHeight:

                            break;

                        case AttributeItemType.Color:
                            attValue = polylineModel.Color;
                            break;

                        case AttributeItemType.Content:

                            break;

                        case AttributeItemType.LayerName:
                            attValue = polyLine.Layer;
                            break;

                        case AttributeItemType.LineScale:
                            attValue = polyLine.LinetypeScale.ToString();
                            break;

                        case AttributeItemType.LineType:
                            attValue = GetLayerLineTypeByID(polyLine);
                            break;

                        case AttributeItemType.Overallwidth:
                            attValue = polyLine.ConstantWidth.ToString();
                            break;

                        case AttributeItemType.TotalArea:

                            break;
                        }

                        item.AtValue = attValue;
                        line.attItemList.Add(item);
                    }
                    polylineModel.Vertices.Add(line);
                }
            }

            return(polylineModel);
        }
Example #18
0
        public static PolyLineModel Polyline2Model(Autodesk.AutoCAD.DatabaseServices.Polyline polyLine)
        {
            PolyLineModel polylineModel = new PolyLineModel();

            polylineModel.individualName   = "";
            polylineModel.individualFactor = "";
            polylineModel.individualCode   = "";
            polylineModel.individualStage  = "";

            // 增加个体编码、个体要素、个体名称
            System.Data.DataTable tb = Method.AutoGenerateNumMethod.GetAllPolylineNumsEx(polyLine);
            if (tb.Rows != null && tb.Rows.Count > 0)
            {
                foreach (System.Data.DataRow row in tb.Rows)
                {
                    if ((string)row["多段线id"] == polyLine.Id.Handle.Value.ToString())
                    {
                        polylineModel.individualName   = (string)row["个体名称"];
                        polylineModel.individualFactor = (string)row["个体要素"];
                        polylineModel.individualCode   = (string)row["个体编码"];
                        polylineModel.individualStage  = (string)row["个体阶段"];
                    }
                }
            }

            polylineModel.Area     = polyLine.Area;
            polylineModel.Closed   = polyLine.Closed;
            polylineModel.Color    = polyLine.ColorIndex == 256 ? MethodCommand.GetLayerColorByID(polyLine.LayerId) : System.Drawing.ColorTranslator.ToHtml(polyLine.Color.ColorValue);
            polylineModel.Vertices = new System.Collections.ArrayList();
            int vn = polyLine.NumberOfVertices;  //lwp已知的多段线

            //if(polylineModel.Closed)
            //{
            //    for (int i = 0; i < vn; i++)
            //    {
            //        Point2d pt = polyLine.GetPoint2dAt(i);

            //        PointF ptf = new PointF((float)pt.X, (float)pt.Y);

            //        polylineModel.Vertices.Add(ptf);
            //    }
            //}
            //else
            //{


            for (int i = 0; i < vn; i++)
            {
                Point2d     pt = polyLine.GetPoint2dAt(i);
                SegmentType st = polyLine.GetSegmentType(i);
                if (st == SegmentType.Arc)
                {
                    ArcModel      arc = new ArcModel();
                    CircularArc2d cir = polyLine.GetArcSegment2dAt(i);
                    //  arc.Center = new System.Drawing.PointF((float)cir.Center.X,(float)cir.Center.Y);
                    arc.Center     = Point2d2Pointf(cir.Center);
                    arc.Radius     = cir.Radius;
                    arc.Startangel = cir.StartAngle;
                    arc.EndAngel   = cir.EndAngle;
                    //  arc.StartPoint = new System.Drawing.PointF((float)cir.StartPoint.X, (float)cir.StartPoint.Y);
                    if (cir.HasStartPoint)
                    {
                        arc.StartPoint = Point2d2Pointf(cir.StartPoint);
                    }
                    //  arc.EndPoint = new System.Drawing.PointF((float)cir.EndPoint.X, (float)cir.EndPoint.Y);
                    if (cir.HasEndPoint)
                    {
                        arc.EndPoint = Point2d2Pointf(cir.EndPoint);
                    }


                    MyPoint spt    = new MyPoint(arc.StartPoint.X, arc.StartPoint.Y);
                    MyPoint ept    = new MyPoint(arc.EndPoint.X, arc.EndPoint.Y);
                    MyPoint center = new MyPoint(arc.Center.X, arc.Center.Y);
                    arc.Color = polylineModel.Color;
                    // arc.pointList = MethodCommand.GetRoationPoint(spt, ept, center, arc.Startangel,arc.EndAngel,cir.IsClockWise);
                    arc.pointList = MethodCommand.GetArcPointsByPoint2d(cir.GetSamplePoints(20));
                    //arc.pointList = MethodCommand.GetArcPoints(arc.Center,arc.Startangel,arc.EndAngel,arc.Radius);
                    //  arc.pointList.Insert(0, arc.StartPoint);
                    //   arc.pointList.Add(arc.EndPoint);
                    polylineModel.Vertices.Add(arc);
                }
                else if (st == SegmentType.Line)
                {
                    LineModel     line   = new LineModel();
                    LineSegment2d lineSe = polyLine.GetLineSegment2dAt(i);
                    if (lineSe.HasStartPoint)
                    {
                        line.StartPoint = Point2d2Pointf(lineSe.StartPoint);
                    }
                    if (lineSe.HasEndPoint)
                    {
                        line.EndPoint = Point2d2Pointf(lineSe.EndPoint);
                    }
                    if (line.StartPoint.X == line.EndPoint.X && line.StartPoint.Y == line.EndPoint.Y)
                    {
                        line.Angle  = 0;
                        line.Length = 0;
                    }
                    else if (line.StartPoint.X == line.EndPoint.X)
                    {
                        line.Angle = 90;
                    }
                    line.Color = polylineModel.Color;
                    polylineModel.Vertices.Add(line);
                }
            }
            //}
            polylineModel.isDashed = GetLayerLineTypeByIDEx(polyLine);
            return(polylineModel);
        }
 public MyLine(MyPoint p1, MyPoint p2)
 {
     P1 = p1;
     P2 = p2;
 }
 protected bool Equals(MyPoint other)
 {
     return(string.Equals(Id, other.Id));
 }
Example #21
0
 public void RotationEdge(MyPoint p, double rotation)
 {
     p1.RotationPoint(p, rotation);
     p2.RotationPoint(p, rotation);
 }
Example #22
0
 private void ChangePoint(MyPoint point)
 {
     point.X = 555;
     point.Y = 222;
 }
 public MyPoint Resize(MyPoint point)
 {
     point.x *= global.mult;
     point.y *= global.mult;
     return point;
 }
Example #24
0
        public GraphicObject(MyPoint point)
        {
            InitializeComponent( );

            DataContext = new GraphicObjectViewModel(point);
        }
Example #25
0
 public void tick()
 {
     // goto next pos
     MyPoint dest = DestList[nextDestIdx];
     if (PathList != null && curPathIdx + 1 >= PathList.Length)
     {
         nextDestIdx++;
         nextDestIdx %= DestList.Count;
         PathList = null;
     }
     curPos = getNextPos(curPos, DestList[nextDestIdx]);
 }
        public static void TestTuples()
        {
            // Notice that they don’t all have to be the same data type.
            (int, string, bool)values = (10, "Moamen", true);

            // you can use Implicity typed var
            var varValues = (Math.PI, "Math", false);

            // By default, the compiler assigns each property the name ItemX,
            //  where X represents the one based position in the tuple.
            //  X starts from 1 to n the number of elements in tuple.
            Console.WriteLine(values.Item1);
            Console.WriteLine(values.Item2);
            Console.WriteLine(values.Item3);

            Console.WriteLine(values.GetType().Name);

            Console.WriteLine(values.Item1.GetType().FullName);
            Console.WriteLine(values.Item2.GetType().FullName);
            Console.WriteLine(values.Item3.GetType().FullName);

            #region Named and unnamed tuples - Deconstruction Tuples

            // Named and unnamed tuples
            //------------------------------------------------------------------------------------------
            // The ValueTuple struct - drived from ValueType - has fields named Item1, Item2, Item3, and so on,
            //      similar to the properties defined in the existing Tuple types.
            //      These names are the only names you can use for unnamed tuples.
            //      When you do not provide any alternative field names to a tuple,
            //      you've created an unnamed tuple.

            // Named tuples still have elements named Item1, Item2, Item3 and so on.
            //      But they also have synonyms for any of those elements that you have named.

            //  In Named tuples, The compiled Microsoft Intermediate Language (MSIL) does not
            //      include the names you've given to tuple elements.

            // Unnamed tuples
            (int, bool)tuple1 = (10, true);
            var tuple2 = (10, true);
            (int, bool)tuple3 = (integer : 10, boolean : true); // right side names ignored by compiler

            // named tuples
            (int integer, bool boolean)tuple4 = (10, true);
            var tuple5 = (integer : 10, boolean : true);

            (int integer, bool boolean)tuple6 = (myInt : 10, myBool : true); // right side names ignored by compiler

            // Deconstruction tuple
            (int integer, bool boolean) = (10, true);

            var(integer1, boolean1) = (10, true);

            (var integer2, var boolean2) = (10, true);


            // Specific names can be added to each property in the tuple on either the right side or the left side of
            //      the statement.
            // Left Side Named Properties
            //------------------------------------------------------------------------------------------
            (int MyInt, string Mystr, bool MyBool)rightSideTuple = (10, "Moamen", true);
            // the properties on the tuple can be accessed using the field names as well as the ItemX notation

            Logger.Title("rightSideTuple with ItemX call");
            Console.WriteLine(rightSideTuple.Item1);
            Console.WriteLine(rightSideTuple.Item2);
            Console.WriteLine(rightSideTuple.Item3);

            Logger.Title("rightSideTuple with Named Properties call");
            Console.WriteLine(rightSideTuple.MyInt);
            Console.WriteLine(rightSideTuple.MyBool);
            Console.WriteLine(rightSideTuple.Mystr);

            // var with Right Side Named Properties - Names as part of the tuple initialization -:
            //------------------------------------------------------------------------------------------
            var leftSideTupleWithVar = (MyInt : 10, MyStr : "Moamen", MyBool : true);

            Logger.Title("leftSideTuple with ItemX call");
            Console.WriteLine(leftSideTupleWithVar.Item1);
            Console.WriteLine(leftSideTupleWithVar.Item2);
            Console.WriteLine(leftSideTupleWithVar.Item3);

            Logger.Title("leftSideTupleWithVar with Named Properties call");
            Console.WriteLine(leftSideTupleWithVar.MyInt);
            Console.WriteLine(leftSideTupleWithVar.MyStr);
            Console.WriteLine(leftSideTupleWithVar.MyBool);


            // var with Left Side Named Properties
            //------------------------------------------------------------------------------------------
            var(MyInt, MyStr, MyBool) = (10, "Moamen", true);
            Logger.Title("leftSideTupleWithVar with ItemX call");
            Console.WriteLine(leftSideTupleWithVar.Item1);
            Console.WriteLine(leftSideTupleWithVar.Item2);
            Console.WriteLine(leftSideTupleWithVar.Item3);

            Logger.Title("leftSideTupleWithVar with Named Properties call");
            Console.WriteLine(leftSideTupleWithVar.MyInt);
            Console.WriteLine(leftSideTupleWithVar.MyStr);
            Console.WriteLine(leftSideTupleWithVar.MyBool);


            // Both Sides Named Properties (Left names ignored and can't be used)
            //------------------------------------------------------------------------------------------
            // While it is not a compiler error to assign names on both sides of the statement,
            //      if you do, the right side will be ignored, and only the left-side names are used.
            (int MyInt, string Mystr, bool MyBool)bothSidesTuple = (MyIntValue : 10, MyStringValue : "Moamen", MyBoolValue : true);

            Logger.Title("bothSidesTuple with ItemX call");
            Console.WriteLine(bothSidesTuple.Item1);
            Console.WriteLine(bothSidesTuple.Item2);
            Console.WriteLine(bothSidesTuple.Item3);

            Logger.Title("bothSidesTuple with Left Named Properties call");
            Console.WriteLine(bothSidesTuple.MyInt);
            Console.WriteLine(bothSidesTuple.Mystr);
            Console.WriteLine(bothSidesTuple.MyBool);

            // ERROR: Cannot Access Tuples With Left Named Properties call when there are Right Names
            //Logger.Title("bothSidesTuple with Right Named Properties call");
            //Console.WriteLine(bothSidesTuple.MyIntValue);
            //Console.WriteLine(bothSidesTuple.MyStrValue);
            //Console.WriteLine(bothSidesTuple.MyBoolValue);


            // Left Side Named Properties with Right Side Explicit properties Types -without var keyword-
            //------------------------------------------------------------------------------------------
            // NOTE: Note that when setting the names on the right, you must use the keyword var.
            //      Setting the data types specifically(even without custom names) triggers
            //      the compiler to use the left side, assign the properties using the ItemX notation,
            //      and ignore any of the custom names set on the right.The following two examples ignore
            //      the MyIntValue, MyStringValue and MyBoolValue names:

            (int, string, bool)leftSideTuple = (MyIntValue : 10, MyStringValue : "Moamen", MyBoolValue : true);


            // So the only way to access the last tuple is to use ItemX notation
            Logger.Title("leftSideTuple with Right Side Explicit properties Types -without var keyword-");
            Console.WriteLine(leftSideTuple.Item1);
            Console.WriteLine(leftSideTuple.Item2);
            Console.WriteLine(leftSideTuple.Item3);

            #endregion

            #region Tuple Projection Initializers
            // Tuple Projection Initializers
            //------------------------------------------------------------------------------------------
            // Beginning with C# 7.1, the field names for a tuple may be provided from the variables used to
            //  initialize the tuple. This is referred to as tuple projection initializers.

            Logger.Title("Tuple Projection Initializers");
            double sum   = 12.5;
            int    count = 5;
            // projected names
            var accumulation = (count, sum);
            Console.WriteLine("accumulation.count = " + accumulation.count);
            Console.WriteLine("accumulation.sum = " + accumulation.sum);

            // You can use Projected Names, or update it with new Explicit Names.
            // If an explicit name is given, that takes precedence over any projected name.
            // and compile error with appear if you call elements with projected names

            // explicit names
            var accumulation2 = (count2 : count, sum2 : sum);
            Console.WriteLine("accumulation.count2 = " + accumulation2.count2);
            Console.WriteLine("accumulation.sum2 = " + accumulation2.sum2);
            // compile Error if you use projected names, as explicit names canceled projected names
            //Console.WriteLine("accumulation.sum = " + accumulation2.sum);
            //Console.WriteLine("accumulation.count = " + accumulation2.count);

            // For any field where an explicit name is not provided, an applicable implicit name is projected.

            var stringContent = "The answer to everything";
            var mixedTuple    = (42, stringContent);
            Console.WriteLine($"mixedTuple = ({mixedTuple.Item1} , {mixedTuple.stringContent})");

            // Mixed tuple with explicit name for first element, and projected name for second element.
            var mixedTuple2 = (integer : 42, stringContent);
            Console.WriteLine($"mixedTuple2 = ({mixedTuple2.integer} , {mixedTuple2.stringContent})");

            // There are two conditions where candidate field names are not projected onto the tuple field:
            // 1- When the candidate name is a reserved tuple name.
            //      Examples include Item3, ToString or Rest.
            // 2- When the candidate name is a duplicate of another tuple field name,
            //      either explicit or implicit.

            // Neither of these conditions cause compile-time errors.Instead,
            //      the elements without projected names do not have semantic
            //      names projected for them.

            // Projection Failure First Case:
            int num    = 10;
            int Item2  = 20;
            var tuple7 = (Item2, num);
            // projection failed as Item2 ia << Reserved Tuple Name >> , and now:
            // first element can be accessed only with implicit name (Item1)
            Console.WriteLine(tuple7.Item1);
            // second element can be accessed with projected name (num) and implicit name (Item2)
            Console.WriteLine(tuple7.num);
            Console.WriteLine(tuple7.Item2);

            // Projection Failure Second Case:

            var point1 = (X : 10, Y : 20);
            var point2 = (X : 30, Y : 40);
            // Projection failed because of Names Ambiguity due to duplication of another tuple field name
            var xCoords = (point1.X, point2.X);
            // we can access xCoords only with Implicit names ItemX Notation
            Console.WriteLine(xCoords.Item1);
            Console.WriteLine(xCoords.Item2);

            //Console.WriteLine(xCoords.X);

            // These situations do not cause compiler errors because that would be a
            //      breaking change for code written with C# 7.0, when tuple field name
            //      projections were not available.

            #endregion

            #region Equality in Tuples

            // Equality in Tuples

            // Beginning with C# 7.3, tuple types support the == and != operators.
            // These operators work by comparing each member of the left argument to
            // each member of the right argument in order. These comparisons short-circuit.
            Logger.Title("Equality in Tuples");
            var left  = (a : 5, b : 10);
            var right = (a : 5, b : 10);
            Console.WriteLine(left == right); // displays 'true'

            // Tuple equality also performs implicit conversions on each member of both tuples.
            // These include lifted conversions, widening conversions, or other implicit conversions.

            // Tuple equality performs lifted conversions if one of the tuples is a nullable tuple
            Logger.Title("lifted conversions if one of the tuples is a nullable tuple");
            var left2 = (a : 10, b : 20);
            (int?a, int?b)nullableRight = (10, 20);
            Console.WriteLine(left2 == nullableRight);

            // converted type of left is (long, long)
            (long a, long b)longTuple = (5, 10);
            Console.WriteLine(left == longTuple); // Also true

            // comparisons performed on (long, long) tuples
            (long a, int b)longFirst  = (5, 10);
            (int a, long b)longSecond = (5, 10);
            Console.WriteLine(longFirst == longSecond); // Also true

            // The names of the tuple members do not participate in tests for equality.However,
            //  if one of the operands is a tuple literal with explicit names, the compiler
            //  generates warning CS8383 if those names do not match the names of the other operand.

            (int a, string b)pair    = (1, "Hello");
            (int z, string y)another = (1, "Hello");
            Console.WriteLine(pair == another);            // true. Member names don't participate.
            Console.WriteLine(pair == (z: 1, y: "Hello")); // warning: literal contains different member names

            //Finally, tuples may contain nested tuples.
            // Tuple equality compares the "shape" of each operand through nested tuples.

            (int, (int, int))nestedTuple = (1, (2, 3));
            Console.WriteLine(nestedTuple == (1, (2, 3)));

            // It's a compile time error to compare two tuples for equality (or inequality)
            //      when they have different shapes. The compiler won't attempt any deconstruction
            //      of nested tuples in order to compare them.

            #endregion


            #region Assignment and tuples
            //The language supports assignment between tuple types that have the same number of elements,
            //      where each right-hand side element can be implicitly converted to its corresponding
            //      left hand side element. Other conversions aren't considered for assignments.
            //      It's a compile time error to assign one tuple to another when they have different shapes.
            //      The compiler won't attempt any deconstruction of nested tuples in order to assign them.
            //      Let's look at the kinds of assignments that are allowed between tuple types.

            // The 'arity' and 'shape' of all these tuples are compatible.
            // The only difference is the field names being used.
            var unnamed        = (42, "The meaning of life");
            var anonymous      = (16, "a perfect square");
            var named          = (Answer : 42, Message : "The meaning of life");
            var differentNamed = (SecretConstant : 42, Label : "The meaning of life");

            //  all of these assignments work:
            unnamed = named;

            named = unnamed;
            // 'named' still has fields that can be referred to
            // as 'answer', and 'message':
            Console.WriteLine($"{named.Answer}, {named.Message}");

            // unnamed to unnamed:
            anonymous = unnamed;

            // named tuples.
            named = differentNamed;
            // The field names are not assigned. 'named' still has
            // fields that can be referred to as 'answer' and 'message':
            Console.WriteLine($"{named.Answer}, {named.Message}");

            // With implicit conversions:
            // int can be implicitly converted to long
            (long, string)conversion = named;

            // explicit conversion of tuple
            (short, string)conversion2 = ((short)named.Answer, named.Message);

            // Notice that the names of the tuples are not assigned. The values of the elements
            //      are assigned following the order of the elements in the tuple.

            // Tuples of different types or numbers of elements are not assignable:
            // Does not compile.
            // CS0029: Cannot assign Tuple(int,int,int) to Tuple(int, string)
            //var differentShape = (1, 2, 3);
            //named = differentShape;



            #endregion

            #region Tuples As Method Return Values

            // Tuples As Method Return Values
            //------------------------------------------------------------------------------------------
            //out parameters were used to return more than one value from a method call.There
            //are additional ways to do this, such as creating a class or structure specifically to return
            //the values.But if this class or struct is only to be used as a data transport for one method,
            //that is extra work and extra code that doesn’t need to be developed.
            //Tuples are perfectly suited for this task, are lightweight, and are easy to declare and use.

            var samples = FillTheseValues();
            Console.WriteLine($"Int is: {samples.a}");
            Console.WriteLine($"String is: {samples.b}");
            Console.WriteLine($"Boolean is: {samples.c}");


            var nameTuple = SplitName("Moamen");
            Console.WriteLine($"Name: {nameTuple.first}{(nameTuple.second == "" ? "" : " ")}{nameTuple.second}{(nameTuple.last == "" ? "" : " ")}{nameTuple.last}");

            nameTuple = SplitName("Moamen Mohammed");
            WriteName(nameTuple);

            nameTuple = SplitName("Moamen Mohammed Soroor");
            WriteName(nameTuple);

            nameTuple = SplitName("Moamen Mohammed Gamal Soroor");
            WriteName(nameTuple);

            nameTuple = SplitName("Moamen Mohammed Gamal Mohammed Soroor");
            WriteName(nameTuple);

            nameTuple = SplitName("Moamen MG.Soroor");
            WriteName(nameTuple);

            // Discards with Tuples
            //------------------------------------------------------------------------------------------
            // Following up on the SplitNames() example, suppose you know that you need only
            //      the first and last names and don’t care about the second.

            var(first, _, last) = SplitName("Moamen Mohammed Soroor");
            Console.WriteLine($"{first}:{last}");

            var(first2, _, _) = SplitName("Moamen Mohammed Soroor");
            Console.WriteLine($"{first2}");

            #endregion


            #region Deconstructing with Tuples

            // Deconstruction
            //------------------------------------------------------------------------------------------
            // You can unpackage all the items in a tuple by deconstructing the tuple returned by a method.
            //      There are three different approaches to deconstructing tuples.



            //MyPoint Sructure Variable
            MyPoint p1 = new MyPoint(10, 20);

            // deconstructing
            var pointValues = p1.Deconstruct();
            Console.WriteLine($"pointValues.px = {pointValues.XPos}");
            Console.WriteLine($"pointValues.py = {pointValues.YPos}");


            // deconstructing
            var(XPos2, YPos2) = p1.Deconstruct();
            Console.WriteLine($"px = {XPos2}");
            Console.WriteLine($"py = {YPos2}");

            #endregion
        }
        public static void TestPakaging1()
        {
            // Создаем в стеке два экземпляра Point
            MyPoint p1 = new MyPoint(10, 10);
            MyPoint p2 = new MyPoint(20, 20);

            // p1 НЕ пакуется для вызова ToString (виртуальный метод)
            Console.WriteLine(p1.ToString()); // "(10, 10)"

            // p1 ПАКУЕТСЯ для вызова GetType (невиртуальный метод)
            Console.WriteLine(p1.GetType()); // "MyPoint"

            // p1 НЕ пакуется для вызова CompareTo
            // p2 НЕ пакуется, потому что вызван CompareTo(MyPoint)
            Console.WriteLine(p1.CompareTo(p2)); // "-1"

            // p1 пакуется , а ссылка размещается в c
            IComparable c = p1;
            Console.WriteLine(c.GetType()); // "MyPoint"

            // p1 НЕ пакуется для вызова CompareTo
            // Поскольку в CompareTo не передается переменная MyPoint,
            // вызывается CompareTo(Object), которому нужна ссылка
            // на упакованный MyPoint
            // c НЕ пакуется, потому что уже ссылается на упакованный MyPoint
            Console.WriteLine(p1.CompareTo(c)); // "0"

            // c НЕ пакуется, потому что уже ссылается на упакованный MyPoint
            // p2 ПАКУЕТСЯ, потому что вызывается CompareTo(Object)
            Console.WriteLine(c.CompareTo(p2));// "-1"

            // c пакуется, а поля копируются в p2
            p2 = (MyPoint)c;

            // Убеждаемся, что поля скопированы в p2
            Console.WriteLine(p2.ToString());// "(10, 10)"
        }
Example #28
0
        private void btnCreatePoly_Click(object sender, EventArgs e)
        {
            MyPoly poly = new MyPoly();
              MyPoint p0 = new MyPoint(-8167838.556196676, 5040265.098729953);
              poly.Ring.Add(p0);
              MyPoint p1 = new MyPoint(-8165392.571291549, 5036137.499202552);
              poly.Ring.Add(p1);
              MyPoint p2 = new MyPoint(-8166004.06751783, 5035678.877032841);
              poly.Ring.Add(p2);
              MyPoint p3 = new MyPoint(-8171354.659497795, 5035678.877032841);
              poly.Ring.Add(p3);
              MyPoint p4 = new MyPoint(-8167838.556196676, 5040265.098729953);
              poly.Ring.Add(p4);

              EditFeatureService(EditType.add, GeometryType.polygon, null, poly);
        }
 // Byte array to write
 // Offset
 private byte getDataFromKey(byte bytePosition)
 {
     int number = (int)bytePosition;
     //if(decryptionPointTemp==null)
     decryptionPointTemp = new MyPoint(0,0);
     decryptionPointTemp.X = number / KEY_WIDTH;
     decryptionPointTemp.Y = number % KEY_HEIGHT;
     byte data = 0;
     if (!decryptionKeyMap.ContainsKey(decryptionPointTemp))
     {
         data = (byte)retrieveDataFromColor(keyBitmap.GetPixel(decryptionPointTemp.X, decryptionPointTemp.Y),decryptionPointTemp);//keyBitmap.GetPixel(decryptionPointTemp.X, decryptionPointTemp.Y).A;
         decryptionKeyMap[new MyPoint(decryptionPointTemp.X, decryptionPointTemp.Y)] = data;
     }
     data = decryptionKeyMap[decryptionPointTemp];
     return data;
 }
Example #30
0
 public void SetCellVisited(MyPoint position)//приховати 'з'їджену' монету та позначити клітинку, як відвідана.
 {
     coinsMap[position.X, position.Y].Visibility   = System.Windows.Visibility.Hidden;
     pacman.myMaze[position.X, position.Y].visited = true;
 }
Example #31
0
 /// <summary>
 /// 获取向量的逆向量
 /// </summary>
 /// <param name="opVector"></param>
 /// <returns></returns>
 internal static MyPoint getAgainstVector(MyPoint opVector)
 {
     return(new MyPoint(-opVector.X, -opVector.Y));
 }
Example #32
0
        private void RemoveDeadEnd(MyPoint position, List <Direction> dirList)
        {
            if (position.X != 0 && position.X != myMaze.GetLength(0) - 1 && position.Y != 0 && position.Y != myMaze.GetLength(1) - 1)//видалити стіни всередині лабіринту
            {
                int randomWall = rand.Next(0, 3);
                RemoveWall(position, dirList[randomWall]);
            }
            else if ((position.X == 0 || position.X == myMaze.GetLength(0) - 1) && (position.Y != 0 && position.Y != myMaze.GetLength(1) - 1))//видалити нижню або верхню стіну (для лівого і правого кордонів)
            {
                Direction dirToRem = (position.X == 0) ? Direction.left : Direction.right;
                dirList.Remove(dirToRem);
                int randomWall = rand.Next(0, 2);
                RemoveWall(position, dirList[randomWall]);
            }
            else if ((position.Y == 0 || position.Y == myMaze.GetLength(1) - 1) && (position.X != 0 && position.X != myMaze.GetLength(0) - 1))//видалити праву або ліву стіну (для верхнього і нижнього кордонів)
            {
                Direction dirToRem = (position.Y == 0) ? Direction.up : Direction.down;
                dirList.Remove(dirToRem);
                int randomWall = rand.Next(0, 2);
                RemoveWall(position, dirList[randomWall]);
            }
            else if (position.X == 0 && position.Y == 0)//верхній лівий кут лабіринта
            {
                Direction dir;
                if (dirList.Contains(Direction.down))
                {
                    dir = Direction.down;
                }
                else
                {
                    dir = Direction.right;
                }

                RemoveWall(position, dir);
            }
            else if (position.X == myMaze.GetLength(0) - 1 && position.Y == 0)//верхній правий кут
            {
                Direction dir;
                if (dirList.Contains(Direction.down))
                {
                    dir = Direction.down;
                }
                else
                {
                    dir = Direction.left;
                }

                RemoveWall(position, dir);
            }
            else if (position.X == 0 && position.Y == myMaze.GetLength(1) - 1)//нижній лівий кут
            {
                Direction dir;
                if (dirList.Contains(Direction.up))
                {
                    dir = Direction.up;
                }
                else
                {
                    dir = Direction.right;
                }

                RemoveWall(position, dir);
            }
            else if (position.X == myMaze.GetLength(0) - 1 && position.Y == myMaze.GetLength(1) - 1)//нижній правий кут
            {
                Direction dir;
                if (dirList.Contains(Direction.up))
                {
                    dir = Direction.up;
                }
                else
                {
                    dir = Direction.left;
                }

                RemoveWall(position, dir);
            }
        }
Example #33
0
 private void btnCreatePoint_Click(object sender, EventArgs e)
 {
     MyPoint point = new MyPoint(-13041634.9497585, 3853952.46755234);
       EditFeatureService(EditType.add, GeometryType.point, point, null);
 }
Example #34
0
        private void SolveMaze(MyPoint currentPosition, Direction direction)
        {
            Cell currentCell = myMaze[currentPosition.X, currentPosition.Y]; //для оптимізації коду, будемо працювати з конкретною клітинкою, а не областю лабіринта

            if (beginning)                                                   // виконується лише при першому виклику метода
            {
                start = currentPosition;                                     // встановити початкову точку

                currentCell.start   = true;
                currentCell.visited = true;

                myMaze[start.X, start.Y] = currentCell;
                beginning = false;
            }
            else
            {
                if (direction == Direction.left)
                {
                    currentCell.rightWall = false;
                    myMaze[currentPosition.X + 1, currentPosition.Y].leftWall = false;
                }
                else if (direction == Direction.right)
                {
                    currentCell.leftWall = false;
                    myMaze[currentPosition.X - 1, currentPosition.Y].rightWall = false;
                }
                else if (direction == Direction.up)
                {
                    currentCell.lowerWall = false;
                    myMaze[currentPosition.X, currentPosition.Y + 1].upperWall = false;
                }
                else if (direction == Direction.down)
                {
                    currentCell.upperWall = false;
                    myMaze[currentPosition.X, currentPosition.Y - 1].lowerWall = false;
                }

                myMaze[currentPosition.X, currentPosition.Y] = currentCell;
                currentCell.visited = true;
            }

            CheckBorder(currentPosition, ref currentCell);

            myMaze[currentPosition.X, currentPosition.Y] = currentCell;

            while (true)                    //цикл який буде відбуватися, поки ми не закінчимо формування лабіринта
            {
                if (currentPosition.X != 0) //перевірити, чи сусідні клітинки були відвідані
                {
                    if (myMaze[currentPosition.X - 1, currentPosition.Y].visited)
                    {
                        currentCell.leftDirChecked = true;
                        myMaze[currentPosition.X - 1, currentPosition.Y].rightDirChecked = true;
                    }
                }

                if (currentPosition.X != myMaze.GetLength(0) - 1)
                {
                    if (myMaze[currentPosition.X + 1, currentPosition.Y].visited)
                    {
                        currentCell.rightDirChecked = true;
                        myMaze[currentPosition.X + 1, currentPosition.Y].leftDirChecked = true;
                    }
                }

                if (currentPosition.Y != 0)
                {
                    if (myMaze[currentPosition.X, currentPosition.Y - 1].visited)
                    {
                        currentCell.upperDirChecked = true;
                        myMaze[currentPosition.X, currentPosition.Y - 1].lowerDirChecked = true;
                    }
                }

                if (currentPosition.Y != myMaze.GetLength(1) - 1)
                {
                    if (myMaze[currentPosition.X, currentPosition.Y + 1].visited)
                    {
                        currentCell.lowerDirChecked = true;
                        myMaze[currentPosition.X, currentPosition.Y + 1].upperDirChecked = true;
                    }
                }

                myMaze[currentPosition.X, currentPosition.Y] = currentCell;

                if (currentCell.leftDirChecked && currentCell.rightDirChecked && currentCell.upperDirChecked && currentCell.lowerDirChecked)
                {// Якщо всі комірки навколо були оброблені, то клітина, де ми зараз, є кінцевою
                    currentCell.end = true;
                    myMaze[currentPosition.X, currentPosition.Y] = currentCell;
                    return;
                }
                else // якщо ні, то згенерувати новий напрямок і перевірити, чи була клітинка відвідана чи ні
                {
                    Direction dir = (Direction)rand.Next(0, 4);

                    if (dir == Direction.left)
                    {
                        if (currentCell.leftDirChecked == false)
                        {
                            currentCell.leftDirChecked = true;
                            myMaze[currentPosition.X, currentPosition.Y] = currentCell;
                            SolveMaze(new MyPoint(currentPosition.X - 1, currentPosition.Y), dir);
                        }
                    }
                    else if (dir == Direction.right)
                    {
                        if (currentCell.rightDirChecked == false)
                        {
                            currentCell.rightDirChecked = true;
                            myMaze[currentPosition.X, currentPosition.Y] = currentCell;
                            SolveMaze(new MyPoint(currentPosition.X + 1, currentPosition.Y), dir);
                        }
                    }
                    else if (dir == Direction.up)
                    {
                        if (currentCell.upperDirChecked == false)
                        {
                            currentCell.upperDirChecked = true;
                            myMaze[currentPosition.X, currentPosition.Y] = currentCell;
                            SolveMaze(new MyPoint(currentPosition.X, currentPosition.Y - 1), dir);
                        }
                    }
                    else if (dir == Direction.down)
                    {
                        if (currentCell.lowerDirChecked == false)
                        {
                            currentCell.lowerDirChecked = true;
                            myMaze[currentPosition.X, currentPosition.Y] = currentCell;
                            SolveMaze(new MyPoint(currentPosition.X, currentPosition.Y + 1), dir);
                        }
                    }
                }
            }
        }
Example #35
0
 public virtual double GetDistanceFromPoint(MyPoint point)
 {
     return(Math.Sqrt(Math.Pow(this.x - point.x, 2) + Math.Pow(this.y - point.y, 2)));
 }
        public void DrawRects()
        {
            using (Graphics g = global.Verschnittoptimierung.display.CreateGraphics())
            {
                using (Pen pen = new Pen(Color.Black, 2))
                {
                    MyPoint edgeLeftUp;
                    MyPoint edgeRightDown;

                    edgeLeftUp = new MyPoint(global.BoardList[0].edgeLeftUp.x, global.BoardList[0].edgeLeftUp.y);
                    edgeRightDown = new MyPoint(30, 30);
            ;

                    Brush brush = new SolidBrush(Color.AntiqueWhite);
                    g.TranslateTransform(global.Verschnittoptimierung.display.AutoScrollPosition.X, global.Verschnittoptimierung.display.AutoScrollPosition.Y);

                    g.DrawRectangle(pen, edgeLeftUp.x, edgeLeftUp.y,
                        edgeRightDown.x - edgeLeftUp.x,
                        edgeRightDown.y - edgeLeftUp.y);

                    g.FillRectangle(brush, edgeLeftUp.x, edgeLeftUp.y,
                        edgeRightDown.x - edgeLeftUp.x,
                        edgeRightDown.y - edgeLeftUp.y);
                }
            }
        }
Example #37
0
 public MyEdge(MyPoint p1, MyPoint p2)
 {
     this.p1 = p1;
     this.p2 = p2;
 }
Example #38
0
        public void AzimuthSame1()
        {
            MyPoint point = new MyPoint(40.698470, -73.951442);

            Assert.Equal(-1.0, point.getAzimuth(new MyPoint(40.698470, -73.951442)));
        }
Example #39
0
            static public Bitmap DrawEdge(Bitmap bm, MyPoint p1, MyPoint p2)
            {
                int x1 = (int)p1.X;
                int y1 = (int)p1.Y;
                int x2 = (int)p2.X;
                int y2 = (int)p2.Y;
                int dx = Math.Abs(x2 - x1);
                int dy = Math.Abs(y2 - y1);
                int sx, sy;

                if (x2 >= x1)
                {
                    sx = 1;
                }
                else
                {
                    sx = -1;
                }
                if (y2 >= y1)
                {
                    sy = 1;
                }
                else
                {
                    sy = -1;
                }
                if (dy < dx)
                {
                    int d  = 2 * dy - dx;
                    int d1 = 2 * dy;
                    int d2 = 2 * (dy - dx);
                    bm.SetPixel(x1, y1, p1.Color);
                    int x = x1 + sx;
                    int y = y1;
                    for (int i = 1; i <= dx; i++)
                    {
                        if (d > 0)
                        {
                            d += d2;
                            y += sy;
                        }
                        else
                        {
                            d += d1;
                        }
                        bm.SetPixel(x, y, p1.Color);
                        x += sx;
                    }
                }
                else
                {
                    int d  = 2 * dx - dy;
                    int d1 = 2 * dx;
                    int d2 = 2 * (dx - dy);
                    bm.SetPixel(x1, y1, p1.Color);
                    int x = x1;
                    int y = y1 + sy;
                    for (int i = 1; i <= dy; i++)
                    {
                        if (d > 0)
                        {
                            d += d2;
                            x += sx;
                        }
                        else
                        {
                            d += d1;
                        }
                        bm.SetPixel(x, y, p1.Color);
                        y += sy;
                    }
                }
                return(bm);
            }
Example #40
0
        public void AzimuthPolus2()
        {
            MyPoint point = new MyPoint(-90, 0);

            Assert.Equal(180, point.getAzimuth(new MyPoint(55.750446, 37.617494)));
        }
Example #41
0
        //Yn просмотреть  и передачу по ссылке

        //Связана с RefreshPoints
        double Yn(double L, double w, double R, out double Tt, out double Rt, ref MyPoint Point3D, ref MyPoint PSV)
        {
            double TT, RT, Ybeg, Yend, Ymid, Fbeg, Fend, Fmid, B;

            //выходные параметры TT, RT



            Ybeg = -100 * R;
            Yend = 100 * R;
            Fbeg = F(L, w, R, Ybeg, out TT, out RT, Point3D, PSV);
            Fend = F(L, w, R, Yend, out TT, out RT, Point3D, PSV);

            while (((Yend - Ybeg) < -0.0001) || ((Yend - Ybeg) > 0.0001))
            {
                Ymid = (Yend + Ybeg) / 2;
                Fmid = F(L, w, R, Ymid, out TT, out RT, Point3D, PSV);
                if (Fmid == 0)
                {
                    Ybeg = Yend = Ymid;
                    break;
                }

                if ((Fbeg > 0) == (Fmid < 0))
                {
                    Yend = Ymid;
                    Fend = F(L, w, R, Yend, out TT, out RT, Point3D, PSV);
                }
                else
                {
                    Ybeg = Ymid;
                    Fbeg = F(L, w, R, Ybeg, out TT, out RT, Point3D, PSV);
                }
            }

            Ymid = (Yend + Ybeg) / 2;
            Fmid = F(L, w, R, Ymid, out TT, out RT, Point3D, PSV);
            Tt   = TT;
            Rt   = RT;
            return(Ymid);
        }
Example #42
0
        /// <summary>
        /// This operation adds, updates and deletes features to the associated feature layer or table(POST only).
        /// </summary>
        /// <param name="type"></param>
        private void EditFeatureService(EditType type, GeometryType geomType, MyPoint myPoint, MyPoly myPoly)
        {
            string formattedRequest = string.Empty;
              string jsonResponse = string.Empty;
              string jsonToSend = string.Empty;
              string attributes = string.Empty;
              string geometry = string.Empty;

              string url = CompleteServiceUrl();

              switch (type)
              {
            case EditType.add:
              {
            attributes = "\"attributes\":{\"";
            int counter = 0;

            if (_records != null)
            {
              foreach (IDataRecord record in _records)
              {
                foreach (string field in _fieldNames)
                {
                  attributes += string.Format("{0}\":\"{1}\",\"", field, record[counter].ToString());
                  counter++;
                }

                break;
              }
            }

            if (counter == 0) //no records added. Create a dummy record.
            {
              foreach (DataGridViewRow row in dataGridViewFields.Rows)
              {
                //todo: did I set a default color symbol?
                attributes += string.Format("{0}\":\"{1}\",\"", row.Cells[0].FormattedValue.ToString(), null);
              }
            }

            //remove the excess. Meaning remove the trailing rubbish
            attributes = attributes.Remove(attributes.Length - 8);

            if (geomType == GeometryType.polygon)
            {
              //Polygon geometry
              MyPoint p;
              jsonToSend = "adds=[{\"geometry\":{\"rings\":[[";
              for (int i = 0; i < myPoly.Ring.Count; i++)
              {
                p = myPoly.Ring[i];
                jsonToSend += "[" + p.X + "," + p.Y + "],";
              }
              jsonToSend = jsonToSend.Remove(jsonToSend.Length - 1, 1);
              jsonToSend += "]],\"spatialReference\":{\"wkid\":102100}}," + attributes + "}}]";

              //example
              // [{"geometry":{"rings":[[[-8304737.273855386,5018862.730810074],[-8286086.638953812,5017945.486470653],[-8280583.172917282,5006632.806284452],
              //[-8303820.029515964,4995931.622324532],[-8322164.916304397,5006938.554397592],[-8304737.273855386,5018862.730810074]]],
              //"spatialReference":{"wkid":102100}},"attributes":{"BUFF_DIST":"3","BufferArea":null,"BufferPerimeter":null}}]

            }
            else
            {
              //NB: Sample does not provide an entry method for the user to enter an XY for point geom types.
              //this is for demo purposes with a point feature service with the spatial ref as set below.
              //Users of this code need to build this functionality into their app, either with text input or map click.
              //Supplied XY places a point on the Coronado Bridge, San Diego, California

              jsonToSend = "adds=[{\"geometry\":{\"x\":" + myPoint.X + ",\"y\":" + myPoint.Y + ",\"spatialReference\":{\"wkid\":102100}}," + attributes + "}}]";
             }

            break;
              }
            case EditType.delete:
              {
            break;
              }
            case EditType.update:
              {
            break;
              }
            default:
              break;
              }

              //Make the HttpWebRequest
              _featureEditResponse = RequestAndResponseHandler.FeatureEditRequest(url, jsonToSend, out jsonResponse);

              switch (type)
              {
            case EditType.add:
              {
            if (_featureEditResponse.addResults == null)
              break;

            lblEditingResponse.Text = string.Format("Success: {0}, ObjectID: {1}, GlobalID: {2}, Error: {3}", _featureEditResponse.addResults[0].success,
              _featureEditResponse.addResults[0].objectId, _featureEditResponse.addResults[0].globalId, _featureEditResponse.addResults[0].error);

            break;
              }
            case EditType.delete:
              {
            break;
              }
            case EditType.update:
              {
            break;
              }
            default:
              break;
              }
        }
Example #43
0
        public void AzimuthAntipod3()
        {
            MyPoint point = new MyPoint(0, 0);

            Assert.Equal(-2.0, point.getAzimuth(new MyPoint(0, -180)));
        }
Example #44
0
        //Связана с Yn
        double F(double L, double w, double R, double Yn, out double Tt, out double Rt, MyPoint P3D, MyPoint PSV)
        {
            double a1, r, Xtd, Ytd, G, Lt, d, h, Rn, tga, X_, Y_, Z_, bn, X, Y, Z, O, A, B, C, D;

            if (FirstForm)
            {
                a1 = 2.4168 * R;
            }
            else
            {
                a1 = 2.841212649 * R;
            }

            if (d_link)
            {
                if (FirstForm)
                {
                    d = 8 * R;
                }
                else
                {
                    d = 8.424412649 * R;
                }
            }
            else
            {
                d = d_in;
            }

            r = 2 * R;
            h = R / Math.Tan(w);
            O = Math.PI / 2 - w;
            if (FirstForm)
            {
                tga = 1 / (8 * Math.Tan(w));
            }
            else
            {
                tga = 0.1187026370 / Math.Tan(w);
            }
            Xtd = a1 - r * Math.Sin(L);
            Ytd = r * Math.Cos(L);

            PSV.X = Xtd;
            PSV.Y = Ytd;
            PSV.Z = 0;

            G = Math.Sqrt(Xtd * Xtd + Ytd * Ytd);

            Lt = Math.Acos(a1 * Math.Cos(L) / G);
            double cosLt = Math.Cos(Lt);
            double sinLt = Math.Sin(Lt);

            Rn = Math.Sqrt(Yn * Yn + d * d);

            X_ = G * (G * cosLt * cosLt + Math.Sqrt(Rn * Rn - G * G * cosLt * cosLt) * sinLt) / Rn;
            Y_ = G * (Math.Sqrt(Rn * Rn - G * G * cosLt * cosLt) - G * sinLt) * cosLt / Rn;
            Z_ = h * (Math.Acos(G * cosLt / Rn) - Math.Atan(Ytd / Xtd) - Lt);

            bn = Math.Atan(Yn / d);

            X = X_ * Math.Cos(bn) - Y_ * Math.Sin(bn);
            Y = X_ * Math.Sin(bn) + Y_ * Math.Cos(bn);
            Z = Z_ + h * bn;

            P3D.X = X; P3D.Y = Y; P3D.Z = Z;
            A     = Yn * (1 - tga / Math.Tan(O));
            if (FirstForm)
            {
                B = -7 * R;
                C = -7 * R / (8 * Math.Tan(w));
            }
            else
            {
                B = -7.424412649 * R;
                C = -0.8812973625 * R / Math.Tan(w);
            }

            D = -R * Yn * (1 - tga / Math.Tan(O));

            Tt = Y * Math.Sin(O) - Z * Math.Cos(O);
            Rt = Math.Sqrt((Tt * Math.Sin(O) - Y) * (Tt * Math.Sin(O) - Y) + (d - X) * (d - X) +
                           (Tt * Math.Cos(O) + Z) * (Tt * Math.Cos(O) + Z));

            return(A * X + B * Y + C * Z + D);
        }
Example #45
0
        public void Distance1()
        {
            MyPoint point = new MyPoint(77.1539, -139.398);

            Assert.Equal(17166029, point.getDistance(new MyPoint(-77.1804, -139.55)));
        }
Example #46
0
        //Строим винтовую лестницу
        private void DrawWireframeDrill()
        {
            Gl.glColor3f(0, 0, 0);
            Gl.glLineWidth(1);

            MyRotate rotate  = new MyRotate();
            MyPoint  tPoint  = new MyPoint();
            MyPoint  tPoint2 = new MyPoint();


            MyPoint[] arr1;// = new MyPoint[64];
            // SetupArray(arr1);


            MyPoint[] arr2 = new MyPoint[64];
            SetupArray(arr2);

            //   O = Math.PI * 1 / 180;

            double h, dH, H, tH, t2H, L2, dL;
            int    i, j;
            int    Q = (int)(O * 180 / Math.PI + 5);


            h  = R / Math.Tan(O);
            H  = array[act_quant / 2].Y;
            dH = (2 * H) / (Q - 1);

            t2H = -H;
            L2  = t2H / h;
            rotate.SetRotate(L2, 0, 0, 1);
            for (j = 0; j < act_quant; j++)
            {
                rotate.TransformPoint(arraySV[j], arr2[j]);
            }

            dL = Math.Atan(arraySV[0].Y / arraySV[0].X);
            dL = (Math.PI - dL) * 2 / (12 - 1);

            for (i = 0; i < Q; i++)
            {
                tH  = t2H;
                t2H = -H + (i + 1) * dH;

                L2 = t2H / h;
                //  CopyArray(arr1, arr2);
                arr1 = arr2.Select(o => o.Clone()).ToArray();
                rotate.SetRotate(L2, 0, 0, 1);
                for (j = 0; j < act_quant; j++)
                {
                    rotate.TransformPoint(arraySV[j], arr2[j]);
                }

                Gl.glBegin(Gl.GL_LINE_STRIP);
                for (j = 0; j < act_quant; j++)
                {
                    Gl.glVertex3d(arr1[j].X, arr1[j].Y, tH);
                }
                Gl.glEnd();

                Gl.glBegin(Gl.GL_LINE_STRIP);
                for (j = 0; j < 12; j++)
                {
                    rotate.SetRotate(dL * j, 0, 0, 1);
                    rotate.TransformPoint(arr1[0], tPoint);
                    Gl.glVertex3d(tPoint.X, tPoint.Y, tH);
                }
                Gl.glEnd();

                if (i < (Q - 1))
                {
                    Gl.glBegin(Gl.GL_LINES);
                    for (j = 0; j < act_quant; j++)
                    {
                        Gl.glVertex3d(arr1[j].X, arr1[j].Y, tH);
                        Gl.glVertex3d(arr2[j].X, arr2[j].Y, t2H);
                    }
                    Gl.glEnd();

                    Gl.glBegin(Gl.GL_LINES);
                    for (j = 0; j < 12; j++)
                    {
                        rotate.SetRotate(dL * j, 0, 0, 1);
                        rotate.TransformPoint(arr1[0], tPoint);
                        rotate.TransformPoint(arr2[0], tPoint2);
                        Gl.glVertex3d(tPoint.X, tPoint.Y, tH);
                        Gl.glVertex3d(tPoint2.X, tPoint2.Y, t2H);
                    }
                    Gl.glEnd();
                }
            }
        }
Example #47
0
        private void Form1_MouseClick(object sender, MouseEventArgs e)
        {
            if (size != 0)
            {
                g = CreateGraphics();
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                Aa[iter] = new Point(PointToClient(Control.MousePosition).X, PointToClient(Control.MousePosition).Y);
                g.FillEllipse(Brushes.DarkBlue, Aa[iter].X - 3, Aa[iter].Y - 3, 6, 6);
                iter++;
                if (iter >= size && iter >= 3)
                {
                    int          j = 1, i = 0;
                    List <Point> S = new List <Point>();
                    S = ConvexHull(Aa.ToList());

                    while (j < S.Count() && (S[j].X != 0 || S[j].Y != 0))
                    {
                        j++;
                    }
                    Point[] polygon = new Point[j];
                    for (i = 0; i < j; i++)
                    {
                        polygon[i] = S[i];
                    }
                    g.FillPolygon(Brushes.Violet, polygon);
                    for (i = 0; i < size; i++)
                    {
                        g.FillEllipse(Brushes.DarkBlue, Aa[i].X - 3, Aa[i].Y - 3, 6, 6);
                    }
                    iter = 0;
                    List <MyPoint> points;
                    points = new List <MyPoint>();
                    for (i = 0; i < S.Count(); i++)
                    {
                        MyPoint m = new MyPoint();
                        m.id    = i;
                        m.point = S[i];
                        points.Add(m);
                    }
                    MyPoint A = points[0], B = points[1], C = points[2];
                    MyPoint bA = (MyPoint)A.Clone(), bB = (MyPoint)B.Clone(), bC = (MyPoint)C.Clone();
                    while (true)
                    {
                        while (true)
                        {
                            while (true)
                            {
                                if (C.id != points.Count() - 1)
                                {
                                    MyPoint nextC = points[C.id + 1];
                                    if (area(A.point, B.point, C.point) < area(A.point, B.point, nextC.point))
                                    {
                                        C = nextC;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }
                            if (B.id != points.Count() - 1)
                            {
                                MyPoint nextB = points[B.id + 1];
                                if (area(A.point, B.point, C.point) < area(A.point, nextB.point, C.point))
                                {
                                    B = nextB;
                                }
                                else
                                {
                                    break;
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                        if (area(A.point, B.point, C.point) > area(bA.point, bB.point, bC.point))
                        {
                            bA = A; bB = B; bC = C;
                        }

                        if (A.id != points.Count() - 1)
                        {
                            A = points[A.id + 1];
                        }
                        else
                        {
                            A = points[0];
                        }

                        if (A.point == B.point)
                        {
                            if (B.id != points.Count() - 1)
                            {
                                B = points[B.id + 1];
                            }
                        }

                        if (B.point == C.point)
                        {
                            if (C.id != points.Count() - 1)
                            {
                                C = points[C.id + 1];
                            }
                        }
                        if (A.id == 0)
                        {
                            break;
                        }
                    }
                    g.FillEllipse(Brushes.Yellow, bA.point.X - 3, bA.point.Y - 3, 6, 6);
                    g.FillEllipse(Brushes.Yellow, bB.point.X - 3, bB.point.Y - 3, 6, 6);
                    g.FillEllipse(Brushes.Yellow, bC.point.X - 3, bC.point.Y - 3, 6, 6);
                    Pen pen = new Pen(Color.Green, 1);
                    g.DrawLine(pen, bA.point, bB.point);
                    g.DrawLine(pen, bB.point, bC.point);
                    g.DrawLine(pen, bC.point, bA.point);
                }
            }
        }
Example #48
0
 public static void invokeFromjs_UpdateSVGPosition(double par_x, double par_y)
 {
     SVGPosition = new MyPoint(par_x, par_y);
 }
Example #49
0
        private MyPoint getNextPos(MyPoint curPos, MyPoint point)
        {
            if (PathList == null)
            {
                PathList = Map.getNextPosList(curPos, point, true).ToArray();
                curPathIdx = 0;
            }
            else
            {
                IEnumerable<MyPoint> pathList = Map.getNextPosList(curPos, point, false);
                if (pathList != null)
                {
                    PathList = pathList.ToArray();
                    curPathIdx = 0;
                }
            }

            MyPoint nextPos = PathList[curPathIdx];
            curPathIdx++;

            return nextPos;
        }
Example #50
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var wrapper = new TestWrapper();

            wrapper.DoWork();

            var wrapper2 = new StudentWrapper("Student A", 8.46);

            Console.WriteLine($"Student's name is {wrapper2.Name}");
            Console.WriteLine($"Student's gpa is {wrapper2.Gpa}");

            var display = new Display();

            display.Print("Hello world 2");

            var e = new EntityWrapper("The Wallman", 20, 35);

            e.Move(5, -10);

            var sa = new MyNamesSplitterClass("Firstname Surname");

            sa.Print();

            MyPoint point = new MyPoint();

            point.x = 1;
            point.x = 2;
            point.x = 3;

            var enum1 = SomeColors.Yellow;
            var enum2 = SomeColorsTyped.Yellow;

            sa.Arrays();
            sa.Avg("Result is", 1, 2, 3, 4, 5, 6, 7, 8, 50);

            uint clustersSize = 3;

            float[,] samples = new float[, ]
            {
                { 0.9f, 2.75f }, // g1 -> .
                { 0.9f, 2.85f }, // g1 -> g2
                { 1f, 3.1f },    // g2 -> .
                { 1.1f, 2.9f },  // g1 -> g2
                { 0.9f, 4f } // g3 -> .
            };

            uint   samplesSize  = (uint)samples.GetLength(0);
            ushort featuresSize = (ushort)samples.GetLength(1);

            float[,] centroids = new float[clustersSize, featuresSize];
            uint[] assignments = new uint[samplesSize];
            float  avgDistance = 0;

            KMCudaWrapper.Clusterize(
                init: KMCUDAInitMethodM.kmcudaInitMethodPlusPlus,
                tolerance: 0.05f,
                yinyang_t: 0.1f,
                metric: KMCUDADistanceMetricM.kmcudaDistanceMetricL2,
                samples_size: samplesSize,
                features_size: featuresSize,
                clusters_size: clustersSize,
                seed: 777,
                device: 1,
                device_ptrs: -1,
                fp16x2: false,
                verbosity: 2,
                samples: samples,
                centroids: ref centroids,
                assignments: ref assignments,
                average_distance: ref avgDistance,
                false
                );

            Console.WriteLine("End");
        }
Example #51
0
        /// <summary>
        /// Алгоритм Рамера — Дугласа — Пекера, для уменьшения точек кривой
        /// </summary>
        /// <param name="pointList">Массив точек, задающий кривую</param>
        /// <param name="startInd">Индекс начала кривой</param>
        /// <param name="endInd">Индекс конца кривой</param>
        /// <param name="epsilon">Точность, возведенная в квадрат</param>
        /// <returns></returns>
        public static MyPoint[] DouglasPeucker(MyPoint[] pointList, int startInd, int endInd, float epsilon)
        {
            //Находим точку с максимальным расстоянием от прямой между первой и последней точками набора
            long numeratorMax = 0, denominatorMax = 1;
            var index = 0;
            for (int i = 1; i < endInd - startInd; i++)
            {
                Multiplications += 2;
                Additions += 2;

                long numerator, denominator;
                PerpendicularDistance(pointList[i + startInd], pointList[startInd], pointList[endInd],
                    out numerator, out denominator);

                if ((numerator*denominatorMax) > (denominator*numeratorMax))
                {
                    Additions++;
                    index = i + startInd;
                    numeratorMax = numerator;
                    denominatorMax = denominator;
                }
            }

            Multiplications++;
            //Если максимальная дистанция больше, чем epsilon, то рекурсивно вызываем её на участках
            if (numeratorMax >= epsilon*denominatorMax)
            {
                Calls++;
                if (Calls > MaxCalls)
                    MaxCalls = Calls;
                MyPoint[] recResults1 = DouglasPeucker(pointList, startInd, index, epsilon);
                Calls--;

                Calls++;
                if (Calls > MaxCalls)
                    MaxCalls = Calls;
                MyPoint[] recResults2 = DouglasPeucker(pointList, index, endInd, epsilon);
                Calls --;

                Additions += 2;
                MyPoint[] result = new MyPoint[recResults1.Length + recResults2.Length - 1];

                for (int i = 0; i < recResults1.Length; i++)
                    result[i] = recResults1[i];

                for (int i = 1; i < recResults2.Length; i++)
                {
                    result[i + recResults1.Length - 1] = recResults2[i];
                    Additions += 2;
                }

                return result;
            }
            else
            {
                //проверка чтобы потом при разностном кодировании X, не выйти за пределы 1 байта
                Additions++;
                if (pointList[endInd].X - pointList[startInd].X > 255)
                {
                    Additions += 2;

                    int length = 0;
                    var deltaX = pointList[endInd].X - pointList[startInd].X;
                    int k = 0;
                    while (length < deltaX)
                    {
                        length += 255;
                        k++;
                        Additions++;
                    }
                    //ну или с делением:
                    //int k = (pointList[endInd].X - pointList[startInd].X)/255 + 1;

                    MyPoint[] resultR = new MyPoint[k + 1];
                    for (int i = 0; i < k; i++)
                    {
                        resultR[i] = pointList[startInd + i*255];
                        Additions ++;
                        Multiplications++;
                    }
                    resultR[k] = pointList[endInd];
                    return resultR;
                }
                else
                {
                    MyPoint[] resultR = new MyPoint[2];
                    resultR[0] = pointList[startInd];
                    resultR[1] = pointList[endInd];
                    return resultR;
                }
            }
        }
Example #52
0
        /// <summary>
        /// Алгоритм Рамера — Дугласа — Пекера, для уменьшения точек кривой
        /// </summary>
        /// <param name="pointList">Массив точек, задающий кривую</param>
        /// <param name="startInd">Индекс начала кривой</param>
        /// <param name="endInd">Индекс конца кривой</param>
        /// <param name="epsilon">Точность, возведенная в квадрат</param>
        /// <returns></returns>
        public static MyPoint[] DouglasPeucker(MyPoint[] pointList, int startInd, int endInd, float epsilon)
        {
            //Находим точку с максимальным расстоянием от прямой между первой и последней точками набора
            long numeratorMax = 0, denominatorMax = 1;
            var  index = 0;

            for (int i = 1; i < endInd - startInd; i++)
            {
                Multiplications += 2;
                Additions       += 2;

                long numerator, denominator;
                PerpendicularDistance(pointList[i + startInd], pointList[startInd], pointList[endInd],
                                      out numerator, out denominator);

                if ((numerator * denominatorMax) > (denominator * numeratorMax))
                {
                    Additions++;
                    index          = i + startInd;
                    numeratorMax   = numerator;
                    denominatorMax = denominator;
                }
            }

            Multiplications++;
            //Если максимальная дистанция больше, чем epsilon, то рекурсивно вызываем её на участках
            if (numeratorMax >= epsilon * denominatorMax)
            {
                Calls++;
                if (Calls > MaxCalls)
                {
                    MaxCalls = Calls;
                }
                MyPoint[] recResults1 = DouglasPeucker(pointList, startInd, index, epsilon);
                Calls--;

                Calls++;
                if (Calls > MaxCalls)
                {
                    MaxCalls = Calls;
                }
                MyPoint[] recResults2 = DouglasPeucker(pointList, index, endInd, epsilon);
                Calls--;

                Additions += 2;
                MyPoint[] result = new MyPoint[recResults1.Length + recResults2.Length - 1];

                for (int i = 0; i < recResults1.Length; i++)
                {
                    result[i] = recResults1[i];
                }

                for (int i = 1; i < recResults2.Length; i++)
                {
                    result[i + recResults1.Length - 1] = recResults2[i];
                    Additions += 2;
                }

                return(result);
            }
            else
            {
                //проверка чтобы потом при разностном кодировании X, не выйти за пределы 1 байта
                Additions++;
                if (pointList[endInd].X - pointList[startInd].X > 255)
                {
                    Additions += 2;

                    int length = 0;
                    var deltaX = pointList[endInd].X - pointList[startInd].X;
                    int k      = 0;
                    while (length < deltaX)
                    {
                        length += 255;
                        k++;
                        Additions++;
                    }
                    //ну или с делением:
                    //int k = (pointList[endInd].X - pointList[startInd].X)/255 + 1;

                    MyPoint[] resultR = new MyPoint[k + 1];
                    for (int i = 0; i < k; i++)
                    {
                        resultR[i] = pointList[startInd + i * 255];
                        Additions++;
                        Multiplications++;
                    }
                    resultR[k] = pointList[endInd];
                    return(resultR);
                }
                else
                {
                    MyPoint[] resultR = new MyPoint[2];
                    resultR[0] = pointList[startInd];
                    resultR[1] = pointList[endInd];
                    return(resultR);
                }
            }
        }
 // Безопасная в отношении типов реализация метода CompareTo
 public Int32 CompareTo(MyPoint other)
 {
     // Используем теорему Пифагора для определения точки,
     // наиболее удаленной от начала координат (0, 0)
     return Math.Sign(Math.Sqrt(m_x * m_x + m_y * m_y)
     - Math.Sqrt(other.m_x * other.m_x + other.m_y * other.m_y));
 }
 /// <summary>
 /// Retrieves the data fom the pixel selected based on
 ///  OddX   OddY    Store
 ///   0     0        A
 ///   0     1        R
 ///   1     0        G
 ///   1     1        B
 /// </summary>
 /// <param name="color"></param>
 /// <param name="point"></param>
 /// <returns></returns>
 private int retrieveDataFromColor(Color color, MyPoint point)
 {
     int data = -1;
     bool evenX = (point.X % 2) == 0;
     bool evenY = (point.Y % 2) == 0;
     if (evenX && evenY)
         data = color.A;
     else if (evenX && !evenY)
         data = color.R;
     else if (!evenX && evenY)
         data = color.G;
     else if (!evenX && !evenY)
         data = color.B;
     return data;
 }
 /// <summary>
 /// Generates a MyPoint object that does not belong to the dictionary passed.
 /// </summary>
 /// <param name="dictionary"></param>
 /// <returns></returns>
 private MyPoint generatePoint(ref Dictionary<int, MyPoint> dictionary )
 {
     MyPoint p = new MyPoint(-1, -1);
     bool operation = true;
     do
     {
         p.X = random.Next(KEY_WIDTH);
         p.Y = random.Next(KEY_HEIGHT);
         operation = dictionary.ContainsValue(p);
     } while (operation);
     return p;
 }
Example #56
0
        public void ShowRects(List<Board> BoardList)
        {
            MyPoint edgeLeftUp = new MyPoint(0 , 0);
            MyPoint edgeRightDown = new MyPoint(0, 0);
            // show rects for each board and add board range
            // do not show rects on collection board
            for(int i = 0; i < BoardList.Count; i++)
            {
                if(BoardList[i].isCollectionBoard == false)
                {
                    // for color
                    int colorPosition = 0;

                    // draw each rect in the board
                    for(int j = 0; j < BoardList[i].RectList.Count; j++)
                    {
                        // 1. calculate rect coords in combination with the board coords
                        edgeLeftUp = new MyPoint(BoardList[i].edgeLeftUp.x + BoardList[i].RectList[j].edgeLeftUp.x,
                            BoardList[i].edgeLeftUp.y + BoardList[i].height - BoardList[i].RectList[j].edgeLeftUp.y);

                        edgeRightDown = new MyPoint(BoardList[i].edgeLeftUp.x + BoardList[i].RectList[j].edgeRightDown.x,
                            BoardList[i].edgeLeftUp.y + BoardList[i].height - BoardList[i].RectList[j].edgeRightDown.y);

                        // for testing:
                        if(edgeLeftUp.y <20)
                        {
                            int s = 1;
                        }

                        // 2. draw rect
                        // 2.1 chosing color
                        List<Color> colorList = new List<Color>();
                        if(global.Verschnittoptimierung.radioButton_colorSchemeMixed.Checked)
                        {
                            colorList.Add(Color.Red);
                            colorList.Add(Color.Orange);
                            colorList.Add(Color.Yellow);
                            colorList.Add(Color.Blue);
                            colorList.Add(Color.Violet);
                            colorList.Add(Color.Pink);
                            colorList.Add(Color.Purple);
                            colorList.Add(Color.Black);
                            colorList.Add(Color.White);
                        }
                        if (global.Verschnittoptimierung.radioButton_colorSchemeBiological.Checked)
                        {
                            colorList.Add(Color.ForestGreen);
                            colorList.Add(Color.Green);
                            colorList.Add(Color.LightSkyBlue);
                            colorList.Add(Color.LawnGreen);
                            colorList.Add(Color.SteelBlue);
                            colorList.Add(Color.LightGreen);
                            colorList.Add(Color.CadetBlue);
                            colorList.Add(Color.DarkOliveGreen);
                            colorList.Add(Color.SkyBlue);
                        }
                        if (global.Verschnittoptimierung.radioButton_colorSchemeConservative.Checked)
                        {
                            colorList.Add(Color.Gray);
                            colorList.Add(Color.Gold);
                            colorList.Add(Color.DarkGray);
                            colorList.Add(Color.Brown);
                            colorList.Add(Color.Silver);
                            colorList.Add(Color.Gray);
                            colorList.Add(Color.DarkBlue);
                            colorList.Add(Color.DarkSlateGray);
                            colorList.Add(Color.WhiteSmoke);
                        }

                        Color chosenColor = colorList[colorPosition % 8];

                        // 2.2 drawing
                        using (Graphics g = global.Verschnittoptimierung.display.CreateGraphics())
                        {
                            using (Pen pen = new Pen(Color.Black, 2))
                            {
                                //global.Verschnittoptimierung.Output.Text = Convert.ToString(global.Verschnittoptimierung.display.Height);

                                Brush brush = new SolidBrush(chosenColor);
                                colorPosition++;
                                g.TranslateTransform(global.Verschnittoptimierung.display.AutoScrollPosition.X, global.Verschnittoptimierung.display.AutoScrollPosition.Y);

                                g.DrawRectangle(pen, edgeLeftUp.x, edgeLeftUp.y,
                                    edgeRightDown.x - edgeLeftUp.x,
                                    edgeRightDown.y - edgeLeftUp.y);

                                g.FillRectangle(brush, edgeLeftUp.x, edgeLeftUp.y,
                                    edgeRightDown.x - edgeLeftUp.x,
                                    edgeRightDown.y - edgeLeftUp.y);
                            }
                        }

                    }
                }
            }
        }
 /// <summary>
 /// Gets the position of the data and converts it to byte format.
 /// If data does not exist,the position is generated and the data and position is added to the
 /// encryptionKeyMap.
 /// </summary>
 /// <param name="data"></param>
 /// <param name="keyBitmap"></param>
 /// <param name="encryptionKeyMap"></param>
 /// <returns></returns>
 private byte getPositionByte(int data,ref Bitmap keyBitmap,ref Dictionary<int,MyPoint> encryptionKeyMap)
 {
     byte result = 0;
     MyPoint p = new MyPoint(-1,-1);
     if (encryptionKeyMap.ContainsKey(data))
     {
         p = encryptionKeyMap[data];
     }
     else//if(p.X == -1 || p.Y == -1) Before
     {
         p = addDataToKeyBitmap(data, ref keyBitmap, ref encryptionKeyMap);
     }
     result = (byte)(p.X * 16 + p.Y);
     return result;
 }
Example #58
0
        public void ShowBoards(List<Board> BoardList, Boolean isFromBenchmark)
        {
            // calculate new point (because drawing goes from leftUp to rightDown
            MyPoint edgeLeftUp = new MyPoint (0, 0);
            MyPoint edgeRightDown = new MyPoint(0, 0);

            for (int i = 0; i < BoardList.Count; i++)
            {
                if(BoardList[i].isCollectionBoard == false && i % 2 == 0)
                {
                    // board gap + (width+gap) * (i/2)
                    edgeLeftUp = new MyPoint(global.boardGap + (i/2) * (BoardList[i].width + global.boardGap), global.boardGap);
                    edgeRightDown = new MyPoint(edgeLeftUp.x + BoardList[i].width, edgeLeftUp.y + BoardList[i].height);
                }
                else if (BoardList[i].isCollectionBoard == false && i % 2 != 0)
                {
                    // 532 = application display height (above scrollbar)
                    edgeLeftUp = new MyPoint(global.boardGap + ((i-1)/2) * (BoardList[i].width + global.boardGap), 532 - (global.boardGap + BoardList[i].height));
                    edgeRightDown = new MyPoint(edgeLeftUp.x + BoardList[i].width, edgeLeftUp.y + BoardList[i].height);
                }
                else if (BoardList[i].isCollectionBoard == true)
                {
                    edgeLeftUp = new MyPoint(BoardList[i-1].edgeRightDown.x + global.boardGap, global.boardGap);
                    edgeRightDown = new MyPoint(edgeLeftUp.x + BoardList[i].width, edgeLeftUp.y + BoardList[i].height);
                }
                else
                {
                    // should not happen
                }

                // IMPORTANT: set edgeLeftUp and edgeRightUp at the benchmark OR in the solution in global,
                // depending on if the boards are from the solution or a benchmark
                if(isFromBenchmark)
                {
                    global.benchmark.boardList[i].edgeLeftUp = edgeLeftUp;
                    global.benchmark.boardList[i].edgeRightDown = edgeRightDown;
                }
                else
                {
                    global.solution.BoardList[i].edgeLeftUp = edgeLeftUp;
                    global.solution.BoardList[i].edgeRightDown = edgeRightDown;
                }

                // drawing
                using (Graphics g = global.Verschnittoptimierung.display.CreateGraphics())
                {
                    using (Pen pen = new Pen(Color.Black, 2))
                    {
                        //global.Verschnittoptimierung.Output.Text = Convert.ToString(global.Verschnittoptimierung.display.Height);

                        Brush brush = new SolidBrush(Color.AliceBlue);
                        g.TranslateTransform(global.Verschnittoptimierung.display.AutoScrollPosition.X, global.Verschnittoptimierung.display.AutoScrollPosition.Y);

                        g.DrawRectangle(pen, edgeLeftUp.x, edgeLeftUp.y,
                            edgeRightDown.x - edgeLeftUp.x,
                            edgeRightDown.y - edgeLeftUp.y);

                        g.FillRectangle(brush, edgeLeftUp.x, edgeLeftUp.y,
                            edgeRightDown.x - edgeLeftUp.x,
                            edgeRightDown.y - edgeLeftUp.y);
                    }
                }
            }
            // reposition button in display to activate horizontal autoscroll
            if (BoardList[BoardList.Count() - 1].edgeRightDown.x > global.displayWidth)
            {
                int newRange = Convert.ToInt32(BoardList[BoardList.Count() - 1].edgeRightDown.x) + 30;
                global.Verschnittoptimierung.buttonInDisplay.Left = newRange;
                global.Verschnittoptimierung.buttonInDisplay.Visible = true;

                global.displayWidth = newRange;
            }
        }
 public Position()
 {
     this.edgeLeftUp = new MyPoint();
     this.edgeRightDown = new MyPoint();
 }
Example #60
0
 public Line(MyPoint a, MyPoint b)
 {
     PointA = a;
     PointB = b;
 }