public void RenderRaster(Graphics g, Bitmap bitmap, RasterStyle style, BoundingRectangle viewBox, BoundingRectangle bitmapBounds, double scaleFactor)
        {
            ICoordinate minPoint = bitmapBounds.Min;
            ICoordinate maxPoint = bitmapBounds.Max;

            if (viewBox.Intersects(bitmapBounds))
            {
                Point minP = new Point((int)((minPoint.X - viewBox.MinX) * scaleFactor),
                                       (int)((viewBox.MaxY - minPoint.Y) * scaleFactor));

                Point maxP = new Point((int)((maxPoint.X - viewBox.MinX) * scaleFactor),
                           (int)((viewBox.MaxY - maxPoint.Y) * scaleFactor));

                g.InterpolationMode = style.InterpolationMode;

                Rectangle r = new Rectangle(minP.X, maxP.Y, maxP.X - minP.X, minP.Y - maxP.Y);

                using (ImageAttributes imageAttributes = new ImageAttributes())
                {
                    imageAttributes.SetColorMatrix(style.ColorAdjustmentMatrix,
                                                   ColorMatrixFlag.Default,
                                                   ColorAdjustType.Bitmap);

                    g.DrawImage(bitmap, r, 0, 0, bitmap.Width, bitmap.Height,
                                GraphicsUnit.Pixel, imageAttributes);
                }
            }
        }
        public void TestHoldValue()
        {
            BoundingRectangle boundingRectangle0 = new BoundingRectangle();
            Assert.AreEqual(boundingRectangle0.Left, 0);
            Assert.AreEqual(boundingRectangle0.Bottom, 0);
            Assert.AreEqual(boundingRectangle0.Right, 0);
            Assert.AreEqual(boundingRectangle0.Top, 0);
            Assert.AreEqual(boundingRectangle0.Height, 0);
            Assert.AreEqual(boundingRectangle0.Width, 0);

            Assert.AreEqual(BoundingRectangle.Empty.Left, 0);
            Assert.AreEqual(BoundingRectangle.Empty.Bottom, 0);
            Assert.AreEqual(BoundingRectangle.Empty.Right, 0);
            Assert.AreEqual(BoundingRectangle.Empty.Top, 0);
            Assert.AreEqual(BoundingRectangle.Empty.Height, 0);
            Assert.AreEqual(BoundingRectangle.Empty.Width, 0);

            BoundingRectangle boundingRectangle1 = new BoundingRectangle(1, 2, 3, 4);
            Assert.AreEqual(boundingRectangle1.Left, 1);
            Assert.AreEqual(boundingRectangle1.Bottom, 2);
            Assert.AreEqual(boundingRectangle1.Right, 3);
            Assert.AreEqual(boundingRectangle1.Top, 4);
            Assert.AreEqual(boundingRectangle1.Height, 2);
            Assert.AreEqual(boundingRectangle1.Width, 2);
        }
        /// <summary>
        /// Читает запись представляющую коллекцию точек.
        /// </summary>
        /// <param name="file">Входной поток</param>
        /// <param name="record">Запись Shape-файла в которую будет помещена прочитанная информация</param>
        /// <param name="bounds">Ограничивающий прямоугольник, с которым должен пересекаться ограничивающий прямоугольник записи</param>
        public override bool Read(Stream file, BoundingRectangle bounds, ShapeFileRecord record)
        {
            try
            {
                record.MinX = file.ReadDouble();// ShapeFile.ReadDouble64_LE(stream);
                record.MinY = file.ReadDouble();// ShapeFile.ReadDouble64_LE(stream);
                record.MaxX = file.ReadDouble();// ShapeFile.ReadDouble64_LE(stream);
                record.MaxY = file.ReadDouble();// ShapeFile.ReadDouble64_LE(stream);

                int numPoints = file.ReadInt32();// ShapeFile.ReadInt32_LE(stream);

                if (!ShapeHandler.IsRecordInView(bounds, record))
                {
                    file.Seek((long)numPoints * 16, SeekOrigin.Current);
                    return false;
                }

                for (int i = 0; i < numPoints; i++)
                {
                    ICoordinate p =
                        PlanimetryEnvironment.NewCoordinate(
                        file.ReadDouble(),//ShapeFile.ReadDouble64_LE(stream),
                        file.ReadDouble());//ShapeFile.ReadDouble64_LE(stream));

                    record.Points.Add(p);
                }

                return true;
            }
            catch { throw; }
        }
 /// <summary>
 /// Writes a <see cref="BoundingRectangle"/> value as an array in X, Y, Width, Height order.
 /// </summary>
 /// <param name="output">The stream to which to write the value.</param>
 /// <param name="value">The value to write.</param>
 public static void WriteBoundingRectangle(CesiumOutputStream output, BoundingRectangle value)
 {
     output.WriteStartSequence();
     output.WriteValue(value.Left);
     output.WriteValue(value.Bottom);
     output.WriteValue(value.Width);
     output.WriteValue(value.Height);
     output.WriteEndSequence();
 }
        public void TestGetHashCode()
        {
            BoundingRectangle boundingRectangle1 = new BoundingRectangle(1, 2, 3, 4);
            BoundingRectangle boundingRectangle2 = new BoundingRectangle(1, 2, 3, 4);
            BoundingRectangle boundingRectangle3 = new BoundingRectangle(2, 3, 4, 5);

            Assert.AreEqual(boundingRectangle1.GetHashCode(), boundingRectangle2.GetHashCode());
            Assert.AreNotEqual(boundingRectangle1.GetHashCode(), boundingRectangle3.GetHashCode());
        }
 public void Init()
 {
     circle1 = new BoundingCircle(Vector2D.YAxis, 2);
     circle2 = new BoundingCircle(Vector2D.XAxis, 2);
     rect1 = BoundingRectangle.FromCircle(circle1);
     circle3 = BoundingCircle.FromRectangle(rect1);
     rect2 = BoundingRectangle.FromCircle(circle3);
     polygon1 = new BoundingPolygon(rect1.Corners());
 }
        public void TestEqualsEpsilon()
        {
            BoundingRectangle boundingRectangle = new BoundingRectangle(1000, 2000, 3000, 4000);
            BoundingRectangle similarBoundingRectangle = new BoundingRectangle(1010, 2010, 3010, 4010);

            Assert.IsTrue(boundingRectangle.EqualsEpsilon(similarBoundingRectangle, 1000));
            Assert.IsTrue(boundingRectangle.EqualsEpsilon(similarBoundingRectangle, 100));
            Assert.IsTrue(boundingRectangle.EqualsEpsilon(similarBoundingRectangle, 10));
            Assert.IsFalse(boundingRectangle.EqualsEpsilon(similarBoundingRectangle, 1));
        }
Exemple #8
0
 /// <summary>Проверка записи на нахождение границ фигуры в указанной области</summary>
 /// <param name="bounds">Границы области</param>
 /// <param name="record">Запись shape-файла</param>
 /// <returns></returns>
 protected static bool IsRecordInView(BoundingRectangle bounds, ShapeFileRecord record)
 {
     if (bounds != null && !bounds.IsEmpty())
     {
         if (!bounds.Intersects(
             new BoundingRectangle(PlanimetryEnvironment.NewCoordinate(record.MinX, record.MinY),
                                   PlanimetryEnvironment.NewCoordinate(record.MaxX, record.MaxY))))
             return false;
     }
     return true;
 }
 public void ContainsPoint()
 {
     BoundingRectangle rect = new BoundingRectangle(0, 0, 2, 2);
     Assert.AreEqual(ContainmentType.Contains, rect.Contains(new Vector2D(1, 1)), "1");
     Assert.AreEqual(ContainmentType.Contains, rect.Contains(new Vector2D(2, 2)), "2");
     Assert.AreEqual(ContainmentType.Contains, rect.Contains(new Vector2D(0, 2)), "3");
     Assert.AreEqual(ContainmentType.Contains, rect.Contains(new Vector2D(0, 0)), "4");
     Assert.AreEqual(ContainmentType.Disjoint, rect.Contains(new Vector2D(2, 3)), "5");
     Assert.AreEqual(ContainmentType.Disjoint, rect.Contains(new Vector2D(-1, 0)), "6");
     Assert.AreEqual(ContainmentType.Disjoint, rect.Contains(new Vector2D(-.0001f, 0)), "7");
     Assert.AreEqual(ContainmentType.Disjoint, rect.Contains(new Vector2D(3, 1)), "8");
     Assert.AreEqual(ContainmentType.Disjoint, rect.Contains(new Vector2D(1, -1)), "9");
 }
        protected override void Open()
        {
            dispose += DemoHelper.BasicDemoSetup(DemoInfo);


            Scene.Engine.AddLogic(new LineFluidLogic(new Line(0, -1, -400), 1.95f, .02f, new Vector2D(0, 0), new Lifespan()));
            Scene.Engine.AddLogic(new GravityField(new Vector2D(0, 1000), new Lifespan()));

            Rectangle rect1 = Viewport.Rectangle;


            BoundingRectangle rect = new BoundingRectangle(rect1.Left, rect1.Top, rect1.Right, rect1.Bottom);
            rect.Min.X -= 75;
            rect.Min.Y -= 75;
            rect.Max.X += 75;
            rect.Max.Y += 75;
            DemoHelper.AddShell(DemoInfo, rect, 100, Scalar.PositiveInfinity).ForEach(delegate(Body b) { b.IgnoresGravity = true; });

            DemoHelper.AddRagDoll(DemoInfo, new Vector2D(340, 300));
            DemoHelper.AddRagDoll(DemoInfo, new Vector2D(640, 300));
            IShape shape = ShapeFactory.CreateSprite(Cache<SurfacePolygons>.GetItem("fighter.png"), 3, 16, 4);

            DemoHelper.AddShape(DemoInfo, shape, 200, new ALVector2D(0, new Vector2D(200, 300)));
            DemoHelper.AddShape(DemoInfo, shape, 100, new ALVector2D(0, new Vector2D(500, 300)));
            DemoHelper.AddRectangle(DemoInfo, 20, 200, 25 / 5, new ALVector2D(0, 600, 600));
            DemoHelper.AddRectangle(DemoInfo, 20, 200, 25 / 5, new ALVector2D(0, 600, 620));
            DemoHelper.AddRectangle(DemoInfo, 50, 100, 50, new ALVector2D(0, 200, 400));
            DemoHelper.AddRectangle(DemoInfo, 50, 100, 50, new ALVector2D(0, 400, 200));

            Vector2D[] waterVertexes = new Vector2D[4]
            {
                 new Vector2D(-10, 400),
                 new Vector2D(10000, 400),
                 new Vector2D(10000, 1000),
                 new Vector2D(-10, 1000)
            };
            ScalarColor3[] waterColor = new ScalarColor3[4]
            {
                new ScalarColor3(0,0,1),
                new ScalarColor3(0,0,1),
                new ScalarColor3(0,0,1),
                new ScalarColor3(0,0,1)
            };
            Colored3VertexesDrawable drawable = new Colored3VertexesDrawable(Gl.GL_QUADS, waterVertexes, waterColor);

            Graphic graphic = new Graphic(drawable, Matrix2x3.Identity, new Lifespan());
            graphic.ZOrder = -1;
            Scene.AddGraphic(graphic);
        }
Exemple #11
0
        /// <summary>
        /// Transforms coordinates of the bounding rectangle.
        /// </summary>
        /// <param name="box">Rectangle to transform</param>
        /// <param name="transform">The transformation to apply</param>
        /// <returns>The transformed rectangle</returns>
        public static BoundingRectangle TransformBoundingRectangle(BoundingRectangle box, IMathTransform transform)
        {
            if (box == null)
                return null;
            ICoordinate[] corners = new ICoordinate[4];
            corners[0] = PlanimetryEnvironment.NewCoordinate(transform.Transform(box.Min.Values()));
            corners[1] = PlanimetryEnvironment.NewCoordinate(transform.Transform(box.Max.Values()));
            corners[2] = PlanimetryEnvironment.NewCoordinate(transform.Transform(PlanimetryEnvironment.NewCoordinate(box.MinX, box.MaxY).Values()));
            corners[3] = PlanimetryEnvironment.NewCoordinate(transform.Transform(PlanimetryEnvironment.NewCoordinate(box.MaxX, box.MinY).Values())); 

            BoundingRectangle result = new BoundingRectangle();
            for (int i = 0; i < 4; i++)
                result.Join(corners[i]);
            return result;
        }
        public void EqualityTest()
        {
            BoundingRectangle boundingRectangle = new BoundingRectangle(1, 2, 3, 4);
            BoundingRectangle sameBoundingRectangle = new BoundingRectangle(1, 2, 3, 4);
            BoundingRectangle diffBoundingRectangle = new BoundingRectangle(2, 3, 4, 5);

            Assert.IsTrue(boundingRectangle.Equals(sameBoundingRectangle));
            Assert.IsFalse(boundingRectangle.Equals(diffBoundingRectangle));
            Assert.IsTrue(boundingRectangle == sameBoundingRectangle);
            Assert.IsTrue(boundingRectangle != diffBoundingRectangle);

            object nonBoundingRectangleObject = new object();
            Assert.IsFalse(boundingRectangle.Equals(nonBoundingRectangleObject));

            object boundingRectangleObject = boundingRectangle;
            Assert.IsTrue(boundingRectangle.Equals(boundingRectangleObject));
        }
Exemple #13
0
        /// <summary>
        /// Читает запись представляющую точку.
        /// </summary>
        /// <param name="file">Входной поток</param>
        /// <param name="record">Запись Shape-файла в которую будет помещена прочитанная информация</param>
        /// <param name="bounds">Ограничивающий прямоугольник, с которым должен пересекаться ограничивающий прямоугольник записи</param>
        public override bool Read(/*BigEndianBinaryReader*/Stream file, BoundingRectangle bounds, ShapeFileRecord record)
        {

            ICoordinate p = PlanimetryEnvironment.NewCoordinate(0, 0);
            p.X = file.ReadDouble();// ShapeFile.ReadDouble64_LE(stream);
            p.Y = file.ReadDouble();// ShapeFile.ReadDouble64_LE(stream);

            if (bounds != null && !bounds.IsEmpty() && !bounds.ContainsPoint(p))
                return false;

            record.Points.Add(p);

            record.MinX = p.X;
            record.MinY = p.Y;
            record.MaxX = record.MinX;
            record.MaxY = record.MinY;

            return true;
        }
        protected override void Open()
        {
            dispose += DemoHelper.BasicDemoSetup(DemoInfo);

            Rectangle rect1 = Viewport.Rectangle;
            BoundingRectangle rect = new BoundingRectangle(rect1.Left, rect1.Top, rect1.Right, rect1.Bottom);
            rect.Min.X -= 75;
            rect.Min.Y -= 75;
            rect.Max.X += 75;
            rect.Max.Y += 75;
            DemoHelper.AddShell(DemoInfo, rect, 100, Scalar.PositiveInfinity).ForEach(delegate(Body b) { b.IgnoresGravity = true; });
            rect.Min.X += 110;
            rect.Min.Y += 110;
            rect.Max.X -= 110;
            rect.Max.Y -= 110;
            IShape shape = ShapeFactory.CreateColoredCircle(3, 7);
            DemoHelper.AddGrid(DemoInfo, shape, 40,
                rect,
                1, 1).ForEach(delegate(Body b) { b.State.Velocity.Linear = new Vector2D(DemoHelper.Rand.Next(-100, 100), DemoHelper.Rand.Next(-100, 100)); });
        }
        public static BoundingRectangle GetBoundsFromPath(List<PathInfo> list)
        {
            // Only support simple paths
            if (list.First().segmentType != SegmentType.Move)
            {
                return null;
            }
            if (list.Last().segmentType != SegmentType.Close)
            {
                return null;
            }
            if (list.Skip(1).Take(list.Count - 2).Any(p => p.segmentType != SegmentType.Line))
            {
                return null;
            }

            BoundingRectangle ret = new BoundingRectangle();
            foreach (var i in list.Take(list.Count - 1))
            {
                ret.UpdateBounds(i.point);
            }

            return ret;
        }
        private void drawPolylineWithIntersectCalculation(Graphics g, Feature feature, PolylineStyle style, BoundingRectangle viewBox, double scaleFactor)
        {
            //selection and rims do not contain dashes, so it is better to paint the entire
            if (style.UseOutline || feature.Selected)
            {
                foreach (LinePath path in feature.Polyline.Paths)
                {
                    PointF[] points = new PointF[path.Vertices.Count];

                    for (int j = 0; j < path.Vertices.Count; j++)
                    {
                        points[j].X = (float)((path.Vertices[j].X - viewBox.MinX) * scaleFactor);
                        points[j].Y = (float)((viewBox.MaxY - path.Vertices[j].Y) * scaleFactor);
                    }

                    if (style.UseOutline || feature.Selected)
                        drawLinePathSelectionAndOutline(g, feature.Selected, points, style);
                }
            }

            List<ICoordinate> currentPath = new List<ICoordinate>();

            using (Pen pen = style.GetPen())
            {
                using(Pen annexPen = style.GetAnnexPen())
                foreach (LinePath path in feature.Polyline.Paths)
                {
                    if (path.Vertices.Count < 2)
                        continue;

                    currentPath.Clear();
                    double currentLength = 0;
                    bool isInternalPath = viewBox.ContainsPoint(path.Vertices[0]);
                    ICoordinate previousPoint = path.Vertices[0];
                    IList<ICoordinate> vertices = path.Vertices;

                    for (int j = 0; j < path.Vertices.Count; j++)
                    {
                        if (isInternalPath) // the inside of the polyline
                        {
                            if (viewBox.ContainsPoint(vertices[j])) //stay inside
                            {
                                currentPath.Add(vertices[j]);
                                continue;
                            }
                            else // go outside
                            {
                                // add a point of intersection
                                List<ICoordinate> crossPoints = getCrossPoints(vertices[j], vertices[j - 1], viewBox);
                                currentPath.Add(crossPoints[0]);

                                //draw
                                drawVisiblePolylinePartWithStyleDetection(g, currentPath, style, pen, annexPen, feature.Selected, viewBox, scaleFactor, currentLength);

                                // are counting the length of a past
                                currentLength += getPathLength(currentPath);

                                // initialize the array outside of the points, polylines and continue execution
                                currentPath.Clear();
                                currentPath.Add(crossPoints[0]);
                                currentPath.Add(vertices[j]);
                                isInternalPath = false;
                                continue;
                            }
                        }
                        else //the outer part of the polyline
                        {
                            if (viewBox.ContainsPoint(vertices[j])) // go inside
                            {
                                //add a point of intersection
                                List<ICoordinate> crossPoints = getCrossPoints(vertices[j], vertices[j - 1], viewBox);
                                currentPath.Add(crossPoints[0]);

                                //are counting the length of a past
                                currentLength += getPathLength(currentPath);

                                // initialize the array of points inside the polyline and continue execution
                                currentPath.Clear();
                                currentPath.Add(crossPoints[0]);
                                currentPath.Add(vertices[j]);
                                isInternalPath = true;
                                continue;
                            }
                            else // cross twice, or remain outside
                            {
                                // look for the point of intersection
                                if (j > 0)
                                {
                                    List<ICoordinate> crossPoints = getCrossPoints(vertices[j], vertices[j - 1], viewBox);
                                    if (crossPoints.Count == 0) // remained outside
                                    {
                                        currentPath.Add(vertices[j]);
                                        continue;
                                    }
                                    if (crossPoints.Count == 2) // crossed 2 times
                                    {
                                        //determine which of the points of intersection must be added to the current path
                                        double d0 = PlanimetryAlgorithms.Distance(crossPoints[0], vertices[j - 1]);
                                        double d1 = PlanimetryAlgorithms.Distance(crossPoints[1], vertices[j - 1]);
                                        if (d0 < d1)
                                            currentPath.Add(crossPoints[0]);
                                        else
                                            currentPath.Add(crossPoints[1]);

                                        // are counting the length of a past
                                        currentLength += getPathLength(currentPath);

                                        currentPath.Clear();

                                        currentPath.Add(crossPoints[d0 < d1 ? 0 : 1]);
                                        currentPath.Add(crossPoints[d0 < d1 ? 1 : 0]);

                                        //draw a segment
                                        drawVisiblePolylinePartWithStyleDetection(g, currentPath, style, pen, annexPen, feature.Selected, viewBox, scaleFactor, currentLength);
                                        // consider the length
                                        currentLength += PlanimetryAlgorithms.Distance(crossPoints[0], crossPoints[1]);

                                        // initialize the external part of the polyline
                                        currentPath.Clear();
                                        if (d0 < d1)
                                            currentPath.Add(crossPoints[1]);
                                        else
                                            currentPath.Add(crossPoints[0]);
                                        currentPath.Add(vertices[j]);
                                        isInternalPath = false;
                                        continue;
                                    }
                                }
                                else // 1st point you just need to add to the list
                                {
                                    currentPath.Add(vertices[j]);
                                    continue;
                                }
                            }
                        }
                    }

                    //Draw a polyline part, if the internal
                    if (isInternalPath)
                        drawVisiblePolylinePartWithStyleDetection(g, currentPath, style, pen, annexPen, feature.Selected, viewBox, scaleFactor, currentLength);
                }
            }
        }
            public BoundingRectangle GetBoundingBox()
            {
                if (_boundingBoxChanged)
                {
                    _boundingBox = _envelopePolygon.GetBoundingRectangle();
                    _boundingBoxChanged = false;
                }

                return _boundingBox;
            }
 public override bool CheckCollision(BoundingRectangle other)
 {
     return(_bounds.CollidesWith(other));
 }
Exemple #19
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="bounds"></param>
 /// <param name="threshold"></param>
 /// <param name="maxDepth"></param>
 public Quadtree(BoundingRectangle bounds, int threshold, int maxDepth)
     : base(bounds, threshold, maxDepth)
 {
 }
Exemple #20
0
 public void TestInitializationFromBadElementsWidth()
 {
     BoundingRectangle boundingRectangle = new BoundingRectangle(2, 2, 1, 3);
 }
 /// <summary>
 /// Adds the features retrieved from data source to the receiver.
 /// </summary>
 /// <param name="receiver">An object that receives features</param>
 /// <param name="bounds">Rectangular region you want to fill with the objects</param>
 public abstract int QueryFeatures(IFeatureReceiver receiver, BoundingRectangle bounds);
        public void AssertThat_Equals_IsFalseForNull()
        {
            var a = new BoundingRectangle(new Vector2(0, 0), new Vector2(10, 10));

            Assert.IsFalse(a.Equals(null));
        }
        /// <summary>
        /// Draw a polygon.
        /// </summary>
        protected virtual void DrawPolygon(Feature feature, Graphics g, PolygonStyle style, TitleStyle titleStyle,
                                           BoundingRectangle viewBox, bool titleVisible, double scaleFactor)
        {
            if (feature.Polygon.Contours.Count == 0)
                return;

            //if (feature.Layer != null && feature.Layer.Title == "adp.TAB")
            //{
            //    drawPrismPolygon(feature, g, viewBox, scaleFactor);
            //    // inscription
            //    if (!string.IsNullOrEmpty(feature.Title) && titleVisible)
            //        addTitleBufferElement(g, feature, titleStyle, viewBox, scaleFactor);
            //    return;
            //}

            if (!_isSelectionRendering && feature.Selected)
            {
                PolygonBufferElement element = new PolygonBufferElement(feature, style, titleStyle, titleVisible);
                _selectedPolygons.Add(element);
                return;
            }

            double pixelsize = 1/scaleFactor;

            if (_reduceSubpixelDetails)
            {
                if (feature.BoundingRectangle.Width < pixelsize && feature.BoundingRectangle.Height < pixelsize)
                    return;

                Polygon tempPolygon = (Polygon) feature.Polygon.Clone();
                tempPolygon.Weed(pixelsize);
                Feature tempFeature = new Feature(FeatureType.Polygon);
                tempFeature.Title = feature.Title;
                tempFeature.Selected = feature.Selected;
                tempFeature.Polygon = tempPolygon;
                feature = tempFeature;

                if (feature.Polygon.Contours.Count == 0)
                    return;
            }

            using (Pen pen = style.GetPen())
            {
                using (GraphicsPath path = new GraphicsPath(FillMode.Alternate))
                {
                    path.StartFigure();

                    float x = (float) ((feature.Polygon.Contours[0].Vertices[0].X - viewBox.MinX)*scaleFactor);
                    float y = (float) ((viewBox.MaxY - feature.Polygon.Contours[0].Vertices[0].Y)*scaleFactor);

                    g.RenderingOrigin = new Point((int) Math.Round(x), (int) Math.Round(y));

                    foreach (Contour c in feature.Polygon.Contours)
                    {
                        // there is no point in trying to draw the contours of the degenerate
                        if (c.Vertices.Count <= 2)
                            continue;

                        PointF[] points = new PointF[c.Vertices.Count];

                        for (int j = 0; j < c.Vertices.Count; j++)
                        {
                            points[j].X = (float) ((c.Vertices[j].X - viewBox.MinX)*scaleFactor);
                            points[j].Y = (float) ((viewBox.MaxY - c.Vertices[j].Y)*scaleFactor);
                        }

                        if (points.Length > 2)
                            path.AddPolygon(points);
                    }

                    path.CloseFigure();

                    // Fill polygon
                    using (Brush b = style.GetBrush())
                    {
                        if (style.FillPatternInternal != null)
                        {
                            int w = style.FillPatternInternal.Width;
                            int h = style.FillPatternInternal.Height;
                            ((TextureBrush) b).TranslateTransform(g.RenderingOrigin.X%w, g.RenderingOrigin.Y%h);
                        }
                        g.FillPath(b, path);
                    }

                    if (feature.Selected)
                    {
                        //Fills the selected polygon

                        //Color color = Color.FromArgb(50, _selectionColor);
                        //using (Brush b = new HatchBrush(HatchStyle.Percent70, color, Color.Transparent))

                        if (_selectionColorChanged || _selectionTexture == null)
                            createSelectionTexture();

                        using (Brush b = new TextureBrush(_selectionTexture))
                        {
                            ((TextureBrush) b).TranslateTransform(g.RenderingOrigin.X%8, g.RenderingOrigin.Y%8);
                            g.FillPath(b, path);
                        }

                        // boundary of the selected polygons
                        using (Pen p = new Pen(_selectionColor, style.BorderWidth + 3))
                        {
                            p.LineJoin = LineJoin.Bevel;
                            g.DrawPath(p, path);
                        }
                    }

                    //boundary of the landfill
                    if (style.BorderVisible)
                        g.DrawPath(pen, path);
                }

                // inscription
                if (!string.IsNullOrEmpty(feature.Title) && titleVisible)
                    addTitleBufferElement(g, feature, titleStyle, viewBox, scaleFactor);
            }
        }
        public void AssertThat_ContainsVector_ContainsPoint()
        {
            var r = new BoundingRectangle(new Vector2(0, 0), new Vector2(10, 10));

            Assert.IsTrue(r.Contains(new Vector2(5, 5)));
        }
        public void AssertThat_ContainsVector_DoesNotContainPoint()
        {
            var r = new BoundingRectangle(new Vector2(0, 0), new Vector2(10, 10));

            Assert.IsFalse(r.Contains(new Vector2(15, 5)));
        }
Exemple #26
0
 /// <summary>
 /// Creates a new mouse sprite
 /// </summary>
 /// <param name="position">The position of the sprite in the game</param>
 public MouseSprite(Vector2 position)
 {
     this.Position = position;
     this.bounds   = new BoundingRectangle(Position + new Vector2(0, 16), 32, 24);
 }
Exemple #27
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="a"></param>
 /// <param name="b"></param>
 /// <returns></returns>
 protected override bool Intersects(BoundingRectangle a, ref BoundingRectangle b)
 {
     return(a.Intersects(b));
 }
Exemple #28
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="container"></param>
 /// <param name="contained"></param>
 /// <returns></returns>
 protected override bool Contains(BoundingRectangle container, ref BoundingRectangle contained)
 {
     return(container.Contains(contained));
 }
 void IFeatureRenderer.DrawPolygon(Feature feature, Graphics g, PolygonStyle style, TitleStyle titleStyle, BoundingRectangle viewBox, bool titleVisible, double scaleFactor)
 {
     DrawPolygon(feature, g, style, titleStyle, viewBox, titleVisible, scaleFactor);
 }
        public void AssertThat_Extent_IsExtent()
        {
            var r = new BoundingRectangle(new Vector2(10, 10), new Vector2(20, 30));

            Assert.AreEqual(new Vector2(10, 20), r.Extent);
        }
        /// <summary>
        /// Draw a point.
        /// </summary>        
        protected virtual void DrawPoint(Feature feature, Graphics g, PointStyle style, TitleStyle titleStyle,
                                         BoundingRectangle viewBox, bool titleVisible, double scaleFactor)
        {
            if (!_isSelectionRendering && feature.Selected)
            {
                PointBufferElement element = new PointBufferElement(feature, style, titleStyle, titleVisible);
                _selectedPoints.Add(element);
                return;
            }

            string _fontName = string.IsNullOrEmpty(style.FontName) ? _symbolsDefaultFontName : style.FontName;
            using (Font f = new Font(_fontName, style.Size, FontStyle.Regular, GraphicsUnit.Pixel))
            {
                using (SolidBrush fontBrush = new SolidBrush(style.Color))
                {
                    SizeF size;
                    SizeF offset;
                    if (style.DisplayKind == PointDisplayKind.Symbol)
                        // character size
                        size = g.MeasureString(style.Symbol.ToString(), f, new PointF(0, 0), _symbolStringFormat);
                    else
                    {
                        // image size
                        if (style.Image != null)
                            size = new SizeF(style.Image.Width, style.Image.Height);
                        else
                            size = new SizeF(1, 1);
                    }
                    //Offset relative to the center point
                    offset = new SizeF(size.Width/2,size.Height/2);

                    switch (style.ContentAlignment)
                    {
                        case ContentAlignment.TopLeft: offset = new SizeF(0, 0); break;
                        case ContentAlignment.TopCenter: offset = new SizeF(size.Width / 2,0); break;
                        case ContentAlignment.TopRight: offset = new SizeF(size.Width, 0); break;



                        case ContentAlignment.BottomLeft: offset = new SizeF(0, size.Height ); break;
                        case ContentAlignment.BottomCenter: offset = new SizeF(size.Width / 2, size.Height); break;
                        case ContentAlignment.BottomRight: offset = new SizeF(size.Width, size.Height); break;



                        case ContentAlignment.MiddleLeft: offset = new SizeF(0, size.Height / 2); break;
                        case ContentAlignment.MiddleCenter: offset = new SizeF(size.Width / 2, size.Height / 2); break;
                        case ContentAlignment.MiddleRight: offset = new SizeF(size.Width, size.Height / 2); break;
    
                        default:
                            throw new NotSupportedException();

                    }
                    IEnumerable<ICoordinate> targetPoints = null;
                    if (feature.FeatureType == FeatureType.Point)
                        targetPoints = new ICoordinate[] {feature.Point.Coordinate};
                    else
                        targetPoints = feature.MultiPoint.Points;

                    foreach (ICoordinate targetPoint in targetPoints)
                    {
                        if (style.DisplayKind == PointDisplayKind.Symbol)
                        {
                            // symbol
                            using (GraphicsPath path = new GraphicsPath())
                            {
                                path.AddString(style.Symbol.ToString(),
                                               f.FontFamily,
                                               (int) f.Style,
                                               f.Size,
                                               new PointF((float) ((targetPoint.X - viewBox.MinX)*scaleFactor-offset.Width),
                                                          (float)
                                                          ((viewBox.MaxY - targetPoint.Y)*scaleFactor -offset.Height)),
                                               _symbolStringFormat);

                                g.FillPath(fontBrush, path);
                            }
                        }
                        else
                        {
                            // image
                            if (style.Image != null)
                                g.DrawImageUnscaled(style.Image,
                                                    new Point(
                                                        (int)
                                                        Math.Round(((targetPoint.X - viewBox.MinX)*scaleFactor -
                                                                    offset.Width)),
                                                        (int)
                                                        Math.Round(((viewBox.MaxY - targetPoint.Y)*scaleFactor -
                                                                    offset.Height))));
                        }

                        if (feature.Selected)
                        {
                            // Frame selected object
                            using (Pen p = new Pen(_selectionColor, 2))
                                g.DrawRectangle(p,
                                                (float)((targetPoint.X - viewBox.MinX) * scaleFactor - offset.Width + 1),
                                                (float)((viewBox.MaxY - targetPoint.Y) * scaleFactor - offset.Height + 1),
                                                size.Width - 2, size.Height - 2);

                            using (Brush b = new SolidBrush(Color.FromArgb(50, _selectionColor)))
                                g.FillRectangle(b, (float)((targetPoint.X - viewBox.MinX) * scaleFactor - offset.Width),
                                                (float)((viewBox.MaxY - targetPoint.Y) * scaleFactor - offset.Height),
                                                size.Width, size.Height);
                        }
                    }

                    // inscription
                    if (!string.IsNullOrEmpty(feature.Title) && titleVisible)
                    {
                        if (feature.FeatureType == FeatureType.Point)
                        {
                            //Location signs point object can not be determined only by coordinates,
                            //without knowing the size of the image of a point object. 
                            //Therefore, the ordinate of a point object is displaced by half the size of the symbol.
                            Feature shp = new Feature(FeatureType.Point);
                            shp.Point = new PointD(feature.Point.X, feature.Point.Y + size.Height/2/scaleFactor);
                            shp.Title = feature.Title;
                            addTitleBufferElement(g, shp, titleStyle, viewBox, scaleFactor);
                        }
                        if (feature.FeatureType == FeatureType.MultiPoint)
                            addTitleBufferElement(g, feature, titleStyle, viewBox, scaleFactor);
                    }
                }
            }
        }
        public void AssertThat_Area_ReturnsArea()
        {
            var r = new BoundingRectangle(new Vector2(10, 10), new Vector2(20, 20));

            Assert.AreEqual(100, r.Area());
        }
Exemple #33
0
        public bool IsOverlappingPlayer(int gridX, int gridY, Point size)
        {
            Rectangle pointRect = new Rectangle(gridX * Tile.Width, gridY * Tile.Height, size.X * Tile.Width, size.Y * Tile.Height);

            return(BoundingRectangle.Intersects(pointRect));
        }
 public bool CheckCollision(BoundingRectangle b)
 {
     return(_level[_activeRoom.Item1, _activeRoom.Item2].CheckForOutOfBounds(b));
 }
 public override void CalcBoundingRectangle(Matrices matrices, out BoundingRectangle rectangle)
 {
     Vector2D.Transform(ref matrices.ToWorld, ref Zero, out rectangle.Max);
     rectangle.Min = rectangle.Max;
 }
        private static Bitmap calcDestRaster(Bitmap source, BoundingRectangle rectangle, ICoordinate[,] warpTransformResult, RasterBindingProgress progress)
        {
            byte[,] fillCount = new byte[source.Width, source.Height];

            Int16[,] r = new Int16[source.Width, source.Height];
            Int16[,] g = new Int16[source.Width, source.Height];
            Int16[,] b = new Int16[source.Width, source.Height];

            for (int i = 0; i < source.Width; i++)
            {
                for (int j = 0; j < source.Height; j++)
                {
                    fillCount[i, j] = 0;
                    r[i, j]         = 0;
                    g[i, j]         = 0;
                    b[i, j]         = 0;
                }
            }

            Bitmap result = new Bitmap(source.Width, source.Height);

            int    startProgressPercent = 70;
            int    endProgressPercent   = 80;
            double completed            = 0;
            double previousPercent      = 0;

            for (int i = 0; i < source.Width; i++)
            {
                for (int j = 0; j < source.Height; j++)
                {
                    int x = getDestRasterX(source.Width, warpTransformResult[i, j], rectangle);
                    int y = getDestRasterY(source.Height, warpTransformResult[i, j], rectangle);

                    if (!double.IsNaN(warpTransformResult[i, j].X) && !double.IsNaN(warpTransformResult[i, j].Y) &&
                        x >= 0 && y >= 0)
                    {
                        fillCount[x, y]++;
                        Color c = source.GetPixel(i, j);
                        r[x, y] += c.R;
                        g[x, y] += c.G;
                        b[x, y] += c.B;
                    }
                }

                notifyProgessListenerIfNeeded(progress, startProgressPercent, endProgressPercent, ref completed, ref previousPercent, source.Width);
            }

            startProgressPercent = 80;
            endProgressPercent   = 90;
            completed            = 0;

            for (int i = 0; i < source.Width; i++)
            {
                for (int j = 0; j < source.Height; j++)
                {
                    int fc = fillCount[i, j];
                    if (fc > 0)
                    {
                        result.SetPixel(i, j,
                                        Color.FromArgb(r[i, j] / fc,
                                                       g[i, j] / fc,
                                                       b[i, j] / fc));
                    }
                    else
                    {
                        result.SetPixel(i, j, Color.Transparent);
                    }
                }

                notifyProgessListenerIfNeeded(progress, startProgressPercent, endProgressPercent, ref completed, ref previousPercent, source.Width);
            }

            startProgressPercent = 90;
            endProgressPercent   = 100;
            completed            = 0;

            for (int i = 0; i < source.Width; i++)
            {
                for (int j = 0; j < source.Height; j++)
                {
                    if (fillCount[i, j] == 0)
                    {
                        fillPixel(i, j, result, fillCount, result.Width, result.Height);
                    }
                }

                notifyProgessListenerIfNeeded(progress, startProgressPercent, endProgressPercent, ref completed, ref previousPercent, source.Width);
            }

            return(result);
        }
 public override bool CheckCollision(BoundingRectangle other)
 {
     return(false);
 }
        private static List<ICoordinate> getCrossPoints(ICoordinate vertex1, ICoordinate vertex2, BoundingRectangle viewBox)
        {
            List<ICoordinate> result = new List<ICoordinate>();
            Segment currentSegment = new Segment(vertex1.X,
                                                 vertex1.Y,
                                                 vertex2.X,
                                                 vertex2.Y);

            addCrossPointToList(new Segment(viewBox.MinX, viewBox.MinY, viewBox.MinX, viewBox.MaxY),
              currentSegment, result);

            addCrossPointToList(new Segment(viewBox.MinX, viewBox.MaxY, viewBox.MaxX, viewBox.MaxY),
                          currentSegment, result);

            addCrossPointToList(new Segment(viewBox.MaxX, viewBox.MaxY, viewBox.MaxX, viewBox.MinY),
                          currentSegment, result);

            addCrossPointToList(new Segment(viewBox.MaxX, viewBox.MinY, viewBox.MinX, viewBox.MinY),
                          currentSegment, result);

            return result;
        }
        public void AssertThat_Inflate_ByNegativeValueLargerThanSize_Throws()
        {
            BoundingRectangle s = new BoundingRectangle(Vector2.Zero, new Vector2(10));

            var result = s.Inflate(-50);
        }
Exemple #40
0
 public void TestInitializationFromBadElementsHeight()
 {
     BoundingRectangle boundingRectangle = new BoundingRectangle(2, 2, 3, 1);
 }
        /// <summary>
        /// Performs a rubbersheeting transformation of raster.
        /// </summary>
        /// <param name="source">A System.Drawing.Bitmap instance containing the source image</param>
        /// <param name="sourceControlPoints">Control points of source</param>
        /// <param name="destinationControlPoints">Control points on the map</param>
        /// <param name="rectangle">A bounding rectangle defining a bouns of transformed raster</param>
        /// <param name="progress">Defines a method which is called to notify a subscriber about completion state.</param>
        /// <returns>A System.Drawing.Bitmap instance containing the transformed image</returns>
        public static Bitmap BindRaster(Bitmap source, Point[] sourceControlPoints, ICoordinate[] destinationControlPoints, out BoundingRectangle rectangle, RasterBindingProgress progress)
        {
#if DEMO
            throw new NotImplementedException("This method is not implemented in demo version.");
#else
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            if (sourceControlPoints.Length != destinationControlPoints.Length)
            {
                throw new ArgumentException("Number of control points of raster and map should be the same.");
            }

            if (sourceControlPoints.Length < 3)
            {
                throw new ArgumentException("Number of control points should not be less than 3");
            }

            if (!checkControlPoints(source.Width, source.Height, sourceControlPoints))
            {
                throw new ArgumentException("At least one source control point is outside raster", "sourceControlPoints");
            }

            ICoordinate[,] warpTransformResult = new ICoordinate[source.Width, source.Height];
            PointF[,] affinneTransformResult   = new PointF[source.Width, source.Height];

            // вычисляем результат аффинного преобразования примененного к координатам точек исходного растра
            calculateAffinneTransform(source.Width, source.Height, affinneTransformResult, sourceControlPoints, destinationControlPoints, progress);

            ICoordinate[] shifts = new ICoordinate[destinationControlPoints.Length];
            for (int i = 0; i < shifts.Length; i++)
            {
                PointF p = affinneTransformResult[sourceControlPoints[i].X, sourceControlPoints[i].Y];
                shifts[i] = PlanimetryEnvironment.NewCoordinate(destinationControlPoints[i].X - p.X, destinationControlPoints[i].Y - p.Y);
            }

            // вычисляем новые координаты точек исходного растра, полученные в результате "коробления"
            calculateRubberSheetTransform(source.Width, source.Height, affinneTransformResult, warpTransformResult, destinationControlPoints, shifts, progress);

            // вычисляем ограничивающий прямоугольник преобразованного растра
            rectangle = new BoundingRectangle();
            for (int i = 0; i < source.Width; i++)
            {
                for (int j = 0; j < source.Height; j++)
                {
                    if (!double.IsNaN(warpTransformResult[i, j].X) && !double.IsNaN(warpTransformResult[i, j].Y))
                    {
                        rectangle.Join(warpTransformResult[i, j]);
                    }
                }
            }

            return(calcDestRaster(source, rectangle, warpTransformResult, progress));
#endif
        }
        public void AssertThat_ClosestPointIsClosestPoint_OnBot()
        {
            var b = new BoundingRectangle(new Vector2(0, 10), new Vector2(20, 30));

            Assert.AreEqual(new Vector2(10, 10), b.ClosestPoint(new Vector2(10, 0)));
        }
Exemple #43
0
 /// <summary>
 /// Creates a new coin sprite
 /// </summary>
 /// <param name="position">The position of the sprite in the game</param>
 public PenguinKing(Vector2 position)
 {
     this.position   = position;
     this.headBounds = new BoundingRectangle(new Vector2(position.X, position.Y - 60), 48, 224);
 }
Exemple #44
0
 public GroupRotationCommand([NotNull] List <Element> elementsToRotate)
 {
     _elementsToRotate  = elementsToRotate ?? throw new ArgumentNullException(nameof(elementsToRotate));
     _boundingRectangle = GetBoundingRectangle(_elementsToRotate);
 }
        private static void drawVisiblePolylinePartWithStyleDetection(Graphics g, List<ICoordinate> path, PolylineStyle style, Pen defaultPen, Pen annexPen, bool selected, BoundingRectangle viewBox, double scaleFactor, double lengthFromBegining)
        {
            // Necessary to calculate the displacement pattern of the pen before drawing a polyline, or generated images will not be used for cross-linking.
            // Pattern in the zero offset polyline vertex set equal to zero.
            // Knowing the length of the zero-vertex to the portion of the polyline, you can calculate the shift pattern at the beginning of the portion.

            float relativeDashSize = getRelativeDashSize(defaultPen);
            float dashSize = style.Width * relativeDashSize;
            float dashOffset = (float)((lengthFromBegining * scaleFactor) % dashSize) / style.Width;
            defaultPen.DashOffset = dashOffset;

            if (style.UseAnnexLine)
            {
                relativeDashSize = getRelativeDashSize(annexPen);
                dashSize = style.Width * relativeDashSize;
                dashOffset = (float)((lengthFromBegining * scaleFactor) % dashSize) / style.Width;
                annexPen.DashOffset = dashOffset;
            }

            // main polyline
            drawVisiblePolylinePart(g, path, defaultPen, viewBox, scaleFactor);
            if (style.UseAnnexLine)
            {
                // More polyline
                drawVisiblePolylinePart(g, path, annexPen, viewBox, scaleFactor);
            }
        }
Exemple #46
0
 public ContainmentType Contains(BoundingRectangle rect)
 {
     ContainmentType result;
     Contains(ref rect, out result);
     return result;
 }
        private void drawPolylineSimple(Graphics g, Feature feature, PolylineStyle style, BoundingRectangle viewBox, double scaleFactor)
        {
            foreach (LinePath path in feature.Polyline.Paths)
            {
                if (path.Vertices.Count < 2)
                    continue;

                PointF[] points = new PointF[path.Vertices.Count];

                for (int j = 0; j < path.Vertices.Count; j++)
                {
                    points[j].X = (float)((path.Vertices[j].X - viewBox.MinX) * scaleFactor);
                    points[j].Y = (float)((viewBox.MaxY - path.Vertices[j].Y) * scaleFactor);
                }

                //selection and Stroke
                if (style.UseOutline || feature.Selected)
                    drawLinePathSelectionAndOutline(g, feature.Selected, points, style);

                using (Pen pen = style.GetPen())
                {
                    pen.DashOffset = 0;

                    //main polyline
                    g.DrawLines(pen, points);
                    if (style.UseAnnexLine)
                        using (Pen annexPen = style.GetAnnexPen())
                        {
                            // additional line
                            g.DrawLines(annexPen, points);
                        }
                }
            }
        }
Exemple #48
0
 public bool Intersects(BoundingRectangle rect)
 {
     bool result;
     Intersects(ref rect, out result);
     return result;
 }
        private void drawPrismPolygon(Feature feature, Graphics g, BoundingRectangle viewBox, double scaleFactor)
        {
            using (Pen pen = new Pen(Color.FromArgb(255, Color.White)))
            {
                using (GraphicsPath path = new GraphicsPath(FillMode.Alternate))
                {
                    path.StartFigure();

                    float x = (float)((feature.Polygon.Contours[0].Vertices[0].X - viewBox.MinX) * scaleFactor);
                    float y = (float)((viewBox.MaxY - feature.Polygon.Contours[0].Vertices[0].Y) * scaleFactor);

                    g.RenderingOrigin = new Point((int)Math.Round(x), (int)Math.Round(y));

                    PointF[][] points = new PointF[feature.Polygon.Contours.Count][];
                    int contourIndex = 0;

                    foreach (Contour c in feature.Polygon.Contours)
                    {
                        points[contourIndex] = new PointF[c.Vertices.Count];

                        for (int j = 0; j < c.Vertices.Count; j++)
                        {
                            points[contourIndex][j].X = (float)((c.Vertices[j].X - viewBox.MinX) * scaleFactor);
                            points[contourIndex][j].Y = (float)((viewBox.MaxY - c.Vertices[j].Y) * scaleFactor);
                        }

                        if (points[contourIndex].Length > 2)
                            path.AddPolygon(points[contourIndex]);

                        contourIndex++;
                    }

                    path.CloseFigure();

                    int prismHeight = 4; //(int)(scaleFactor / 10000.0);

                    // boundary of the lower base of the prism
                    g.DrawPath(pen, path);

                    // Fill the lower base of the prism
                    using (Brush b = new SolidBrush(Color.FromArgb(50, 225, 225, 225)))
                    {
                        g.FillPath(b, path);
                    }

                    // border vertical faces
                    foreach (PointF[] contour in points)
                        for (int i = 0; i < contour.Length; i++)
                            g.DrawLine(pen, contour[i], new PointF(contour[i].X, contour[i].Y - prismHeight));

                    //Fill vertical faces
                    using (Brush b = new SolidBrush(Color.FromArgb(50, 60, 60, 60)))
                    {
                        List<Segment> segments = new List<Segment>();
                        List<bool> isForeSegment = new List<bool>();

                        foreach (PointF[] contour in points)
                            for (int i = 0; i < contour.Length; i++)
                            {
                                int j = i < contour.Length - 1 ? i + 1 : 0;
                                if (contour[i].X != contour[i].Y)
                                {
                                    segments.Add(new Segment(contour[i].X, contour[i].Y, contour[j].X, contour[j].Y));
                                    isForeSegment.Add(true);
                                }
                            }

                        for(int i = 0 ; i < segments.Count; i++)
                        {
                            double cX = segments[i].Center().X;
                            double cY = segments[i].Center().Y;

                            for (int j = 0; j < segments.Count; j++)
                            {
                                if (i != j)
                                { 
                                    double v1x = segments[j].V1.X;
                                    double v2x = segments[j].V2.X;
                                    double v1y = segments[j].V1.Y;
                                    double v2y = segments[j].V2.Y;

                                    if(v1x > v2x)
                                    {
                                        double temp = v1x;
                                        v1x = v2x;
                                        v2x = temp;
                                    }

                                    if (v1x < cX && v2x >= cX)
                                    {
                                        double crossY = v1y + (cX - v1x) / (v2x - v1x) * (v2y - v1y);
                                        if(crossY > cY)
                                            isForeSegment[i] = !isForeSegment[i];
                                    }
                                }
                            }
                        }

                        for (int i = 0; i < segments.Count; i++)
                        {
                            if (isForeSegment[i])
                                g.FillPolygon(b, new PointF[] 
                                {
                                    new PointF((float)segments[i].V1.X, (float)segments[i].V1.Y),
                                    new PointF((float)segments[i].V2.X, (float)segments[i].V2.Y),
                                    new PointF((float)segments[i].V2.X, (float)segments[i].V2.Y - prismHeight),
                                    new PointF((float)segments[i].V1.X, (float)segments[i].V1.Y - prismHeight)
                                });
                        }
                    }

                    // Fill the upper base of the prism
                    using (Brush b = new SolidBrush(Color.FromArgb(200, Color.FromArgb(245, 245, 245))))
                    {
                        path.Transform(new Matrix(1, 0, 0, 1, 0, -prismHeight));
                        g.FillPath(b, path);
                    }

                    // boundary of the upper base of the prism
                    g.DrawPath(pen, path);
                }
            }
        }
Exemple #50
0
        internal void MoveWordAndCanvasList(IList <WordAndCanvas> wordAndCanvasList)
        {
            if (wordAndCanvasList == null)
            {
                throw new ArgumentNullException(nameof(wordAndCanvasList));
            }
            if (wordAndCanvasList.Count == 0)
            {
                throw new ArgumentException("Zero words in list", nameof(wordAndCanvasList));
            }

            // If bounding rectangle is updated, need to redraw background grid
            BoundingRectangle r = viewModel.Layout.Bounds;

            if (!r.Equals(gridBounding))
            {
                UpdateBackgroundGrid();
            }

            // Compute distance moved on 1st element to choose animation speed (duration)
            WordPosition wp1      = wordAndCanvasList.First().WordPosition;
            WordCanvas   wc1      = wordAndCanvasList.First().WordCanvas;
            double       deltaX   = (double)wc1.GetValue(Canvas.LeftProperty) - wp1.StartColumn * UnitSize;
            double       deltaY   = (double)wc1.GetValue(Canvas.TopProperty) - wp1.StartRow * UnitSize;
            double       distance = Math.Sqrt(deltaX * deltaX + deltaY * deltaY);

            // If distance is null, for instance after a selection click, we're done
            if (distance <= 0.0001)
            {
                return;
            }

            // Group animations in a storyboard to simplify premature ending
            var sb       = new Storyboard();
            var duration = new Duration(TimeSpan.FromSeconds(distance >= UnitSize ? 0.35 : 0.1));

            finalMoveWordAnimationData = new List <(Canvas, DependencyProperty, double)>();
            foreach (WordAndCanvas wac in wordAndCanvasList)
            {
                WordCanvas wc = wac.WordCanvas;

                double          finalLeftValue = wac.WordPosition.StartColumn * UnitSize;
                DoubleAnimation daLeft         = new DoubleAnimation
                {
                    Duration = duration,
                    From     = (double)wc.GetValue(Canvas.LeftProperty),
                    To       = finalLeftValue
                };
                Storyboard.SetTarget(daLeft, wc);
                Storyboard.SetTargetProperty(daLeft, new PropertyPath("Left"));
                sb.Children.Add(daLeft);
                finalMoveWordAnimationData.Add((wc, Canvas.LeftProperty, finalLeftValue));

                double          finalTopValue = wac.WordPosition.StartRow * UnitSize;
                DoubleAnimation daTop         = new DoubleAnimation
                {
                    Duration = duration,
                    From     = (double)wc.GetValue(Canvas.TopProperty),
                    To       = finalTopValue
                };
                Storyboard.SetTarget(daTop, wc);
                Storyboard.SetTargetProperty(daTop, new PropertyPath("Top"));
                sb.Children.Add(daTop);
                finalMoveWordAnimationData.Add((wc, Canvas.TopProperty, finalTopValue));
            }
            IsMoveWordAnimationInProgress = true;
            sb.Completed += Sb_Completed;
            sb.Begin();
        }
 void IFeatureRenderer.FlushTitles(Graphics g, BoundingRectangle viewBox, double scaleFactor)
 {
     FlushTitles(g, viewBox, scaleFactor);
 }
 /// <summary>
 /// Adds features retrieved from the data source to the receiver.
 /// </summary>
 /// <param name="receiver">An object that receives features</param>
 /// <param name="bounds">Rectangular region you want to fill with the objects</param>
 /// <rereturns>A number of retrieved features</rereturns>
 public override int QueryFeatures(IFeatureReceiver receiver, BoundingRectangle bounds)
 {
     return(InternalQueryFeatures(receiver, getSelectString(bounds)));
 }
        /// <summary>
        /// Drawing the line.
        /// </summary>
        protected virtual void DrawPolyline(Feature feature, Graphics g, PolylineStyle style, TitleStyle titleStyle,
                                            BoundingRectangle viewBox, bool titleVisible, double scaleFactor)
        {
            if (!_isSelectionRendering && feature.Selected)
            {
                PolylineBufferElement element = new PolylineBufferElement(feature, style, titleStyle, titleVisible);
                _selectedPolylines.Add(element);
                return;
            }

            double pixelsize = 1/scaleFactor;

            if (_reduceSubpixelDetails)
            {
                if (feature.BoundingRectangle.Width < pixelsize && feature.BoundingRectangle.Height < pixelsize)
                    return;

                Polyline p1 = (Polyline) feature.Polyline.Clone();
                p1.Weed(pixelsize);
                Feature tempFeature = new Feature(FeatureType.Polyline);
                tempFeature.Title = feature.Title;
                tempFeature.Selected = feature.Selected;
                tempFeature.Polyline = p1;
                feature = tempFeature;

                if (feature.Polyline.Paths.Count == 0)
                    return;
            }

            using (Pen pen = style.GetPen())
            {
                if (Math.Min(viewBox.Width/(feature.BoundingRectangle.Width),
                             viewBox.Height/(feature.BoundingRectangle.Height)) < 2)
                    drawPolylineWithIntersectCalculation(g, feature, style, viewBox, scaleFactor);
                else
                    drawPolylineSimple(g, feature, style, viewBox, scaleFactor);

                // inscription
                if (!string.IsNullOrEmpty(feature.Title) && titleVisible)
                    addTitleBufferElement(g, feature, titleStyle, viewBox, scaleFactor);
            }
        }
        /// <summary>
        /// Adds the features retrieved from cache to the receiver.
        /// </summary>
        /// <param name="processAttributes">A value indicating whether the attributes will be processed or not</param>
        /// <param name="cacheAccessor">Cache accessor instance</param>
        /// <param name="fr">An object that receives the retrieved features</param>
        /// <param name="bounds">Rectangle that defines a query region</param>
        /// <returns>Number of retrieved features</returns>
        public static int FillFromCache(IFeatureCollectionCacheAccessor cacheAccessor, IFeatureReceiver fr, BoundingRectangle bounds, bool processAttributes)
        {
            ISpatialIndex pointsIndex    = cacheAccessor.RestoreFeaturesIndex(MapAround.Mapping.FeatureType.Point);
            ISpatialIndex polylinesIndex = cacheAccessor.RestoreFeaturesIndex(MapAround.Mapping.FeatureType.Polyline);
            ISpatialIndex polygonsIndex  = cacheAccessor.RestoreFeaturesIndex(MapAround.Mapping.FeatureType.Polygon);

            BoundingRectangle b;

            if (!bounds.IsEmpty())
            {
                b = bounds.GetBoundingRectangle();
            }
            else
            {
                b = new BoundingRectangle();
                b.Join(pointsIndex.IndexedSpace);
                b.Join(polylinesIndex.IndexedSpace);
                b.Join(polygonsIndex.IndexedSpace);
            }

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

            pointsIndex.QueryObjectsInRectangle(bounds, points);

            List <Feature> polylines = new List <Feature>();

            polylinesIndex.QueryObjectsInRectangle(bounds, polylines);

            List <Feature> polygons = new List <Feature>();

            polygonsIndex.QueryObjectsInRectangle(bounds, polygons);

            points.ForEach(point => fr.AddFeature((Feature)point.Clone()));
            polylines.ForEach(polyline => fr.AddFeature((Feature)polyline.Clone()));
            polygons.ForEach(polygon => fr.AddFeature((Feature)polygon.Clone()));

            if (processAttributes)
            {
                fr.FeatureAttributeNames.Clear();
                IList <string> attributeNames = cacheAccessor.RestoreAttributeNames();
                foreach (string s in attributeNames)
                {
                    fr.FeatureAttributeNames.Add(s);
                }
            }

            return(points.Count + polylines.Count + polygons.Count);
        }
 public BoundingRectangleEventArgs(BoundingRectangle rectangle)
 {
     Rectangle = rectangle;
 }
 public override bool CheckCollision(BoundingRectangle other)
 {
     throw new NotImplementedException();
 }
Exemple #57
0
 public void Contains(ref BoundingRectangle rect, out ContainmentType result)
 {
     Contains(rect.Corners(), out result);
 }
            internal void QueryObjectsInRectangle <T>(BoundingRectangle box, IList <T> objects)
                where T : IIndexable
            {
                // если прямоугольник ячейки не пересекается
                // с запрашиваемым прямоугольником - считать нечего
                if (!box.Intersects(_fullRectangle))
                {
                    return;
                }

                // если прямоугольник ячейки целиком содержится в
                // запрашиваемом прямоугольнике - добавляем все объекты рекурсивно
                if (box.ContainsRectangle(this._fullRectangle))
                {
                    addAllObjectsRecursively(objects);
                    return;
                }

                // если прямоугольник объектов ячейки целиком содержится в
                // запрашиваемом прямоугольнике - добавляем все объекты этой ячейки
                if (_geometriesRectangle != null && box.ContainsRectangle(_geometriesRectangle))
                {
                    foreach (IIndexable obj in _objects)
                    {
                        objects.Add((T)obj);
                    }
                }
                else
                {
                    // иначе выполняем проверки на пересечение
                    // прямоугольников для каждого объекта
                    foreach (IIndexable obj in _objects)
                    {
                        if (box.Intersects(obj.BoundingRectangle))
                        {
                            objects.Add((T)obj);
                        }
                    }
                }

                // если дочерние узлы отсутствуют,
                // дальше считать нечего
                if (!HasChildren)
                {
                    return;
                }

                // разбираемся с детьми
                if (_leftUpChild != null)
                {
                    _leftUpChild.QueryObjectsInRectangle(box, objects);
                }

                if (_rightUpChild != null)
                {
                    _rightUpChild.QueryObjectsInRectangle(box, objects);
                }

                if (_rightDownChild != null)
                {
                    _rightDownChild.QueryObjectsInRectangle(box, objects);
                }

                if (_leftDownChild != null)
                {
                    _leftDownChild.QueryObjectsInRectangle(box, objects);
                }
            }
Exemple #59
0
 public void Intersects(ref BoundingRectangle rect, out bool result)
 {
     Intersects(this.vertexes, rect.Corners(), out result);
 }
        public void RenderRaster(Graphics g, Bitmap bitmap, RasterStyle style, BoundingRectangle viewBox, BoundingRectangle bitmapBounds, double scaleFactor)
        {
            ICoordinate minPoint = bitmapBounds.Min;
            ICoordinate maxPoint = bitmapBounds.Max;

            if (viewBox.Intersects(bitmapBounds))
            {
                Point minP = new Point((int)((minPoint.X - viewBox.MinX) * scaleFactor),
                                       (int)((viewBox.MaxY - minPoint.Y) * scaleFactor));

                Point maxP = new Point((int)((maxPoint.X - viewBox.MinX) * scaleFactor),
                                       (int)((viewBox.MaxY - maxPoint.Y) * scaleFactor));

                g.InterpolationMode = style.InterpolationMode;

                Rectangle r = new Rectangle(minP.X, maxP.Y, maxP.X - minP.X, minP.Y - maxP.Y);

                using (ImageAttributes imageAttributes = new ImageAttributes())
                {
                    imageAttributes.SetColorMatrix(style.ColorAdjustmentMatrix,
                                                   ColorMatrixFlag.Default,
                                                   ColorAdjustType.Bitmap);

                    g.DrawImage(bitmap, r, 0, 0, bitmap.Width, bitmap.Height,
                                GraphicsUnit.Pixel, imageAttributes);
                }
            }
        }