public WorkingEntry(bool deadlocked, Array2D<bool> map, Coordinate2D coordinate, Coordinate2D[] coordinates)
 {
     Deadlocked = deadlocked;
     Map = map;
     Coordinate = coordinate;
     Coordinates = coordinates;
 }
Beispiel #2
0
        public static IEnumerable<Coordinate2D[]> GetAlternatingAxisSets(Coordinate2D[] set, int size)
        {
            // Initialize the state used to enumerate the snake set.
            AlternatingAxisState state = new AlternatingAxisState();
            state.Set = set;
            state.SetMap = GetSetMap(set);
            state.N = set.Length;
            state.K = size;
            state.Coordinates = new Coordinate2D[size];

            // Enumerate all the coordinate sets that consist of sequences
            // of alternating vertical and horizonal turns.
            foreach (Coordinate2D coord in state.Set)
            {
                state.Coordinates[0] = coord;
                state.Index = 1;

                // Enumerate sets that start with a vertical turn.
                foreach (Coordinate2D[] coords in GetAlternatingAxisSets(state, Axis.Vertical))
                {
                    yield return coords;
                }

                // Enumerate sets that start with a horizontal turn.
                foreach (Coordinate2D[] coords in GetAlternatingAxisSets(state, Axis.Horizontal))
                {
                    yield return coords;
                }
            }
        }
 public Entry(bool deadlocked, Array2D<bool> map, Coordinate2D coordinate, Coordinate2D[] coordinates, Entry[] entries)
 {
     Deadlocked = deadlocked;
     Map = map;
     Coordinate = coordinate;
     Coordinates = coordinates;
     Entries = entries;
 }
    /// <summary>
    /// Create a circular polygon around a mappoint for with a radius in pixels.
    /// </summary>
    /// <param name="mapPoint">Center of the circle as a mappoint.</param>
    /// <param name="pixels">Circle radius in screen pixels.</param>
    /// <returns>A polygon geometry.</returns>
    private Polygon CreateSearchPolygon(MapPoint mapPoint, int pixels)
    {
      //get search radius
      var screenPoint = MapView.Active.MapToScreen(mapPoint);
      var radiusScreenPoint = new System.Windows.Point((screenPoint.X + pixels), screenPoint.Y);
      var radiusMapPoint = MapView.Active.ScreenToMap(radiusScreenPoint);
      var searchRadius = GeometryEngine.Distance(mapPoint, radiusMapPoint);

      //build a search circle geometry
      var cent = new Coordinate2D(mapPoint);
      var searchGeom = EllipticArcBuilder.CreateEllipticArcSegment(cent, searchRadius, esriArcOrientation.esriArcClockwise, MapView.Active.Map.SpatialReference);
      var searchPB = new PolygonBuilder(new[] { searchGeom });
      return searchPB.ToGeometry();
    }
        public ColorMapHelper(WarpedDataSource2D<double> field, Box2 regionBox, double minT, double maxT)
        {
            this.minT = minT;
            this.maxT = maxT;

            warpedField = field;

            if (regionBox != null)
            {
                this.tileBox = new GeoRect(
                    regionBox.MinCoordinate.X, regionBox.MinCoordinate.Y,
                    regionBox.MaxCoordinate.X - regionBox.MinCoordinate.X,
                    regionBox.MaxCoordinate.Y - regionBox.MinCoordinate.Y);
                this.regionBox = regionBox;
            }

            System.Windows.Point[,] grid = warpedField.Grid;

            Coordinate2D minCoordinate = new Coordinate2D(grid[0, 0].X, grid[0, 0].Y);
            Coordinate2D maxCoordinate = new Coordinate2D(grid[warpedField.Width - 1, warpedField.Height - 1].X, grid[warpedField.Width - 1, warpedField.Height - 1].Y);


            for (int j = 0; j < warpedField.Height; j++)
            {
                for (int i = 0; i < warpedField.Width; i++)
                {
                    if (grid[i, j].X < minCoordinate.X)
                        minCoordinate.X = grid[i, j].X;

                    if (grid[i, j].X > maxCoordinate.X)
                        maxCoordinate.X = grid[i, j].X;

                    if (grid[i, j].Y < minCoordinate.Y)
                        minCoordinate.Y = grid[i, j].Y;

                    if (grid[i, j].Y > maxCoordinate.Y)
                        maxCoordinate.Y = grid[i, j].Y;
                }
            }

            gridBox = new GeoRect(
                minCoordinate.X,
                minCoordinate.Y,
                maxCoordinate.X - minCoordinate.X,
                maxCoordinate.Y - minCoordinate.Y);

            palette = new LinearPalette(swm.Colors.Blue, swm.Colors.Green, swm.Colors.Red);
            workingTriangle = new RasterTriangle();
        }
Beispiel #6
0
 public void evaluateTile(int x, int y)
 {
     foreach (LayerController l in layers)
     {
         Coordinate2D   currPos = Coordinate2D.Is(x, y);
         TileController t       = l.tiles[currPos];
         if (!t)
         {
             continue;     // check Controller
         }
         if (!t.isTriggering)
         {
             continue;                  // only active
         }
         if (t.triggerType == TileTriggers.Item)
         {
             ItemScript i = t.GetComponent <ItemScript>();
             if (!i)
             {
                 continue;     // check if Item
             }
             if (playerScript.playerInventory.Count < playerScript.maxInvetorySpace)
             {
                 l.tiles[currPos].isTriggering           = false;
                 l.tiles[currPos].spriteRenderer.enabled = false;
                 playerScript.playerInventory.Add(i);
                 //TODO: Pickup sound
                 //TODO: Pickup info message
             }
         }
         if (t.triggerType == TileTriggers.NextFloorStairs)
         {
             string nextFloor = "ProceduralGeneratedLevel";
             if (t.triggerParameters != null)
             {
                 nextFloor = (string)t.triggerParameters;
             }
             UnityEngine.SceneManagement.SceneManager.LoadScene(nextFloor);
         }
     }
 }
Beispiel #7
0
 public void TestIndexRadius()
 {
     {
         var c  = new Coordinate2D(11.343629, 48.083797);
         var r  = 50;
         var nc = 4;
         AssertIndexRadius(c, r, nc);
     }
     {
         var c  = new Coordinate2D(11.344827, 48.083752);
         var r  = 10;
         var nc = 1;
         AssertIndexRadius(c, r, nc);
     }
     {
         var c  = new Coordinate2D(11.344827, 48.083752);
         var r  = 5;
         var nc = 0;
         AssertIndexRadius(c, r, nc);
     }
 }
Beispiel #8
0
        public void GetPassableNeighbors_ShouldReturnAllNeighbors_WhenAllNeighborsArePassable()
        {
            var graph = GraphFactory.CreateRectangularGraph(3, 3, MovementTypesFixture.GetMovementTypes(),
                                                            MovementTypesFixture.Ground);
            var center2d = new Coordinate2D(1, 1, OffsetTypes.OddRowsRight);
            var center   = center2d.To3D();

            var expectedPassableNeighbors2d = new List <Coordinate2D>
            {
                new Coordinate2D(1, 0, OffsetTypes.OddRowsRight),
                new Coordinate2D(2, 0, OffsetTypes.OddRowsRight),
                new Coordinate2D(2, 1, OffsetTypes.OddRowsRight),
                new Coordinate2D(2, 2, OffsetTypes.OddRowsRight),
                new Coordinate2D(1, 2, OffsetTypes.OddRowsRight),
                new Coordinate2D(0, 1, OffsetTypes.OddRowsRight)
            };
            var expectedPassableNeighbors = Coordinate2D.To3D(expectedPassableNeighbors2d);

            Assert.That(graph.GetPassableNeighbors(center2d), Is.EqualTo(expectedPassableNeighbors2d));
            Assert.That(graph.GetPassableNeighbors(center), Is.EqualTo(expectedPassableNeighbors));
        }
Beispiel #9
0
        public bool Initialise(Dimension screenSize, IntPtr windowHandle)
        {
            ScreenSize    = new Dimension(screenSize.Width, screenSize.Height);
            MousePosition = new Coordinate2D <int>(0, 0);
            DirectInput   = new DirectInput();

            Keyboard = new Keyboard(DirectInput);
            Keyboard.Properties.BufferSize = 256;
            Keyboard.SetCooperativeLevel(windowHandle, CooperativeLevel.Foreground | CooperativeLevel.NonExclusive);

            var result = true;

            try
            {
                Keyboard.Acquire();
            }
            catch (SharpDXException ex)
            {
                Log.WriteToFile(ErrorLevel.Error, "Input.Initialise (Keyboard)", ex, true);

                result = false;
            }

            Mouse = new Mouse(DirectInput);
            Mouse.Properties.AxisMode = DeviceAxisMode.Relative;
            Mouse.SetCooperativeLevel(windowHandle, CooperativeLevel.Foreground | CooperativeLevel.NonExclusive);

            try
            {
                Mouse.Acquire();
            }
            catch (SharpDXException ex)
            {
                Log.WriteToFile(ErrorLevel.Error, "Input.Initialise (Mouse)", ex, true);

                result = false;
            }

            return(result);
        }
        private void AddTableToLayout(Layout layout, Map theMap, MapFrame mfElm, string layerName, SetPage setPage, double yOffset)
        {
            var lyrs = theMap.FindLayers(layerName, true);

            if (lyrs.Count > 0)
            {
                Layer lyr      = lyrs[0];
                var   ptSymbol = GetPointSymbolFromLayer(lyr);
                if (ptSymbol != null)
                {
                    Coordinate2D llSym = new Coordinate2D(setPage.XOffsetMapMarginalia, setPage.YOffsetSymbol + yOffset);
                    var          geom  = MapPointBuilderEx.CreateMapPoint(llSym);
                    var          sym   = ElementFactory.Instance.CreateGraphicElement(layout, geom, ptSymbol);

                    Coordinate2D llText     = new Coordinate2D(setPage.XOffsetMapMarginalia + sym.GetWidth(), setPage.YOffsetSymbol + yOffset - sym.GetHeight() / 2);
                    var          geomLLText = MapPointBuilderEx.CreateMapPoint(llText);
                    var          text       = ElementFactory.Instance.CreateTextGraphicElement(layout, TextType.PointText, geomLLText);
                    text.SetAnchor(Anchor.CenterPoint);
                    text.SetHeight(text.GetHeight());
                    if (text.GetHeight() > sym.GetHeight())
                    {
                        sym.SetLockedAspectRatio(true);
                        sym.SetHeight(text.GetHeight());
                    }
                    else
                    {
                        text.SetLockedAspectRatio(true);
                        text.SetHeight(sym.GetHeight());
                    }
                }
                Coordinate2D llTab1         = new Coordinate2D(setPage.XOffsetMapMarginalia, yOffset - setPage.HeightPartsMarginalia);
                Coordinate2D urTab1         = new Coordinate2D(setPage.XOffsetMapMarginalia + setPage.XWidthMapMarginalia, yOffset);
                var          tableFrameInfo = new TableFrameInfo()
                {
                    MapFrameName = mfElm.Name,
                    MapMemberUri = lyr.URI
                };
                var table1 = ElementFactory.Instance.CreateMapSurroundElement(layout, EnvelopeBuilderEx.CreateEnvelope(llTab1, urTab1), tableFrameInfo) as TableFrame;
            }
        }
Beispiel #11
0
        public static IEnumerable<Coordinate2D[]> GetAdjacentCoordinateSets(Coordinate2D[] set, int size, int minimumAdjacent, bool fourNeighborAdjacent)
        {
            Coordinate2D[] coords = new Coordinate2D[size];
            int n = set.Length;
            foreach (int[] combination in CombinationUtils.GetCombinations(set.Length, size))
            {
                // Copy the coordinates in the combination.
                for (int i = 0; i < size; i++)
                {
                    coords[i] = set[combination[i]];
                }

                // Count the number of adjacent pairs.
                int adjacent = 0;
                if (minimumAdjacent > 0)
                {
                    for (int i = 0; i < size - 1; i++)
                    {
                        Coordinate2D coord1 = coords[i];
                        for (int j = i + 1; j < size; j++)
                        {
                            Coordinate2D coord2 = coords[j];
                            int distance = fourNeighborAdjacent ?
                                Coordinate2D.GetOrthogonalDistance(coord1, coord2) :
                                Coordinate2D.GetDiagonalDistance(coord1, coord2);
                            if (distance == 1)
                            {
                                adjacent++;
                            }
                        }
                    }
                }

                // Verify minimum adjacency.
                if (adjacent >= minimumAdjacent)
                {
                    yield return coords;
                }
            }
        }
Beispiel #12
0
        public static async Task DisplayLegendAsync(Layout layout, string styleCategory, string styleName)
        {
            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                //Build 2D envelope geometry
                Coordinate2D leg_ll = new Coordinate2D(0.5, 0.3);
                Coordinate2D leg_ur = new Coordinate2D(2.14, 2.57);
                Envelope leg_env    = EnvelopeBuilder.CreateEnvelope(leg_ll, leg_ur);

                //Reference MF, create legend and add to layout
                MapFrame mapFrame = layout.FindElement(Constants.MAPS_DEFAULT_MAP_FRAME_NAME) as MapFrame;
                if (mapFrame == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Map frame not found", "WARNING");
                    return;
                }
                Legend legendElm = LayoutElementFactory.Instance.CreateLegend(layout, leg_env, mapFrame);
                legendElm.SetName(Constants.MAPS_LEGEND);
                legendElm.SetAnchor(Anchor.BottomLeftCorner);

                // Turn off all of the layers to start
                CIMLegend cimLeg = legendElm.GetDefinition() as CIMLegend;
                foreach (CIMLegendItem legItem in cimLeg.Items)
                {
                    legItem.ShowHeading = false;
                    legItem.IsVisible   = false;
                }

                // Format other elements in the legend
                cimLeg.GraphicFrame.BorderSymbol = new CIMSymbolReference
                {
                    Symbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlackRGB, 1.5, SimpleLineStyle.Solid)
                };
                cimLeg.GraphicFrame.BorderGapX = 3;
                cimLeg.GraphicFrame.BorderGapY = 3;
                // Apply the changes
                legendElm.SetDefinition(cimLeg);
            });
        }
        /// <summary>
        ///     Loops through a given matrix and fills its cells with Rotating Walk values until all neighbouring cells have been
        ///     visited.
        /// </summary>
        /// <param name="matrix">The matrix to fill.</param>
        /// <param name="currentPos">The current position in the matrix.</param>
        /// <param name="stepCount">The current cell value counter.</param>
        private static void FillMatrix(int[,] matrix, Coordinate2D currentPos, ref int stepCount)
        {
            Debug.Assert(matrix != null, "Null matrix passed!");
            Debug.Assert(currentPos != null, "Null coordinates passed!");

            var directionOfMovement = new Coordinate2D(1, 1);

            matrix[currentPos.Row, currentPos.Col] = ++stepCount;

            while (CanMoveInAnyDirection(matrix, currentPos))
            {
                while (!IsInsideMatrix(currentPos + directionOfMovement, matrix.GetLength(0)) ||
                       HasBeenVisited(currentPos + directionOfMovement, matrix))
                {
                    directionOfMovement = GetNextDirectionOfMovementClockwise(directionOfMovement);
                }

                currentPos.Row += directionOfMovement.Row;
                currentPos.Col += directionOfMovement.Col;
                matrix[currentPos.Row, currentPos.Col] = ++stepCount;
            }
        }
        private void AddTableToLayout(Layout layout, Map theMap, MapFrame mfElm, string layerName, SetPage setPage, double yOffset)
        {
            var lyrs = theMap.FindLayers(layerName, true);

            if (lyrs.Count > 0)
            {
                Layer lyr = lyrs[0];

                Coordinate2D llTab1         = new Coordinate2D(setPage.XOffsetMapMarginalia, yOffset - 2 * setPage.HeightPartsMarginalia);
                Coordinate2D urTab1         = new Coordinate2D(setPage.XOffsetMapMarginalia + setPage.XWidthMapMarginalia, yOffset);
                var          tableFrameInfo = new TableFrameInfo()
                {
                    MapFrameName = mfElm.Name,
                    MapMemberUri = lyr.URI
                };
                var theTable = ElementFactory.Instance.CreateMapSurroundElement(layout, EnvelopeBuilderEx.CreateEnvelope(llTab1, urTab1), tableFrameInfo) as TableFrame;
                var def      = theTable.GetDefinition() as CIMTableFrame;
                def.FittingStrategy = TableFrameFittingStrategy.AdjustColumnsAndSize;
                def.FillingStrategy = TableFrameFillingStrategy.ShowAllRows;
                theTable.SetDefinition(def);
            }
        }
        public IReadOnlyList <(TItem, double)> Radius(Coordinate2D c, double radius)
        {
            var neighbors = new List <(TItem, double)>();
            var env       = this.Spatial.Envelope(c, radius);

            var visitor = new IndexItemVisitor <TItem>(item =>
            {
                var geometry = this.ItemGeometryGetter(item);
                var f        = this.Spatial.Intercept(geometry, c);
                var p        = this.Spatial.Interpolate(geometry, this.ItemLengthGetter(item), f);
                var d        = this.Spatial.Distance(p, c);

                if (d < radius)
                {
                    neighbors.Add((item, f));
                }
            });

            Index.Query(env, visitor);

            return(neighbors);
        }
Beispiel #16
0
            private static double AngleDegrees(Coordinate2D a, Coordinate2D center, Coordinate2D b)
            {
                double centerX = center.X;
                double centerY = center.Y;

                double acX = a.X - centerX;
                double acY = a.Y - centerY;
                double bcX = b.X - centerX;
                double bcY = b.Y - centerY;

                double radians = Math.Atan2(acX * bcY - bcX * acY, acX * bcX + acY * bcY) %
                                 (2 * Math.PI);

                double degrees = radians * 180 / Math.PI;

                if (degrees < 0)
                {
                    degrees += 360;
                }

                return(degrees);
            }
Beispiel #17
0
        public void GetRange_ShouldGetCorrectRange()
        {
            var graph = GraphFactory.CreateRectangularGraph(6, 7, MovementTypesFixture.GetMovementTypes(),
                                                            MovementTypesFixture.Ground);
            var center2d = new Coordinate2D(3, 2, OffsetTypes.OddRowsRight);
            var center   = center2d.To3D();

            var expectedRange2D = new List <Coordinate2D>
            {
                // Closest circle
                new Coordinate2D(4, 2, OffsetTypes.OddRowsRight),
                new Coordinate2D(3, 1, OffsetTypes.OddRowsRight),
                new Coordinate2D(2, 1, OffsetTypes.OddRowsRight),
                new Coordinate2D(2, 2, OffsetTypes.OddRowsRight),
                new Coordinate2D(2, 3, OffsetTypes.OddRowsRight),
                new Coordinate2D(3, 3, OffsetTypes.OddRowsRight),
                // Second circle
                new Coordinate2D(5, 2, OffsetTypes.OddRowsRight),
                new Coordinate2D(4, 1, OffsetTypes.OddRowsRight),
                new Coordinate2D(4, 3, OffsetTypes.OddRowsRight),
                new Coordinate2D(4, 0, OffsetTypes.OddRowsRight),
                new Coordinate2D(3, 0, OffsetTypes.OddRowsRight),
                new Coordinate2D(2, 0, OffsetTypes.OddRowsRight),
                new Coordinate2D(1, 1, OffsetTypes.OddRowsRight),
                new Coordinate2D(1, 2, OffsetTypes.OddRowsRight),
                new Coordinate2D(1, 3, OffsetTypes.OddRowsRight),
                new Coordinate2D(2, 4, OffsetTypes.OddRowsRight),
                new Coordinate2D(3, 4, OffsetTypes.OddRowsRight),
                new Coordinate2D(4, 4, OffsetTypes.OddRowsRight)
            };
            var expectedMovementRange =
                Coordinate2D.To3D(expectedRange2D);

            var range = graph.GetRange(center, 2);

            Assert.That(range, Is.EquivalentTo(expectedMovementRange));

            Assert.That(graph.GetRange(center2d, 2), Is.EquivalentTo(expectedRange2D));
        }
Beispiel #18
0
        private Coordinate2D <float> FindRayIntersectionPoint()
        {
            var inverseViewMatrix = Matrix.Invert(_camera.ViewMatrix);
            var direction         = new Vector3()
            {
                X = inverseViewMatrix.M31,
                Y = inverseViewMatrix.M32,
                Z = inverseViewMatrix.M33
            };

            _quadTree.GetHeightAtPosition(_camera.Position.X, _camera.Position.Z, out float playerHeight);
            playerHeight += 2.0f;

            var origin = new Vector3(_camera.Position.X, playerHeight, _camera.Position.Z);

            var unitDirection = Vector3.Normalize(direction) / 5;

            var testDistance      = 0.1f;
            var intersectionFound = false;

            Coordinate2D <float> intersection = null;

            while (!intersectionFound && testDistance < 40.0f)
            {
                var currentLocation = origin + (unitDirection * testDistance);

                var heightFound = _quadTree.GetHeightAtPosition(currentLocation.X, currentLocation.Z, out float height);

                if (heightFound && height > currentLocation.Y)
                {
                    intersection      = new Coordinate2D <float>(currentLocation.X, currentLocation.Z);
                    intersectionFound = true;
                }

                testDistance += 0.1f;
            }

            return(intersection);
        }
Beispiel #19
0
        public Day01() : base(01, 2016, "")
        {
            Coordinate2D facing   = (0, 1);
            Coordinate2D location = (0, 0);

            HashSet <(int, int)> visited = new HashSet <(int, int)>();

            foreach (string instruction in Input.Split(", "))
            {
                if (instruction[0] == 'R')
                {
                    facing = facing.RotateCW();
                }
                else
                {
                    facing = facing.RotateCCW();
                }

                int          distance = int.Parse(instruction.Substring(1));
                Coordinate2D offset   = distance * facing;

                for (int i = 0; i < distance; i++)
                {
                    Coordinate2D visitedLocation = location + (i * facing);

                    if (visited.Contains(visitedLocation) && partTwo == null)
                    {
                        partTwo = (Math.Abs(visitedLocation.x) + Math.Abs(visitedLocation.y)).ToString();
                    }

                    visited.Add(visitedLocation);
                }

                location += offset;
            }

            partOne = (Math.Abs(location.x) + Math.Abs(location.y)).ToString();
        }
Beispiel #20
0
        public void CreateLineGraphic()
        {
            var graphicsLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <ArcGIS.Desktop.Mapping.GraphicsLayer>().FirstOrDefault();

            if (graphicsLayer == null)
            {
                return;
            }
            QueuedTask.Run(() =>
            {
                #region Line Graphic Element using CIMGraphic
                //On the QueuedTask
                //Place a line symbol using the extent's lower left and upper right corner.
                var extent = MapView.Active.Extent;
                //get the lower left corner of the extent
                var pointFromCoordinates = new Coordinate2D(extent.XMin, extent.YMin);
                //get the upper right corner of the extent
                var pointToCoordinates     = new Coordinate2D(extent.XMax, extent.YMax);
                List <Coordinate2D> points = new List <Coordinate2D> {
                    pointFromCoordinates, pointToCoordinates
                };
                //create the polyline
                var lineSegment = PolylineBuilder.CreatePolyline(points);

                //specify a symbol
                var line_symbol = SymbolFactory.Instance.ConstructLineSymbol(
                    ColorFactory.Instance.GreenRGB);

                //create a CIMGraphic
                var graphic = new CIMLineGraphic()
                {
                    Symbol = line_symbol.MakeSymbolReference(),
                    Line   = lineSegment,
                };
                graphicsLayer.AddElement(graphic);
                #endregion
            });
        }
Beispiel #21
0
        /// <summary>
        /// 1- Convert each Coordinate of PostGisLineString int NetTopology Coordinate.
        /// 2- Create NetTopologyLineString with all Coordinates from previous step.
        /// Throw ArgumentNullException if any of input marameter is null.
        /// </summary>
        /// <param name="geometry">a PostgisLineString. No restriction.</param>
        /// <returns>a NetTopology LineString</returns>
        private static Geometry ProcessLineString(PostgisLineString geometry)
        {
            if (geometry != null)
            {
                //1-
                int          pointCount = geometry.PointCount;
                Coordinate[] coords     = new Coordinate[pointCount];

                for (int i = 0; i < pointCount; i++)
                {
                    Coordinate2D coord2D = geometry[i];
                    coords[i]   = new Coordinate();
                    coords[i].X = coord2D.X;
                    coords[i].Y = coord2D.Y;
                }
                //2-
                return(new LineString(coords));
            }
            else
            {
                throw new ArgumentNullException();
            }
        }
Beispiel #22
0
        private static Coordinate2D[] parseGMLRing(XElement ringElement)
        {
            var poslist = ringElement.Elements(GMLposList).SingleOrDefault()
                          ?? ringElement.Elements(GML32posList).Single();
            var ndims   = int.Parse(poslist.Attribute("srsDimension").Value);
            var numbers = poslist.Value.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (ndims == 2)
            {
                var r = new Coordinate2D[numbers.Length / 2];
                for (int i = 0; i < r.Length; i++)
                {
                    r[i] = new Coordinate2D(double.Parse(numbers[i * 2]), double.Parse(numbers[i * 2 + 1]));
                }
                return(r);
            }
            else if (ndims == 3)
            {
                var r = new Coordinate2D[numbers.Length / 3];
                for (int i = 0; i < r.Length; i++)
                {
                    var x = double.Parse(numbers[i * 3]);
                    var y = double.Parse(numbers[i * 3 + 1]);
                    var z = double.Parse(numbers[i * 3 + 2]);
                    if (z != 0)
                    {
                        throw new NotImplementedException("taartz");
                    }
                    r[i] = new Coordinate2D(x, y);
                }
                return(r);
            }
            else
            {
                throw new NotImplementedException("taart");
            }
        }
 private PostgisPolygon CreatePostGisPolygon(int id)
 {
     Coordinate2D[][] pgCoords = new Coordinate2D[2][];
     if (id == 1)
     {
         pgCoords[0] = new Coordinate2D[] {
             new Coordinate2D(0, 0),
             new Coordinate2D(10, 0),
             new Coordinate2D(10, 10),
             new Coordinate2D(0, 10),
             new Coordinate2D(0, 0)
         };
         pgCoords[1] = new Coordinate2D[] {
             new Coordinate2D(1, 1),
             new Coordinate2D(2, 1),
             new Coordinate2D(2, 2),
             new Coordinate2D(1, 1)
         };
     }
     else
     {
         pgCoords[0] = new Coordinate2D[] {
             new Coordinate2D(10, 10),
             new Coordinate2D(100, 10),
             new Coordinate2D(100, 100),
             new Coordinate2D(10, 100),
             new Coordinate2D(10, 10)
         };
         pgCoords[1] = new Coordinate2D[] {
             new Coordinate2D(50, 50),
             new Coordinate2D(51, 50),
             new Coordinate2D(51, 52),
             new Coordinate2D(50, 50)
         };
     }
     return(new PostgisPolygon(pgCoords));
 }
Beispiel #24
0
        /// <summary>
        /// Called when the sketch finishes. This is where we will create the sketch operation and then execute it.
        /// </summary>
        /// <param name="geometry">The geometry created by the sketch.</param>
        /// <returns>A Task returning a Boolean indicating if the sketch complete event was successfully handled.</returns>
        protected override Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            if (CurrentTemplate == null || geometry == null)
            {
                return(Task.FromResult(false));
            }

            return(QueuedTask.Run(() =>
            {
                //build a circular arc
                var cent = new Coordinate2D(geometry as MapPoint);
                var circleEAB = EllipticArcBuilder.CreateEllipticArcSegment(cent, Radius, esriArcOrientation.esriArcClockwise, MapView.Active.Map.SpatialReference);

                // find the source layer and determine whether polyline/polygon.  Create the appropriate shape
                var lyr = CurrentTemplate.Layer as BasicFeatureLayer;
                Geometry circleGeom = null;
                if (lyr.ShapeType == esriGeometryType.esriGeometryPolygon)
                {
                    circleGeom = PolygonBuilder.CreatePolygon(new[] { circleEAB });
                }
                else
                {
                    circleGeom = PolylineBuilder.CreatePolyline(circleEAB);
                }

                // Create an edit operation
                var createOperation = new EditOperation();
                createOperation.Name = string.Format("Create circular {0}", CurrentTemplate.Layer.Name);
                createOperation.SelectNewFeatures = true;

                // Queue feature creation
                createOperation.Create(CurrentTemplate, circleGeom);

                // Execute the operation
                return createOperation.ExecuteAsync();
            }));
        }
        public void TestPostGisLineStringReturnLineStringWithCoordinatesAndSRS()
        {
            StubFieldValueGetter valueGetter = new StubFieldValueGetter();

            valueGetter.OrdinalToStub = 0;
            valueGetter.FieldCount    = 1;
            Coordinate2D[] coords = new Coordinate2D[] { new Coordinate2D(_X1, _Y1), new Coordinate2D(_X2, _Y2), new Coordinate2D(_X3, _Y3) };
            valueGetter.GeometryToStub      = new PostgisLineString(coords);
            valueGetter.GeometryToStub.SRID = _SRID;
            Geometry geomResult = HRConverterPostGisToNetTopologySuite.ConvertFrom(valueGetter);

            Assert.NotNull(geomResult);
            Assert.IsType <LineString>(geomResult);
            LineString lineStringResult = (LineString)geomResult;

            Assert.Equal(3, lineStringResult.Coordinates.Length);
            Assert.Equal(_X1, lineStringResult.Coordinates[0].X);
            Assert.Equal(_Y1, lineStringResult.Coordinates[0].Y);
            Assert.Equal(_X2, lineStringResult.Coordinates[1].X);
            Assert.Equal(_Y2, lineStringResult.Coordinates[1].Y);
            Assert.Equal(_X3, lineStringResult.Coordinates[2].X);
            Assert.Equal(_Y3, lineStringResult.Coordinates[2].Y);
            Assert.Equal(_SRID, lineStringResult.SRID);
        }
Beispiel #26
0
 public static async Task SetDefaultMapFrameDimensionAsync(string mapFrameName, Layout oLayout, Map oMap, double xMin,
                                                           double yMin, double xMax, double yMax)
 {
     await QueuedTask.Run(() =>
     {
         //Finding the mapFrame with mapFrameName
         if (!(oLayout.FindElement(mapFrameName) is MapFrame mfElm))
         {
             //Build 2D envelope geometry
             Coordinate2D mf_ll = new Coordinate2D(xMin, yMin);
             Coordinate2D mf_ur = new Coordinate2D(xMax, yMax);
             Envelope mf_env    = EnvelopeBuilder.CreateEnvelope(mf_ll, mf_ur);
             mfElm = LayoutElementFactory.Instance.CreateMapFrame(oLayout, mf_env, oMap);
             mfElm.SetName(mapFrameName);
         }
         // Remove border from map frame
         var mapFrameDefn = mfElm.GetDefinition() as CIMMapFrame;
         mapFrameDefn.GraphicFrame.BorderSymbol = new CIMSymbolReference
         {
             Symbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlackRGB, 0, SimpleLineStyle.Null)
         };
         mfElm.SetDefinition(mapFrameDefn);
     });
 }
Beispiel #27
0
        private static void CreateSemiEvaluatePoint(int i, double angle, double semi, Coordinate2D point, FeatureClass fc_evaluatePoints)
        {
            double       yStep         = Math.Sin(angle) * semi;
            double       xStep         = Math.Cos(angle) * semi;
            double       risk          = CalCollisionRisk(i);
            Coordinate2D evaluatePoint = new Coordinate2D()
            {
                X = point.X + xStep,
                Y = point.Y + yStep
            };
            MapPoint p = MapPointBuilder.CreateMapPoint(evaluatePoint, SpatialReferenceBuilder.CreateSpatialReference(3857));

            using (RowBuffer rowBuffer = fc_evaluatePoints.CreateRowBuffer())
            {
                // Either the field index or the field name can be used in the indexer.
                rowBuffer[ConstDefintion.ConstFieldName_r_estimate] = risk;
                rowBuffer[ConstDefintion.ConstFieldName_factor]     = 0.05 * i;
                rowBuffer[ConstDefintion.ConstFieldName_Shape]      = p;
                using (Feature feature = fc_evaluatePoints.CreateRow(rowBuffer))
                {
                    feature.Store();
                }
            }
        }
 public void TestTwoPointsAzimuth()
 {
     { //Quadrant 1
         var point1 = new Coordinate2D(1.0, 1.0);
         var point2 = new Coordinate2D(100.0, 100.0);
         Assert.Equal(45.0, Spatial.Azimuth(point1, point2, 0D), 1);
         Assert.Equal(45.0, Spatial.Azimuth(point1, point2, 0.5), 1);
         Assert.Equal(45.0, Spatial.Azimuth(point1, point2, 1.0), 1);
     }
     { //Quadrant 2
         var point1 = new Coordinate2D(1.0, -1.0);
         var point2 = new Coordinate2D(100.0, -100.0);
         Assert.Equal(135.0, Spatial.Azimuth(point1, point2, 0D), 1);
         Assert.Equal(135.0, Spatial.Azimuth(point1, point2, 0.5), 1);
         Assert.Equal(135.0, Spatial.Azimuth(point1, point2, 1.0), 1);
     } //Quardant 3
     {
         var point1 = new Coordinate2D(1.0, 1.0);
         var point2 = new Coordinate2D(-100.0, -100.0);
         Assert.Equal(225.0, Spatial.Azimuth(point1, point2, 0D), 1);
         Assert.Equal(225.0, Spatial.Azimuth(point1, point2, 0.5), 1);
         Assert.Equal(225.0, Spatial.Azimuth(point1, point2, 1.0), 1);
     }
 }
Beispiel #29
0
 private static Array2D<bool> GetSetMap(IEnumerable<Coordinate2D> set)
 {
     Coordinate2D maxCoord = new Coordinate2D(0, 0);
     foreach (Coordinate2D coord in set)
     {
         maxCoord.Row = Math.Max(maxCoord.Row, coord.Row);
         maxCoord.Column = Math.Max(maxCoord.Column, coord.Column);
     }
     Array2D<bool> setMap = new Array2D<bool>(maxCoord.Row + 2, maxCoord.Column + 2);
     foreach (Coordinate2D coord in set)
     {
         setMap[coord] = true;
     }
     return setMap;
 }
Beispiel #30
0
 public static Coordinate2D[] SortCoordinates(params Coordinate2D[] coords)
 {
     Coordinate2D[] sortedCoords = new Coordinate2D[coords.Length];
     coords.CopyTo(sortedCoords, 0);
     Array.Sort<Coordinate2D>(sortedCoords);
     return sortedCoords;
 }
Beispiel #31
0
 private static Direction GetDirectionBetween(Coordinate2D coord1, Coordinate2D coord2)
 {
     if (coord1.Row == coord2.Row)
     {
         return coord1.Column < coord2.Column ? Direction.Right : Direction.Left;
     }
     if (coord1.Column == coord2.Column)
     {
         return coord1.Row < coord2.Row ? Direction.Down : Direction.Up;
     }
     return Direction.None;
 }
Beispiel #32
0
 public void AddSokoban(Coordinate2D newSokobanCoord)
 {
     AddSokoban(newSokobanCoord.Row, newSokobanCoord.Column);
 }
Beispiel #33
0
 public static IEnumerable<Coordinate2D[]> GetCoordinateSets(Coordinate2D[] set, int size)
 {
     Coordinate2D[] coords = new Coordinate2D[size];
     int n = set.Length;
     foreach (int[] combination in CombinationUtils.GetCombinations(set.Length, size))
     {
         // Copy the coordinates in the combination.
         for (int i = 0; i < size; i++)
         {
             coords[i] = set[combination[i]];
         }
         yield return coords;
     }
 }
Beispiel #34
0
 private void pictureGrid_MouseUp(object sender, MouseEventArgs e)
 {
     mouseUpCoord = GetMouseCell(e);
     if (inMouseDrag)
     {
         if (mouseDownCoord != mouseUpCoord)
         {
             HandleMouseDrag();
         }
         inMouseDrag = false;
     }
 }
Beispiel #35
0
 public SEGH()
 {
     coor = new Coordinate2D<double>();
     cocc = new COCC();
     c2il = new List<C2IL>();
     c3il = new List<C3IL>();
     c2fl = new List<C2FL>();
     c3fl = new List<C3FL>();
 }
        async public void MoveMF(string elmName)
        {
            Globals.i_correct = Globals.i_correct + 1;

            LayoutView layoutView = LayoutView.Active;
            Layout     layout     = layoutView.Layout;

            if (elmName == "Rectangle 1")
            {
                MapFrame mf1 = layout.FindElement("MF1") as MapFrame;
                await QueuedTask.Run(() => mf1.SetX(4));

                await QueuedTask.Run(() => mf1.SetY(0.5));
            }
            if (elmName == "Rectangle 2")
            {
                MapFrame mf2 = layout.FindElement("MF2") as MapFrame;
                await QueuedTask.Run(() => mf2.SetX(7));

                await QueuedTask.Run(() => mf2.SetY(0.5));
            }
            if (elmName == "Rectangle 3")
            {
                MapFrame mf3 = layout.FindElement("MF3") as MapFrame;
                await QueuedTask.Run(() => mf3.SetX(10));

                await QueuedTask.Run(() => mf3.SetY(0.5));
            }
            if (elmName == "Rectangle 4")
            {
                MapFrame mf4 = layout.FindElement("MF4") as MapFrame;
                await QueuedTask.Run(() => mf4.SetX(10));

                await QueuedTask.Run(() => mf4.SetY(3.5));
            }
            if (elmName == "Rectangle 5")
            {
                MapFrame mf5 = layout.FindElement("MF5") as MapFrame;
                await QueuedTask.Run(() => mf5.SetX(7));

                await QueuedTask.Run(() => mf5.SetY(3.5));
            }
            if (elmName == "Rectangle 6")
            {
                MapFrame mf6 = layout.FindElement("MF6") as MapFrame;
                await QueuedTask.Run(() => mf6.SetX(4));

                await QueuedTask.Run(() => mf6.SetY(3.5));
            }

            TextElement    statusText = layout.FindElement("Status") as TextElement;
            TextProperties statusProp = statusText.TextProperties;

            if (Globals.i_correct == 1)
            {
                statusProp.Text = "Nice job!  You got " + Globals.i_correct.ToString() + " correct out of " + Globals.i_guesses + " attempt.";
            }
            else
            {
                statusProp.Text = "Nice job!  You got " + Globals.i_correct.ToString() + " correct out of " + Globals.i_guesses + " attempts.";
            }
            await QueuedTask.Run(() => statusText.SetTextProperties(statusProp));

            if (Globals.i_correct == 6) //YOU WIN
            {
                statusProp.Text = "GAME OVER!  You got " + Globals.i_correct.ToString() + " correct out of " + Globals.i_guesses + " attempts.";
                await QueuedTask.Run(() => statusText.SetTextProperties(statusProp));

                //Turn off rectangles
                GraphicElement rec1 = layout.FindElement("Rectangle 1") as GraphicElement;
                await QueuedTask.Run(() => rec1.SetVisible(false));

                GraphicElement rec2 = layout.FindElement("Rectangle 2") as GraphicElement;
                await QueuedTask.Run(() => rec2.SetVisible(false));

                GraphicElement rec3 = layout.FindElement("Rectangle 3") as GraphicElement;
                await QueuedTask.Run(() => rec3.SetVisible(false));

                GraphicElement rec4 = layout.FindElement("Rectangle 4") as GraphicElement;
                await QueuedTask.Run(() => rec4.SetVisible(false));

                GraphicElement rec5 = layout.FindElement("Rectangle 5") as GraphicElement;
                await QueuedTask.Run(() => rec5.SetVisible(false));

                GraphicElement rec6 = layout.FindElement("Rectangle 6") as GraphicElement;
                await QueuedTask.Run(() => rec6.SetVisible(false));

                //Toggle MFs
                MapFrame mf1 = layout.FindElement("MF1") as MapFrame;
                await QueuedTask.Run(() => mf1.SetVisible(false));

                MapFrame mf2 = layout.FindElement("MF2") as MapFrame;
                await QueuedTask.Run(() => mf2.SetVisible(false));

                MapFrame mf3 = layout.FindElement("MF3") as MapFrame;
                await QueuedTask.Run(() => mf3.SetVisible(false));

                MapFrame mf4 = layout.FindElement("MF4") as MapFrame;
                await QueuedTask.Run(() => mf4.SetVisible(false));

                MapFrame mf5 = layout.FindElement("MF5") as MapFrame;
                await QueuedTask.Run(() => mf5.SetVisible(false));

                MapFrame mf6 = layout.FindElement("MF6") as MapFrame;
                await QueuedTask.Run(() => mf6.SetVisible(false));

                MapFrame mainMF = layout.FindElement("Main MF") as MapFrame;
                await QueuedTask.Run(() => mainMF.SetVisible(true));

                //Update title
                TextElement    titleText = layout.FindElement("Title") as TextElement;
                TextProperties titleProp = titleText.TextProperties;
                titleProp.Text = "Not any more!";
                await QueuedTask.Run(() => titleText.SetTextProperties(titleProp));

                //New Game
                TextElement    instrText = layout.FindElement("Instructions") as TextElement;
                TextProperties instrProp = instrText.TextProperties;
                instrProp.Text = "<bol>Instructions: </bol> " +
                                 "\n\n\n\n\n\n\n\n\n - Click the 'New Game' command if you want to play again.";
                await QueuedTask.Run(() => instrText.SetTextProperties(instrProp));

                //Zoomto finished puzzle area
                Coordinate2D ll = new Coordinate2D(3, 0);
                Coordinate2D ur = new Coordinate2D(14, 7.5);

                await QueuedTask.Run(() =>
                {
                    Envelope env = EnvelopeBuilderEx.CreateEnvelope(ll, ur);
                    layoutView.ZoomTo(env);
                });


                //Turn off selection changed events
                Globals.selEvents = false;
            }
        }
        private bool CanPullDoor(Coordinate2D boxCoord, Direction direction)
        {
            Coordinate2D evacuatedCoord = boxCoord - direction;
            Coordinate2D sokobanCoord = boxCoord + direction;

            // If the evacuated square contacts the interior on
            // one of its sides and the sokoban square also
            // contacts another interior square on one of its
            // sides then a path has been opened up to the outside.
            Direction perpendicular = Direction.Rotate(direction);
            if (pathFinder.IsAccessible(evacuatedCoord - perpendicular) ||
                pathFinder.IsAccessible(evacuatedCoord + perpendicular))
            {
                if (pathFinder.IsAccessible(sokobanCoord - perpendicular) ||
                    pathFinder.IsAccessible(sokobanCoord + perpendicular))
                {
                    return true;
                }
            }

            // Otherwise keep trying to pull the box further in
            // while avoiding the direction we just came from.
            Direction oppositeDirection = Direction.GetOpposite(direction);
            foreach (Direction otherDirection in Direction.Directions)
            {
                if (otherDirection == oppositeDirection)
                {
                    continue;
                }

                if (pathFinder.IsAccessible(boxCoord + otherDirection) &&
                    pathFinder.IsAccessible(boxCoord + 2 * otherDirection))
                {
                    if (CanPullDoor(boxCoord + otherDirection, otherDirection))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
Beispiel #38
0
 public ProPluginTreasuremapCursor(IEnumerator <TreasuremapRouteItem> enumerator, Coordinate2D startingPoint)
 {
     _lastEndPoint = _startingPoint = startingPoint;
     _enumerator   = enumerator;
 }
Beispiel #39
0
        public override bool Read([CanBeNull] out PostgisGeometry result)
        {
            Contract.Assert(_inByteaMode != true);
            if (!_inByteaMode.HasValue)
            {
                _inByteaMode = false;
            }

            result = default(PostgisGeometry);
            if (_id == 0)
            {
                if (_readBuf.ReadBytesLeft < 5)
                {
                    return(false);
                }
                _bo = (ByteOrder)_readBuf.ReadByte();
                _id = _readBuf.ReadUInt32(_bo);
            }
            if (!_srid.HasValue)
            {
                if ((_id & (uint)EwkbModifier.HasSRID) != 0)
                {
                    if (_readBuf.ReadBytesLeft < 4)
                    {
                        return(false);
                    }
                    _srid = _readBuf.ReadUInt32(_bo);
                }
                else
                {
                    _srid = 0;
                }
            }

            switch ((WkbIdentifier)(_id & 7))
            {
            case WkbIdentifier.Point:
                _lastId = _id;
                if (_readBuf.ReadBytesLeft < 16)
                {
                    return(false);
                }
                result = new PostgisPoint(_readBuf.ReadDouble(_bo), _readBuf.ReadDouble(_bo))
                {
                    SRID = _srid.Value
                };
                return(true);

            case WkbIdentifier.LineString:
                _lastId = _id;
                if (_ipts == -1)
                {
                    if (_readBuf.ReadBytesLeft < 4)
                    {
                        return(false);
                    }
                    _points = new Coordinate2D[_readBuf.ReadInt32(_bo)];
                    _ipts   = 0;
                }
                for (; _ipts < _points.Length; _ipts++)
                {
                    if (_readBuf.ReadBytesLeft < 16)
                    {
                        return(false);
                    }
                    _points[_ipts] = new Coordinate2D(_readBuf.ReadDouble(_bo), _readBuf.ReadDouble(_bo));
                }
                result = new PostgisLineString(_points)
                {
                    SRID = _srid.Value
                };
                return(true);

            case WkbIdentifier.Polygon:
                _lastId = _id;
                if (_irng == -1)
                {
                    if (_readBuf.ReadBytesLeft < 4)
                    {
                        return(false);
                    }
                    _rings = new Coordinate2D[_readBuf.ReadInt32(_bo)][];
                    _irng  = 0;
                }

                for (; _irng < _rings.Length; _irng++)
                {
                    if (_ipts == -1)
                    {
                        if (_readBuf.ReadBytesLeft < 4)
                        {
                            return(false);
                        }
                        _rings[_irng] = new Coordinate2D[_readBuf.ReadInt32(_bo)];
                        _ipts         = 0;
                    }
                    for (; _ipts < _rings[_irng].Length; _ipts++)
                    {
                        if (_readBuf.ReadBytesLeft < 16)
                        {
                            return(false);
                        }
                        _rings[_irng][_ipts] = new Coordinate2D(_readBuf.ReadDouble(_bo), _readBuf.ReadDouble(_bo));
                    }
                    _ipts = -1;
                }
                result = new PostgisPolygon(_rings)
                {
                    SRID = _srid.Value
                };
                return(true);

            case WkbIdentifier.MultiPoint:
                _lastId = _id;
                if (_ipts == -1)
                {
                    if (_readBuf.ReadBytesLeft < 4)
                    {
                        return(false);
                    }
                    _points = new Coordinate2D[_readBuf.ReadInt32(_bo)];
                    _ipts   = 0;
                }
                for (; _ipts < _points.Length; _ipts++)
                {
                    if (_readBuf.ReadBytesLeft < 21)
                    {
                        return(false);
                    }
                    _readBuf.Skip(5);
                    _points[_ipts] = new Coordinate2D(_readBuf.ReadDouble(_bo), _readBuf.ReadDouble(_bo));
                }
                result = new PostgisMultiPoint(_points)
                {
                    SRID = _srid.Value
                };
                return(true);

            case WkbIdentifier.MultiLineString:
                _lastId = _id;
                if (_irng == -1)
                {
                    if (_readBuf.ReadBytesLeft < 4)
                    {
                        return(false);
                    }
                    _rings = new Coordinate2D[_readBuf.ReadInt32(_bo)][];
                    _irng  = 0;
                }

                for (; _irng < _rings.Length; _irng++)
                {
                    if (_ipts == -1)
                    {
                        if (_readBuf.ReadBytesLeft < 9)
                        {
                            return(false);
                        }
                        _readBuf.Skip(5);
                        _rings[_irng] = new Coordinate2D[_readBuf.ReadInt32(_bo)];
                        _ipts         = 0;
                    }
                    for (; _ipts < _rings[_irng].Length; _ipts++)
                    {
                        if (_readBuf.ReadBytesLeft < 16)
                        {
                            return(false);
                        }
                        _rings[_irng][_ipts] = new Coordinate2D(_readBuf.ReadDouble(_bo), _readBuf.ReadDouble(_bo));
                    }
                    _ipts = -1;
                }
                result = new PostgisMultiLineString(_rings)
                {
                    SRID = _srid.Value
                };
                return(true);

            case WkbIdentifier.MultiPolygon:
                _lastId = _id;
                if (_ipol == -1)
                {
                    if (_readBuf.ReadBytesLeft < 4)
                    {
                        return(false);
                    }
                    _pols = new Coordinate2D[_readBuf.ReadInt32(_bo)][][];
                    _ipol = 0;
                }

                for (; _ipol < _pols.Length; _ipol++)
                {
                    if (_irng == -1)
                    {
                        if (_readBuf.ReadBytesLeft < 9)
                        {
                            return(false);
                        }
                        _readBuf.Skip(5);
                        _pols[_ipol] = new Coordinate2D[_readBuf.ReadInt32(_bo)][];
                        _irng        = 0;
                    }
                    for (; _irng < _pols[_ipol].Length; _irng++)
                    {
                        if (_ipts == -1)
                        {
                            if (_readBuf.ReadBytesLeft < 4)
                            {
                                return(false);
                            }
                            _pols[_ipol][_irng] = new Coordinate2D[_readBuf.ReadInt32(_bo)];
                            _ipts = 0;
                        }
                        for (; _ipts < _pols[_ipol][_irng].Length; _ipts++)
                        {
                            if (_readBuf.ReadBytesLeft < 16)
                            {
                                return(false);
                            }
                            _pols[_ipol][_irng][_ipts] = new Coordinate2D(_readBuf.ReadDouble(_bo), _readBuf.ReadDouble(_bo));
                        }
                        _ipts = -1;
                    }
                    _irng = -1;
                }
                result = new PostgisMultiPolygon(_pols)
                {
                    SRID = _srid.Value
                };
                return(true);

            case WkbIdentifier.GeometryCollection:
                PostgisGeometry[] g;
                int i;
                if (_icol.Count == 0)
                {
                    if (_readBuf.ReadBytesLeft < 4)
                    {
                        _lastId = _id;
                        return(false);
                    }
                    g = new PostgisGeometry[_readBuf.ReadInt32(_bo)];
                    i = 0;
                    if (_newGeom)     // We need to know whether we're in a nested geocoll or not.
                    {
                        _id      = 0;
                        _newGeom = false;
                    }
                    else
                    {
                        _id     = _lastId;
                        _lastId = 0;
                    }
                }
                else
                {
                    g = _geoms.Pop();
                    i = _icol.Pop();
                    if (_icol.Count == 0)
                    {
                        _id     = _lastId;
                        _lastId = 0;
                    }
                }
                for (; i < g.Length; i++)
                {
                    PostgisGeometry geom;

                    if (!Read(out geom))
                    {
                        _icol.Push(i);
                        _geoms.Push(g);
                        _id = (uint)WkbIdentifier.GeometryCollection;
                        return(false);
                    }
                    g[i] = geom;
                    Reset();
                }
                result = new PostgisGeometryCollection(g)
                {
                    SRID = _srid.Value
                };
                return(true);

            default:
                throw new InvalidOperationException("Unknown Postgis identifier.");
            }
        }
 public bool Contains(Coordinate2D sokobanCoord)
 {
     HashKey key = level.GetOccupantsHashKey() ^ HashKey.GetSokobanHashKey(sokobanCoord);
     return set.Contains(key);
 }
Beispiel #41
0
        private Level GenerateLevelBlob(State state, int size, Array2D<Cell> designData, Array2D<bool> designFixed, out int designRow, out int designColumn)
        {
            // Inflate size for extra cells to be subtracted.
            int blobSize = size * (density + 100) / 100;
            // Create larger work array and corresponding fixed map.
            Array2D<Cell> array = new Array2D<Cell>(2 * size, 2 * size);
            array.SetAll(Cell.Outside);
            Array2D<bool> arrayFixed = new Array2D<bool>(array.Height, array.Width);

            // Adjust design data so that outside or undefined cells are empty.
            Array2D<Cell> designDataCopy = new Array2D<Cell>(designData);
            designDataCopy.Replace(Cell.Outside, Cell.Empty);
            designDataCopy.Replace(Cell.Undefined, Cell.Empty);

            // Copy design into middle of work array.
            designRow = size;
            designColumn = size;
            designDataCopy.CopyTo(array, designRow + 1, designColumn + 1, 1, 1, designData.Height - 2, designData.Width - 2);
            designFixed.CopyTo(arrayFixed, designRow + 1, designColumn + 1, 1, 1, designData.Height - 2, designData.Width - 2);

            // Set intial boundaries.
            int rowMin = array.Height;
            int colMin = array.Width;
            int rowMax = -1;
            int colMax = -1;
            int count = 0;
            foreach (Coordinate2D coord in array.Coordinates)
            {
                if (!Level.IsOutside(array[coord]))
                {
                    rowMin = Math.Min(rowMin, coord.Row);
                    colMin = Math.Min(colMin, coord.Column);
                    rowMax = Math.Max(rowMax, coord.Row);
                    colMax = Math.Max(colMax, coord.Column);
                    count++;
                }
            }

            while (count < blobSize)
            {
                // Choose an edge at random.
                int edge = state.Random.Next(4);
                int row = 0;
                int column = 0;
                int limit = 0;
                int hIncr = 0;
                int vIncr = 0;
                switch (edge)
                {
                    case 0:
                        row = rowMin - 1;
                        column = colMin + state.Random.Next(colMax - colMin + 1);
                        limit = rowMax - rowMin + 1;
                        vIncr = 1;
                        hIncr = 0;
                        break;
                    case 1:
                        row = rowMax + 1;
                        column = colMin + state.Random.Next(colMax - colMin + 1);
                        limit = rowMax - rowMin + 1;
                        vIncr = -1;
                        hIncr = 0;
                        break;
                    case 2:
                        row = rowMin + state.Random.Next(rowMax - rowMin + 1);
                        column = colMin - 1;
                        limit = colMax - colMin + 1;
                        vIncr = 0;
                        hIncr = 1;
                        break;
                    case 3:
                        row = rowMin + state.Random.Next(rowMax - rowMin + 1);
                        column = colMax + 1;
                        limit = colMax - colMin + 1;
                        vIncr = 0;
                        hIncr = -1;
                        break;
                }

                // Search along a line until we hit a empty or fixed cell.
                bool found = false;
                for (int i = 0; i < limit; i++)
                {
                    if (array[row + vIncr, column + hIncr] != Cell.Outside || arrayFixed[row + vIncr, column + hIncr])
                    {
                        if (!arrayFixed[row, column])
                        {
                            found = true;
                        }
                        break;
                    }
                    row += vIncr;
                    column += hIncr;
                }

                // If we didn't find anything, try again.
                if (!found)
                {
                    continue;
                }

                // Don't allow the level to grow outside the array.
                if (row < 1 || row >= array.Height - 1 || column < 1 || column >= array.Width - 1)
                {
                    continue;
                }

                // Add the new square and update the boundaries.
                array[row, column] = Cell.Empty;
                rowMin = Math.Min(rowMin, row);
                colMin = Math.Min(colMin, column);
                rowMax = Math.Max(rowMax, row);
                colMax = Math.Max(colMax, column);
                count++;
            }

            int attemptsLeft = 2 * (count - size);
            while (count > size && attemptsLeft > 0)
            {
                // Choose a new square at random.
                int row = rowMin + state.Random.Next(rowMax - rowMin + 1);
                int column = colMin + state.Random.Next(colMax - colMin + 1);
                Coordinate2D coord = new Coordinate2D(row, column);
                if (!array.IsValid(coord))
                {
                    continue;
                }

                // Avoid existing walls and outside areas.
                if (!Level.IsInside(array[coord]))
                {
                    continue;
                }

                // We might get into an infinite loop.
                attemptsLeft--;

                // Avoid fixed cells.
                if (arrayFixed[coord])
                {
                    continue;
                }

                // Avoid cells on the perimeter.
                bool isAdjacent = false;
                foreach (Coordinate2D neighbor in coord.EightNeighbors)
                {
                    if (array[neighbor] == Cell.Outside)
                    {
                        isAdjacent = true;
                        break;
                    }
                }
                if (isAdjacent)
                {
                    continue;
                }

                // Remove the cell.
                array[coord] = Cell.Wall;
                count--;

            }

            // Extract the constructed level.
            Array2D<Cell> subarray = array.GetSubarray(rowMin - 1, colMin - 1, rowMax - rowMin + 3, colMax - colMin + 3);
            subarray.Replace(Cell.Outside, Cell.Wall);
            Level level = new Level(subarray);

            // Adjust design coordinate.
            designRow -= rowMin - 1;
            designColumn -= colMin - 1;

            return level;
        }
Beispiel #42
0
 private void pictureGrid_MouseDown(object sender, MouseEventArgs e)
 {
     mouseDownCoord = GetMouseCell(e);
     if (e.Button == MouseButtons.Left)
     {
         if (e.Clicks == 2)
         {
             inMouseDrag = false;
             HandleDoubleClick();
         }
         else if (e.Clicks == 1)
         {
             inMouseDrag = true;
         }
     }
 }
Beispiel #43
0
 public void MoveSokoban(Coordinate2D coord)
 {
     MoveSokoban(coord.Row, coord.Column);
 }
        public async void Examples2()
        {
            //var scenelayerName = featSceneLayer?.Name;

            #region Has Associated FeatureService

            var featSceneLayer = MapView.Active.Map.GetLayersAsFlattenedList()
                                 .OfType <FeatureSceneLayer>().First();
            if (featSceneLayer.HasAssociatedFeatureService)
            {
                //Can Select and Search...possibly edit
            }

            #endregion

            #region Search Rows on the FeatureSceneLayer

            //var featSceneLayer = ...;
            if (!featSceneLayer.HasAssociatedFeatureService)
            {
                return;//Search and Select not supported
            }
            //Multipatch (Object3D) or point?
            var is3dObject = ((ISceneLayerInfo)featSceneLayer).SceneServiceLayerType
                             == esriSceneServiceLayerType.Object3D;
            await QueuedTask.Run(() =>
            {
                var queryFilter = new QueryFilter
                {
                    WhereClause = "Name = 'Ponderosa Pine'",
                    SubFields   = "*"
                };

                int rowCount = 0;
                //or select... var select = featSceneLayer.Select(queryFilter)
                using (RowCursor rowCursor = featSceneLayer.Search(queryFilter))
                {
                    while (rowCursor.MoveNext())
                    {
                        using (var feature = rowCursor.Current as Feature)
                        {
                            var oid    = feature.GetObjectID();
                            var shape  = feature.GetShape();
                            var attrib = feature["Name"];
                            if (is3dObject)
                            {
                                //shape is a multipatch
                            }
                            else
                            {
                                //shape is a point
                            }
                            rowCount += 1;
                        }
                    }
                }
            });

            #endregion

            #region Hide Selected features and Show Hidden features

            //var featSceneLayer = ...;
            if (featSceneLayer.HasAssociatedFeatureService)
            {
                return;//Search and Select not supported
            }
            await QueuedTask.Run(() =>
            {
                QueryFilter qf = new QueryFilter()
                {
                    ObjectIDs = new List <long>()
                    {
                        6069, 6070, 6071
                    },
                    SubFields = "*"
                };
                featSceneLayer.Select(qf, SelectionCombinationMethod.New);

                featSceneLayer.HideSelectedFeatures();
                var selectionCount = featSceneLayer.SelectionCount;

                featSceneLayer.ShowHiddenFeatures();
                selectionCount = featSceneLayer.SelectionCount;
            });

            #endregion

            #region Use MapView Selection SelectFeaturesEx or GetFeaturesEx

            //var featSceneLayer = ...;
            var sname = featSceneLayer.Name;

            await QueuedTask.Run(() =>
            {
                //Select all features within the current map view
                var sz = MapView.Active.GetViewSize();

                var c_ll = new Coordinate2D(0, 0);
                var c_ur = new Coordinate2D(sz.Width, sz.Height);
                //Use screen coordinates for 3D selection on MapView
                var env = EnvelopeBuilder.CreateEnvelope(c_ll, c_ur);

                //HasAssociatedFeatureService does not matter for SelectFeaturesEx
                //or GetFeaturesEx
                var result = MapView.Active.SelectFeaturesEx(env);
                //var result = MapView.Active.GetFeaturesEx(env);

                //The list of object ids from SelectFeaturesEx
                var oids1 = result.Where(kvp => kvp.Key.Name == sname).First().Value;
                //TODO - use the object ids

                MapView.Active.Map.ClearSelection();
            });

            #endregion

            #region Use Select or Search with a Spatial Query

            //var featSceneLayer = ...;
            //var sname = featSceneLayer.Name;
            await QueuedTask.Run(() =>
            {
                if (!featSceneLayer.HasAssociatedFeatureService)
                {
                    return;//no search or select
                }
                //Select all features within the current map view
                var sz      = MapView.Active.GetViewSize();
                var map_pt1 = MapView.Active.ClientToMap(new System.Windows.Point(0, sz.Height));
                var map_pt2 = MapView.Active.ClientToMap(new System.Windows.Point(sz.Width, 0));

                //Convert to an envelope
                var temp_env = EnvelopeBuilder.CreateEnvelope(map_pt1, map_pt2, MapView.Active.Map.SpatialReference);

                //Project if needed to the layer spatial ref
                SpatialReference sr = null;
                using (var fc = featSceneLayer.GetFeatureClass())
                    using (var fdef = fc.GetDefinition())
                        sr = fdef.GetSpatialReference();

                var env = GeometryEngine.Instance.Project(temp_env, sr) as Envelope;

                //Set up a query filter
                var sf = new SpatialQueryFilter()
                {
                    FilterGeometry      = env,
                    SpatialRelationship = SpatialRelationship.Intersects,
                    SubFields           = "*"
                };

                //Select against the feature service
                var select = featSceneLayer.Select(sf);
                if (select.GetCount() > 0)
                {
                    //enumerate over the selected features
                    using (var rc = select.Search())
                    {
                        while (rc.MoveNext())
                        {
                            using (var feature = rc.Current as Feature)
                            {
                                var oid = feature.GetObjectID();
                                //etc.
                            }
                        }
                    }
                }

                MapView.Active.Map.ClearSelection();
            });

            #endregion
        }
Beispiel #45
0
        async Task <PostgisGeometry> DoRead(NpgsqlReadBuffer buf, WkbIdentifier id, ByteOrder bo, bool async)
        {
            switch (id)
            {
            case WkbIdentifier.Point:
                await buf.Ensure(16, async);

                return(new PostgisPoint(buf.ReadDouble(bo), buf.ReadDouble(bo)));

            case WkbIdentifier.LineString:
            {
                await buf.Ensure(4, async);

                var points = new Coordinate2D[buf.ReadInt32(bo)];
                for (var ipts = 0; ipts < points.Length; ipts++)
                {
                    await buf.Ensure(16, async);

                    points[ipts] = new Coordinate2D(buf.ReadDouble(bo), buf.ReadDouble(bo));
                }
                return(new PostgisLineString(points));
            }

            case WkbIdentifier.Polygon:
            {
                await buf.Ensure(4, async);

                var rings = new Coordinate2D[buf.ReadInt32(bo)][];

                for (var irng = 0; irng < rings.Length; irng++)
                {
                    await buf.Ensure(4, async);

                    rings[irng] = new Coordinate2D[buf.ReadInt32(bo)];
                    for (var ipts = 0; ipts < rings[irng].Length; ipts++)
                    {
                        await buf.Ensure(16, async);

                        rings[irng][ipts] = new Coordinate2D(buf.ReadDouble(bo), buf.ReadDouble(bo));
                    }
                }
                return(new PostgisPolygon(rings));
            }

            case WkbIdentifier.MultiPoint:
            {
                await buf.Ensure(4, async);

                var points = new Coordinate2D[buf.ReadInt32(bo)];
                for (var ipts = 0; ipts < points.Length; ipts++)
                {
                    await buf.Ensure(21, async);

                    await buf.Skip(5, async);

                    points[ipts] = new Coordinate2D(buf.ReadDouble(bo), buf.ReadDouble(bo));
                }
                return(new PostgisMultiPoint(points));
            }

            case WkbIdentifier.MultiLineString:
            {
                await buf.Ensure(4, async);

                var rings = new Coordinate2D[buf.ReadInt32(bo)][];

                for (var irng = 0; irng < rings.Length; irng++)
                {
                    await buf.Ensure(9, async);

                    await buf.Skip(5, async);

                    rings[irng] = new Coordinate2D[buf.ReadInt32(bo)];
                    for (var ipts = 0; ipts < rings[irng].Length; ipts++)
                    {
                        await buf.Ensure(16, async);

                        rings[irng][ipts] = new Coordinate2D(buf.ReadDouble(bo), buf.ReadDouble(bo));
                    }
                }
                return(new PostgisMultiLineString(rings));
            }

            case WkbIdentifier.MultiPolygon:
            {
                await buf.Ensure(4, async);

                var pols = new Coordinate2D[buf.ReadInt32(bo)][][];

                for (var ipol = 0; ipol < pols.Length; ipol++)
                {
                    await buf.Ensure(9, async);

                    await buf.Skip(5, async);

                    pols[ipol] = new Coordinate2D[buf.ReadInt32(bo)][];
                    for (var irng = 0; irng < pols[ipol].Length; irng++)
                    {
                        await buf.Ensure(4, async);

                        pols[ipol][irng] = new Coordinate2D[buf.ReadInt32(bo)];
                        for (var ipts = 0; ipts < pols[ipol][irng].Length; ipts++)
                        {
                            await buf.Ensure(16, async);

                            pols[ipol][irng][ipts] = new Coordinate2D(buf.ReadDouble(bo), buf.ReadDouble(bo));
                        }
                    }
                }
                return(new PostgisMultiPolygon(pols));
            }

            case WkbIdentifier.GeometryCollection:
            {
                await buf.Ensure(4, async);

                var g = new PostgisGeometry[buf.ReadInt32(bo)];

                for (var i = 0; i < g.Length; i++)
                {
                    await buf.Ensure(5, async);

                    var elemBo = (ByteOrder)buf.ReadByte();
                    var elemId = (WkbIdentifier)(buf.ReadUInt32(bo) & 7);

                    g[i] = await DoRead(buf, elemId, elemBo, async);
                }
                return(new PostgisGeometryCollection(g));
            }

            default:
                throw new InvalidOperationException("Unknown Postgis identifier.");
            }
        }
Beispiel #46
0
 public void TestPolygonEnumeration()
 {
     var a = new Coordinate2D[2][] {
         new Coordinate2D[4] { new Coordinate2D(0D, 0D), new Coordinate2D(0D, 1D),
                               new Coordinate2D(1D, 1D), new Coordinate2D(0D, 0D) },
         new Coordinate2D[5] { new Coordinate2D(0D, 0D), new Coordinate2D(0D, 2D),
                               new Coordinate2D(2D, 2D),new Coordinate2D(2D, 0D),
                              new Coordinate2D(0D, 0D) } };
     Assert.That(a.SequenceEqual(new PostgisPolygon(a)));
 }
Beispiel #47
0
 public void Reset()
 {
     _lastEndPoint = _startingPoint;
     _enumerator.Reset();
 }
        public ProbesDataSource(Guid guid, IDataSource2D<double> field, Host host)
            : base(guid)
        {
            // set up the Ontology, a description of the kind of data we contain.
            // See DataSource sample for more details.
            OntologySpecification o = this.Ontology.Edit();
            o.PrimitiveTypes.Create("RasterPatch", "GeoEntity", typeof(RasterPatch2));
            this.UpdateOntology(o);

            EntitySpecification entitySpec = new EntitySpecification(this.Ontology.EntityTypes["GeoEntity"]); // the default entity type
            entity = this.EntityAuthorityReference.EntityAuthority.CreateEntity(true, entitySpec);

            this.wfield = field;

            System.Windows.Point[,] grid = wfield.Grid;
            Coordinate2D minCoordinate = new Coordinate2D(grid[0, 0].X, grid[0, 0].Y);
            Coordinate2D maxCoordinate = new Coordinate2D(grid[field.Width - 1, field.Height - 1].X, grid[field.Width - 1, field.Height - 1].Y);


            for (int j = 0; j < field.Height; j++)
            {
                for (int i = 0; i < field.Width; i++)
                {
                    if (grid[i, j].X < minCoordinate.X)
                        minCoordinate.X = grid[i, j].X;

                    if (grid[i, j].X > maxCoordinate.X)
                        maxCoordinate.X = grid[i, j].X;

                    if (grid[i, j].Y < minCoordinate.Y)
                        minCoordinate.Y = grid[i, j].Y;

                    if (grid[i, j].Y > maxCoordinate.Y)
                        maxCoordinate.Y = grid[i, j].Y;
                }
            }

            gridBox = new GeoRect(
                minCoordinate.X,
                minCoordinate.Y,
                maxCoordinate.X - minCoordinate.X,
                maxCoordinate.Y - minCoordinate.Y);

            dataType = DSDataType.TwoDim;
            this.host = host;

            probesHelper = new ProbesHelper("ProbeSample.png", false);
        }
Beispiel #49
0
        public void MoveBox(int oldBoxRow, int oldBoxColumn, int newBoxRow, int newBoxColumn)
        {
            if (!boxesAssessed)
            {
                AssessBoxes();
            }

            #if DEBUG
            if (validate)
            {
                // Perform extra checks in debug build.
                if (oldBoxRow != newBoxRow || oldBoxColumn != newBoxColumn)
                {
                    if (!IsBox(oldBoxRow, oldBoxColumn))
                    {
                        throw new Exception("no box on old coordinate");
                    }
                    if (!IsEmpty(newBoxRow, newBoxColumn))
                    {
                        throw new Exception("new box coordinate is not empty");
                    }
                }
            }
            #endif

            Cell oldBoxCell = (data[oldBoxRow, oldBoxColumn] &= ~Cell.Box);
            Cell newBoxCell = (data[newBoxRow, newBoxColumn] |= Cell.Box);

            unfinishedBoxes += IsTarget(oldBoxCell) ? 1 : 0;
            unfinishedBoxes -= IsTarget(newBoxCell) ? 1 : 0;

            int boxIndex = boxMap[oldBoxRow, oldBoxColumn];
            boxMap[newBoxRow, newBoxColumn] = boxIndex;
            boxCoordinates[boxIndex] = new Coordinate2D(newBoxRow, newBoxColumn);

            #if DEBUG
            if (validate)
            {
                ValidateBoxes();
            }
            #endif

            if (markAccessible)
            {
                AddAccessible();
            }
        }
        private bool IsPossiblePosition(Coordinate2D coord, int accessibleSquares)
        {
            // Find accessible coordinates from this square.
            pathFinder.Find(coord);

            // If the sokoban started in this region, it is
            // theoretically possible for it to be confined
            // in a small area.
            if (pathFinder.IsAccessible(originalLevel.SokobanCoordinate))
            {
                // If the sokoban is confined to a single square
                // then this position is only possible if
                // all the boxes are also in their starting
                // positions.
                if (accessibleSquares == 1)
                {
                    for (int i = 0; i < boxes; i++)
                    {
                        if (!originalLevel.IsBox(boxCoordinates[i]))
                        {
                            return false;
                        }
                    }
                }
                return true;
            }

            // If there are four or fewer squares in the
            // region, it is not possible for the sokoban
            // to close itself in if it wasn't already
            // there at the beginning of the level.
            if (accessibleSquares <= 4)
            {
                return false;
            }

            // If there are five or six squares, the position
            // is possible only if there is a box that can
            // be pulled in to open a door to the outside.
            if (accessibleSquares <= 6)
            {
                if (CanPullDoor())
                {
                    return true;
                }
                return false;
            }

            return true;
        }
Beispiel #51
0
        async protected override void OnClick()
        {
            LayoutView layoutView = LayoutView.Active;

            //Prevent tool from executing based on some conditions
            if (layoutView == null)
            {
                System.Windows.MessageBox.Show("Can't find layout view, try clicking New Game Board");
                return;
            }

            if (layoutView.Layout.Name != "Game Board")
            {
                System.Windows.MessageBox.Show("Wrong layout view: should be Game Board");
                return;
            }

            await QueuedTask.Run(() =>
            {
                //Reference the layout for moving map frames and adding new layout elements
                Layout layout = layoutView.Layout;

                //Check to see if elements were already scrambled
                MapFrame mfTest = layout.FindElement("MF1") as MapFrame;
                if (mfTest != null)
                {
                    System.Windows.MessageBox.Show("Game pieces already scrambled");
                    return;
                }

                //Build 6 envelopes to represent the locations of puzzle pieces along the outer edges
                Coordinate2D env1_ll = new Coordinate2D(0.5, 0.5);
                Coordinate2D env1_ur = new Coordinate2D(3.5, 3.5);
                Envelope env1        = EnvelopeBuilder.CreateEnvelope(env1_ll, env1_ur);

                Coordinate2D env2_ll = new Coordinate2D(0.5, 4);
                Coordinate2D env2_ur = new Coordinate2D(3.5, 7);
                Envelope env2        = EnvelopeBuilder.CreateEnvelope(env2_ll, env2_ur);

                Coordinate2D env3_ll = new Coordinate2D(0.5, 7.5);
                Coordinate2D env3_ur = new Coordinate2D(3.5, 10.5);
                Envelope env3        = EnvelopeBuilder.CreateEnvelope(env3_ll, env3_ur);

                Coordinate2D env4_ll = new Coordinate2D(13.5, 0.5);
                Coordinate2D env4_ur = new Coordinate2D(16.5, 3.5);
                Envelope env4        = EnvelopeBuilder.CreateEnvelope(env4_ll, env4_ur);

                Coordinate2D env5_ll = new Coordinate2D(13.5, 4);
                Coordinate2D env5_ur = new Coordinate2D(16.5, 7);
                Envelope env5        = EnvelopeBuilder.CreateEnvelope(env5_ll, env5_ur);

                Coordinate2D env6_ll = new Coordinate2D(13.5, 7.5);
                Coordinate2D env6_ur = new Coordinate2D(16.5, 10.5);
                Envelope env6        = EnvelopeBuilder.CreateEnvelope(env6_ll, env6_ur);

                //Randomize the envelopes by assigning new envelope variables used for map frame creation
                //Also remove the assigned env before selecting the next random env
                List <Envelope> envList = new List <Envelope> {
                    env1, env2, env3, env4, env5, env6
                };

                Random r1   = new Random();
                int i1      = r1.Next(envList.Count);
                Envelope e1 = envList[i1];
                envList.Remove(e1);

                Random r2   = new Random();
                int i2      = r2.Next(envList.Count);
                Envelope e2 = envList[i2];
                envList.Remove(e2);

                Random r3   = new Random();
                int i3      = r3.Next(envList.Count);
                Envelope e3 = envList[i3];
                envList.Remove(e3);

                Random r4   = new Random();
                int i4      = r4.Next(envList.Count);
                Envelope e4 = envList[i4];
                envList.Remove(e4);

                Random r5   = new Random();
                int i5      = r5.Next(envList.Count);
                Envelope e5 = envList[i5];
                envList.Remove(e5);

                Random r6   = new Random();
                int i6      = r6.Next(envList.Count);
                Envelope e6 = envList[i6];
                envList.Remove(e6);

                //Reference the active map view and gets its center location
                //MapView map = MapView.Active;
                MapFrame mapFrame = layout.FindElement("Main MF") as MapFrame;
                Camera cam        = mapFrame.Camera;
                double x          = cam.X;
                double y          = cam.Y;
                double scale      = cam.Scale;
                double delta      = scale * 1.5 / 12 / 3.28084; //scale * 1/2 of a 3" MF / 12" per foot / 3.28084 feet per meter

                //Insert Map Frame 1 at random location
                MapFrame mf1Elm = LayoutElementFactory.Instance.CreateMapFrame(layout, e1, mapFrame.Map);
                mf1Elm.SetName("MF1");
                Camera mf1cam = mf1Elm.Camera;
                mf1cam.X      = x - (delta * 2);
                mf1cam.Y      = y - delta;
                mf1cam.Scale  = scale;
                mf1Elm.SetCamera(mf1cam);

                //Insert Map Frame 2 at random location
                MapFrame mf2Elm = LayoutElementFactory.Instance.CreateMapFrame(layout, e2, mapFrame.Map);
                mf2Elm.SetName("MF2");
                Camera mf2cam = mf2Elm.Camera;
                mf2cam.X      = x;
                mf2cam.Y      = y - delta;
                mf2cam.Scale  = scale;
                mf2Elm.SetCamera(mf2cam);

                //Insert Map Frame 3 at random location
                MapFrame mf3Elm = LayoutElementFactory.Instance.CreateMapFrame(layout, e3, mapFrame.Map);
                mf3Elm.SetName("MF3");
                Camera mf3cam = mf3Elm.Camera;
                mf3cam.X      = x + (delta * 2);
                mf3cam.Y      = y - delta;
                mf3cam.Scale  = scale;
                mf3Elm.SetCamera(mf3cam);

                //Insert Map Frame 4 at random location

                MapFrame mf4Elm = LayoutElementFactory.Instance.CreateMapFrame(layout, e4, mapFrame.Map);
                mf4Elm.SetName("MF4");
                Camera mf4cam = mf4Elm.Camera;
                mf4cam.X      = x + (delta * 2);
                mf4cam.Y      = y + delta;
                mf4cam.Scale  = scale;
                mf4Elm.SetCamera(mf4cam);

                //Insert Map Frame 5 at random location
                MapFrame mf5Elm = LayoutElementFactory.Instance.CreateMapFrame(layout, e5, mapFrame.Map);
                mf5Elm.SetName("MF5");
                Camera mf5cam = mf5Elm.Camera;
                mf5cam.X      = x;
                mf5cam.Y      = y + delta;
                mf5cam.Scale  = scale;
                mf5Elm.SetCamera(mf5cam);

                //Insert Map Frame 6 at random location
                MapFrame mf6Elm = LayoutElementFactory.Instance.CreateMapFrame(layout, e6, mapFrame.Map);
                mf6Elm.SetName("MF6");
                Camera mf6cam = mf6Elm.Camera;
                mf6cam.X      = x - (delta * 2);
                mf6cam.Y      = y + delta;
                mf6cam.Scale  = scale;
                mf6Elm.SetCamera(mf6cam);

                //Create 6 polygon boxes that represent where the outer map frames need to be placed.
                Coordinate2D box1_ll = new Coordinate2D(4, 0.5);
                Coordinate2D box1_ur = new Coordinate2D(7, 3.5);
                Envelope box1_env    = EnvelopeBuilder.CreateEnvelope(box1_ll, box1_ur);
                GraphicElement box1  = LayoutElementFactory.Instance.CreateRectangleGraphicElement(layout, box1_env);
                box1.SetName("Rectangle 1");

                Coordinate2D box2_ll = new Coordinate2D(7, 0.5);
                Coordinate2D box2_ur = new Coordinate2D(10, 3.5);
                Envelope box2_env    = EnvelopeBuilder.CreateEnvelope(box2_ll, box2_ur);
                GraphicElement box2  = LayoutElementFactory.Instance.CreateRectangleGraphicElement(layout, box2_env);
                box2.SetName("Rectangle 2");

                Coordinate2D box3_ll = new Coordinate2D(10, 0.5);
                Coordinate2D box3_ur = new Coordinate2D(13, 3.5);
                Envelope box3_env    = EnvelopeBuilder.CreateEnvelope(box3_ll, box3_ur);
                GraphicElement box3  = LayoutElementFactory.Instance.CreateRectangleGraphicElement(layout, box3_env);
                box3.SetName("Rectangle 3");

                Coordinate2D box4_ll = new Coordinate2D(10, 3.5);
                Coordinate2D box4_ur = new Coordinate2D(13, 6.5);
                Envelope box4_env    = EnvelopeBuilder.CreateEnvelope(box4_ll, box4_ur);
                GraphicElement box4  = LayoutElementFactory.Instance.CreateRectangleGraphicElement(layout, box4_env);
                box4.SetName("Rectangle 4");

                Coordinate2D box5_ll = new Coordinate2D(7, 3.5);
                Coordinate2D box5_ur = new Coordinate2D(10, 6.5);
                Envelope box5_env    = EnvelopeBuilder.CreateEnvelope(box5_ll, box5_ur);
                GraphicElement box5  = LayoutElementFactory.Instance.CreateRectangleGraphicElement(layout, box5_env);
                box5.SetName("Rectangle 5");

                Coordinate2D box6_ll = new Coordinate2D(4, 3.5);
                Coordinate2D box6_ur = new Coordinate2D(7, 6.5);
                Envelope box6_env    = EnvelopeBuilder.CreateEnvelope(box6_ll, box6_ur);
                GraphicElement box6  = LayoutElementFactory.Instance.CreateRectangleGraphicElement(layout, box6_env);
                box6.SetName("Rectangle 6");

                //Find MainMF and set invisible
                MapFrame mainMF = layout.FindElement("Main MF") as MapFrame;
                mainMF.SetVisible(false);

                //Update Instructions
                TextElement steps = layout.FindElement("Instructions") as TextElement;
                string text       = "<bol>Instructions: </bol>\n\n  - Click the 'Play Game' command" as String;
                var stepsProp     = steps.TextProperties;
                stepsProp.Text    = text;
                steps.SetTextProperties(stepsProp);
            });

            layoutView.ClearElementSelection();
        }
        public bool CheckIntersection(LatLonAlt location)
        {
            bool hasIntersections = false;

            foreach (VisualPushpin pin in intersectedValues)
            {
                host.Geometry.RemoveGeometry(pin.Pushpin.LayerId, pin.Pushpin.Id);
            }
            intersectedValues.Clear();

            lock (probesLayers)
            {
                foreach (ProbesLayer probesLayer in probesLayers)
                {
                    if (probesLayer.IsVisible)
                    {

                        if (probesLayer.DataSource.Field is IDataSource2D<double>)
                        {
                            //for warped grids
                            IDataSource2D<double> field = probesLayer.DataSource.Field as IDataSource2D<double>;
                            System.Windows.Point[,] grid = field.Grid;

                            Coordinate2D minCoordinate = new Coordinate2D(grid[0, 0].X, grid[0, 0].Y);
                            Coordinate2D maxCoordinate = new Coordinate2D(grid[field.Width - 1, field.Height - 1].X, grid[field.Width - 1, field.Height - 1].Y);

                            bool intersectionFound = false;
                            for (int j = 0; j < field.Height; j++)
                            {
                                for (int i = 0; i < field.Width; i++)
                                {
                                    if (grid[i, j].X < minCoordinate.X)
                                        minCoordinate.X = grid[i, j].X;

                                    if (grid[i, j].X > maxCoordinate.X)
                                        maxCoordinate.X = grid[i, j].X;

                                    if (grid[i, j].Y < minCoordinate.Y)
                                        minCoordinate.Y = grid[i, j].Y;

                                    if (grid[i, j].Y > maxCoordinate.Y)
                                        maxCoordinate.Y = grid[i, j].Y;
                                }
                            }

                            if (location.LatitudeDegrees > minCoordinate.Y && location.LongitudeDegrees > minCoordinate.X && location.LongitudeDegrees < maxCoordinate.X && location.LatitudeDegrees < maxCoordinate.Y)
                            {
                                for (int i = 0; i < field.Width; i++)
                                {
                                    for (int j = 0; j < field.Height; j++)
                                    {
                                        LatLonAlt gridPos = LatLonAlt.CreateUsingDegrees(field.Grid[i, j].Y, field.Grid[i, j].X, 0);
                                        if (CheckEnvirons(gridPos, location, probesLayer.DataSource.Step))
                                        {
                                            if (!hasIntersections)
                                                hasIntersections = true;

                                            intersectedValues.Add(new VisualPushpin(60, 60, field.Data[i, j].ToString(), gridPos, null, Guid.NewGuid().ToString()));
                                            intersectionFound = true;
                                            break;
                                        }
                                    }
                                    if (intersectionFound)
                                        break;
                                }
                            }
                        }
                        else if (probesLayer.DataSource.Field is PointSet)
                        {
                            PointSet pointSet = probesLayer.DataSource.Field as PointSet;
                            if (probesLayer.IsVisible)
                            {
                                for (int i = 0; i < pointSet.Data.Count; i++)
                                {
                                    LatLonAlt gridPos = LatLonAlt.CreateUsingDegrees(pointSet.Data[i].Latitude, pointSet.Data[i].Longitude, 0);
                                    if (CheckEnvirons(gridPos, location, probesLayer.DataSource.Step))
                                    {
                                        if (!hasIntersections)
                                            hasIntersections = true;

                                        intersectedValues.Add(new VisualPushpin(60, 60, pointSet.Data[i].Value.ToString(), gridPos, null, Guid.NewGuid().ToString()));
                                        break;
                                    }
                                }
                            }

                        }
                    }
                }
            }
            return hasIntersections;
        }
Beispiel #53
0
 public new Cell this[Coordinate2D coord]
 {
     get
     {
         return data[coord];
     }
     set
     {
         if (IsSokobanBoxOrTarget(data[coord.Row, coord.Column]) || IsSokobanBoxOrTarget(value))
         {
             sokobanAssessed = false;
             boxesAssessed = false;
         }
         outsideAssessed = false;
         data[coord.Row, coord.Column] = value;
     }
 }
Beispiel #54
0
 public bool IsDeadlocked(Coordinate2D coord)
 {
     return IsDeadlocked(coord.Row, coord.Column);
 }
Beispiel #55
0
 public int BoxIndex(Coordinate2D coord)
 {
     return BoxIndex(coord.Row, coord.Column);
 }
Beispiel #56
0
        private void VisitAllPulls(Coordinate2D coord)
        {
            if (!simpleDeadlockMap[coord])
            {
                return;
            }

            simpleDeadlockMap[coord] = false;

            foreach (Direction direction in Direction.Directions)
            {
                if (level.IsFloor(coord + direction) && level.IsFloor(coord + 2 * direction))
                {
                    VisitAllPulls(coord + direction);
                }
            }
        }
Beispiel #57
0
 public void MoveBox(Coordinate2D oldBoxCoordinate, Coordinate2D newBoxCoordinate)
 {
     MoveBox(oldBoxCoordinate.Row, oldBoxCoordinate.Column, newBoxCoordinate.Row, newBoxCoordinate.Column);
 }
 private bool IsBoxIndependent(Coordinate2D coord, params Coordinate2D[] coords)
 {
     foreach (Coordinate2D neighbor in coord.EightNeighbors)
     {
         if (level.IsWall(neighbor))
         {
             return false;
         }
     }
     foreach (Coordinate2D otherCoord in coords)
     {
         if (otherCoord != coord && Coordinate2D.GetDiagonalDistance(coord, otherCoord) <= 1)
         {
             return false;
         }
     }
     return true;
 }
Beispiel #59
0
        static int Main(string[] args)
        {
            _time = Stopwatch.StartNew();

            var options = new Options();

            Parser.Default.ParseArguments <Options>(args).WithParsed(o =>
            {
                options        = o;
                options.Loaded = true;
            });

            if (!options.Loaded)
            {
                return(-1);
            }

            // Parameter Validation
            try
            {
                if (options.LimitX != null)
                {
                    var splittedLimit = options.LimitX.Split(',').Select(x => Convert.ToInt32(x)).OrderBy(x => x).ToArray();
                    if (splittedLimit.Length != 2)
                    {
                        throw new ArgumentOutOfRangeException("LimitX");
                    }
                    options.LimitXLow  = splittedLimit[0];
                    options.LimitXHigh = splittedLimit[1];
                }
            }
            catch (Exception)
            {
                Console.WriteLine($"The value '{options.LimitX}' for the LimitZ parameter is not valid. Try something like -10,10");
                return(-1);
            }

            try
            {
                if (options.LimitZ != null)
                {
                    var splittedLimit = options.LimitZ.Split(',').Select(x => Convert.ToInt32(x)).OrderBy(x => x).ToArray();
                    if (splittedLimit.Length != 2)
                    {
                        throw new ArgumentOutOfRangeException("LimitZ");
                    }
                    options.LimitZLow  = splittedLimit[0];
                    options.LimitZHigh = splittedLimit[1];
                }
            }
            catch (Exception)
            {
                Console.WriteLine($"The value '{options.LimitZ}' for the LimitZ parameter is not valid. Try something like -10,10");
                return(-1);
            }

            var world = new World();

            try
            {
                Console.WriteLine("Opening world...");
                world.Open(options.MinecraftWorld);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Could not open world at '{options.MinecraftWorld}'!. Did you specify the .../db folder?");
                Console.WriteLine("The reason was:");
                Console.WriteLine(ex.Message);
                return(-1);
            }



            // Start Generation
            int xmin = 0;
            int xmax = 0;
            int zmin = 0;
            int zmax = 0;
            HashSet <UInt64> hashedCoordinateKeys = null;

            if (options.LimitXLow.HasValue && options.LimitXHigh.HasValue && options.LimitZHigh.HasValue &&
                options.LimitZLow.HasValue)
            {
                _totalChunk = (options.LimitXHigh.Value - options.LimitXLow.Value + 1) *
                              (options.LimitZHigh.Value - options.LimitZLow.Value + 1);
            }
            else
            {
                Console.WriteLine("Generating a list of all chunk keys in the database.\nThis could take a few minutes");
                var keys = world.ChunkKeys.ToHashSet();

                unchecked
                {
                    hashedCoordinateKeys = keys.Select(x => Coordinate2D.CreateHashKey(x.X, x.Y)).ToHashSet();
                }

                _totalChunk = keys.Count;
                Console.WriteLine($"Total Chunk count {keys.Count}");
                Console.WriteLine();

                xmin = keys.Min(x => x.X);
                xmax = keys.Max(x => x.X);
                zmin = keys.Min(x => x.Y);
                zmax = keys.Max(x => x.Y);

                Console.WriteLine($"The total dimensions of the map are");
                Console.WriteLine($"  X: {xmin} to {xmax}");
                Console.WriteLine($"  Z: {zmin} to {zmax}");
                Console.WriteLine();
            }

            if (options.LimitXLow.HasValue && options.LimitXHigh.HasValue)
            {
                xmin = options.LimitXLow.Value;
                xmax = options.LimitXHigh.Value;
                Console.WriteLine($"Limiting X to {xmin} to {xmax}");
            }
            if (options.LimitZLow.HasValue && options.LimitZHigh.HasValue)
            {
                zmin = options.LimitZLow.Value;
                zmax = options.LimitZHigh.Value;
                Console.WriteLine($"Limiting Z to {zmin} to {zmax}");
            }
            if (options.LimitY > 0)
            {
                Console.WriteLine($"Limiting Y to {options.LimitY}");
            }



            Console.WriteLine("Reading terrain_texture.json...");
            var json     = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"textures", "terrain_texture.json"));
            var ts       = new TerrainTextureJsonParser(json, "");
            var textures = ts.Textures;

            Console.WriteLine();

            const int chunkSize          = 256;
            int       chunksPerDimension = 2;
            int       tileSize           = chunkSize * chunksPerDimension;

            var maxDiameter = Math.Max(Math.Abs(xmax - xmin + 1), Math.Abs(zmax - zmin + 1));

            Console.WriteLine($"The maximum diameter of the map is {maxDiameter}");

            maxDiameter = (maxDiameter + (chunksPerDimension - 1)) / chunksPerDimension;
            Console.WriteLine($"For {chunksPerDimension} chunks per tile, new max diameter is {maxDiameter}");

            var zoom        = (int)(Math.Ceiling(Math.Log(maxDiameter) / Math.Log(2)));
            int extendedDia = (int)Math.Pow(2, zoom);

            Console.WriteLine($"To generate the zoom levels, we expand the diameter to {extendedDia}");
            Console.WriteLine($"This results in {zoom+1} zoom levels");
            List <Exception> exes = new List <Exception>();


            IRenderStrategy strat = null;

            switch (options.Strategy)
            {
            case Strategy.ParallelFor:
                strat = new ParallelForRenderStrategy();
                break;

            case Strategy.SingleFor:
                strat = new SingleForRenderStrategy();
                break;

            default:
                strat = new SingleForRenderStrategy();
                break;
            }

            strat.RenderSettings = new RenderSettings()
            {
                RenderCoords       = options.RenderCoords,
                RenderMode         = options.RenderMode,
                MaxNumberOfThreads = options.MaxNumberOfThreads,
                Keys             = hashedCoordinateKeys,
                YMax             = options.LimitY,
                BrillouinJ       = options.BrillouinJ,
                BrillouinDivider = options.BrillouinDivider
            };
            strat.InitialDiameter    = extendedDia;
            strat.InitialZoomLevel   = (int)zoom;
            strat.World              = world;
            strat.TotalChunkCount    = _totalChunk;
            strat.TexturePath        = Path.Combine(Environment.CurrentDirectory, "textures");
            strat.TextureDictionary  = textures;
            strat.OutputPath         = options.OutputPath;
            strat.TileSize           = tileSize;
            strat.ChunksPerDimension = chunksPerDimension;
            strat.ChunkSize          = chunkSize;
            strat.ZMin            = zmin;
            strat.ZMax            = zmax;
            strat.XMin            = xmin;
            strat.XMax            = xmax;
            strat.ChunksRendered += RenderDisplay;
            strat.RenderInitialLevel();
            var missingTextures = strat.MissingTextures;

            File.WriteAllLines("missingtextures.txt", missingTextures.Distinct());

            strat.ZoomLevelRenderd += RenderZoom;
            strat.RenderZoomLevels();


            try
            {
                var mapHtml = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "map.thtml"));
                mapHtml = mapHtml.Replace("%maxnativezoom%", zoom.ToString());
                mapHtml = mapHtml.Replace("%maxzoom%", (zoom + 2).ToString());
                mapHtml = mapHtml.Replace("%tilesize%", (tileSize).ToString());
                mapHtml = mapHtml.Replace("%factor%", (Math.Pow(2, zoom - 4)).ToString());
                File.WriteAllText(Path.Combine(options.OutputPath, options.MapHtml), mapHtml);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Could not write map.html");
                Console.WriteLine(ex.Message);
            }

            world.Close();

            Console.WriteLine("Total Time {0}", _time.Elapsed);

            return(0);
        }
        public RasterPatch2 GetTilePatch(IDataSource2D<double> field, Box2 regionBox, double iconSize)
        {
            System.Windows.Point[,] grid = field.Grid;

            Coordinate2D minCoordinate = new Coordinate2D(grid[0, 0].X, grid[0, 0].Y);
            Coordinate2D maxCoordinate = new Coordinate2D(grid[field.Width - 1, field.Height - 1].X, grid[field.Width - 1, field.Height - 1].Y);


            for (int j = 0; j < field.Height; j++)
            {
                for (int i = 0; i < field.Width; i++)
                {
                    if (grid[i, j].X < minCoordinate.X)
                        minCoordinate.X = grid[i, j].X;

                    if (grid[i, j].X > maxCoordinate.X)
                        maxCoordinate.X = grid[i, j].X;

                    if (grid[i, j].Y < minCoordinate.Y)
                        minCoordinate.Y = grid[i, j].Y;

                    if (grid[i, j].Y > maxCoordinate.Y)
                        maxCoordinate.Y = grid[i, j].Y;
                }
            }

            GeoRect gridBox = new GeoRect(
                minCoordinate.X,
                minCoordinate.Y,
                maxCoordinate.X - minCoordinate.X,
                maxCoordinate.Y - minCoordinate.Y);

            GeoRect tileBox = new GeoRect(
                regionBox.MinCoordinate.X,
                regionBox.MinCoordinate.Y,
                regionBox.MaxCoordinate.X - regionBox.MinCoordinate.X,
                regionBox.MaxCoordinate.Y - regionBox.MinCoordinate.Y);

            GeoRect intersectionRect = GeoRect.Intersect(gridBox, tileBox);

            if (intersectionRect != null)
            {
                int width = 256;
                int height = 256;
                Bitmap resultBitmap = new Bitmap(width, height);
                Graphics graphics = Graphics.FromImage(resultBitmap);
                for (int i = 0; i < field.Width; i++)
                {
                    for (int j = 0; j < field.Height; j++)
                    {
                        GeoRect workingRect = new GeoRect(
                            field.Grid[i, j].X - iconSize / 2.0,
                            field.Grid[i, j].Y - iconSize / 2.0,
                            iconSize,
                            iconSize);
                        if (GeoRect.IntersectionExist(workingRect, intersectionRect))
                        {
                            int x0 = (int)(Math.Min(width, Math.Max(0, field.Grid[i, j].X - iconSize / 2.0 - tileBox.Left) / tileBox.Width * width));
                            int y0 = (int)(Math.Min(height, Math.Max(0, tileBox.Top - field.Grid[i, j].Y - iconSize / 2.0) / tileBox.Height * height));

                            int x1 = (int)(Math.Min(width, Math.Max(0, field.Grid[i, j].X + iconSize / 2.0 - tileBox.Left) / tileBox.Width * width));
                            int y1 = (int)(Math.Min(height, Math.Max(0, tileBox.Top - field.Grid[i, j].Y + iconSize / 2.0) / tileBox.Height * height));

                            double widthX = Math.Min(tileBox.Width, iconSize);
                            double heightY = Math.Min(tileBox.Height, iconSize);


                            lock (icon)
                            {
                                int x2 = 0;
                                if (field.Grid[i, j].X - iconSize / 2.0 < tileBox.Left)
                                {
                                    x2 = icon.Width - (int)((double)(x1 - x0) * icon.Width / (widthX / tileBox.Width * width));
                                }

                                int y2 = 0;
                                if (tileBox.Top - field.Grid[i, j].Y - iconSize / 2.0 < 0)
                                {
                                    y2 = icon.Height - (int)((double)(y1 - y0) * icon.Height / (heightY / tileBox.Height * height));
                                }

                                graphics.DrawImage(
                                    icon,
                                    new Rectangle(x0, y0, x1 - x0, y1 - y0),
                                    x2,
                                    y2,
                                    (int)((double)(x1 - x0) * icon.Width / (widthX / tileBox.Width * width)),
                                    (int)((double)(y1 - y0) * icon.Height / (heightY / tileBox.Height * height)),
                                    GraphicsUnit.Pixel);
                            }
                        }

                    }
                }
                return new RasterPatch2(
                    regionBox,
                    resultBitmap,
                    Wgs84CoordinateReferenceSystem.Instance);
            }
            else
            {
                return null;
            }
        }