// Draw the unsimplified polygon
        private void DrawPolygon()
        {
            MapPoint center = MyMapView.Extent.GetCenter();
            double lat = center.Y;
            double lon = center.X + 300;
            double latOffset = 300;
            double lonOffset = 300;

            var points = new PointCollection()
            {
                new MapPoint(lon - lonOffset, lat),
                new MapPoint(lon, lat + latOffset),
                new MapPoint(lon + lonOffset, lat),
                new MapPoint(lon, lat - latOffset),
                new MapPoint(lon - lonOffset, lat),
                new MapPoint(lon - 2 * lonOffset, lat + latOffset),
                new MapPoint(lon - 3 * lonOffset, lat),
                new MapPoint(lon - 2 * lonOffset, lat - latOffset),
                new MapPoint(lon - 1.5 * lonOffset, lat + latOffset),
                new MapPoint(lon - lonOffset, lat)
            };
            _unsimplifiedPolygon = new Polygon(points, MyMapView.SpatialReference);

			_polygonOverlay.Graphics.Clear();
			_polygonOverlay.Graphics.Add(new Graphic(_unsimplifiedPolygon));
        }
Ejemplo n.º 2
0
        private PointCollection RossCalculate1(RossData CurrentData, double inc)
        {
            
            PointCollection points = new PointCollection();
            var maxAngle = CurrentData.SuggestedMaxTurns * 2 * Math.PI;
            var X = 0.0;
            var Y = 0.0;
            var N = (CurrentData.N == -CurrentData.N)
                ? CurrentData.N - 1.0
                : CurrentData.N + 1.0;
                        
            var Phi1 = FNR(CurrentData.Phi1);
            var Phi2 = FNR(CurrentData.Phi2);
            var Phi3 = FNR(CurrentData.Phi3);

            X = CurrentData.Ex1 * Math.Cos(0) + CurrentData.SR * Math.Cos(Phi1) + CurrentData.Fl * Math.Cos(Phi2) + CurrentData.Fr * Math.Cos(Phi3);
            Y = CurrentData.Ex1 * Math.Sin(0) + CurrentData.SR * Math.Sin(Phi1) + CurrentData.Fl * Math.Sin(Phi2) + CurrentData.Fr * Math.Sin(Phi3);
            points.Add(new Point(X, Y));

            for (var Theta = inc; Theta <= maxAngle; Theta += inc)
            {
                X = CurrentData.Ex1 * Math.Cos(Theta) + CurrentData.SR * Math.Cos(N * Theta + Phi1) + CurrentData.Fl * Math.Cos(CurrentData.M * Theta + Phi2) + CurrentData.Fr * Math.Cos(CurrentData.L * Theta + Phi3);
                Y = CurrentData.Ex1 * Math.Sin(Theta) + CurrentData.SR * Math.Sin(N * Theta + Phi1) + CurrentData.Fl * Math.Sin(CurrentData.M * Theta + Phi2) + CurrentData.Fr * Math.Sin(CurrentData.L * Theta + Phi3);
                points.Add(new Point(X, Y));
            }
            return points;
        }
		// Draw the unsimplified polygon
		private void DrawPolygon()
		{
			// Get current viewpoints extent from the MapView
			var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
			var viewpointExtent = currentViewpoint.TargetGeometry.Extent; 

			MapPoint center = viewpointExtent.GetCenter();
			double lat = center.Y;
			double lon = center.X + 300;
			double latOffset = 300;
			double lonOffset = 300;

			var points = new PointCollection()
			{
				new MapPoint(lon - lonOffset, lat),
				new MapPoint(lon, lat + latOffset),
				new MapPoint(lon + lonOffset, lat),
				new MapPoint(lon, lat - latOffset),
				new MapPoint(lon - lonOffset, lat),
				new MapPoint(lon - 2 * lonOffset, lat + latOffset),
				new MapPoint(lon - 3 * lonOffset, lat),
				new MapPoint(lon - 2 * lonOffset, lat - latOffset),
				new MapPoint(lon - 1.5 * lonOffset, lat + latOffset),
				new MapPoint(lon - lonOffset, lat)
			};
			_unsimplifiedPolygon = new Polygon(points, MyMapView.SpatialReference);

			_polygonOverlay.Graphics.Clear();
			_polygonOverlay.Graphics.Add(new Graphic(_unsimplifiedPolygon));
		}
Ejemplo n.º 4
0
        public static PointCollection GetSelectionPolygon(Rect topRect, Rect bottomRect, double width, double offsetX, double lineInterval)
        {
            double lineIntervalCompensation = 0;
            if(lineInterval < 1)
            {
                lineIntervalCompensation = 1 - lineInterval;
            }
            double topRectCompensation = topRect.Height * lineIntervalCompensation;
            double bottmRectCompensation = bottomRect.Height * lineIntervalCompensation;

            var pointCollection = new PointCollection();
            if (topRect.Top < bottomRect.Top)
            {
                pointCollection.Add(new Point(offsetX, topRect.Bottom));
                pointCollection.Add(new Point(topRect.Left, topRect.Bottom));
                pointCollection.Add(new Point(topRect.Left, topRect.Top + topRectCompensation));
                pointCollection.Add(new Point(width - offsetX, topRect.Top + topRectCompensation));
                pointCollection.Add(new Point(width - offsetX, bottomRect.Top + bottmRectCompensation));
                pointCollection.Add(new Point(bottomRect.Right, bottomRect.Top + bottmRectCompensation));
                pointCollection.Add(new Point(bottomRect.Right, bottomRect.Bottom));
                pointCollection.Add(new Point(offsetX, bottomRect.Bottom));
            }
            else
            {
                pointCollection.Add(new Point(topRect.Left, topRect.Bottom));
                pointCollection.Add(new Point(topRect.Left, topRect.Top + topRectCompensation));
                pointCollection.Add(new Point(bottomRect.Right, bottomRect.Top + bottmRectCompensation));
                pointCollection.Add(new Point(bottomRect.Right, bottomRect.Bottom));
            }
            return pointCollection;
        } 
Ejemplo n.º 5
0
 public PointCollection BarrelOutline(double inc)
 {
     PointCollection pc = new PointCollection();
     double phse = rad * Phase;
     double lastr = 0;
     double r;
     double tp;
     double a = 0;
     Point pd;
     int N = (int)Math.Floor(1.0 / inc);
     for (double i = 1; i < N; i++)
     {
         double f = i * inc;
         r = CalcR(f, 0);
         a = f * twopi + phse;
         tp = ToolPosition + r - lastr;
         pd = new Point(tp * Math.Cos(a), tp * Math.Sin(a));
         pc.Add(pd);
         lastr = r;
     }
     r = CalcR(1.0, 0);
     a = twopi + phse;
     tp = ToolPosition + r - lastr;
     pd = new Point(tp * Math.Cos(a), tp * Math.Sin(a));
     pc.Add(pd);
     return pc;
 }
Ejemplo n.º 6
0
        private static Polygon MultiPolygonWktToPolygon(string wkt)
        {
            var polygon = new Polygon();

            var pointCollection = new PointCollection();
            var removed = wkt.Replace("MULTIPOLYGON (", "");
            var preSplit = removed.Replace(")), ((", "|");
            var rings = preSplit.Split('|');

            foreach (var r in rings)
            {
                PointCollection pc = new PointCollection();

                var r1 = r.Replace("(", "");
                var r2 = r1.Replace(")", "");
                var r3 = r2.Trim();

                var coords = r3.Split(',');
                foreach(var coord in coords)
                {
                    coord.Trim();
                    var xy = coord.Trim().Split(' ');
                    if (xy.Length != 2)
                    continue;

                    pc.Add(new MapPoint(double.Parse(xy[0], CultureInfo.InvariantCulture), double.Parse(xy[1], CultureInfo.InvariantCulture)));
                }

                polygon.Rings.Add(pc);
            }

            return polygon;
        }
Ejemplo n.º 7
0
        public void OnPointerPressed(InqCanvas inqCanvas, PointerRoutedEventArgs e)
        {
            Debug.WriteLine(e.Pointer.PointerDeviceType);
            _currentStroke = new PointCollection();
            _polyline = new Polyline
            {
                Stroke = new SolidColorBrush(StrokeColor),
                StrokeThickness = 3,
                StrokeLineJoin = PenLineJoin.Round
            };
            inqCanvas.Children.Add(_polyline);

            _polyline.Points = _currentStroke;

            var point = e.GetCurrentPoint(inqCanvas);

            _strokeBuilder.BeginStroke(point);
            _currentStroke.Add(point.Position);

            //_inkManager.

            /*
            //TODO: add data binding for thickness and color
            _currentStroke.StrokeThickness = Math.Max(4.0 * e.GetCurrentPoint(inqCanvas).Properties.Pressure, 2);
            _currentInqLineView.StrokeThickness = _currentStroke.StrokeThickness;
            inqCanvas.Children.Add(_currentInqLineView);
            var currentPoint = e.GetCurrentPoint(inqCanvas);
            _currentStroke.AddPoint(new Point(currentPoint.Position.X, currentPoint.Position.Y));
            */
        }
        public InsertPointsCommandFactory(WorldEditor worldEditor, IWorldContainer parentObject, int index)
        {
            this.app = worldEditor;
            this.parent = (PointCollection) parentObject;
            this.index = index;

            // placing = true;
        }
 public ParallelCoordsPolyline()
 {
     this.InitializeComponent();
     _polylinePoints = new PointCollection();
     _selected = false;
     _filtered = false;
     _searched = false;
 }
 public InsertPointsCommand(WorldEditor worldEditor, IWorldContainer parent, Vector3 newPoint, int index)
 {
     this.app = worldEditor;
     this.parent = (PointCollection) parent;
     this.newPoint = newPoint;
     this.index = index;
     this.placing = true;
 }
        private void OnViewpointChanged(object sender, EventArgs e)
        {
            // Unhook the event
            _myMapView.ViewpointChanged -= OnViewpointChanged;

            // Get area that is shown in a MapView
            Polygon visibleArea = _myMapView.VisibleArea;

            // Get extent of that area
            Envelope extent = visibleArea.Extent;
   
            // Get central point of the extent
            MapPoint centerPoint = extent.GetCenter();

            // Create values inside the visible extent for creating graphic
            var extentWidth = extent.Width / 5;
            var extentHeight = extent.Height / 10;

            // Create point collection
            PointCollection points = new PointCollection(SpatialReferences.WebMercator)
                {
                    new MapPoint(centerPoint.X - extentWidth * 2, centerPoint.Y - extentHeight * 2),
                    new MapPoint(centerPoint.X - extentWidth * 2, centerPoint.Y + extentHeight * 2),
                    new MapPoint(centerPoint.X + extentWidth * 2, centerPoint.Y + extentHeight * 2),
                    new MapPoint(centerPoint.X + extentWidth * 2, centerPoint.Y - extentHeight * 2)
                };

            // Create overlay to where graphics are shown
            GraphicsOverlay overlay = new GraphicsOverlay();

            // Add points to the graphics overlay
            foreach (var point in points)
            {
                // Create new graphic and add it to the overlay
                overlay.Graphics.Add(new Graphic(point));
            }

            // Create symbol for points
            SimpleMarkerSymbol pointSymbol = new SimpleMarkerSymbol()
            {
                Color = System.Drawing.Color.Yellow,
                Size = 30,
                Style = SimpleMarkerSymbolStyle.Square,
            };

            // Create simple renderer with symbol
            SimpleRenderer renderer = new SimpleRenderer(pointSymbol);

            // Set renderer to graphics overlay
            overlay.Renderer = renderer;

            // Make sure that the UI changes are done in the UI thread
            RunOnUiThread(() =>
            {
                // Add created overlay to the MapView
                _myMapView.GraphicsOverlays.Add(overlay);
            });
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Convert a collection of points into a <see cref="PointCollectionList"/> that can be used as paths in <see cref="Polyline"/> types
 /// or rings in <see cref="Polygon"/> types
 /// </summary>
 /// <param name="points"></param>
 /// <returns></returns>
 public static PointCollectionList ToPointCollectionList(this IEnumerable<Point> points)
 {
     var result = new PointCollectionList();
     var pointCollection = new PointCollection();
     foreach (var point in points)
         pointCollection.Add(point.ToPointCollectionEntry());
     result.Add(pointCollection);
     return result;
 }
 public RoomDrawingViewModel()
 {
     this.roomCorners = new PointCollection();
     this.Translate = new DelegateCommandWithParameter<ManipulationDeltaRoutedEventArgs>(this.ExecuteTranslateCommand);
     this.DisableInertia = new DelegateCommandWithParameter<ManipulationInertiaStartingRoutedEventArgs>(this.ExecuteDisableInertiaCommand);
     this.Scale = new DelegateCommandWithParameter<ManipulationDeltaRoutedEventArgs>(this.ExecuteScaleCommand);
     this.BackToMainMenu = new DelegateCommand(this.ExecuteBackToMainMenuCommand);
     this.ShowWallSizes = new DelegateCommand(this.ExecuteShowWallSizesCommand);
 }
		// Helper method
		private static PointCollection FromArray(params double[] parameters)
		{
			PointCollection coll = new PointCollection();
			for (int i = 0; i < parameters.Length - 1; i+=2)
			{
				coll.Add(new MapPoint(parameters[i], parameters[i + 1]));
			}
			return coll;
		}
Ejemplo n.º 15
0
 public MPPoint(int pointNum, PointCollection parent, WorldEditor worldEditor, string meshName, string meshMaterial, Vector3 position, MPPointType type)
 {
     this.PointNum = pointNum;
     this.parent = parent;
     this.app = worldEditor;
     this.meshName = meshName;
     this.meshMaterial = meshMaterial;
     this.position = position;
     this.type = type;
 }
 public QueryBoxListItemViewModel(TimeSeries ts, int resultNo)
 {
     TimeSeriesModel = ts;
     ResultNo = resultNo.ToString();
     Name = ts.MetaData.Name;
     Points = new PointCollection();
     SelectionX = GraphWidth*ts.MetaData.SelectionStart;
     SelectionWidth = GraphWidth * ts.MetaData.SelectionEnd - SelectionX;
     UpdateGraph();
 }
Ejemplo n.º 17
0
        // METHOD IsCCW() IS MODIFIED FROM ANOTHER WORK AND IS ORIGINALLY BASED ON GeoTools.NET:
        /*
         *  Copyright (C) 2002 Urban Science Applications, Inc.
         *
         *  This library is free software; you can redistribute it and/or
         *  modify it under the terms of the GNU Lesser General Public
         *  License as published by the Free Software Foundation; either
         *  version 2.1 of the License, or (at your option) any later version.
         *
         *  This library is distributed in the hope that it will be useful,
         *  but WITHOUT ANY WARRANTY; without even the implied warranty of
         *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
         *  Lesser General Public License for more details.
         *
         *  You should have received a copy of the GNU Lesser General Public
         *  License along with this library; if not, write to the Free Software
         *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
         *
         */
        /// <summary>
        /// Tests whether a ring is oriented counter-clockwise.
        /// </summary>
        /// <param name="ring">Ring to test.</param>
        /// <returns>Returns true if ring is oriented counter-clockwise.</returns>
        public static bool IsCCW(PointCollection ring)
        {
            MapPoint PrevPoint, NextPoint;
            MapPoint p;

            // Check if the ring has enough vertices to be a ring
            if (ring.Count < 3) throw (new ArgumentException("Invalid LinearRing"));

            // find the point with the largest Y coordinate
            MapPoint hip = ring[0];
            int hii = 0;
            for (int i = 1; i < ring.Count; i++)
            {
                p = ring[i];
                if (p.Y > hip.Y)
                {
                    hip = p;
                    hii = i;
                }
            }
            // Point left to Hip
            int iPrev = hii - 1;
            if (iPrev < 0) iPrev = ring.Count - 2;
            // Point right to Hip
            int iNext = hii + 1;
            if (iNext >= ring.Count) iNext = 1;
            PrevPoint = ring[iPrev];
            NextPoint = ring[iNext];

            // translate so that hip is at the origin.
            // This will not affect the area calculation, and will avoid
            // finite-accuracy errors (i.e very small vectors with very large coordinates)
            // This also simplifies the discriminant calculation.
            double prev2X = PrevPoint.X - hip.X;
            double prev2Y = PrevPoint.Y - hip.Y;
            double next2X = NextPoint.X - hip.X;
            double next2Y = NextPoint.Y - hip.Y;
            // compute cross-product of vectors hip->next and hip->prev
            // (e.g. area of parallelogram they enclose)
            double disc = next2X*prev2Y - next2Y*prev2X;
            // If disc is exactly 0, lines are collinear.  There are two possible cases:
            //	(1) the lines lie along the x axis in opposite directions
            //	(2) the line lie on top of one another
            //  (2) should never happen, so we're going to ignore it!
            //	(Might want to assert this)
            //  (1) is handled by checking if next is left of prev ==> CCW

            if (disc == 0.0)
            {
                // poly is CCW if prev x is right of next x
                return (PrevPoint.X > NextPoint.X);
            }
            // if area is positive, points are ordered CCW
            return (disc > 0.0);
        }
 protected void SetPolylinePointsProperty(Polyline polyline, PointCollection pointCollection)
 {
     // Changing .Points during an Arrange pass can create a layout cycle on Silverlight
     if (!polyline.Points.SequenceEqual(pointCollection))
     {
         polyline.Points = pointCollection;
         // In rare cases, Silverlight doesn't update the line visual to match the new points;
         // calling InvalidateArrange works around that problem.
         polyline.InvalidateArrange();
     }
 }
		// Helper method
		private static PointCollection FromArray(params double[] parameters)
		{
			PointCollection coll = new PointCollection(SpatialReferences.Wgs84);
			var mapPointBuilder = new MapPointBuilder(SpatialReferences.Wgs84);
			for (int i = 0; i < parameters.Length - 1; i+=2)
			{
				mapPointBuilder.SetValues(parameters[i], parameters[i + 1]);
				coll.Add(mapPointBuilder.ToGeometry());
			}
			return coll;
		}
Ejemplo n.º 20
0
        public Hex(LandType type)
        {
            landType = type;
            diceRollValue = -1;

            neighboringHexes = new Hex[6];
            Points = new PointCollection();
            for (int i = 0; i < 6; ++i)
            {
                neighboringHexes[i] = null;
            }
        }
 /// <summary>
 /// Updates the shape for the series.
 /// </summary>
 /// <param name="definitionPoints">Locations of the points of each SeriesDefinition in the series.</param>
 protected override void UpdateShape(IList<IEnumerable<Point>> definitionPoints)
 {
     for (int i = 0; i < SeriesDefinitions.Count; i++)
     {
         PointCollection pointCollection = new PointCollection();
         foreach (Point p in ((ActualIndependentAxis is ICategoryAxis) ? definitionPoints[i].OrderBy(p => p.X) : definitionPoints[i]))
         {
             pointCollection.Add(p);
         }
         SetPolylinePointsProperty((Polyline)SeriesDefinitionShapes[SeriesDefinitions[i]], pointCollection);
     }
 }
 Polygon envelopeToPolygon(Envelope env)
 {
     PointCollection points = new PointCollection();
     points.Add(new MapPoint(env.XMin, env.YMin, env.SpatialReference));
     points.Add(new MapPoint(env.XMin, env.YMax, env.SpatialReference));
     points.Add(new MapPoint(env.XMax, env.YMax, env.SpatialReference));
     points.Add(new MapPoint(env.XMax, env.YMin, env.SpatialReference));
     points.Add(new MapPoint(env.XMin, env.YMin, env.SpatialReference));
     Polygon polygon = new Polygon();
     polygon.Rings.Add(points);
     return polygon;
 }
		// Creates a polyline with two paths in the shape of an 'X' centered at the given point
		private Polyline CreatePolylineX(MapPoint center, double length)
		{
			var halfLen = length / 2.0;

			PointCollection coords1 = new PointCollection();
			coords1.Add(new MapPoint(center.X - halfLen, center.Y + halfLen));
			coords1.Add(new MapPoint(center.X + halfLen, center.Y - halfLen));

			PointCollection coords2 = new PointCollection();
			coords2.Add(new MapPoint(center.X + halfLen, center.Y + halfLen));
			coords2.Add(new MapPoint(center.X - halfLen, center.Y - halfLen));

			return new Polyline(new List<PointCollection> { coords1, coords2 }, MyMapView.SpatialReference);
		}
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            double valueAsDouble = DebugHelper.CastAndAssert<double>(value);

            double LeftBase = 20;

            double RightBase = 20;

            if (BaseShape == null)
            {
                BaseShape = new Polygon();

                BaseShape.Points.Add(new Point(-20,25));
                BaseShape.Points.Add(new Point(-20,20));
                BaseShape.Points.Add(new Point(0,0));
                BaseShape.Points.Add(new Point(20,20));
                BaseShape.Points.Add(new Point(20,25));
            }

            PointCollection newShape = new PointCollection();

            double maxValue = Windows.UI.Xaml.Window.Current.Bounds.Width;

            if (BaseShape != null)
            {
                foreach (Point j in BaseShape.Points)
                {
                    double shiftX = j.X;

                    if (valueAsDouble < LeftBase)
                    {
                        if (j.X < 0)
                        {
                            shiftX = j.X * valueAsDouble / LeftBase;
                        }
                    }
                    if ((maxValue - valueAsDouble) < RightBase)
                    {
                        if (j.X > 0)
                        {
                            shiftX = j.X * (maxValue - valueAsDouble) / RightBase;
                        }
                    }

                    newShape.Add(new Point(shiftX, j.Y));
                }
            }

            return newShape;
        }
Ejemplo n.º 25
0
        public RoadObject(String objectName, IWorldContainer parentContainer, WorldEditor worldEditor, int halfWidth)
        {
            name = objectName;
            parent = parentContainer;
            app = worldEditor;
            children = new List<IWorldObject>();

            this.HalfWidth = halfWidth;
            this.nameValuePairs = new NameValueObject();

            points = new PointCollection(this, app, false, true, app.Config.RoadPointMeshName, app.Config.RoadPointMaterial, MPPointType.Road);
            Add(points);
            points.PointsChanged += new PointsChangedEventHandler(PointsChangedHandler);
        }
Ejemplo n.º 26
0
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var sw = Window.Current.Bounds.Width;
            var sh = Window.Current.Bounds.Height;
            var input = (PointCollection) value;

            var pc = new PointCollection();
            foreach (var p in input)
            {
                pc.Add(new Point(p.X * sw * 0.08, p.Y * sh * 0.08));

            }

            return pc;
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Generates texture coordinates as if mesh were a cylinder.
        /// </summary>
        /// <param name="mesh">The mesh</param>
        /// <param name="cylinderAxis">The axis of rotation for the cylinder</param>
        /// <returns>The generated texture coordinates</returns>
        public static void GenerateCylindricalTextureCoordinates(this MeshGeometry3D mesh, Vector3D cylinderAxis)
        {
            Rect3D bounds = mesh.Bounds;
            int count = mesh.Positions.Count;
            PointCollection texcoords = new PointCollection(count);
            IEnumerable<Point3D> positions = TransformPoints(ref bounds, mesh.Positions, ref cylinderAxis);

            mesh.TextureCoordinates.Clear();
            foreach (Point3D vertex in positions)
            {
                mesh.TextureCoordinates.Add(new Point(
                    GetUnitCircleCoordinate(-vertex.Z, vertex.X),
                    1.0 - GetPlanarCoordinate(vertex.Y, bounds.Y, bounds.SizeY)));
            }
        }
Ejemplo n.º 28
0
 private PointCollection CalculateWheels(WheelsData CurrentData, 
                                         double inc)
 {
     PointCollection pts = new PointCollection();
     var maxAngle = CurrentData.SuggestedMaxTurns * 2 * Math.PI; 
     for (double t = 0; t < maxAngle; t += inc)
     {
         Complex c = new Complex();
         foreach (WheelStageData sd in CurrentData.Stages)
         {
             c += sd.Amplitude * Complex.Exp(new Complex(0,sd.Frequency * t ));
         }
         pts.Add(new Point(c.Real, c.Imaginary));
     }
     return pts;
 }
 /// <summary>
 /// Updates the Shape for the series.
 /// </summary>
 /// <param name="definitionPoints">Locations of the points of each SeriesDefinition in the series.</param>
 protected override void UpdateShape(IList<IEnumerable<Point>> definitionPoints)
 {
     for (int i = SeriesDefinitions.Count - 1; 0 < i; i--)
     {
         PointCollection pointCollection = new PointCollection();
         IEnumerable<Point> topPoints = (ActualIndependentAxis is ICategoryAxis) ? definitionPoints[i].OrderBy(p => p.X) : definitionPoints[i];
         foreach (Point p in topPoints)
         {
             pointCollection.Add(p);
         }
         IEnumerable<Point> bottomPoints = (ActualIndependentAxis is ICategoryAxis) ? definitionPoints[i - 1].OrderByDescending(p => p.X) : definitionPoints[i - 1].Reverse();
         foreach (Point p in bottomPoints)
         {
             pointCollection.Add(p);
         }
         SetPolygonPointsProperty((Polygon)SeriesDefinitionShapes[SeriesDefinitions[i]], pointCollection);
     }
     if (1 <= SeriesDefinitions.Count)
     {
         double plotAreaMaximumDependentCoordinate = ActualDependentAxis.GetPlotAreaCoordinate(ActualDependentRangeAxis.Range.Maximum).Value;
         IComparable zeroValue = ActualDependentRangeAxis.Origin ?? 0.0;
         if (zeroValue.CompareTo(ActualDependentRangeAxis.Range.Minimum) < 0)
         {
             zeroValue = ActualDependentRangeAxis.Range.Minimum;
         }
         if (0 < zeroValue.CompareTo(ActualDependentRangeAxis.Range.Maximum))
         {
             zeroValue = ActualDependentRangeAxis.Range.Maximum;
         }
         double zeroCoordinate = ActualDependentAxis.GetPlotAreaCoordinate(zeroValue).Value;
         PointCollection pointCollection = new PointCollection();
         Point[] topPoints = ((ActualIndependentAxis is ICategoryAxis) ? definitionPoints[0].OrderBy(p => p.X) : definitionPoints[0]).ToArray();
         foreach (Point p in topPoints)
         {
             pointCollection.Add(p);
         }
         if (0 < topPoints.Length)
         {
             Point firstPoint = topPoints[0];
             Point lastPoint = topPoints[topPoints.Length - 1];
             pointCollection.Add(new Point(lastPoint.X, plotAreaMaximumDependentCoordinate - zeroCoordinate));
             pointCollection.Add(new Point(firstPoint.X, plotAreaMaximumDependentCoordinate - zeroCoordinate));
         }
         SetPolygonPointsProperty((Polygon)SeriesDefinitionShapes[SeriesDefinitions[0]], pointCollection);
     }
 }
        private void AjaxReport01()
        {
            // hcVendas.Appearance = new Appearance { renderTo = "container", zoomType = "x" };
               // hcVendas.YAxis.Add(new YAxisItem { title = new Title("SoC"), type = AxisDataType.linear });
            //hcVendas.XAxis.Add(new XAxisItem { maxZoom = 5, labels = (new Labels { rotation = 45, step = 2 }) });

            hcVendas.Title = new Title("SoC Daily");
            hcVendas.SubTitle = new SubTitle("Min - Max - Dash");

            hcVendas.Theme = "gray";
            hcVendas.Legend = new Legend { align = Align.right, layout = Layout.vertical, verticalAlign = VerticalAlign.top, x = -10, y = 70, borderWidth = 0 };
               hcVendas.Appearance = new Appearance { renderTo = "container", animation=false};
               hcVendas.YAxis.Add(new YAxisItem {title = new Title("SoC %")});
             //  hcVendas.XAxis.Add(new XAxisItem { title = new Title("Time in Hours") });
               hcVendas.XAxis.Add(new XAxisItem { type = AxisDataType.datetime, dateTimeLabelFormats = new DateTimeLabelFormats { hour = "%H" }, title = new Title("Time in Hours") });
              // hcVendas.XAxis.Add(new XAxisItem { categories = new object[] { "1:00", "2:00", "3:00", "4:00", "5:00", "6:00", "7:00", "8:00", "9:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00", "24:00"} });

              // hcVendas.Tooltip = new ToolTip("Highcharts.dateFormat("%H:%M", this.x) +": "+ this.y");

            //Get point collection
            var pointCollectionSocMin = new PointCollection();
            var pointCollectionSocMax = new PointCollection();
            var pointCollectionSocDas = new PointCollection();
            GetChartData gd = new GetChartData();

             DateTime dt1 = new DateTime(2015,8,22);

             DataTable dataTable = gd.GetSoCDt(194, dt1);
            foreach (DataRow row in dataTable.Rows)
            {
                pointCollectionSocMin.Add(new Point(Convert.ToInt64((DateTime.Parse(row["Time_Occur"].ToString()).Subtract(new DateTime(2015, 1, 1))).TotalMilliseconds), Convert.ToDouble(row["SocMin"])));
                pointCollectionSocMax.Add(new Point(Convert.ToInt64((DateTime.Parse(row["Time_Occur"].ToString()).Subtract(new DateTime(2015, 1, 1))).TotalMilliseconds), Convert.ToDouble(row["SocMax"])));
                pointCollectionSocDas.Add(new Point(Convert.ToInt64((DateTime.Parse(row["Time_Occur"].ToString()).Subtract(new DateTime(2015, 1, 1))).TotalMilliseconds), Convert.ToDouble(row["SocDash"])));
               // pointCollection.Add(new Point(DateTime.Parse(row["Time_Occur"].ToString()), Convert.ToDouble(row["SocMin"])));
            }

            //Add data to serie
            var series = new Collection<Serie> { new Serie { name = "SocMin", data = pointCollectionSocMin.ToArray() }, new Serie { name = "SocMax", data = pointCollectionSocMax.ToArray() }, new Serie { name = "SocDash",  data = pointCollectionSocDas.ToArray() } };
            hcVendas.PlotOptions = new PlotOptionsLine {marker= new Marker{enabled=false}, dataLabels = new DataLabels { enabled = false }};

            //Bind the control
            hcVendas.DataSource = series;
            hcVendas.DataBind();
        }
Ejemplo n.º 31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ColumnSeries"/> class.
 /// </summary>
 public ColumnSeries()
 {
     ColumnPoints = new PointCollection();
     IsFill       = true;
 }
Ejemplo n.º 32
0
        /// <summary>
        /// Generates the datas.
        /// </summary>
        override public void GenerateDatas()
        {
            ColumnPoints.Clear();

            if (this.Points != null && this.SeriesContainer != null)
            {
                if (!IsPointsGenerated)
                {
                    Parts.Clear();
                }
                StartEndPoints = new PointCollection();
                Rects          = new List <Rect>();
                CalculateMinAndMax();
                ChartPoint oldPoint = new ChartPoint()
                {
                    XValue = double.MinValue, YValue = double.MinValue
                };
                IntializePoints();
                Point startAndEndPoint = CalculateColumnSeriesInfo();
                foreach (ChartPoint point in this.Points)
                {
                    if (CheckValuePoint(oldPoint, point))
                    {
                        Point linePoint  = NormalizePoint(new Point(point.XValue, point.YValue));
                        Point startPoint = NormalizePoint(new Point(point.XValue + startAndEndPoint.X, point.YValue));
                        Point endPoint   = NormalizePoint(new Point(point.XValue + startAndEndPoint.Y, YMin));
                        StartEndPoints.Add(startPoint);
                        StartEndPoints.Add(endPoint);
                        ColumnPoints.Add(linePoint);
                        Rects.Add(new Rect(startPoint, endPoint));
                        oldPoint = point;
                    }
                }
                if (this.RenderingMode == RenderingMode.Default)
                {
                    //if (!UseSinglePart)
                    //{
                    if (!IsPointsGenerated)
                    {
                        for (int i = 0; i <= this.StartEndPoints.Count - 2; i += 2)
                        {
                            if (CheckValue(StartEndPoints[i].X) && CheckValue(StartEndPoints[i].Y) && CheckValue(StartEndPoints[i + 1].X) && CheckValue(StartEndPoints[i + 1].Y))
                            {
                                ColumnPart columnPart = new ColumnPart(StartEndPoints[i].X, StartEndPoints[i].Y, StartEndPoints[i + 1].X, StartEndPoints[i + 1].Y);
                                SetBindingForStrokeandStrokeThickness(columnPart);
                                this.Parts.Add(columnPart);
                            }
                            //}
                            //else
                            //{
                            //    LineSinglePart singlePart = new LineSinglePart(this.ColumnPoints);
                            //    SetBindingForStrokeandStrokeThickness(singlePart);
                            //    this.Parts.Add(singlePart);
                            //}
                        }
                        IsPointsGenerated = true;
                    }
                    else
                    {
                        int i = 0;
                        foreach (ColumnPart part in this.Parts)
                        {
                            if (CheckValue(StartEndPoints[i].X) && CheckValue(StartEndPoints[i].Y) && CheckValue(StartEndPoints[i + 1].X) && CheckValue(StartEndPoints[i + 1].Y))
                            {
                                part.X1 = StartEndPoints[i].X;
                                part.Y1 = StartEndPoints[i].Y;
                                part.X2 = StartEndPoints[i + 1].X;
                                part.Y2 = StartEndPoints[i + 1].Y;
                                part.Refresh();
                            }
                            i += 2;
                        }
                    }
                }
            }
            else
            {
                Parts.Clear();
            }

            if (this.SeriesContainer != null)
            {
                this.SeriesContainer.Invalidate();
            }
            IsRefreshed = false;
        }
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            var pointsObj = converter.Convert(values, targetType, parameter, culture);

            if (pointsObj != null)
            {
                PointCollection pc = (PointCollection)pointsObj;

                //finding left-top corner
                var   left2   = pc.OrderBy(p => p.X).Take(2);
                Point lefttop = left2.OrderBy(p => p.Y).Take(1).Single();


                //finding ridgt-top corner
                var   right2   = pc.OrderByDescending(p => p.X).Take(2);
                Point rigthtop = right2.OrderBy(p => p.Y).Take(1).Single();

                //finding left-bottom corner
                Point leftbottom = left2.OrderByDescending(p => p.Y).Take(1).Single();

                //finding right-bottom corner
                Point rigthbottom = right2.OrderByDescending(p => p.Y).Take(1).Single();

                Point p1, p4;

                //special case
                if ((lefttop.X < leftbottom.X) && (leftbottom.X < rigthtop.X) && (rigthtop.X < rigthbottom.X) && ((lefttop - rigthtop).LengthSquared < (rigthtop - rigthbottom).LengthSquared))
                {
                    p4 = rigthtop;
                    p1 = rigthbottom;
                }
                else
                {
                    if ((lefttop - rigthtop).LengthSquared < (lefttop - leftbottom).LengthSquared)
                    {
                        p4 = leftbottom;
                        p1 = lefttop;
                    }
                    else
                    {
                        p4 = lefttop;
                        p1 = rigthtop;
                    }
                }


                TranslateTransform tt = new TranslateTransform(p4.X, p4.Y);

                double angle = 0.0;
                if (Math.Abs(p1.X - p4.X) < 1e-6)   //close to vertical
                {
                    if (p1.Y > p4.Y)
                    {
                        angle = 90.0;
                    }
                    else
                    {
                        angle = -90;
                    }
                }
                else
                {
                    angle = Math.Atan((p1.Y - p4.Y) / (p1.X - p4.X)) / Math.PI * 180.0;
                }

                RotateTransform rt = new RotateTransform(angle);

                TransformGroup tg = new TransformGroup();
                tg.Children.Add(rt);
                tg.Children.Add(tt);

                return(tg);
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 34
0
        private void BtnBrowsCsv_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Create OpenFileDialog
                Microsoft.Win32.OpenFileDialog OfdTxtfile = new Microsoft.Win32.OpenFileDialog();
                OfdTxtfile.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
                // Display OpenFileDialog by calling ShowDialog method
                Nullable <bool> result = OfdTxtfile.ShowDialog();

                //Checking the result of Browsing
                if (result == true)
                {
                    string filename = OfdTxtfile.FileName;
                    TxtCsv.Text = filename;
                    //
                    Int64 Timestamp;
                    //Use RowNumber to Ignore the lines which are not usable
                    int Gazex, Gazey, RowNumber = 0;
                    //Opens a text file, reads all lines of the file, and then closes the file.
                    string[] lines = System.IO.File.ReadAllLines(OfdTxtfile.FileName);
                    //Create List of Points which contain Gazex,Gazey
                    PointCollection collection = new PointCollection();
                    //Read each line and Draw the Lines
                    foreach (string line in lines)
                    {
                        RowNumber++;
                        //If beacuse The first three numbers are not Usable
                        if (RowNumber > 6)
                        {
                            var temp = line.Split('\t');
                            //If Timestamp is not null
                            if (temp[7].Length > 0)
                            {
                                Timestamp = Int64.Parse(temp[7]);
                                //If Gazex and Gazey is not null
                                if (temp[23].Length > 0 && temp[24].Length > 0)
                                {
                                    Gazex = Int32.Parse(temp[23]);
                                    Gazey = Int32.Parse(temp[24]);
                                    //If Gazex and Gazey is inside the Image
                                    if (Gazex >= 0 && Gazex <= 1280 && Gazey >= 0 && Gazey <= 1024)
                                    {
                                        Point TP = new Point {
                                            X = Gazex, Y = Gazey
                                        };
                                        collection.Add(TP);
                                    }
                                }
                            }
                        }
                    }
                    DrawLine(collection);
                }
                else
                {
                    MessageBox.Show("Please Select the File again");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 35
0
        /// <summary>
        /// 绑定数据生成控件
        /// </summary>
        private void CreateControl()
        {
            if (ItemsSource == null || ItemsCount == 0)
            {
                return;
            }
            if (Width == double.NaN || Height == 0)
            {
                return;
            }
            if (mPanel == null)
            {
                return;
            }

            double          transformAngle  = -90 - 360 / ItemsCount / 2;
            RotateTransform rotateTransform = new RotateTransform(transformAngle)
            {
                CenterX = Width / 2, CenterY = Height / 2
            };

            //清空
            mPanel.Children.Clear();
            _ListPath.Clear();
            this.SelectedItem = null;

            var centerPoint = new Point(Width / 2, Height / 2);

            //Win32.POINT screenPos = new Win32.POINT();
            //var endPoint = PointFromScreen(new Point(screenPos.X, screenPos.Y));

            if (ItemsSource != null && !string.IsNullOrEmpty(DisplayPath))
            {
                int paletteIndex = 0;
                //Brush fill = new SolidColorBrush(Color.FromArgb(0xFF, 0xBA, 0xBA, 0xBA));
                //Brush stroke = new SolidColorBrush(Colors.Black);
                Style style = new Style();
                style.Setters.Add(new Setter {
                    Property = Path.FillProperty, Value = new SolidColorBrush(Color.FromArgb(0xFF, 0xBA, 0xBA, 0xBA))
                });
                style.Setters.Add(new Setter {
                    Property = Path.StrokeProperty, Value = new SolidColorBrush(Colors.Transparent)
                });
                int itemCount = 0;
                foreach (object item in ItemsSource)
                {
                    //获取调色板
                    if (Palette != null && Palette.Count > 0)
                    {
                        style = Palette[paletteIndex];
                        //foreach (Setter setter in style.Setters)
                        //{
                        //    if (setter.Property == Path.FillProperty)
                        //        fill = (Brush)setter.Value;
                        //    if (setter.Property == Path.StrokeProperty)
                        //        stroke = (Brush)setter.Value;
                        //}
                        paletteIndex++;
                        if (paletteIndex >= Palette.Count)
                        {
                            paletteIndex = 0;
                        }
                    }

                    PropertyInfo propertyDisplayText = item.GetType().GetProperty(DisplayPath);

                    //插入块
                    Path path = new Path();
                    path.Name            = "piePath";
                    path.Style           = style;
                    path.StrokeThickness = 0;
                    //pathFigure.Segments.Add(new ArcSegment
                    //{
                    //    Point = new Point(ActualWidth, ActualHeight / 2),
                    //    IsLargeArc = false,
                    //    Size = new Size(ActualWidth / ItemsCount * 3, ActualHeight / 2),
                    //    SweepDirection = SweepDirection.Clockwise
                    //});

                    //pathFigure.Segments.Add(new LineSegment
                    //{
                    //    Point = new Point(ActualWidth / ItemsCount * 3, ActualHeight / 2)
                    //});

                    //pathFigure.Segments.Add(new ArcSegment
                    //{
                    //    Point = new Point(ActualWidth / 2, ActualHeight / ItemsCount),
                    //    Size = new Size((ActualWidth / 2), 0),
                    //    SweepDirection = SweepDirection.Counterclockwise
                    //});
                    StreamGeometry  streamGeometry = new StreamGeometry();
                    int             previewPath    = 360 / ItemsCount * itemCount;
                    int             nextPath       = 360 / ItemsCount * (itemCount + 1);
                    PointCollection points         = new PointCollection();
                    using (StreamGeometryContext geometryContext = streamGeometry.Open())
                    {
                        for (int i = previewPath; i <= nextPath; i++)
                        {
                            double pathOutterAngle = Math.PI * (i / 180.0);
                            double outterY         = Height / 2 + (OutterCircleSize * Math.Sin(pathOutterAngle));
                            double outterX         = Width / 2 + (OutterCircleSize * Math.Cos(pathOutterAngle));
                            Point  OutterPoint     = new Point(outterX, outterY);
                            if (i == previewPath)
                            {
                                geometryContext.BeginFigure(OutterPoint, true, true);
                            }
                            else
                            {
                                points.Add(OutterPoint);
                            }
                        }

                        for (int j = nextPath - 1; j >= previewPath; j--)
                        {
                            double pathInnerAngle = Math.PI * (j / 180.0);
                            double innerY         = Height / 2 + (InnerCircleSize * Math.Sin(pathInnerAngle));
                            double innerX         = Width / 2 + (InnerCircleSize * Math.Cos(pathInnerAngle));
                            Point  innerPoint     = new Point(innerX, innerY);
                            points.Add(innerPoint);
                        }
                        geometryContext.PolyLineTo(points, true, true);
                    }
                    _ListPoints.Add(points);
                    itemCount++;
                    path.Opacity = 0;
                    path.Data    = streamGeometry;
                    path.Tag     = item;
                    TransformGroup group = new TransformGroup();
                    group.Children.Add(rotateTransform);
                    path.RenderTransform = group;
                    DoubleAnimation opacityUpAnmiation = new DoubleAnimation();
                    opacityUpAnmiation.BeginTime = new TimeSpan(0, 0, 0, 0, itemCount * 90 - 20);
                    opacityUpAnmiation.Duration  = new Duration(TimeSpan.FromSeconds(0.2));
                    opacityUpAnmiation.From      = 0;
                    opacityUpAnmiation.To        = 0.95;

                    Storyboard.SetTarget(opacityUpAnmiation, path);
                    Storyboard.SetTargetProperty(opacityUpAnmiation, new PropertyPath("Opacity"));
                    _ShowUpStoryboard.Children.Add(opacityUpAnmiation);

                    DoubleAnimation opacityDownAnmiation = new DoubleAnimation();
                    opacityDownAnmiation.BeginTime = new TimeSpan(0, 0, 0, 0, itemCount * 90 - 20);
                    opacityDownAnmiation.Duration  = new Duration(TimeSpan.FromSeconds(0.2));
                    opacityDownAnmiation.From      = 0.95;
                    opacityDownAnmiation.To        = 0;

                    Storyboard.SetTarget(opacityDownAnmiation, path);
                    Storyboard.SetTargetProperty(opacityDownAnmiation, new PropertyPath("Opacity"));
                    _HiddenStoryboard.Children.Add(opacityDownAnmiation);

                    //path.Visibility = Visibility.Collapsed;

                    //ObjectAnimationUsingKeyFrames visibilityAnimation = new ObjectAnimationUsingKeyFrames();
                    //DiscreteObjectKeyFrame frame = new DiscreteObjectKeyFrame(Visibility.Visible, new TimeSpan(0, 0, 0, 5));
                    //visibilityAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.5));
                    //visibilityAnimation.KeyFrames.Add(frame);
                    //visibilityAnimation.BeginTime = new TimeSpan(0, 0, 0, 0, itemCount * 90 - 20);
                    //Storyboard.SetTarget(visibilityAnimation, path);
                    //Storyboard.SetTargetProperty(visibilityAnimation, new PropertyPath("Visibility"));
                    //_ShowUpStoryboard.Children.Add(visibilityAnimation);
                    //DoubleAnimationUsingPath pathAnmiation = new DoubleAnimationUsingPath();
                    //pathAnmiation.BeginTime = new TimeSpan(0, 0, 0, 0, paletteIndex * 150);
                    //pathAnmiation.Duration = new Duration(TimeSpan.FromSeconds(0.5));
                    //pathAnmiation.PathGeometry = path.Data.GetFlattenedPathGeometry();

                    //Storyboard.SetTarget(pathAnmiation, path);
                    //Storyboard.SetTargetProperty(pathAnmiation, new PropertyPath("Data.Figures[0].Segments[0].Point"));

                    //sboard.Children.Add(pathAnmiation);
                    //path.MouseEnter += (sender, e) =>
                    //{
                    //    AnimationHelper.ScaleEasingInAnimation(path, isActivatedScaleAnimation);
                    //};

                    //path.MouseLeave += (sender, e) =>
                    //{
                    //    AnimationHelper.ScaleEasingOutAnimation(path);
                    //    isActivatedScaleAnimation = true;
                    //};

                    //path.MouseUp += (sender, e) =>
                    //{
                    //    path_MouseUp(path);
                    //};
                    Panel.SetZIndex(path, 3);
                    mPanel.Children.Add(path);
                    _ListPath.Add(path);

                    //插入文字
                    if (ShowText)
                    {
                        double mAngle       = 1 * 360 / ItemsCount + 0;
                        string title        = propertyDisplayText.GetValue(item, null).ToString();
                        double cAngle       = ((nextPath + previewPath) / 2.0 + transformAngle) % 360;
                        double titleAngle   = Math.PI * (cAngle / 180.0);
                        double titleOutterY = Height / 2 + (OutterCircleSize * Math.Sin(titleAngle));
                        double titleOutterX = Width / 2 + (OutterCircleSize * Math.Cos(titleAngle));
                        double titleInnerY  = Height / 2 + (InnerCircleSize * Math.Sin(titleAngle));
                        double titleInnerX  = Width / 2 + (InnerCircleSize * Math.Cos(titleAngle));
                        double length       = Math.Sqrt(Math.Pow(titleOutterX - titleInnerX, 2) + Math.Pow(titleOutterY - titleInnerY, 2));
                        Size   titleSize    = ComputeRect(title, ShowTextSize);
                        double halfHeight   = titleSize.Height / 2;
                        double pers         = halfHeight / length + 0.5;
                        Point  titlePoint   = new Point(titleInnerX + (titleOutterX - titleInnerX) * pers, titleInnerY + (titleOutterY - titleInnerY) * pers);

                        TextBlock textBlock = new TextBlock {
                            Name = "pieBlock", TextWrapping = TextWrapping.NoWrap, TextAlignment = TextAlignment.Center, Text = title, FontSize = ShowTextSize, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Colors.White), Style = null, Opacity = 0
                        };
                        textBlock.HorizontalAlignment = HorizontalAlignment.Left;
                        textBlock.VerticalAlignment   = VerticalAlignment.Top;
                        textBlock.Margin = new Thickness(title.Length < 4 ? titlePoint.X + LabelSpace - 12 : titlePoint.X + LabelSpace - 20, titlePoint.Y + LabelSpace - 8, 0, 0);
                        //if (mAngle <= 90)
                        //{
                        //    //textBlock.HorizontalAlignment = HorizontalAlignment.Left;
                        //    //textBlock.VerticalAlignment = VerticalAlignment.Bottom;
                        //    textBlock.Margin = new Thickness(titlePoint.X + LabelSpace - 12, 0, 0, this.ActualHeight - titlePoint.Y + LabelSpace - 6);
                        //}
                        //else
                        //{
                        //    if (mAngle <= 180)
                        //    {
                        //        //textBlock.HorizontalAlignment = HorizontalAlignment.Left;
                        //        //textBlock.VerticalAlignment = VerticalAlignment.Top;
                        //        textBlock.Margin = new Thickness(titlePoint.X + LabelSpace - 12, titlePoint.Y + LabelSpace - 6, 0, 0);
                        //    }
                        //    else
                        //    {
                        //        if (mAngle <= 270)
                        //        {
                        //            //textBlock.HorizontalAlignment = HorizontalAlignment.Right;
                        //            //textBlock.VerticalAlignment = VerticalAlignment.Top;
                        //            textBlock.Margin = new Thickness(0, titlePoint.Y + LabelSpace - 6, this.ActualWidth - titlePoint.X + LabelSpace + 12, 0);
                        //        }
                        //        else
                        //        {
                        //            //textBlock.HorizontalAlignment = HorizontalAlignment.Right;
                        //            //textBlock.VerticalAlignment = VerticalAlignment.Bottom;
                        //            textBlock.Margin = new Thickness(0, 0, this.ActualWidth + LabelSpace - 12, this.ActualHeight + LabelSpace - 12);
                        //        }
                        //    }
                        //}

                        //textBlock.MouseEnter += (sender, e) =>
                        //{
                        //    AnimationHelper.ScaleEasingInAnimation(path, false);
                        //};

                        //textBlock.MouseLeave += (sender, e) =>
                        //{
                        //    AnimationHelper.ScaleEasingInAnimation(path, false);
                        //    isActivatedScaleAnimation = false;
                        //};

                        //textBlock.MouseUp += (sender, e) =>
                        //{
                        //    path_MouseUp(path);
                        //};

                        DoubleAnimation opacityTextUpAnmiation = new DoubleAnimation();
                        opacityTextUpAnmiation.BeginTime = new TimeSpan(0, 0, 0, 0, itemCount * 90 - 20);
                        opacityTextUpAnmiation.Duration  = new Duration(TimeSpan.FromSeconds(0.2));
                        opacityTextUpAnmiation.From      = 0;
                        opacityTextUpAnmiation.To        = 0.95;
                        Storyboard.SetTarget(opacityTextUpAnmiation, textBlock);
                        Storyboard.SetTargetProperty(opacityTextUpAnmiation, new PropertyPath("Opacity"));
                        _ShowUpStoryboard.Children.Add(opacityTextUpAnmiation);

                        DoubleAnimation opacityTextDownAnmiation = new DoubleAnimation();
                        opacityTextDownAnmiation.BeginTime = new TimeSpan(0, 0, 0, 0, itemCount * 90 - 20);
                        opacityTextDownAnmiation.Duration  = new Duration(TimeSpan.FromSeconds(0.2));
                        opacityTextDownAnmiation.From      = 0.95;
                        opacityTextDownAnmiation.To        = 0;

                        Storyboard.SetTarget(opacityTextDownAnmiation, textBlock);
                        Storyboard.SetTargetProperty(opacityTextDownAnmiation, new PropertyPath("Opacity"));
                        _HiddenStoryboard.Children.Add(opacityTextDownAnmiation);
                        Panel.SetZIndex(textBlock, 6);
                        mPanel.Children.Add(textBlock);
                    }
                }
            }
        }
Ejemplo n.º 36
0
 public PolyLineSegment()
 {
     Points          = new PointCollection();
     Points.Changed += OnSubobjectChanged;
 }
Ejemplo n.º 37
0
        /// <summary>
        /// 图像处理定时器,定时响应函数,完成霍夫变换,矩形三角形检测
        /// </summary>
        private void ProcessTick(object sender, EventArgs e)
        {
            Stopwatch watch = new Stopwatch();      //计时运算时间

            if (houghCircles_radioButton.Checked)
            {
                #region circle detection
                watch.Start();
                //霍夫圆变换的四个参数
                double cannyThreshold             = (double)param1_UpDown.Value;
                double circleAccumulatorThreshold = (double)param2_UpDown.Value;
                double dp       = (double)dp_UpDown.Value;
                double min_dist = (double)minDist_UpDown.Value;
                //霍夫圆变换检测圆形
                CircleF[] circles = CvInvoke.HoughCircles(_smoothedGrayFrame, HoughType.Gradient,
                                                          dp, min_dist, cannyThreshold, circleAccumulatorThreshold, 5);
                watch.Stop();
                houghTime_lab.Text = String.Format("耗时: {0} ms", watch.ElapsedMilliseconds);
                #endregion

                #region draw circles
                _frame.CopyTo(_circleImage);
                foreach (CircleF circle in circles)
                {
                    //构造字符串,包含圆心、半径信息
                    String centerText = String.Format(" ({0}, {1}, R={2})", circle.Center.X, circle.Center.Y, circle.Radius);
                    //在图像中绘制检测到的圆心(在圆心处画半径为1的圆)
                    CvInvoke.Circle(_circleImage, Point.Round(circle.Center), 1, new Bgr(Color.Red).MCvScalar, 2);
                    //在图像中绘制检测到的圆轮廓
                    CvInvoke.Circle(_circleImage, Point.Round(circle.Center), (int)circle.Radius, new Bgr(Color.Red).MCvScalar, 2);
                    //在圆心处显示圆心、半径信息
                    CvInvoke.PutText(_circleImage, centerText, Point.Round(circle.Center),
                                     FontFace.HersheyPlain, 0.8, new Bgr(Color.DarkOrange).MCvScalar);
                }
                proImageBox.Image = _circleImage;
                #endregion
            }
            else if (rectDetect_radioButton.Checked)
            {
                #region Find triangles and rectangles
                watch.Reset(); watch.Start();
                //新建存储三角形圆形信息的两个List
                List <Triangle2DF> triangleList = new List <Triangle2DF>();
                List <RotatedRect> boxList      = new List <RotatedRect>(); //a box is a rotated rectangle

                using (VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint())
                {
                    CvInvoke.FindContours(_cannyFrame, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);
                    int count = contours.Size;
                    for (int i = 0; i < count; i++)
                    {
                        using (VectorOfPoint contour = contours[i])
                            using (VectorOfPoint approxContour = new VectorOfPoint())
                            {
                                CvInvoke.ApproxPolyDP(contour, approxContour, CvInvoke.ArcLength(contour, true) * 0.05, true);
                                if (CvInvoke.ContourArea(approxContour, false) > 250) //only consider contours with area greater than 250
                                {
                                    if (approxContour.Size == 3)                      //The contour has 3 vertices, it is a triangle
                                    {
                                        Point[] pts = approxContour.ToArray();
                                        triangleList.Add(new Triangle2DF(
                                                             pts[0],
                                                             pts[1],
                                                             pts[2]
                                                             ));
                                    }
                                    else if (approxContour.Size == 4) //The contour has 4 vertices.
                                    {
                                        #region determine if all the angles in the contour are within [80, 100] degree
                                        bool            isRectangle = true;
                                        Point[]         pts         = approxContour.ToArray();
                                        LineSegment2D[] edges       = PointCollection.PolyLine(pts, true);

                                        for (int j = 0; j < edges.Length; j++)
                                        {
                                            double angle = Math.Abs(
                                                edges[(j + 1) % edges.Length].GetExteriorAngleDegree(edges[j]));
                                            if (angle < 80 || angle > 100)
                                            {
                                                isRectangle = false;
                                                break;
                                            }
                                        }
                                        #endregion

                                        if (isRectangle)
                                        {
                                            boxList.Add(CvInvoke.MinAreaRect(approxContour));
                                        }
                                    }
                                }
                            }
                    }
                }

                watch.Stop();
                rectTime_lab.Text = String.Format("耗时: {0} ms", watch.ElapsedMilliseconds);
                #endregion

                #region draw triangles and rectangles
                _frame.CopyTo(_triangleRectangleImage);
                foreach (Triangle2DF triangle in triangleList)
                {
                    CvInvoke.Polylines(_triangleRectangleImage, Array.ConvertAll(triangle.GetVertices(), Point.Round), true, new Bgr(Color.Blue).MCvScalar, 2);
                }
                foreach (RotatedRect box in boxList)
                {
                    CvInvoke.Polylines(_triangleRectangleImage, Array.ConvertAll(box.GetVertices(), Point.Round), true, new Bgr(Color.DarkOrange).MCvScalar, 2);
                }
                proImageBox.Image = _triangleRectangleImage;
                #endregion
            }
            else if (canny_radioButton.Checked)
            {
                proImageBox.Image = _cannyFrame;
            }
        }
Ejemplo n.º 38
0
        private async void GetInputThreadFunction()
        {
            int    count = 0;
            double accXVal, accYVal, accZVal;
            double velXVal = 0, velYVal = 0, velZVal = 0;
            Vector x_shift = new Vector(-1, 0);
            //int time = 0;
            Action onReadTimeoutAction = OnReadTimeout; // Create a delegate to execute on a timeout.
            var    cts = new CancellationTokenSource(); // The CancellationTokenSource specifies the timeout value and the action to take on a timeout.

            cts.Token.Register(onReadTimeoutAction);    // Specify the function to call on a timeout.
            PointCollection points   = new PointCollection();
            bool            zcDetect = true;
            int             oldCount = 0;
            int             packetCounterVal;
            int             lostPacketCount    = 0;
            int             prevPacketCounter  = 0;
            double          lossPercentage     = 0;
            double          prevLossPercentage = 0;;

            while (true)
            {
                try
                {
                    if (_deviceHandleObtained && (inputReportBuf != null))
                    {
                        cts.CancelAfter(60 * 1000);  // Cancel the read if it hasn't completed after a timeout.

                        // Stops waiting when data is available or on timeout:
                        Int32 bytesRead = await _myHid.GetInputReportViaInterruptTransfer(_deviceData, inputReportBuf, cts);

                        if (bytesRead > 0)
                        {
                            ErrorBox.Dispatcher.Invoke(() => { ErrorBox.Text = "bytes read (includes report ID) = " + Convert.ToString(bytesRead); });
                            //for (int i = 0; i < inputReportBuffer.Length; i++)
                            //   InfoBox.Text += inputReportBuffer[i].ToString() + " ";
                            packetCounterVal = inputReportBuf[1] + inputReportBuf[2] * 256;
                            if (0 != prevPacketCounter)
                            {
                                if (packetCounterVal != (prevPacketCounter + 1))
                                {
                                    lostPacketCount += (packetCounterVal - (prevPacketCounter + 1));
                                }
                            }
                            prevPacketCounter = packetCounterVal;


                            //ValueTextBlock.Dispatcher.Invoke(() => { ValueTextBlock.Text = ((sbyte)inputReportBuf[3]).ToString(); });
                            //AccValProgressBar.Dispatcher.Invoke(() => { AccValProgressBar.Value = (double)((sbyte)inputReportBuf[3]); });
                            totalInputReports++;
                            accXVal  = (double)((sbyte)inputReportBuf[3]);
                            accYVal  = (double)((sbyte)inputReportBuf[4]);
                            accZVal  = (double)((sbyte)(inputReportBuf[5] - 64));
                            velXVal += accXVal * 0.0327 * 15.31 / 2.0;
                            velYVal += accYVal * 0.0327 * 15.31 / 2.0;
                            velZVal += accZVal * 0.0327 * 15.31 / 2.0;
                            if (accXVal > accXMax)
                            {
                                accXMax = accXVal;
                            }
                            if (accXVal < accXMin)
                            {
                                accXMin = accXVal;
                            }
                            if (accXVal > 0)
                            {
                                zcDetect = true;
                            }
                            if ((accXVal < 0) && (zcDetect == true))
                            {
                                if ((oldCount > 0) && (inputReportFrequency > 0))
                                {
                                    accXCount++;
                                    accXFreq = (double)inputReportFrequency / (double)(totalInputReports - oldCount);
                                    AccXFreqText.Dispatcher.Invoke(() =>
                                    {
                                        AccXFreqText.Text  = string.Format("{0}", (int)(accXFreq * 60));
                                        AccXCountText.Text = string.Format("{0}", accXCount);
                                    });
                                }
                                oldCount = totalInputReports;
                                zcDetect = false;
                            }
                            count++;
                            AccXPolyline.Dispatcher.Invoke(() =>
                            {
                                if (count >= 200)
                                {
                                    accXPoints.RemoveAt(0);
                                    //velXPoints.RemoveAt(0);
                                    accYPoints.RemoveAt(0);
                                    //velYPoints.RemoveAt(0);
                                    accZPoints.RemoveAt(0);
                                    //velZPoints.RemoveAt(0);
                                    for (int i = 0; i < accXPoints.Count; i++)
                                    {
                                        accXPoints[i] += x_shift;
                                        // velXPoints[i] += x_shift;
                                        accYPoints[i] += x_shift;
                                        // velYPoints[i] += x_shift;
                                        accZPoints[i] += x_shift;
                                        // velZPoints[i] += x_shift;
                                    }
                                    accXPoints.Add(new Point(200, 150 + accXVal));
                                    //  velXPoints.Add(new Point(200, 150 + velXVal));
                                    accYPoints.Add(new Point(200, 150 + accYVal));
                                    //  velYPoints.Add(new Point(200, 150 + velYVal));
                                    accZPoints.Add(new Point(200, 150 + accZVal));
                                    //  velZPoints.Add(new Point(200, 150 + velZVal));
                                }
                                else
                                {
                                    accXPoints.Add(new Point(count, 150 + accXVal));
                                    // velXPoints.Add(new Point(count * 4, 150 + velXVal));
                                    accYPoints.Add(new Point(count, 150 + accYVal));
                                    // velYPoints.Add(new Point(count * 4, 150 + velYVal));
                                    accZPoints.Add(new Point(count, 150 + accZVal));
                                    //  velZPoints.Add(new Point(count * 4, 150 + velZVal));
                                }
                            });

                            CountTextBlock.Dispatcher.Invoke(() =>
                            {
                                if (totalInputReports > 0)
                                {
                                    lossPercentage = (double)(lostPacketCount) * 100 / totalInputReports;
                                }
                                CountTextBlock.Text      = totalInputReports.ToString();
                                LossTextBlock.Text       = string.Format("{0:0.0}%", lossPercentage);
                                LossTextBlock.Foreground = (lossPercentage > prevLossPercentage) ? Brushes.Red : Brushes.Green;
                                prevLossPercentage       = lossPercentage;
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    DisplayException(Name, ex);
                }
            }
        }
Ejemplo n.º 39
0
        public void CalcFinalOutputVectorAdditionCoords(double translationArrowLen, double xCoord, double yCoord, PointCollection pc, string resourceSuffix)
        {
            double xFinal = translationArrowLen * Math.Cos(sldrTranslationAngle.Value * Math.PI / 180.0) + xCoord;
            double yFinal = translationArrowLen * Math.Sin(sldrTranslationAngle.Value * Math.PI / 180.0) + yCoord;

            double arrowLen = Math.Sqrt(xFinal * xFinal + yFinal * yFinal);

            BuildVectorArrowPointPath(pc, arrowLen, "finalVectorArrowPoints" + resourceSuffix);

            double angle = Math.Atan2(yFinal, xFinal);

            angle *= 180.0 / Math.PI;
            angle %= 360.0;
            Resources["finalAngle" + resourceSuffix] = angle;
            Resources["finalSpeed" + resourceSuffix] = arrowLen / m_scale / 3.2;
        }
Ejemplo n.º 40
0
 public static void SetChartNewDataCollection(DependencyObject obj, PointCollection value)
 {
     obj.SetValue(ChartNewDataCollectionProperty, value);
 }
Ejemplo n.º 41
0
        private void findShapes(Image <Bgr, byte> img)
        {
            UMat uimage = new UMat();

            CvInvoke.CvtColor(img, uimage, ColorConversion.Bgr2Gray);

            //use image pyr to remove noise
            UMat pyrDown = new UMat();

            CvInvoke.PyrDown(uimage, pyrDown);
            CvInvoke.PyrUp(pyrDown, uimage);

            //Image<Gray, Byte> gray = img.Convert<Gray, Byte>().PyrWDown().PyrUp();
            UMat blurred = new UMat();

            CvInvoke.GaussianBlur(uimage, blurred, new Size(21, 21), 1.0);

            #region circle detection
            Stopwatch watch          = Stopwatch.StartNew();
            double    cannyThreshold = 70.0;
            //double circleAccumulatorThreshold = 2*(GetContrast(uimage))-50;
            double    circleAccumulatorThreshold = 60;
            CircleF[] circles = CvInvoke.HoughCircles(blurred, HoughType.Gradient, 2.0, 5.0, cannyThreshold, circleAccumulatorThreshold, 5, 100);
            //outputLabel.Text += "C: " + circles.Length;

            watch.Stop();
            //msgBuilder.Append(String.Format("Hough circles - {0} ms; ", watch.ElapsedMilliseconds));
            #endregion

            #region Canny and edge detection
            watch.Reset(); watch.Start();
            double cannyThresholdLinking = 125.0;
            UMat   cannyEdges            = new UMat();
            CvInvoke.Canny(uimage, cannyEdges, cannyThreshold, cannyThresholdLinking);

            LineSegment2D[] lines = CvInvoke.HoughLinesP(
                cannyEdges,
                1,              //Distance resolution in pixel-related units
                Math.PI / 45.0, //Angle resolution measured in radians.
                20,             //threshold
                30,             //min Line width
                10);            //gap between lines

            watch.Stop();
            //outputLabel.Text += "\nL: " + lines.Length;
            //msgBuilder.Append(String.Format("Canny & Hough lines - {0} ms; ", watch.ElapsedMilliseconds));
            #endregion

            //#region Find triangles and rectangles
            watch.Reset(); watch.Start();
            List <Triangle2DF>   triangleList  = new List <Triangle2DF>();
            List <RotatedRect>   rectangleList = new List <RotatedRect>();
            List <RotatedRect>   boxList       = new List <RotatedRect>();   //a box is a rotated rectangle
            List <LineSegment2D> lineBoxes     = new List <LineSegment2D>(); //for the species that looks like a line
            List <CircleF>       circleList    = new List <CircleF>();

            using (VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint())
            {
                CvInvoke.FindContours(cannyEdges, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);
                int count = contours.Size;
                for (int i = 0; i < count; i++)
                {
                    using (VectorOfPoint contour = contours[i])
                        using (VectorOfPoint approxContour = new VectorOfPoint())
                        {
                            CvInvoke.ApproxPolyDP(contour, approxContour, CvInvoke.ArcLength(contour, true) * 0.05, true);
                            if (CvInvoke.ContourArea(approxContour, false) > 250) //only consider contours with area greater than 250
                            {
                                if (approxContour.Size == 3)                      //The contour has 3 vertices, it is a triangle
                                {
                                    Point[] pts = approxContour.ToArray();
                                    triangleList.Add(new Triangle2DF(
                                                         pts[0],
                                                         pts[1],
                                                         pts[2]
                                                         ));
                                }
                                else if (approxContour.Size == 4) //The contour has 4 vertices.
                                {
                                    #region determine if all the angles in the contour are within [80, 100] degree
                                    bool            isRectangle = true;
                                    Point[]         pts         = approxContour.ToArray();
                                    LineSegment2D[] edges       = PointCollection.PolyLine(pts, true);

                                    for (int j = 0; j < edges.Length; j++)
                                    {
                                        double angle = Math.Abs(
                                            edges[(j + 1) % edges.Length].GetExteriorAngleDegree(edges[j]));
                                        if (angle < 80 || angle > 100)
                                        {
                                            isRectangle = false;
                                            break;
                                        }
                                    }
                                    //rectangleList.Add(CvInvoke.MinAreaRect(approxContour));
                                    #endregion

                                    if (isRectangle)
                                    {
                                        boxList.Add(CvInvoke.MinAreaRect(approxContour));
                                    }
                                }

                                pictureBox1.Image = imgInput.Bitmap;
                            }
                        }
                    textBox8.Text = (triangleList.Count / 2).ToString();
                    textBox6.Text = (boxList.Count / 2).ToString();
                    textBox4.Text = rectangleList.Count.ToString();
                    textBox2.Text = circles.Length.ToString();
                }
            }

            #region draw triangles and rectangles
            Image <Bgr, Byte> triangleRectangleImage = img.CopyBlank();
            foreach (Triangle2DF triangle in triangleList)
            {
                img.Draw(triangle, new Bgr(Color.DarkBlue), 2);
            }
            foreach (RotatedRect box in boxList)
            {
                img.Draw(box, new Bgr(Color.DarkOrange), 2);
            }
            #endregion

            #region draw circles
            foreach (CircleF circle in circles)
            {
                img.Draw(circle, new Bgr(Color.Cyan), 2);
            }
            #endregion

            #region draw lines
            Image <Bgr, Byte> lineImage = img.CopyBlank();
            foreach (LineSegment2D line in lines)
            {
                img.Draw(line, new Bgr(Color.Green), 2);
            }
            #endregion

            pictureBox1.Image = img.ToBitmap();
        }
Ejemplo n.º 42
0
        //画图
        private static void OnDrawMap(ChartType type, ChartControlView chartControl, Canvas TemplateCanvas)
        {
            foreach (var canvas in chartControl.TemplateRoot.Children)
            {
                (canvas as Canvas).Visibility = Visibility.Visible;
            }

            var    standPoints    = GetChartNewDataCollection(chartControl);
            Canvas OtherHistogram = chartControl.Template.FindName("otherHistogram", chartControl) as Canvas;
            Canvas Fangraph       = chartControl.Template.FindName("Fangraph", chartControl) as Canvas;

            switch (type)
            {
            case ChartType.PolyLine:     //折线图
            {
                TemplateCanvas.Children.Remove(OtherHistogram);
                //TemplateCanvas.Children.Remove(OtherFangraph);
                foreach (var item in TemplateCanvas.Children)
                {
                    Console.WriteLine("子项" + item.GetType().Name);
                }
            }
            break;

            case ChartType.Cylinder:
            {
                TemplateCanvas.Children.Remove(OtherHistogram);
            }
            break;

            case ChartType.Histogram:      //直方图
            {
                Path   Histogram = TemplateCanvas.FindName("Histogram") as Path;
                double width     = 2 * chartControl.XTickValueInterval / 3;
                //double intervalHeight = chartControl.YTickValueInterval;
                PointCollection RightTopPoints = standPoints;
                PointCollection LeftTopPoints  = new PointCollection();
                for (int i = 0; i < standPoints.Count; i++)
                {
                    LeftTopPoints.Add(new Point(standPoints[i].X - width, standPoints[i].Y));
                }
                PointCollection LeftBottomPoints = new PointCollection();
                for (int i = 0; i < standPoints.Count; i++)
                {
                    LeftBottomPoints.Add(new Point(standPoints[i].X - width, chartControl.CenterPoint.Y));
                }
                PointCollection RightBottomPoints = new PointCollection();
                for (int i = 0; i < standPoints.Count; i++)
                {
                    RightBottomPoints.Add(new Point(standPoints[i].X, chartControl.CenterPoint.Y));
                }

                string data = string.Empty;
                for (int i = 0; i < standPoints.Count; i++)
                {
                    string data1 = $"M {RightTopPoints[i].X},{RightTopPoints[i].Y} {LeftTopPoints[i].X},{LeftTopPoints[i].Y}";
                    string data2 = $" {LeftBottomPoints[i].X},{LeftBottomPoints[i].Y} {RightBottomPoints[i].X},{RightBottomPoints[i].Y} ";
                    data += data1 + data2;
                }

                Histogram.Data = Geometry.Parse(data);

                for (int i = 0; i < chartControl.ChartDataCollection.Count; i++)
                {
                    TextBlock textBlock = new TextBlock();
                    textBlock.Text          = chartControl.ChartDataCollection[i].Y.ToString();
                    textBlock.Foreground    = Brushes.White;
                    textBlock.TextAlignment = TextAlignment.Center;
                    textBlock.Margin        = new Thickness(standPoints[i].X - 30, standPoints[i].Y - 20, 0, 0);
                    OtherHistogram.Children.Add(textBlock);
                }
                if (!TemplateCanvas.Children.Contains(OtherHistogram))
                {
                    TemplateCanvas.Children.Add(OtherHistogram);
                }

                Console.WriteLine("DATA:" + data);
                Console.WriteLine("柱形图:" + Histogram.Name);
            }
            break;

            case ChartType.Dottedgram:
                break;

            case ChartType.Fangraph:      //饼图
            {
                foreach (var canvas in chartControl.TemplateRoot.Children)
                {
                    if ((canvas as Canvas).Name.Equals("drawChart"))
                    {
                        (canvas as Canvas).Visibility = Visibility.Visible;
                    }
                    else
                    {
                        (canvas as Canvas).Visibility = Visibility.Collapsed;
                    }
                }

                //圆的方程(x-a)^2 + (y-b)^2 = r^2
                List <double> anglesList = new List <double>();       //角度
                double        sumY       = 0;
                foreach (var p in chartControl.ChartDataCollection)
                {
                    sumY += p.Y;
                }
                foreach (var p in chartControl.ChartDataCollection)
                {
                    anglesList.Add(p.Y / sumY * 2 * Math.PI);
                }

                //圆上分割点
                List <Point> points = new List <Point>();
                //圆中心点
                //Point center = new Point(0, 0);
                Point center = new Point(chartControl.Width / 2, chartControl.Height / 2);
                //圆的半径
                double r     = chartControl.Width > chartControl.Height ? 2 / 5D * chartControl.Height : 2 / 5D * chartControl.Width;
                double angle = 0D;
                for (int i = 0; i < chartControl.ChartDataCollection.Count; i++)
                {
                    angle += anglesList[i];
                    double x = center.X + r * Math.Cos(angle);
                    double y = center.Y + r * Math.Sin(angle);
                    points.Add(new Point(x, y));
                }

                Path ellipsePath = new Path();
                ellipsePath.Data = new EllipseGeometry(center, r, r);
                //ellipsePath.Stroke = Brushes.Red;
                //ellipsePath.StrokeThickness = 2;
                Fangraph.Children.Add(ellipsePath);

                Brush[] brushes = new Brush[7] {
                    Brushes.Red, Brushes.BlueViolet, Brushes.Yellow, Brushes.Blue, Brushes.SaddleBrown, Brushes.Purple, Brushes.BlueViolet
                };
                for (int i = 0; i < points.Count; i++)
                {
                    Path   path   = new Path();
                    string source = "";
                    if (i == points.Count - 1)
                    {
                        source = $"M {points[i].X},{points[i].Y} A {r},{r} 50 0 1 {points[0].X},{points[0].Y} L {center.X},{center.Y}";
                    }
                    else
                    {
                        source = $"M {points[i].X},{points[i].Y} A {r},{r} 50 0 1 {points[i + 1].X},{points[i + 1].Y} L {center.X},{center.Y}";
                    }
                    path.Data = Geometry.Parse(source);
                    path.Fill = brushes[i];
                    Fangraph.Children.Add(path);
                }
                ////画小圆
                //for (int i = 0; i < points.Count; i++)
                //{
                //    Path path = new Path();
                //    path.Data = new EllipseGeometry(points[i], 10, 10);
                //    path.Fill = brushes[i];
                //    Fangraph.Children.Add(path);
                //}

                ////如果原点为左上角,则需要平移
                //TranslateTransform transform = new TranslateTransform(300, 300);
                //Fangraph.RenderTransform = transform;

                //int roateAngle = 180;
                //while (true)
                //{
                //    roateAngle += 1;
                //    RotateTransform rotateTransform = new RotateTransform(roateAngle, 300, 300);
                //    Fangraph.RenderTransform = rotateTransform;
                //    Thread.Sleep(50);
                //}

                //DoubleAnimationUsingKeyFrames doubleAnimationUsingKeyFrames = new DoubleAnimationUsingKeyFrames();
                //Duration duration = new Duration(TimeSpan.FromSeconds(3));
                //DiscreteDoubleKeyFrame discreteDoubleKeyFrame = new DiscreteDoubleKeyFrame(roateAngle);
                //doubleAnimationUsingKeyFrames.Duration = duration;
                //doubleAnimationUsingKeyFrames.KeyFrames.Add(discreteDoubleKeyFrame);
                //AnimationClock clock = doubleAnimationUsingKeyFrames.CreateClock();
                //Fangraph.ApplyAnimationClock(RenderTransformProperty, clock);
            }
            break;

            default:
                break;
            }
        }
Ejemplo n.º 43
0
            public static MtpPicture ParsePicture(
                MtpVisualObjectLib objectLib,
                MtpDataSourceSubscriber subscriber,
                Dictionary <string, SystemUnitClassType> refIdToDynamicInstance,
                SystemUnitClassType picture,
                MtpSymbolMapRecordList makeUpConfigRecs = null)
            {
                // result
                var res = new MtpPicture();

                res.Picture = picture;

                // first, set up the canvas
                if (true)
                {
                    var width  = MtpAmlHelper.FindAttributeValueByNameFromDouble(picture.Attribute, "Width");
                    var height = MtpAmlHelper.FindAttributeValueByNameFromDouble(picture.Attribute, "Height");
                    if (width == null || height == null || width < 1 || height < 1)
                    {
                        return(null);
                    }
                    res.TotalSize = new Size(width.Value, height.Value);
                }

                // assume, that the elements below are in a list
                foreach (var ie in picture.InternalElement)
                {
                    // the check described in VDI2658 rely on RefBaseSystemUnitPath
                    if (ie == null || ie.Name == null || ie.RefBaseSystemUnitPath == null)
                    {
                        continue;
                    }

                    var refID = MtpAmlHelper.FindAttributeValueByName(ie.Attribute, "RefID");

                    // do a classification based on numbers to easily comapre
                    var ec = 0;
                    if (ie.RefBaseSystemUnitPath.Trim() == "MTPHMISUCLib/Connection/Pipe")
                    {
                        ec = 100;
                    }
                    if (ie.RefBaseSystemUnitPath.Trim() == "MTPHMISUCLib/Connection/FunctionLine")
                    {
                        ec = 101;
                    }
                    if (ie.RefBaseSystemUnitPath.Trim() == "MTPHMISUCLib/Connection/MeasurementLine")
                    {
                        ec = 102;
                    }
                    if (ie.RefBaseSystemUnitPath.Trim() == "MTPHMISUCLib/VisualObject")
                    {
                        ec = 200;
                    }
                    if (ie.RefBaseSystemUnitPath.Trim() == "MTPHMISUCLib/TopologyObject/Termination/Nozzle")
                    {
                        ec = 300;
                    }
                    if (ie.RefBaseSystemUnitPath.Trim() == "MTPHMISUCLib/TopologyObject/Termination/Source")
                    {
                        ec = 301;
                    }
                    if (ie.RefBaseSystemUnitPath.Trim() == "MTPHMISUCLib/TopologyObject/Termination/Sink")
                    {
                        ec = 302;
                    }

                    //
                    // Pipe, FunctionLine, MeasurementLine
                    //
                    if (ec >= 100 && ec <= 199)
                    {
                        // access (still string) information
                        var edgepath = MtpAmlHelper.FindAttributeValueByName(ie.Attribute, "Edgepath");
                        if (edgepath == null)
                        {
                            continue;
                        }
                        var points = MtpAmlHelper.PointCollectionFromString(edgepath);
                        if (points == null || points.Count < 2)
                        {
                            continue;
                        }

                        var co = new MtpConnectionObject();
                        co.Name     = ie.Name;
                        co.RefID    = refID;
                        co.ObjClass = ec;
                        co.points   = points;
                        res.Objects.Add(co);
                    }

                    //
                    // Nozzle information?
                    //
                    var nozzlePoints      = new PointCollection();
                    var measurementPoints = new PointCollection();
                    // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                    if (ec >= 200 && ec <= 399)
                    {
                        foreach (var ie2 in ie.InternalElement)
                        {
                            if (ie2 != null &&
                                ie2.RefBaseSystemUnitPath?.Trim() == "MTPHMISUCLib/PortObject/Nozzle")
                            {
                                // found nozzle with valid information?
                                var nx = MtpAmlHelper.FindAttributeValueByNameFromDouble(ie2.Attribute, "X");
                                var ny = MtpAmlHelper.FindAttributeValueByNameFromDouble(ie2.Attribute, "Y");
                                if (nx != null && ny != null)
                                {
                                    // add
                                    nozzlePoints.Add(new Point(nx.Value, ny.Value));
                                }
                            }

                            if (ie2 != null &&
                                ie2.RefBaseSystemUnitPath?.Trim() == "MTPHMISUCLib/PortObject/MeasurementPoint")
                            {
                                // found measurement point with valid information?
                                var nx = MtpAmlHelper.FindAttributeValueByNameFromDouble(ie2.Attribute, "X");
                                var ny = MtpAmlHelper.FindAttributeValueByNameFromDouble(ie2.Attribute, "Y");
                                if (nx != null && ny != null)
                                {
                                    // add
                                    measurementPoints.Add(new Point(nx.Value, ny.Value));
                                }
                            }
                        }
                    }

                    if (ie.Name == "V001")
                    {
                        ;
                    }

                    //
                    // VisualObject
                    //
                    if (ec >= 200 && ec <= 299)
                    {
                        // create object and parse
                        var vo = new MtpVisualObject();
                        vo.Name     = ie.Name;
                        vo.RefID    = refID;
                        vo.ObjClass = ec;
                        vo.Parse(ie);
                        if (!vo.IsValid())
                        {
                            continue;
                        }
                        res.Objects.Add(vo);

                        // add ports
                        vo.logicalPorts      = null;
                        vo.measurementPoints = measurementPoints;
                        vo.nozzlePoints      = nozzlePoints;

                        // try find an XAML object
                        vo.visObj = objectLib.FindVisualObjectByClass(vo.eVer, vo.eClass, vo.eIrdi);

                        // help improving this search
                        if (makeUpConfigRecs != null)
                        {
                            makeUpConfigRecs.Add(new MtpSymbolMapRecord(
                                                     vo.eVer, vo.eClass, vo.eIrdi, SymbolDefault: "{to be set}",
                                                     Comment: "" + vo.Name + "," + vo.RefID));
                        }

                        // try find dynamic instances
                        if (vo.refID != null && refIdToDynamicInstance != null &&
                            refIdToDynamicInstance.ContainsKey(vo.refID))
                        {
                            // try get the dynamic instance
                            var ieDI = refIdToDynamicInstance[vo.refID] as InternalElementType;

                            if (ieDI != null && ieDI.RefBaseSystemUnitPath != null &&
                                ieDI.RefBaseSystemUnitPath.Trim().Length > 0)
                            {
                                var bsup = ieDI.RefBaseSystemUnitPath.Trim();

                                if (bsup == "MTPDataObjectSUCLib/DataAssembly/AnaView" ||
                                    bsup == "MTPDataObjectSUCLib/DataAssembly/IndicatorElement/AnaView")
                                {
                                    vo.dynInstance = new MtpDiAnaView();
                                }
                                if (bsup == "MTPDataObjectSUCLib/DataAssembly/AnaView/AnaMon" ||
                                    bsup == "MTPDataObjectSUCLib/DataAssembly/IndicatorElement/AnaView/AnaMon")
                                {
                                    vo.dynInstance = new MtpDiAnaMon();
                                }

                                if (bsup == "MTPDataObjectSUCLib/DataAssembly/DIntiew" ||
                                    bsup == "MTPDataObjectSUCLib/DataAssembly/IndicatorElement/DIntView")
                                {
                                    vo.dynInstance = new MtpDiDIntView();
                                }
                                if (bsup == "MTPDataObjectSUCLib/DataAssembly/AnaView/DIntMon" ||
                                    bsup == "MTPDataObjectSUCLib/DataAssembly/IndicatorElement/AnaView/DIntMon")
                                {
                                    vo.dynInstance = new MtpDiDIntMon();
                                }

                                if (bsup == "MTPDataObjectSUCLib/DataAssembly/BinView" ||
                                    bsup == "MTPDataObjectSUCLib/DataAssembly/IndicatorElement/BinView")
                                {
                                    vo.dynInstance = new MtpDiBinView();
                                }

                                if (bsup == "MTPDataObjectSUCLib/DataAssembly/BinMon" ||
                                    bsup == "MTPDataObjectSUCLib/DataAssembly/IndicatorElement/BinMon")
                                {
                                    vo.dynInstance = new MtpDiBinMon();
                                }

                                if (bsup == "MTPDataObjectSUCLib/DataAssembly/BinVlv")
                                {
                                    vo.dynInstance = new MtpDiBinValve();
                                }
                                if (bsup == "MTPDataObjectSUCLib/DataAssembly/MonBinVlv")
                                {
                                    vo.dynInstance = new MtpDiMonBinValve();
                                }

                                if (bsup == "MTPDataObjectSUCLib/DataAssembly/BinDrv")
                                {
                                    vo.dynInstance = new MtpDiBinDrive();
                                }

                                if (bsup == "MTPDataObjectSUCLib/DataAssembly/ActiveElement/PIDCtrl")
                                {
                                    vo.dynInstance = new MtpDiPIDCntl();
                                }
                            }

                            // found?
                            if (vo.dynInstance != null)
                            {
                                vo.dynInstance.PopulateFromAml(ie.Name, ieDI, subscriber);
                            }
                        }
                    }

                    //
                    // Topology Object
                    //
                    // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                    if (ec >= 300 && ec <= 309)
                    {
                        // create object and parse
                        var to = new MtpTopologyObject();
                        to.Name     = ie.Name;
                        to.RefID    = refID;
                        to.ObjClass = ec;
                        to.Parse(ie);
                        if (!to.IsValid())
                        {
                            continue;
                        }
                        res.Objects.Add(to);

                        // add ports
                        to.logicalPorts      = null;
                        to.measurementPoints = measurementPoints;
                        to.nozzlePoints      = nozzlePoints;

                        // draw source / sink?
                        // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                        if (ec >= 301 && ec <= 302)
                        {
                            // get visual object
                            to.visObj = objectLib.FindVisualObjectByName(
                                new[] { "Source_general", "Sink_general" }[ec - 301]);
                        }
                    }
                }

                // return picture
                return(res);
            }
Ejemplo n.º 44
0
 /// <summary>
 ///     Initializes a new instance of the ArrowPolyline class.
 /// </summary>
 public ArrowPolyline()
 {
     Points = new PointCollection();
 }
        public MultipleTransformationsExample()
        {
            // Declare scene objects.
            Viewport3D      myViewport3D    = new Viewport3D();
            Model3DGroup    myModel3DGroup  = new Model3DGroup();
            GeometryModel3D myGeometryModel = new GeometryModel3D();
            ModelVisual3D   myModelVisual3D = new ModelVisual3D();

            // Defines the camera used to view the 3D object. In order to view the 3D object,
            // the camera must be positioned and pointed such that the object is within view
            // of the camera.
            PerspectiveCamera myPCamera = new PerspectiveCamera();

            // Specify where in the 3D scene the camera is.
            myPCamera.Position = new Point3D(0, 0, 2);

            // Specify the direction that the camera is pointing.
            myPCamera.LookDirection = new Vector3D(0, 0, -1);

            // Define camera's horizontal field of view in degrees.
            myPCamera.FieldOfView = 60;

            // Asign the camera to the viewport
            myViewport3D.Camera = myPCamera;

            // Define the lights cast in the scene. Without light, the 3D object cannot
            // be seen. Note: to illuminate an object from additional directions, create
            // additional lights.
            DirectionalLight myDirectionalLight = new DirectionalLight();

            myDirectionalLight.Color     = Colors.White;
            myDirectionalLight.Direction = new Vector3D(-0.61, -0.5, -0.61);

            myModel3DGroup.Children.Add(myDirectionalLight);

            // The geometry specifes the shape of the 3D plane. In this sample, a flat sheet
            // is created.
            MeshGeometry3D myMeshGeometry3D = new MeshGeometry3D();

            // Create a collection of normal vectors for the MeshGeometry3D.
            Vector3DCollection myNormalCollection = new Vector3DCollection();

            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myMeshGeometry3D.Normals = myNormalCollection;

            // Create a collection of vertex positions for the MeshGeometry3D.
            Point3DCollection myPositionCollection = new Point3DCollection();

            myPositionCollection.Add(new Point3D(-0.5, -0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, -0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(-0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(-0.5, -0.5, 0.5));
            myMeshGeometry3D.Positions = myPositionCollection;

            // Create a collection of texture coordinates for the MeshGeometry3D.
            PointCollection myTextureCoordinatesCollection = new PointCollection();

            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myMeshGeometry3D.TextureCoordinates = myTextureCoordinatesCollection;

            // Create a collection of triangle indices for the MeshGeometry3D.
            Int32Collection myTriangleIndicesCollection = new Int32Collection();

            myTriangleIndicesCollection.Add(0);
            myTriangleIndicesCollection.Add(1);
            myTriangleIndicesCollection.Add(2);
            myTriangleIndicesCollection.Add(3);
            myTriangleIndicesCollection.Add(4);
            myTriangleIndicesCollection.Add(5);
            myMeshGeometry3D.TriangleIndices = myTriangleIndicesCollection;

            // Apply the mesh to the geometry model.
            myGeometryModel.Geometry = myMeshGeometry3D;

            // The material specifies the material applied to the 3D object. In this sample a
            // linear gradient covers the surface of the 3D object.

            // Create a horizontal linear gradient with four stops.
            LinearGradientBrush myHorizontalGradient = new LinearGradientBrush();

            myHorizontalGradient.StartPoint = new Point(0, 0.5);
            myHorizontalGradient.EndPoint   = new Point(1, 0.5);
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Yellow, 0.0));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Red, 0.25));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Blue, 0.75));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.LimeGreen, 1.0));

            // Define material and apply to the mesh geometries.
            DiffuseMaterial myMaterial = new DiffuseMaterial(myHorizontalGradient);

            myGeometryModel.Material = myMaterial;
            // <SnippetMultiple3DTransformationsCodeExampleInline1>
            // Apply multiple transformations to the object. In this sample, a rotation and scale
            // transform is applied.

            // Create and apply a transformation that rotates the object.
            RotateTransform3D   myRotateTransform3D   = new RotateTransform3D();
            AxisAngleRotation3D myAxisAngleRotation3d = new AxisAngleRotation3D();

            myAxisAngleRotation3d.Axis   = new Vector3D(0, 3, 0);
            myAxisAngleRotation3d.Angle  = 40;
            myRotateTransform3D.Rotation = myAxisAngleRotation3d;

            // Add the rotation transform to a Transform3DGroup
            Transform3DGroup myTransform3DGroup = new Transform3DGroup();

            myTransform3DGroup.Children.Add(myRotateTransform3D);

            // Create and apply a scale transformation that stretches the object along the local x-axis
            // by 200 percent and shrinks it along the local y-axis by 50 percent.
            ScaleTransform3D myScaleTransform3D = new ScaleTransform3D();

            myScaleTransform3D.ScaleX = 2;
            myScaleTransform3D.ScaleY = 0.5;
            myScaleTransform3D.ScaleZ = 1;

            // Add the scale transform to the Transform3DGroup.
            myTransform3DGroup.Children.Add(myScaleTransform3D);

            // Set the Transform property of the GeometryModel to the Transform3DGroup which includes
            // both transformations. The 3D object now has two Transformations applied to it.
            myGeometryModel.Transform = myTransform3DGroup;
            // </SnippetMultiple3DTransformationsCodeExampleInline1>
            // Add the geometry model to the model group.
            myModel3DGroup.Children.Add(myGeometryModel);

            // Add the group of models to the ModelVisual3d.
            myModelVisual3D.Content = myModel3DGroup;

            myViewport3D.Children.Add(myModelVisual3D);

            // Apply the viewport to the page so it will be rendered.
            this.Content = myViewport3D;
        }
Ejemplo n.º 46
0
        private void btStart_Click(object sender, RoutedEventArgs e)
        {
            //set initial conditions
            m1     = 5;
            m2     = 3;
            L1     = 75;
            L2     = 75;
            theta1 = Math.PI / 4;
            theta2 = Math.PI / 6;
            w1     = 0;
            w2     = 0;
            h      = 0.05;

            //remove the pendulums if they already are drawn on screen
            if (line1 != null)
            {
                PaintCanvas.Children.Remove(line1);
            }
            if (line2 != null)
            {
                PaintCanvas.Children.Remove(line2);
            }
            if (mass1 != null)
            {
                PaintCanvas.Children.Remove(mass1);
            }
            if (mass2 != null)
            {
                PaintCanvas.Children.Remove(mass2);
            }
            if (pointsSet != null)
            {
                PaintCanvas.Children.Remove(trace);
                pointsSet.Clear();
                tracePoints.Clear();
            }

            //draw the initial positions
            mass1X = L1 * Math.Sin(theta1) + wallPegX;
            mass1Y = L1 * Math.Cos(theta1) + wallPegY;
            line1  = CreateLine(wallPegX, wallPegY, mass1X, mass1Y, black);
            mass1  = CreateEllipse(15, 15, blue);
            PaintCanvas.Children.Add(line1);
            PaintCanvas.Children.Add(mass1);
            Canvas.SetTop(mass1, mass1Y - 7.5);
            Canvas.SetLeft(mass1, mass1X - 7.5);
            Canvas.SetZIndex(mass1, 1);

            mass2X = L2 * Math.Sin(theta2) + mass1X;
            mass2Y = L2 * Math.Cos(theta2) + mass1Y;
            line2  = CreateLine(mass1X, mass1Y, mass2X, mass2Y, black);
            mass2  = CreateEllipse(15 * m2 / m1, 15 * m2 / m1, blue);
            PaintCanvas.Children.Add(line2);
            PaintCanvas.Children.Add(mass2);
            Canvas.SetLeft(mass2, mass2X - ((15 * m2 / m1) / 2));
            Canvas.SetTop(mass2, mass2Y - ((15 * m2 / m1) / 2));
            Canvas.SetZIndex(mass2, 1);

            //begin filling the set to draw the trace line
            trace       = new Polyline();
            pointsSet   = new HashSet <Point>();
            tracePoints = new PointCollection();
            Point p = new Point(mass2X, mass2Y);

            pointsSet.Add(p);
            tracePoints.Add(p);

            timer.Start();
        }
Ejemplo n.º 47
0
        // If the point already exists, return its index.
        // Otherwise create the point and return its new index.
        protected int AddPoint(Dictionary <Point3D, int> pointDictionary, Point3DCollection points, PointCollection texture_coords, Point3D point)
        {
            try
            {
                // If the point is in the point dictionary,
                // return its saved index.
                if (pointDictionary.ContainsKey(point))
                {
                    return(pointDictionary[point]);
                }

                // We didn't find the point. Create it.
                points.Add(point);
                pointDictionary.Add(point, points.Count - 1);

                // Set the point's texture coordinates.
                texture_coords.Add(
                    new System.Windows.Point(
                        (point.X - XIndexMin) * Texture_xscale,
                        (point.Z - ZIndexMax) * Texture_zscale));

                // Return the new point's index.
                return(points.Count - 1);
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 48
0
        } // end of UpdateSensors function

        public void SensorFrame(Point[] depthPts, Point[] chairPts, int debug)
        {
            // Clear frame
            sensorCanvas.Children.Clear();

            // Draw chair on screen
            Rectangle chair = new Rectangle();

            chair.StrokeThickness = 1;
            chair.Fill            = new SolidColorBrush(Colors.Cyan);
            chair.Width           = chairWidth;
            chair.Height          = chairHeight;
            Canvas.SetTop(chair, chairY1);
            Canvas.SetLeft(chair, chairX1);
            sensorCanvas.Children.Add(chair);

            // These checks should only determine contents of depthPts and chairPts

            if (debug == 0) // Use sensor data
            {
            }
            else if (debug == 1)                                           // Use static dummy data w/ five sensors (three in front, one per side
            {
                chairPts[0] = new Point(chairX1, 400);                     // Left middle side sensor
                chairPts[1] = new Point(chairX1, chairY1);                 // Left corner side sensor   ||
                chairPts[2] = new Point(chairX1, chairY1);                 // Left front sensor         ||
                chairPts[3] = new Point(400, chairY1);                     // Middle front sensor
                chairPts[4] = new Point(chairX2, chairY1);                 // Right front sensor        ||
                chairPts[5] = new Point(chairX2, chairY1);                 // Right corner side sensor  ||
                chairPts[6] = new Point(chairX2, 400);                     // Right side sensor

                depthPts[0] = new Point(chairX1 - (50 * scale), 400);      // Left middle side depth
                depthPts[1] = new Point(chairX1 - (75 * scale), chairY1);  // Left corner side depth    ||
                depthPts[2] = new Point(chairX1, chairY1 - (100 * scale)); // Left front depth         ||
                depthPts[3] = new Point(400, chairY1 - (125 * scale));     // Middle front depth
                depthPts[4] = new Point(chairX2, chairY1 - (150 * scale)); // Right front depth        ||
                depthPts[5] = new Point(chairX2 + (175 * scale), chairY1); // Right corner side depth  ||
                depthPts[6] = new Point(chairX2 + (200 * scale), 400);     // Right side depth
            }
            else // Use generated data for representing possible sensor values
            {
                GenerateDepths(out depthPts, out chairPts);
            }



            // Loop that draws depth lines
            for (int i = 0; i < chairPts.Length; i++)
            {
                PlotLine(chairPts[i], depthPts[i]);
            }

            // Loop that connects depthPts
            for (int j = 0; j < depthPts.Length - 1; j++)
            {
                PlotLine(depthPts[j], depthPts[j + 1]);
            }

            // Loop that draws heat squares
            // 250 = green = safe
            // 150 = yellow = warning
            // 60 = red = danger
            for (int k = 0; k < depthPts.Length - 1; k++)
            {
                Polygon heat = new Polygon();


                LinearGradientBrush heatMap = new LinearGradientBrush(); // Colors.Red, Colors.Green, new Point(chairX1,chairY2), new Point(chairX1-gradientLength, chairY2));

                GradientStop r = new GradientStop();
                r.Color = Colors.Red;

                GradientStop y = new GradientStop();
                y.Color = Colors.Yellow;

                GradientStop g = new GradientStop();
                g.Color = Colors.Green;


                if (k < snsrsPerSide) // Left side
                {
                    heatMap.StartPoint = new Point(0, 0);
                    heatMap.EndPoint   = new Point(1, 0);
                    r.Offset           = 0.8;
                    y.Offset           = 0.6;
                    g.Offset           = 0.0;
                }
                else if (k > snsrsPerSide * 2 - 1) // Right side
                {
                    heatMap.StartPoint = new Point(0, 0);
                    heatMap.EndPoint   = new Point(1, 0);
                    r.Offset           = 0.0;
                    y.Offset           = 0.4;
                    g.Offset           = 0.8;
                }
                else // Top side
                {
                    heatMap.StartPoint = new Point(0, 1);
                    heatMap.EndPoint   = new Point(0, 0);
                    r.Offset           = 0.3;
                    y.Offset           = 0.6;
                    g.Offset           = 0.7;
                }

                heat.Fill = heatMap;

                Point midpoint = MidPoint(depthPts[k], depthPts[k + 1]);

                if (midpoint.X < chairX1 && midpoint.Y < chairY1)
                {
                    heatMap.StartPoint = new Point(0, 0);
                    heatMap.EndPoint   = new Point(1, 1);
                }
                else if (midpoint.X > chairX2 && midpoint.Y < chairY1)
                {
                    heatMap.StartPoint = new Point(1, 1);
                    heatMap.EndPoint   = new Point(0, 0);
                }



                heatMap.GradientStops.Add(r);
                heatMap.GradientStops.Add(y);
                heatMap.GradientStops.Add(g);

                // Make polygon filled with gradient
                //heat.Fill = heatMap;
                // Need this for some reason
                heat.StrokeThickness = 1;

                // Add all four points of a polygon
                PointCollection pC = new PointCollection();
                pC.Add(depthPts[k]);
                pC.Add(chairPts[k]);
                pC.Add(chairPts[k + 1]);
                pC.Add(depthPts[k + 1]);
                heat.Points = pC;

                sensorCanvas.Children.Add(heat);
            }
        }
 public void SetPoints(PointCollection relocatedDrawablePoints)
 {
     Shape.Points = relocatedDrawablePoints;
 }
 private void UpdateShape()
 {
     ShapeInPixels = new PointCollection(_ship.Shape.Select(p => new Point(p.X / _metersPerPixel.Value, -p.Y / _metersPerPixel.Value)));
     PropertyChanged.Raise(() => ShapeInPixels);
 }
Ejemplo n.º 51
0
        /// <summary>
        /// interpolation Circle or arc
        /// </summary>
        public static PointCollection CircleByStep(Point StartPoint, Point EndPoint, double radius, double radiusEdge, SweepDirection clockwise, double CRS, double Delta = 360)
        {
            Delta *= Math.PI / 180;

            PointCollection lObject = new PointCollection();

            if (Delta != 0)
            {
                Point Center = GetCenterArc(StartPoint, EndPoint, radius, clockwise == SweepDirection.Clockwise, Delta > Math.PI && clockwise == SweepDirection.Counterclockwise);

                double StartAngle = Math.PI * 2 - Math.Atan2(StartPoint.Y - Center.Y, StartPoint.X - Center.X);

                double koeff = (radius / radiusEdge) < 0.3 ? 0.3 : (radius / radiusEdge);
                koeff = (radius / radiusEdge) > 3 ? 3 : (radius / radiusEdge);

                double RadianStep = Delta / (int)((Delta * radius) / CRS);

                for (double radian = 0; radian <= Delta * 1.005; radian += RadianStep)
                {
                    double Angle = (StartAngle + (clockwise == SweepDirection.Counterclockwise ? radian : -radian)) % (2 * Math.PI);

                    lObject.Add(new Point(
                                    Center.X + (radius * Math.Cos(Angle)),
                                    Center.Y - (radius * Math.Sin(Angle))
                                    ));
                }
            }
            else
            {
                if (clockwise == SweepDirection.Counterclockwise)
                {
                    lObject.Add(StartPoint);
                    lObject.Add(EndPoint);
                }
                else
                {
                    lObject.Add(EndPoint);
                    lObject.Add(StartPoint);
                }
            }

            return(lObject);

            Point GetCenterArc(Point StartPt, Point EndPt, double r, bool Clockwise, bool large)
            {
                double radsq = r * r;
                double q     = Math.Sqrt(Math.Pow(EndPt.X - StartPt.X, 2) + Math.Pow(EndPt.Y - StartPt.Y, 2));
                double x3    = (StartPt.X + EndPt.X) / 2;
                double y3    = (StartPt.Y + EndPt.Y) / 2;
                double d1    = 0;
                double d2    = 0;

                if (radsq > 0)
                {
                    d1 = Math.Sqrt(radsq - ((q / 2) * (q / 2))) * ((StartPt.Y - EndPt.Y) / q) * (large ? -1 : 1);
                    d2 = Math.Sqrt(radsq - ((q / 2) * (q / 2))) * ((EndPt.X - StartPt.X) / q) * (large ? -1 : 1);
                }
                return(new Point(
                           x3 + (Clockwise ? d1 : -d1),
                           y3 + (Clockwise ? d2 : -d2)
                           ));
            }
        }
        private List <RotatedRect> getRects(Image <Bgr, Byte> img)
        {
            //img = img.Resize(400, 400, Inter.Linear, true);

            //Convert the image to grayscale and filter out the noise
            UMat uimage = new UMat();

            CvInvoke.CvtColor(img, uimage, ColorConversion.Bgr2Gray);

            //use image pyr to remove noise
            UMat pyrDown = new UMat();

            CvInvoke.PyrDown(uimage, pyrDown);
            CvInvoke.PyrUp(pyrDown, uimage);

            double cannyThreshold        = 180.0;
            double cannyThresholdLinking = 120.0;
            UMat   cannyEdges            = new UMat();

            CvInvoke.Canny(uimage, cannyEdges, cannyThreshold, cannyThresholdLinking);

            LineSegment2D[] lines = CvInvoke.HoughLinesP(
                cannyEdges,
                1,              //Distance resolution in pixel-related units
                Math.PI / 45.0, //Angle resolution measured in radians.
                20,             //threshold
                30,             //min Line width
                10);            //gap between lines


            List <RotatedRect> boxList = new List <RotatedRect>(); //a box is a rotated rectangle

            using (VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint())
            {
                CvInvoke.FindContours(cannyEdges, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);
                int count = contours.Size;
                for (int i = 0; i < count; i++)
                {
                    using (VectorOfPoint contour = contours[i])
                        using (VectorOfPoint approxContour = new VectorOfPoint())
                        {
                            CvInvoke.ApproxPolyDP(contour, approxContour, CvInvoke.ArcLength(contour, true) * 0.05, true);
                            if (CvInvoke.ContourArea(approxContour, false) > 250) //only consider contours with area greater than 250
                            {
                                if (approxContour.Size == 4)                      //The contour has 4 vertices.
                                {
                                    bool            isRectangle = true;
                                    Point[]         pts         = approxContour.ToArray();
                                    LineSegment2D[] edges       = PointCollection.PolyLine(pts, true);

//                                for (int j = 0; j < edges.Length; j++)
//                                {
//                                    double angle = Math.Abs(
//                                       edges[(j + 1) % edges.Length].GetExteriorAngleDegree(edges[j]));
//                                    if (angle < 80 || angle > 100)
//                                    {
//                                        isRectangle = false;
//                                        break;
//                                    }
//                                }

                                    if (isRectangle)
                                    {
                                        boxList.Add(CvInvoke.MinAreaRect(approxContour));
                                    }
                                }
                            }
                        }
                }
            }
            return(boxList);
        }
Ejemplo n.º 53
0
 /// <summary>
 /// This implementation is too heavily tied to the XRNA format as far as
 /// how the geometry is specified, we may want to do some of the conversion in
 /// the provider.
 /// </summary>
 public SSParallelogramLabelViewModel()
 {
     VertexPoints = new PointCollection();
 }
Ejemplo n.º 54
0
        public static APath ToAPath(this Geometry geometry, Context context)
        {
            APath path = new APath();

            float density = context.Resources.DisplayMetrics.Density;

            if (geometry is LineGeometry)
            {
                LineGeometry lineGeometry = geometry as LineGeometry;

                path.MoveTo(
                    density * (float)lineGeometry.StartPoint.X,
                    density * (float)lineGeometry.StartPoint.Y);

                path.LineTo(
                    density * (float)lineGeometry.EndPoint.X,
                    density * (float)lineGeometry.EndPoint.Y);
            }
            else if (geometry is RectangleGeometry)
            {
                var rect = (geometry as RectangleGeometry).Rect;

                path.AddRect(
                    density * (float)rect.Left,
                    density * (float)rect.Top,
                    density * (float)rect.Right,
                    density * (float)rect.Bottom,
                    APath.Direction.Cw);
            }
            else if (geometry is EllipseGeometry)
            {
                EllipseGeometry ellipseGeometry = geometry as EllipseGeometry;

                path.AddOval(new RectF(
                                 density * (float)(ellipseGeometry.Center.X - ellipseGeometry.RadiusX),
                                 density * (float)(ellipseGeometry.Center.Y - ellipseGeometry.RadiusY),
                                 density * (float)(ellipseGeometry.Center.X + ellipseGeometry.RadiusX),
                                 density * (float)(ellipseGeometry.Center.Y + ellipseGeometry.RadiusY)),
                             APath.Direction.Cw);
            }
            else if (geometry is GeometryGroup)
            {
                GeometryGroup geometryGroup = geometry as GeometryGroup;

                path.SetFillType(geometryGroup.FillRule == FillRule.Nonzero ? APath.FillType.Winding : APath.FillType.EvenOdd);

                foreach (Geometry child in geometryGroup.Children)
                {
                    APath childPath = child.ToAPath(context);
                    path.AddPath(childPath);
                }
            }
            else if (geometry is PathGeometry)
            {
                PathGeometry pathGeometry = geometry as PathGeometry;

                path.SetFillType(pathGeometry.FillRule == FillRule.Nonzero ? APath.FillType.Winding : APath.FillType.EvenOdd);

                foreach (PathFigure pathFigure in pathGeometry.Figures)
                {
                    path.MoveTo(
                        density * (float)pathFigure.StartPoint.X,
                        density * (float)pathFigure.StartPoint.Y);

                    Point lastPoint = pathFigure.StartPoint;

                    foreach (PathSegment pathSegment in pathFigure.Segments)
                    {
                        // LineSegment
                        if (pathSegment is LineSegment)
                        {
                            LineSegment lineSegment = pathSegment as LineSegment;

                            path.LineTo(
                                density * (float)lineSegment.Point.X,
                                density * (float)lineSegment.Point.Y);
                            lastPoint = lineSegment.Point;
                        }
                        // PolylineSegment
                        else if (pathSegment is PolyLineSegment)
                        {
                            PolyLineSegment polylineSegment = pathSegment as PolyLineSegment;
                            PointCollection points          = polylineSegment.Points;

                            for (int i = 0; i < points.Count; i++)
                            {
                                path.LineTo(
                                    density * (float)points[i].X,
                                    density * (float)points[i].Y);
                            }
                            lastPoint = points[points.Count - 1];
                        }
                        // BezierSegment
                        else if (pathSegment is BezierSegment)
                        {
                            BezierSegment bezierSegment = pathSegment as BezierSegment;

                            path.CubicTo(
                                density * (float)bezierSegment.Point1.X, density * (float)bezierSegment.Point1.Y,
                                density * (float)bezierSegment.Point2.X, density * (float)bezierSegment.Point2.Y,
                                density * (float)bezierSegment.Point3.X, density * (float)bezierSegment.Point3.Y);

                            lastPoint = bezierSegment.Point3;
                        }
                        // PolyBezierSegment
                        else if (pathSegment is PolyBezierSegment)
                        {
                            PolyBezierSegment polyBezierSegment = pathSegment as PolyBezierSegment;
                            PointCollection   points            = polyBezierSegment.Points;

                            if (points.Count >= 3)
                            {
                                for (int i = 0; i < points.Count; i += 3)
                                {
                                    path.CubicTo(
                                        density * (float)points[i + 0].X, density * (float)points[i + 0].Y,
                                        density * (float)points[i + 1].X, density * (float)points[i + 1].Y,
                                        density * (float)points[i + 2].X, density * (float)points[i + 2].Y);
                                }
                            }

                            lastPoint = points[points.Count - 1];
                        }
                        // QuadraticBezierSegment
                        else if (pathSegment is QuadraticBezierSegment)
                        {
                            QuadraticBezierSegment bezierSegment = pathSegment as QuadraticBezierSegment;

                            path.QuadTo(
                                density * (float)bezierSegment.Point1.X, density * (float)bezierSegment.Point1.Y,
                                density * (float)bezierSegment.Point2.X, density * (float)bezierSegment.Point2.Y);

                            lastPoint = bezierSegment.Point2;
                        }
                        // PolyQuadraticBezierSegment
                        else if (pathSegment is PolyQuadraticBezierSegment)
                        {
                            PolyQuadraticBezierSegment polyBezierSegment = pathSegment as PolyQuadraticBezierSegment;
                            PointCollection            points            = polyBezierSegment.Points;

                            if (points.Count >= 2)
                            {
                                for (int i = 0; i < points.Count; i += 2)
                                {
                                    path.QuadTo(
                                        density * (float)points[i + 0].X, density * (float)points[i + 0].Y,
                                        density * (float)points[i + 1].X, density * (float)points[i + 1].Y);
                                }
                            }

                            lastPoint = points[points.Count - 1];
                        }
                        // ArcSegment
                        else if (pathSegment is ArcSegment)
                        {
                            ArcSegment arcSegment = pathSegment as ArcSegment;

                            List <Point> points = new List <Point>();

                            GeometryHelper.FlattenArc(
                                points,
                                lastPoint,
                                arcSegment.Point,
                                arcSegment.Size.Width,
                                arcSegment.Size.Height,
                                arcSegment.RotationAngle,
                                arcSegment.IsLargeArc,
                                arcSegment.SweepDirection == SweepDirection.CounterClockwise,
                                1);

                            for (int i = 0; i < points.Count; i++)
                            {
                                path.LineTo(
                                    density * (float)points[i].X,
                                    density * (float)points[i].Y);
                            }

                            if (points.Count > 0)
                            {
                                lastPoint = points[points.Count - 1];
                            }
                        }
                    }

                    if (pathFigure.IsClosed)
                    {
                        path.Close();
                    }
                }
            }

            return(path);
        }
Ejemplo n.º 55
0
        public void UpdateWireLocation(string dotNameA, string dotNameB, Polyline pl)
        {
            bool direction = false;
            int  n         = -1;

            Point startLine1;
            Point startline2;
            Point line1;
            Point line2;
            Point endLine2;
            Point endLine1;

            PointCollection polylinePoints = new PointCollection();

            Image dotA = FindDot(dotNameA);

            if (dotA == null)
            {
                foreach (SpecificElement se in lc.ec.GetAllElements())
                {
                    if (se.GetName() == dotNameA)
                    {
                        dotA = se.GetElement();
                    }
                }
            }

            if (dotA != null)
            {
                direction = DetermineDirection(dotNameA);
                n         = DetermineDirection2(dotNameA);

                startLine1 = new Point(dotA.RenderTransform.Value.OffsetX + 7, dotA.RenderTransform.Value.OffsetY + 9);

                if (dotNameB == "mouse")
                {
                    endLine1 = new Point(Mouse.GetPosition(canvas).X, Mouse.GetPosition(canvas).Y);
                }
                else
                {
                    Image dotB = FindDot(dotNameB);

                    if (dotB != null)
                    {
                        endLine1 = new Point(dotB.RenderTransform.Value.OffsetX + 7, dotB.RenderTransform.Value.OffsetY + 5);
                    }
                    else
                    {
                        foreach (SpecificElement se in lc.ec.GetAllElements())
                        {
                            if (se.GetName() == dotNameB)
                            {
                                dotB = se.GetElement();
                            }
                        }
                        endLine1 = new Point(dotB.RenderTransform.Value.OffsetX + 5, dotB.RenderTransform.Value.OffsetY + 7);
                    }
                }

                if (!direction)
                {
                    startline2 = new Point(startLine1.X + 25 * n, startLine1.Y);
                }
                else
                {
                    startline2 = new Point(startLine1.X, startLine1.Y + 25 * n);
                }

                direction = DetermineDirection(dotNameB);
                n         = DetermineDirection2(dotNameB);

                if (!direction)
                {
                    endLine2 = new Point(endLine1.X + 25 * n, endLine1.Y);
                }
                else
                {
                    endLine2 = new Point(endLine1.X, endLine1.Y + 25 * n);
                }

                direction = DetermineDirection(dotNameA);

                if (!direction)
                {
                    line1 = new Point(startline2.X, endLine2.Y);
                    line2 = new Point(endLine2.X, endLine2.Y);
                }
                else
                {
                    line1 = new Point(endLine2.X, startline2.Y);
                    line2 = new Point(endLine2.X, endLine2.Y);
                }

                polylinePoints.Add(startLine1);
                polylinePoints.Add(startline2);
                polylinePoints.Add(line1);
                polylinePoints.Add(line2);
                polylinePoints.Add(endLine2);
                polylinePoints.Add(endLine1);

                pl.Points = polylinePoints;
            }
        }
Ejemplo n.º 56
0
        /// <summary>
        /// Updates the text block when the visual appearance changed.
        /// </summary>
        private void VisualChanged()
        {
            this.meshes.Clear();

            if (this.Items == null)
            {
                this.Content = null;
                return;
            }

            var items = this.Items.Where(i => !string.IsNullOrEmpty(i.Text)).ToList();
            var group = new Model3DGroup();

            while (items.Count > 0)
            {
                Dictionary <string, FrameworkElement> elementMap;
                Dictionary <FrameworkElement, Rect>   elementPositions;
                var material = TextGroupVisual3D.CreateTextMaterial(
                    items, this.CreateElement, this.Background, out elementMap, out elementPositions);
                material.Freeze();

                var billboards         = new List <Billboard>();
                var addedChildren      = new List <BillboardTextItem>();
                var textureCoordinates = new PointCollection();
                foreach (var item in items)
                {
                    var element = elementMap[item.Text];
                    var r       = elementPositions[element];
                    if (r.Bottom > 1)
                    {
                        break;
                    }

                    billboards.Add(
                        new Billboard(
                            item.Position,
                            element.ActualWidth,
                            element.ActualHeight,
                            item.HorizontalAlignment,
                            item.VerticalAlignment,
                            item.DepthOffset));
                    textureCoordinates.Add(new Point(r.Left, r.Bottom));
                    textureCoordinates.Add(new Point(r.Right, r.Bottom));
                    textureCoordinates.Add(new Point(r.Right, r.Top));
                    textureCoordinates.Add(new Point(r.Left, r.Top));

                    addedChildren.Add(item);
                }

                var g = new MeshGeometry3D
                {
                    TriangleIndices    = BillboardGeometryBuilder.CreateIndices(billboards.Count),
                    TextureCoordinates = textureCoordinates,
                    Positions          = this.builder.GetPositions(billboards)
                };
                group.Children.Add(new GeometryModel3D(g, material));
                this.meshes.Add(g, billboards);
                foreach (var c in addedChildren)
                {
                    items.Remove(c);
                }
            }

            this.Content = group;
        }
Ejemplo n.º 57
0
 public double Area(PointCollection points)
 {
     return(Math.Abs(points.Take(points.Count - 1).Select((p, i) => (points[i + 1].X - p.X) * (points[i + 1].Y + p.Y)).Sum() / 2));
 }
        private void Initialize()
        {
            // Configure the basemap
            _myMapView.Map = new Map(Basemap.CreateTopographic());

            // Create the graphics overlay and set the selection color
            _graphicsOverlay = new GraphicsOverlay()
            {
                SelectionColor = System.Drawing.Color.Yellow
            };

            // Add the overlay to the MapView
            _myMapView.GraphicsOverlays.Add(_graphicsOverlay);

            // Create the point collection that defines the polygon
            PointCollection polygonPoints = new PointCollection(SpatialReferences.WebMercator)
            {
                new MapPoint(-5991501.677830, 5599295.131468),
                new MapPoint(-6928550.398185, 2087936.739807),
                new MapPoint(-3149463.800709, 1840803.011362),
                new MapPoint(-1563689.043184, 3714900.452072),
                new MapPoint(-3180355.516764, 5619889.608838)
            };

            // Create the polygon
            Polygon polygonGeometry = new Polygon(polygonPoints);

            // Define the symbology of the polygon
            SimpleLineSymbol polygonOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Green, 2);
            SimpleFillSymbol polygonFillSymbol    = new SimpleFillSymbol(SimpleFillSymbolStyle.ForwardDiagonal, System.Drawing.Color.Green, polygonOutlineSymbol);

            // Create the polygon graphic and add it to the graphics overlay
            _polygonGraphic = new Graphic(polygonGeometry, polygonFillSymbol);
            _graphicsOverlay.Graphics.Add(_polygonGraphic);

            // Create the point collection that defines the polyline
            var polylinePoints = new PointCollection(SpatialReferences.WebMercator)
            {
                new MapPoint(-4354240.726880, -609939.795721),
                new MapPoint(-3427489.245210, 2139422.933233),
                new MapPoint(-2109442.693501, 4301843.057130),
                new MapPoint(-1810822.771630, 7205664.366363)
            };

            // Create the polyline
            Polyline polylineGeometry = new Polyline(polylinePoints);

            // Create the polyline graphic and add it to the graphics overlay
            _polylineGraphic = new Graphic(polylineGeometry, new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, System.Drawing.Color.Red, 4));
            _graphicsOverlay.Graphics.Add(_polylineGraphic);

            // Create the point geometry that defines the point graphic
            MapPoint pointGeometry = new MapPoint(-4487263.495911, 3699176.480377, SpatialReferences.WebMercator);

            // Define the symbology for the point
            SimpleMarkerSymbol locationMarker = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, System.Drawing.Color.Blue, 10);

            // Create the point graphic and add it to the graphics overlay
            _pointGraphic = new Graphic(pointGeometry, locationMarker);
            _graphicsOverlay.Graphics.Add(_pointGraphic);

            // Listen for taps; the spatial relationships will be updated in the handler
            _myMapView.GeoViewTapped += myMapView_GeoViewTapped;

            // Set the viewpoint to center on the point
            _myMapView.SetViewpointCenterAsync(pointGeometry, 200000000);
        }
Ejemplo n.º 59
0
 /// <summary>
 /// Command which draw pentagon
 /// </summary>
 /// <param name="dataContext">Class DataContext</param>
 public DrawPentagonCommand(DataContext dataContext)
 {
     _pointCollection = new PointCollection();
     _dataContext     = dataContext;
 }
Ejemplo n.º 60
0
        private void RenderHeightmap(Heightmap heightmap, int hm_cellsize)
        {
            Point3DCollection points = new Point3DCollection();
            //float peak = heightmap.Max();
            float maxsize = Math.Max(heightmap.height, heightmap.width);
            float scale   = 2;

            for (int y = 0; y < heightmap.height; y++)
            {
                for (int x = 0; x < heightmap.width; x++)
                {
                    points.Add(new Point3D(x / (maxsize - 0.5) * scale, heightmap[x, y] / (maxsize - 0.5) * scale, y / (maxsize - 0.5) * scale));
                }
            }

            Int32Collection indices = new Int32Collection();

            for (int y = 0; y < heightmap.height - 1; y++)
            {
                for (int x = 0; x < heightmap.width - 1; x++)
                {
                    //First triangle
                    indices.Add(x + y * heightmap.width);
                    indices.Add(x + (y + 1) * heightmap.width);
                    indices.Add((x + 1) + y * heightmap.width);
                    //Second triangle
                    indices.Add((x + 1) + y * heightmap.width);
                    indices.Add(x + (y + 1) * heightmap.width);
                    indices.Add((x + 1) + (y + 1) * heightmap.width);
                }
            }

            PointCollection texture = new PointCollection();

            for (int y = 0; y < heightmap.height; y++)
            {
                for (int x = 0; x < heightmap.width; x++)
                {
                    texture.Add(new Point(x / (double)heightmap.width, y / (double)heightmap.height));
                    //texture.Add(new Point(x / (double)heightmap.width, (y + 1) / (double)heightmap.height));
                    //texture.Add(new Point((x + 1) / (double)heightmap.width, y / (double)heightmap.height));

                    //texture.Add(new Point((x + 1) / (double)heightmap.width, y / (double)heightmap.height));
                    //texture.Add(new Point(x / (double)heightmap.width, (y + 1) / (double)heightmap.height));
                    //texture.Add(new Point((x + 1) / (double)heightmap.width, (y + 1) / (double)heightmap.height));
                }
            }
            //MeshGeometry3D newmesh = new MeshGeometry3D();
            //newmesh.Positions = points;
            //newmesh.TriangleIndices = indices;
            //newmesh.TextureCoordinates = texture;
            //
            //GeometryModel3D model = new GeometryModel3D();
            //model.Geometry = newmesh;
            //ModelVisual3D mv3d = new ModelVisual3D();
            //mv3d.Content = model;
            //
            //viewport3D1.Children.Remove(MyModel);
            //viewport3D1.Children.Add(mv3d);
            meshMain.Positions          = points;
            meshMain.TriangleIndices    = indices;
            meshMain.TextureCoordinates = texture;
            translate.OffsetX           = -scale / 2 * heightmap.width / maxsize;
            translate.OffsetZ           = -scale / 2 * heightmap.height / maxsize;
            translate.OffsetY           = -scale / 2;
        }