Exemple #1
0
        public static void Generate(IMapGrid map, Params param)
        {
            m_params = param;
            map.Init();

            // round block
            for (int x = 0; x < map.Width; x++)
                for (int y = 0; y < map.Height; y++)
                    if (x == 0 || y == 0 || x == (map.Width - 1) || y == (map.Height - 1))
                        map.SetID (x, y, MapGridTypes.ID.Blocked);
                    else
                        map.SetID (x, y, MapGridTypes.ID.Empty);

            // create rooms
            PlaceRooms(map);

            // create corridors
            PlaceCorridors(map);

            // place stairs
            PlaceStairs(map);

            // remove dead ends
            if (m_params.RemoveDeadEnd)
                RemoveDeadEnds(map);

            // final cleanup
            Cleanup(map);
        }
Exemple #2
0
            // Serialization
            public void RegisterGrid(IMapGrid grid)
            {
                if (GridIDMap.ContainsKey(grid.Index))
                {
                    throw new InvalidOperationException();
                }

                Grids.Add(grid);
                GridIDMap.Add(grid.Index, GridIDMap.Count);
            }
 public bool TryGetGrid(GridId gridId, out IMapGrid grid)
 {
     if (_grids.TryGetValue(gridId, out var gridinterface))
     {
         grid = gridinterface;
         return(true);
     }
     grid = null;
     return(false);
 }
 private void btnDelete_Click(object sender, EventArgs e)
 {
     if (this.checkedListBox1.SelectedIndex != -1)
     {
         IMapGrid mapGrid = (this.checkedListBox1.SelectedItem as MapGridWrap).MapGrid;
         this.imapGrids_0.DeleteMapGrid(mapGrid);
         this.checkedListBox1.Items.RemoveAt(this.checkedListBox1.SelectedIndex);
         (this.ipageLayout_0 as IActiveView).Refresh();
     }
 }
Exemple #5
0
        public void _setChunkDirty(IMapGrid grid, MapIndices chunk)
        {
            var data = _mapChunkData[grid.Index];

            if (data.TryGetValue(chunk, out var datum))
            {
                datum.Dirty = true;
            }
            // Don't need to set it if we don't have an entry since lack of an entry is treated as dirty.
        }
Exemple #6
0
        public async Task NoSuffocationTest()
        {
            var options = new ServerContentIntegrationOption {
                ExtraPrototypes = Prototypes
            };
            var server = StartServer(options);

            await server.WaitIdleAsync();

            var mapLoader     = server.ResolveDependency <IMapLoader>();
            var mapManager    = server.ResolveDependency <IMapManager>();
            var entityManager = server.ResolveDependency <IEntityManager>();

            MapId               mapId;
            IMapGrid            grid       = null;
            RespiratorComponent respirator = null;
            EntityUid           human      = default;

            var testMapName = "Maps/Test/Breathing/3by3-20oxy-80nit.yml";

            await server.WaitPost(() =>
            {
                mapId = mapManager.CreateMap();
                grid  = mapLoader.LoadBlueprint(mapId, testMapName);
            });

            Assert.NotNull(grid, $"Test blueprint {testMapName} not found.");

            await server.WaitAssertion(() =>
            {
                var center      = new Vector2(0.5f, -1.5f);
                var coordinates = new EntityCoordinates(grid.GridEntityId, center);
                human           = entityManager.SpawnEntity("HumanBodyAndBloodstreamDummy", coordinates);

                Assert.True(entityManager.HasComponent <SharedBodyComponent>(human));
                Assert.True(entityManager.TryGetComponent(human, out respirator));
                Assert.False(respirator.Suffocating);
            });

            var increment = 10;


            for (var tick = 0; tick < 600; tick += increment)
            {
                await server.WaitRunTicks(increment);

                await server.WaitAssertion(() =>
                {
                    Assert.False(respirator.Suffocating, $"Entity {entityManager.GetComponent<MetaDataComponent>(human).EntityName} is suffocating on tick {tick}");
                });
            }

            await server.WaitIdleAsync();
        }
Exemple #7
0
        private void _updateChunkMesh(IMapGrid grid, IMapChunk chunk)
        {
            var data = _mapChunkData[grid.Index];

            if (!data.TryGetValue(chunk.Indices, out var datum))
            {
                datum = _initChunkBuffers(grid, chunk);
            }

            var vertexPool = ArrayPool <Vertex2D> .Shared;
            var indexPool  = ArrayPool <ushort> .Shared;

            var vertexBuffer = vertexPool.Rent(_verticesPerChunk(chunk));
            var indexBuffer  = indexPool.Rent(_indicesPerChunk(chunk));

            try
            {
                var i = 0;
                foreach (var tile in chunk)
                {
                    var regionMaybe = _tileDefinitionManager.TileAtlasRegion(tile.Tile);
                    if (regionMaybe == null)
                    {
                        continue;
                    }

                    var region = regionMaybe.Value;

                    var vIdx = i * 4;
                    vertexBuffer[vIdx + 0] = new Vertex2D(tile.X, tile.Y, region.Left, region.Bottom);
                    vertexBuffer[vIdx + 1] = new Vertex2D(tile.X + 1, tile.Y, region.Right, region.Bottom);
                    vertexBuffer[vIdx + 2] = new Vertex2D(tile.X + 1, tile.Y + 1, region.Right, region.Top);
                    vertexBuffer[vIdx + 3] = new Vertex2D(tile.X, tile.Y + 1, region.Left, region.Top);
                    var nIdx = i * GetQuadBatchIndexCount();
                    var tIdx = (ushort)(i * 4);
                    QuadBatchIndexWrite(indexBuffer, ref nIdx, tIdx);
                    i += 1;
                }

                GL.BindVertexArray(datum.VAO);
                CheckGlError();
                datum.EBO.Use();
                datum.VBO.Use();
                datum.EBO.Reallocate(new Span <ushort>(indexBuffer, 0, i * GetQuadBatchIndexCount()));
                datum.VBO.Reallocate(new Span <Vertex2D>(vertexBuffer, 0, i * 4));
                datum.Dirty     = false;
                datum.TileCount = i;
            }
            finally
            {
                vertexPool.Return(vertexBuffer);
                indexPool.Return(indexBuffer);
            }
        }
Exemple #8
0
        /// <summary>
        /// Tests whether the prototype is going to conflict with anything previously placed in this location on the snap grid
        /// </summary>
        public bool CanSpawnAt(IMapGrid grid, Vector2 position)
        {
            if (!grid.OnSnapCenter(position) && !grid.OnSnapBorder(position)) //We only check snap position logic at this time, extensible for other behavior
            {
                return(true);
            }
            var entitymanager = IoCManager.Resolve <IEntityManager>();
            var entities      = entitymanager.GetEntitiesAt(position);

            return(!entities.SelectMany(e => e.Prototype._snapFlags).Any(f => _snapFlags.Contains(f)));
        }
        public async Task SpawnTest()
        {
            var server = StartServerDummyTicker();
            await server.WaitIdleAsync();

            var      mapMan       = server.ResolveDependency <IMapManager>();
            var      entityMan    = server.ResolveDependency <IEntityManager>();
            var      prototypeMan = server.ResolveDependency <IPrototypeManager>();
            var      mapLoader    = server.ResolveDependency <IMapLoader>();
            var      pauseMan     = server.ResolveDependency <IPauseManager>();
            var      prototypes   = new List <EntityPrototype>();
            IMapGrid grid         = default;
            IEntity  testEntity;

            //Build up test environment
            server.Post(() =>
            {
                var mapId = mapMan.CreateMap();
                pauseMan.AddUninitializedMap(mapId);
                grid = mapLoader.LoadBlueprint(mapId, "Maps/stationstation.yml");
            });

            server.Assert(() =>
            {
                var testLocation = new GridCoordinates(new Vector2(0, 0), grid);

                //Generate list of non-abstract prototypes to test
                foreach (var prototype in prototypeMan.EnumeratePrototypes <EntityPrototype>())
                {
                    if (prototype.Abstract)
                    {
                        continue;
                    }

                    prototypes.Add(prototype);
                }

                //Iterate list of prototypes to spawn
                foreach (var prototype in prototypes)
                {
                    Assert.DoesNotThrow(() =>
                    {
                        Logger.LogS(LogLevel.Debug, "EntityTest", $"Testing: {prototype.ID}");
                        testEntity = entityMan.SpawnEntity(prototype.ID, testLocation);
                        server.RunTicks(2);
                        Assert.That(testEntity.Initialized);
                        entityMan.DeleteEntity(testEntity.Uid);
                    }, "Entity '{0}' threw an exception.",
                                        prototype.ID);
                }
            });

            await server.WaitIdleAsync();
        }
Exemple #10
0
        private (float x, float y) TransformLocalPosition(Vector2 position, IMapGrid grid)
        {
            var xOffset  = (int)Math.Abs(grid.LocalBounds.Left);
            var yOffset  = (int)Math.Abs(grid.LocalBounds.Bottom);
            var tileSize = grid.TileSize;

            var x = ((float)Math.Floor(position.X) + xOffset) * tileSize * TilePainter.TileImageSize;
            var y = ((float)Math.Floor(position.Y) + yOffset) * tileSize * TilePainter.TileImageSize;

            return(x, y);
        }
        /// <summary>
        ///     Spawns a spotlight ground turret that will track any living entities in range.
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="localPosition"></param>
        public static void SpawnLightTurret(IMapGrid grid, Vector2 localPosition)
        {
            var entMan = IoCManager.Resolve <IServerEntityManager>();
            var tBase  = entMan.SpawnEntity("TurretBase");

            tBase.GetComponent <IServerTransformComponent>().LocalPosition = new LocalCoordinates(localPosition, grid);

            var tTop = entMan.SpawnEntity("TurretTopLight");

            tTop.GetComponent <IServerTransformComponent>().LocalPosition = new LocalCoordinates(localPosition, grid);
            tTop.GetComponent <IServerTransformComponent>().AttachParent(tBase);
        }
Exemple #12
0
        private void btnNext_Click(object sender, EventArgs e)
        {
            switch (this.short_0)
            {
            case 1:
                this.m_pMapGrid = this.mapGridTypeProperty_0.CreateMapGrid();
                this.mapGridStylePropertyPage_0.MapGrid = this.m_pMapGrid;
                if (!(this.m_pMapGrid is IIndexGrid))
                {
                    this.mapGridCoordinatePropertyPage_0.MapGrid = this.m_pMapGrid;
                    break;
                }
                this.indexGridLabelPropertyPage_0.MapGrid = this.m_pMapGrid;
                break;

            case 2:
                if (!this.mapGridStylePropertyPage_0.Do())
                {
                    return;
                }
                this.mapGridStylePropertyPage_0.Visible = false;
                if (this.m_pMapGrid is IIndexGrid)
                {
                    this.indexGridLabelPropertyPage_0.Visible = true;
                    this.indexGridLabelPropertyPage_0.Init();
                }
                else
                {
                    this.mapGridCoordinatePropertyPage_0.Visible = true;
                    this.mapGridCoordinatePropertyPage_0.Init();
                }
                goto Label_0166;

            case 3:
                this.indexGridLabelPropertyPage_0.Visible    = false;
                this.mapGridCoordinatePropertyPage_0.Visible = false;
                this.mapGridBorderPropertyPage_0.Visible     = true;
                this.mapGridBorderPropertyPage_0.Init();
                this.btnNext.Visible = false;
                this.btnOK.Visible   = true;
                goto Label_0166;

            default:
                goto Label_0166;
            }
            this.mapGridBorderPropertyPage_0.MapGrid = this.m_pMapGrid;
            this.mapGridCoordinatePropertyPage_0.Init();
            this.mapGridTypeProperty_0.Visible      = false;
            this.mapGridStylePropertyPage_0.Visible = true;
            this.btnLast.Enabled = true;
Label_0166:
            this.short_0 = (short)(this.short_0 + 1);
        }
        private void SpawnPulse(IMapGrid mapGrid)
        {
            if (!TryFindRandomGrid(mapGrid, out var coordinates))
            {
                return;
            }

            var pulse = _entityManager.SpawnEntity("RadiationPulse", coordinates);

            pulse.GetComponent <RadiationPulseComponent>().DoPulse();
            ResetTimeUntilPulse();
        }
    private static PuddleComponent?GetPuddle(IEntityManager entityManager, IMapGrid mapGrid, Vector2i pos)
    {
        foreach (var uid in mapGrid.GetAnchoredEntities(pos))
        {
            if (entityManager.TryGetComponent(uid, out PuddleComponent puddleComponent))
            {
                return(puddleComponent);
            }
        }

        return(null);
    }
Exemple #15
0
        public IMapGrid CreateMapGrid(int int_0)
        {
            IMapGrid grid = null;

            switch (int_0)
            {
            case 0:
                grid = new GraticuleClass();
                break;

            case 1:
                grid = new MeasuredGridClass();
                break;

            case 2:
                grid = new IndexGridClass();
                break;
            }
            if (grid == null)
            {
                return(null);
            }
            grid.SetDefaults(this.m_pMapFrame);
            grid.LineSymbol = null;
            IMarkerSymbol symbol = new SimpleMarkerSymbolClass();

            (symbol as ISimpleMarkerSymbol).Style = esriSimpleMarkerStyle.esriSMSCross;
            grid.TickMarkSymbol = symbol;
            if (grid is IMeasuredGrid)
            {
                IFormattedGridLabel label  = new FormattedGridLabelClass();
                INumericFormat      format = new NumericFormatClass
                {
                    AlignmentOption = esriNumericAlignmentEnum.esriAlignLeft,
                    AlignmentWidth  = 0,
                    RoundingOption  = esriRoundingOptionEnum.esriRoundNumberOfDecimals,
                    RoundingValue   = 3,
                    ShowPlusSign    = true,
                    UseSeparator    = true,
                    ZeroPad         = true
                };
                label.Format = format as INumberFormat;
                (label as IGridLabel).LabelOffset = 6.0;
                grid.LabelFormat = label as IGridLabel;
                IEnvelope mapBounds = this.m_pMapFrame.MapBounds;
                (grid as IMeasuredGrid).FixedOrigin = true;
                (grid as IMeasuredGrid).XOrigin     = mapBounds.XMin + 500.0;
                (grid as IMeasuredGrid).YOrigin     = mapBounds.YMin + 500.0;
                grid.SetTickVisibility(false, false, false, false);
                grid.SetSubTickVisibility(false, false, false, false);
            }
            return(grid);
        }
    public bool NeedsVacuumFixing(IMapGrid mapGrid, Vector2i indices)
    {
        var value = false;

        var enumerator = GetObstructingComponentsEnumerator(mapGrid, indices);

        while (enumerator.MoveNext(out var airtight))
        {
            value |= airtight.FixVacuum;
        }

        return(value);
    }
        public void Initialize(IMapGrid mapGrid)
        {
            for (var x = 0; x < ChunkSize; x++)
            {
                for (var y = 0; y < ChunkSize; y++)
                {
                    var tileRef = mapGrid.GetTileRef(new MapIndices(x + _indices.X, y + _indices.Y));
                    CreateNode(tileRef);
                }
            }

            Dirty();
        }
Exemple #18
0
        /// <inheritdoc />
        public IMapGrid FindGridAt(Vector2 worldPos)
        {
            IMapGrid grid = GetDefaultGrid();

            foreach (var kvGrid in _grids)
            {
                if (kvGrid.Value.AABBWorld.Contains(worldPos) && kvGrid.Value.Index != GridId.DefaultGrid)
                {
                    grid = kvGrid.Value;
                }
            }
            return(grid);
        }
 /// <summary>
 ///     Finds the grid at this world coordinate
 /// </summary>
 /// <param name="WorldPos">The X coordinate in the world.</param>
 public bool TryFindGridAt(Vector2 worldPos, out IMapGrid currentgrid)
 {
     foreach (var kvGrid in _grids)
     {
         if (kvGrid.Value.AABBWorld.Contains(worldPos))
         {
             currentgrid = kvGrid.Value;
             return(true);
         }
     }
     currentgrid = GetDefaultGrid();
     return(false);
 }
Exemple #20
0
        public async Task NoSuffocationTest()
        {
            var options = new ServerContentIntegrationOption {
                ExtraPrototypes = Prototypes
            };
            var server = StartServerDummyTicker(options);

            await server.WaitIdleAsync();

            var mapLoader     = server.ResolveDependency <IMapLoader>();
            var mapManager    = server.ResolveDependency <IMapManager>();
            var entityManager = server.ResolveDependency <IEntityManager>();

            MapId               mapId;
            IMapGrid            grid       = null;
            MetabolismComponent metabolism = null;
            IEntity             human      = null;

            var testMapName = "Maps/Test/Breathing/3by3-20oxy-80nit.yml";

            await server.WaitPost(() =>
            {
                mapId = mapManager.CreateMap();
                grid  = mapLoader.LoadBlueprint(mapId, testMapName);
            });

            Assert.NotNull(grid, $"Test blueprint {testMapName} not found.");

            await server.WaitAssertion(() =>
            {
                var center      = new Vector2(0.5f, -1.5f);
                var coordinates = new EntityCoordinates(grid.GridEntityId, center);
                human           = entityManager.SpawnEntity("HumanBodyAndBloodstreamDummy", coordinates);

                Assert.True(human.TryGetComponent(out SharedBodyComponent body));
                Assert.True(body.HasMechanismBehavior <LungBehavior>());
                Assert.True(human.TryGetComponent(out metabolism));
                Assert.False(metabolism.Suffocating);
            });

            var increment = 10;

            for (var tick = 0; tick < 600; tick += increment)
            {
                await server.WaitRunTicks(increment);

                Assert.False(metabolism.Suffocating, $"Entity {human.Name} is suffocating on tick {tick}");
            }

            await server.WaitIdleAsync();
        }
Exemple #21
0
        public async Task TestCollisionWakeGrid()
        {
            var options = new ServerIntegrationOptions {
                ExtraPrototypes = Prototype
            };

            options.CVarOverrides["physics.timetosleep"] = "0.0";
            var server = StartServer(options);
            await server.WaitIdleAsync();

            var entManager = server.ResolveDependency <IEntityManager>();
            var mapManager = server.ResolveDependency <IMapManager>();

            IMapGrid         grid    = default !;
Exemple #22
0
        /// <inheritdoc />
        public IMapGrid FindGridAt(LocalCoordinates worldPos)
        {
            var      pos  = worldPos.ToWorld().Position;
            IMapGrid grid = GetDefaultGrid();

            foreach (var kvGrid in _grids)
            {
                if (kvGrid.Value.AABBWorld.Contains(pos) && kvGrid.Value.Index != GridId.DefaultGrid)
                {
                    grid = kvGrid.Value;
                }
            }
            return(grid);
        }
Exemple #23
0
        internal override void CalculateNewSprite(IMapGrid grid)
        {
            base.CalculateNewSprite(grid);

            var(cornerNE, cornerNW, cornerSW, cornerSE) = CalculateCornerFill(grid);

            if (Sprite != null)
            {
                Sprite.LayerSetState(ReinforcedCornerLayers.NE, $"{_reinforcedStateBase}{(int) cornerNE}");
                Sprite.LayerSetState(ReinforcedCornerLayers.SE, $"{_reinforcedStateBase}{(int) cornerSE}");
                Sprite.LayerSetState(ReinforcedCornerLayers.SW, $"{_reinforcedStateBase}{(int) cornerSW}");
                Sprite.LayerSetState(ReinforcedCornerLayers.NW, $"{_reinforcedStateBase}{(int) cornerNW}");
            }
        }
        private YamlSequenceNode SaveBpNode(IMapGrid grid)
        {
            var root = new YamlSequenceNode();

            var node = YamlGridSerializer.SerializeGrid(grid);

            root.Add(node);

            var ents = new YamlEntitySerializer();

            _entityMan.SaveGridEntities(ents, grid.Index);
            root.Add(ents.GetRootNode());
            return(root);
        }
Exemple #25
0
        public async Task LoadSaveTicksSaveSaltern()
        {
            var server = StartServerDummyTicker();
            await server.WaitIdleAsync();

            var mapLoader  = server.ResolveDependency <IMapLoader>();
            var mapManager = server.ResolveDependency <IMapManager>();
            var pauseMgr   = server.ResolveDependency <IPauseManager>();

            IMapGrid grid = default;

            // Load stationstation.yml as uninitialized map, and save it to ensure it's up to date.
            server.Post(() =>
            {
                var mapId = mapManager.CreateMap();
                pauseMgr.AddUninitializedMap(mapId);
                pauseMgr.SetMapPaused(mapId, true);
                grid = mapLoader.LoadBlueprint(mapId, "Maps/saltern.yml");
                mapLoader.SaveBlueprint(grid.Index, "load save ticks save 1.yml");
            });

            // Run 5 ticks.
            server.RunTicks(5);

            server.Post(() =>
            {
                mapLoader.SaveBlueprint(grid.Index, "/load save ticks save 2.yml");
            });

            await server.WaitIdleAsync();

            var userData = server.ResolveDependency <IResourceManager>().UserData;

            string one;
            string two;

            using (var stream = userData.Open(new ResourcePath("/load save ticks save 1.yml"), FileMode.Open))
                using (var reader = new StreamReader(stream))
                {
                    one = reader.ReadToEnd();
                }

            using (var stream = userData.Open(new ResourcePath("/load save ticks save 2.yml"), FileMode.Open))
                using (var reader = new StreamReader(stream))
                {
                    two = reader.ReadToEnd();
                }

            Assert.That(one, Is.EqualTo(two));
        }
        public async Task Test()
        {
            var options = new ServerIntegrationOptions {
                ExtraPrototypes = Prototypes
            };
            var server = StartServerDummyTicker(options);

            IEntity generator = null;

            IMapGrid grid1 = null;
            IMapGrid grid2 = null;

            // Create grids
            server.Assert(() =>
            {
                var mapMan = IoCManager.Resolve <IMapManager>();

                mapMan.CreateMap(new MapId(1));
                grid1 = mapMan.CreateGrid(new MapId(1));
                grid2 = mapMan.CreateGrid(new MapId(1));

                var entityMan = IoCManager.Resolve <IEntityManager>();

                generator = entityMan.SpawnEntity("GravityGeneratorDummy", grid2.ToCoordinates());
                Assert.That(generator.HasComponent <GravityGeneratorComponent>());
                Assert.That(generator.HasComponent <ApcPowerReceiverComponent>());
                var generatorComponent = generator.GetComponent <GravityGeneratorComponent>();
                var powerComponent     = generator.GetComponent <ApcPowerReceiverComponent>();
                Assert.That(generatorComponent.Status, Is.EqualTo(GravityGeneratorStatus.Unpowered));
                powerComponent.NeedsPower = false;
            });
            server.RunTicks(1);

            server.Assert(() =>
            {
                var generatorComponent = generator.GetComponent <GravityGeneratorComponent>();

                Assert.That(generatorComponent.Status, Is.EqualTo(GravityGeneratorStatus.On));

                var entityMan   = IoCManager.Resolve <IEntityManager>();
                var grid1Entity = entityMan.GetEntity(grid1.GridEntityId);
                var grid2Entity = entityMan.GetEntity(grid2.GridEntityId);

                Assert.That(!grid1Entity.GetComponent <GravityComponent>().Enabled);
                Assert.That(grid2Entity.GetComponent <GravityComponent>().Enabled);
            });

            await server.WaitIdleAsync();
        }
Exemple #27
0
        public void Run(Image gridCanvas, IMapGrid grid)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            if (!_entities.TryGetValue(grid.Index, out var entities))
            {
                Console.WriteLine($"No entities found on grid {grid.Index}");
                return;
            }

            _entityPainter.Run(gridCanvas, entities);
            Console.WriteLine($"{nameof(GridPainter)} painted grid {grid.Index} in {(int) stopwatch.Elapsed.TotalMilliseconds} ms");
        }
Exemple #28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MappedRover"/> class on
        /// the given map at the specified coordinates.
        /// </summary>
        /// <param name="map">Map to place rover on</param>
        /// <param name="x">Initial X coordinate</param>
        /// <param name="y">Initial Y coordinate</param>
        /// <param name="direction">Initial direction to face; defaults to
        /// North if not specified.</param>
        /// <exception cref="InvalidOperationException"></exception>
        public MappedRover(IMapGrid map, int x, int y,
                           Direction direction = Direction.North)
        {
            _map        = map;
            XCoordinate = x;
            YCoordinate = y;
            Direction   = direction;

            // Verify that the rover is in a valid position
            if (!map.ContainsPoint(XCoordinate, YCoordinate))
            {
                throw new InvalidOperationException("Rover was placed outside" +
                                                    " of map boundaries");
            }
        }
Exemple #29
0
        public static IEnumerable <Node> GetNodesInTile(IComponentManager compMgr, IMapGrid grid, Vector2i coords)
        {
            foreach (var entityUid in grid.GetAnchoredEntities(coords))
            {
                if (!compMgr.TryGetComponent(entityUid, out NodeContainerComponent? container))
                {
                    continue;
                }

                foreach (var node in container.Nodes.Values)
                {
                    yield return(node);
                }
            }
        }
        /// <summary>
        ///     Finds the grid at this world coordinate
        /// </summary>
        /// <param name="xWorld">The X coordinate in the world.</param>
        /// <param name="yWorld">The Y coordinate in the world.</param>
        public bool TryFindGridAt(float xWorld, float yWorld, out IMapGrid currentgrid)
        {
            var pos = new Vector2(xWorld, yWorld);

            foreach (var kvGrid in _grids)
            {
                if (kvGrid.Value.AABBWorld.Contains(pos))
                {
                    currentgrid = kvGrid.Value;
                    return(true);
                }
            }
            currentgrid = GetDefaultGrid();
            return(false);
        }
Exemple #31
0
        /// <summary>
        /// Occurs when this command is clicked
        /// </summary>
        public override void OnClick()
        {
            IGraphicsContainer gc = m_PageLayControl.ActiveView.GraphicsContainer;

            IMap map = m_PageLayControl.ActiveView.FocusMap;

            IMapFrame       mf = gc.FindFrame(map) as IMapFrame;
            IMapGridFactory ipMapGridFactory = new MeasuredGridFactoryClass();
            IMapGrid        mg  = ipMapGridFactory.Create(mf);
            IMapGrids       mgs = mf as IMapGrids;

            mgs.AddMapGrid(mg);
            m_PageLayControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics,
                                                       null, null);
        }
Exemple #32
0
        static void CleanupTunnel(IMapGrid map, int x, int y)
        {
            if (map.GetID(x, y) != MapGridTypes.ID.Tunnel && map.GetID(x, y) != MapGridTypes.ID.TunnelEnd)
                return;

            int tuncells = map.GetBCross(x, y).Count(e => e.Type == MapGridTypes.ID.Tunnel);
            int empty = map.GetBCross(x, y).Count (e => e.Type == MapGridTypes.ID.Empty || e.Type == MapGridTypes.ID.Blocked);

            if (tuncells != 1 || empty != 3)
                return;

            var all_dirs = Enum.GetValues (typeof(Direction)).Cast<Direction> ().ToList ();
            foreach (var dir in all_dirs) {
                map.SetID (x, y, MapGridTypes.ID.Empty);
                if (dir == Direction.Up) CleanupTunnel (map, x, y - 1);
                if (dir == Direction.Right) CleanupTunnel (map, x + 1, y);
                if (dir == Direction.Down) CleanupTunnel (map, x, y + 1);
                if (dir == Direction.Left) CleanupTunnel (map, x - 1, y);
            }
        }
Exemple #33
0
        static void Cleanup(IMapGrid map)
        {
            // cleanup empty
            for (int x = 0; x < map.Width; x++) {
                for (int y = 0; y < map.Height; y++) {
                    if (map.GetID(x, y) == MapGridTypes.ID.Empty)
                        map.SetID (x, y, MapGridTypes.ID.Blocked);
                    if (map.GetID(x, y) == MapGridTypes.ID.TunnelEnd)
                        map.SetID (x, y, MapGridTypes.ID.Tunnel);
                }
            }

            // cleanup tunnels
            for (int x = 0; x < map.Width; x++) {
                for (int y = 0; y < map.Height; y++) {
                    if (map.GetID(x, y) == MapGridTypes.ID.Tunnel) {
                        if (!map.GetBBox(x, y).Any(z => z.Type != MapGridTypes.ID.Blocked))
                            map.SetID (x, y, MapGridTypes.ID.Blocked);
                    }
                }
            }
        }
Exemple #34
0
        static List<MapGridTypes.Room> GetRooms(IMapGrid map)
        {
            int roomId = 0;
            List<MapGridTypes.Room> sills = new List<MapGridTypes.Room> ();

            for (int i = 0; i < map.Width/2; i++) {
                for (int j = 0; j < map.Height/2; j++) {
                    MapGridTypes.Room r = new MapGridTypes.Room(new Point(i*2 + 1, j*2 + 1), ++roomId);
                    r.Width = Math.Max (m_params.RoomMinSize, Utils.Rand.Next (m_params.RoomMaxSize/2)*2 + 1);
                    r.Height = Math.Max (m_params.RoomMinSize, Utils.Rand.Next (m_params.RoomMaxSize/2)*2 + 1);

                    bool isFree = true;
                    for (int x = r.Pos.X - 3; x < (r.Pos.X + r.Width + 3) && isFree; x++)
                        for (int y = r.Pos.Y - 3; y <  (r.Pos.Y + r.Height + 3) && isFree; y++)
                            isFree = (map.GetID(x, y) == MapGridTypes.ID.Empty);

                    if (isFree) {
                        for (int x = r.Pos.X - 1; x < (r.Pos.X + r.Width + 1); x++)
                            for (int y = r.Pos.Y - 1; y <  (r.Pos.Y + r.Height + 1); y++)
                                map.SetID (x, y, MapGridTypes.ID.Sill);

                        sills.Add(r);
                    }
                }
            }

            for (int x = 0; x < map.Width; x++)
                for (int y = 0; y < map.Height; y++)
                    if (map.GetID(x, y) == MapGridTypes.ID.Sill)
                        map.SetID (x, y, MapGridTypes.ID.Empty);

            return sills;
        }
Exemple #35
0
        static void OpenCorridor(IMapGrid map, int i, int j, Direction last_dir)
        {
            var all_dirs = Enum.GetValues(typeof(Direction)).Cast<Direction>().ToList();
            var dirs = new List<Direction>();

            all_dirs.Shuffle();
            if (Utils.Rand.Next (100) < m_params.TunnelsCurveWeight) dirs.Add(last_dir);
            dirs.AddRange(all_dirs.Where(x => !dirs.Contains(x)));

            foreach (var dir in dirs)
            {
                int xs = i*2 + 1;
                int ys = j*2 + 1;
                int xe = xs;
                int ye = ys;
                int xm = xs;
                int ym = ys;

                if (dir == Direction.Right) { xe = (i + 1)*2 + 1; xm = (i + 1)*2; } // right
                if (dir == Direction.Down) { ye = (j + 1)*2 + 1; ym = (j + 1)*2; } // down
                if (dir == Direction.Left) { xe = (i - 1)*2 + 1; xm = i*2; } // left
                if (dir == Direction.Up) { ye = (j - 1)*2 + 1; ym = j*2; } // up

                if ((map.GetID (xs, ys) == MapGridTypes.ID.Empty
                     || map.GetID (xs, ys) == MapGridTypes.ID.TunnelEnd
                     || map.GetID (xs, ys) == MapGridTypes.ID.Tunnel)
                    && map.GetID (xm, ym) == MapGridTypes.ID.Empty
                    && (map.GetID (xe, ye) == MapGridTypes.ID.Empty || map.GetID (xe, ye) == MapGridTypes.ID.Door))
                {
                    if (map.GetID (xs, ys) == MapGridTypes.ID.Empty)
                        map.SetID (xs, ys, MapGridTypes.ID.TunnelEnd);
                    else
                        map.SetID (xs, ys, MapGridTypes.ID.Tunnel);

                    if (map.GetID (xe, ye) == MapGridTypes.ID.Empty) {
                        map.SetID (xm, ym, MapGridTypes.ID.Tunnel);
                        map.SetID (xe, ye, MapGridTypes.ID.TunnelEnd);
                    }
                    else
                        map.SetID (xm, ym, MapGridTypes.ID.TunnelEnd);

                    if (dir == Direction.Right) i++;
                    if (dir == Direction.Down) j++;
                    if (dir == Direction.Left) i--;
                    if (dir == Direction.Up) j--;

                    OpenCorridor(map, i, j, dir);
                }
            }
        }
Exemple #36
0
        static void PlaceStairs(IMapGrid map)
        {
            List<Point> ends = new List<Point> ();

            for (int x = 0; x < map.Width; x++)
                for (int y = 0; y < map.Height; y++)
                    if (map.GetID(x, y) == MapGridTypes.ID.TunnelEnd)
                        ends.Add (new Point () { X = x, Y = y });

            ends.Shuffle ();

            map.StairUp = ends [0];
            map.StairDown = map.StairUp;
            foreach (var st in ends) {
                if (Utils.Dist(st, map.StairUp) > Utils.Dist(map.StairDown, map.StairUp))
                    map.StairDown = st;
            }
            map.SetID (map.StairUp.X, map.StairUp.Y,  MapGridTypes.ID.StairUp);
            map.SetID (map.StairDown.X, map.StairDown.Y, MapGridTypes.ID.StairDown);
        }
Exemple #37
0
        static void RemoveDeadEnds(IMapGrid map)
        {
            for (int i = 0; i < map.Width/2; i++) {
                for (int j = 0; j < map.Height/2; j++) {
                    int x = i * 2 + 1;
                    int y = j * 2 + 1;

                    if (map.GetID(x, y) != MapGridTypes.ID.TunnelEnd)
                        continue;

                    CleanupTunnel (map, x, y);
                }
            }
        }
Exemple #38
0
        static void PlaceCorridors(IMapGrid map)
        {
            for (int i = 0; i < map.Width/2; i++) {
                for (int j = 0; j < map.Height/2; j++) {
                    int x = i * 2 + 1;
                    int y = j * 2 + 1;

                    if (map.GetID(x, y) != MapGridTypes.ID.Empty)
                        continue;

                    OpenCorridor (map, i, j, Utils.RandomEnumValue<Direction> ());
                }
            }

            // fixup tunnels end
            for (int x = 0; x < map.Width; x++) {
                for (int y = 0; y < map.Height; y++) {
                    if (map.GetID(x, y) == MapGridTypes.ID.TunnelEnd) {
                        if (map.GetBBox(x, y).Any(z => z.Type == MapGridTypes.ID.Door))
                            map.SetID (x, y, MapGridTypes.ID.Tunnel);
                    }
                }
            }
        }
Exemple #39
0
 public Params(IMapGrid map)
 {
     RoomMaxSize = 7;
     RoomMinSize = 5;
     RoomsNumber = map.Height*map.Width/RoomMaxSize*RoomMinSize;
     TunnelsCurveWeight = 10;
     RemoveDeadEnd = false;
 }
Exemple #40
0
        static void PlaceRooms(IMapGrid map)
        {
            for (int i = 0; i < m_params.RoomsNumber; i++) {
                List<MapGridTypes.Room> sills = GetRooms(map);
                sills.Shuffle();

                if (sills.Count == 0)
                    continue;

                MapGridTypes.Room r = sills.First();

                // alloc room
                for (int x = r.Pos.X - 1; x < (r.Pos.X + r.Width + 1); x++)
                    for (int y = r.Pos.Y - 1; y <  (r.Pos.Y + r.Height + 1); y++)
                        if (x == (r.Pos.X - 1) || x == (r.Pos.X + r.Width) ||
                            y == (r.Pos.Y - 1) || y == (r.Pos.Y + r.Height))
                            map.SetID (x, y, MapGridTypes.ID.Blocked);
                        else
                            map.SetID (x, y, MapGridTypes.ID.Room);

                // open room
                int doors = 2;
                while (doors > 0) {
                    Direction dir = Utils.RandomEnumValue<Direction>();
                    MapGridTypes.Door door = null;
                    if (dir == Direction.Right) { // right
                        int y = r.Pos.Y + Utils.Rand.Next(r.Height/2)*2;
                        if (map.GetID (r.Pos.X + r.Width + 1, y) == MapGridTypes.ID.Empty
                            && map.GetID (r.Pos.X + r.Width + 2, y) == MapGridTypes.ID.Empty
                            && map.GetID (r.Pos.X + r.Width, y - 1) != MapGridTypes.ID.Door
                            && map.GetID (r.Pos.X + r.Width, y + 1) != MapGridTypes.ID.Door) {
                            door = new MapGridTypes.Door (new Point(r.Pos.X + r.Width, y));
                        }
                    }
                    if (dir == Direction.Down) { // down
                        int x = r.Pos.X + Utils.Rand.Next(r.Width/2)*2;
                        if (map.GetID (x, r.Pos.Y + r.Height + 1) == MapGridTypes.ID.Empty
                            && map.GetID (x, r.Pos.Y + r.Height + 2) == MapGridTypes.ID.Empty
                            && map.GetID (x - 1, r.Pos.Y + r.Height) != MapGridTypes.ID.Door
                            && map.GetID (x + 1, r.Pos.Y + r.Height) != MapGridTypes.ID.Door) {
                            door = new MapGridTypes.Door (new Point (x, r.Pos.Y + r.Height));
                        }
                    }
                    if (dir == Direction.Left) { // left
                        int y = r.Pos.Y + Utils.Rand.Next(r.Height/2)*2;
                        if (map.GetID (r.Pos.X - 1, y) == MapGridTypes.ID.Empty
                            && map.GetID (r.Pos.X - 2, y) == MapGridTypes.ID.Empty
                            && map.GetID (r.Pos.X, y - 1) != MapGridTypes.ID.Door
                            && map.GetID (r.Pos.X, y + 1) != MapGridTypes.ID.Door) {
                            door = new MapGridTypes.Door (new Point (r.Pos.X, y));
                        }
                    }
                    if (dir == Direction.Up) { // up
                        int x = r.Pos.X + Utils.Rand.Next(r.Width/2)*2;
                        if (map.GetID (x, r.Pos.Y - 1) == MapGridTypes.ID.Empty
                            && map.GetID (x, r.Pos.Y - 2) == MapGridTypes.ID.Empty
                            && map.GetID (x - 1, r.Pos.Y) != MapGridTypes.ID.Door
                            && map.GetID (x + 1, r.Pos.Y) != MapGridTypes.ID.Door) {
                            door = new MapGridTypes.Door (new Point (x, r.Pos.Y));
                        }
                    }
                    if (door != null) {
                        r.Doors.Add(door);
                        map.SetID (door.Pos.X, door.Pos.Y, MapGridTypes.ID.Door);
                        doors--;
                    }
                }
                map.AddRoom(r);
            }
        }