Beispiel #1
0
 void Start()
 {
     _grid = transform.parent.GetComponent<Grid>();
     _map = transform.parent.GetComponent<TileMap>();
     Coordinates = new IntVec2(-1, -1);
     transform.position = _grid.ToWorld(Coordinates);
 }
Beispiel #2
0
 public Plane2D(IntVec2 from, IntVec2 to)
 {
     Vector2 fromVec = new Vector2(from.X, from.Y);
     Vector2 toVec = new Vector2(to.X, to.Y);
     Vector2 direction = (toVec - fromVec).normalized;
     normal = new Vector2(direction.y, -direction.x);
     offset = normal.x * fromVec.x + normal.y * fromVec.y;
 }
Beispiel #3
0
 public void AddTile(IntVec2 pos, GameObject tile)
 {
     _tiles.Add(pos, tile);
     tile.transform.parent = transform;
     if (OnChange != null)
     {
         OnChange.Invoke(pos, tile);
     }
 }
Beispiel #4
0
    public IntVec2[] FindPath(IntVec2 from, IntVec2 to, bool[,] pathMap, IntVec2[] moveDirections)
    {
        openNodes.Clear();
        closedNodes.Clear();

        Node searchNode = new Node();
        searchNode.point = from;
        bool endReached = false;

        Plane2D directPath = new Plane2D(from, to);

        openNodes.Add(searchNode, 0);

        while (openNodes.Size > 0)
        {
            searchNode = openNodes.Pop();

            if (searchNode.point.Equals(to)) {
                endReached = true;
                break;
            }

            IntVec2 p = searchNode.point;

            foreach (IntVec2 direction in moveDirections)
            {
                IntVec2 newPos = p + direction;
                if (newPos.X >= 0 && newPos.X < pathMap.GetLength(0) &&
                    newPos.Y >= 0 && newPos.Y < pathMap.GetLength(1) &&
                    pathMap[newPos.X, newPos.Y] && !closedNodes.Contains(newPos))
                {
                    AddOpenNode(searchNode, newPos, to, directPath);
                }
            }
            closedNodes.Add(searchNode.point);
        }

        if (endReached)
        {
            IntVec2[] path = new IntVec2[searchNode.steps + 1];
            for (int i = searchNode.steps; i >= 0; i--)
            {
                path[i] = searchNode.point;
                searchNode = searchNode.from;
            }

            return path;
        }

        return null;
    }
Beispiel #5
0
    void Awake()
    {
        _game = FindObjectOfType<Game>();

        _sprite = GetComponent<SpriteRenderer>().sprite;
        _texture = Instantiate(_sprite.texture) as Texture2D;

        textureSize = new IntVec2(_texture.width, _texture.height);
        maskSize = new IntVec2(_explosionMask.width, _explosionMask.height);

        _hitPoint = new GameObject("hitPoint").transform;
        _hitPoint.SetParent(transform);
        _hitPoint.localPosition = Vector3.zero;
    }
 private void FindGoodCenterLocation()
 {
     if (this.SingleMap.Size.x <= 16 || this.SingleMap.Size.z <= 16)
     {
         throw new Exception("Map too small for elemental assault");
     }
     for (int i = 0; i < 10; i++)
     {
         this.centerLocation = new IntVec2(Rand.Range(8, base.SingleMap.Size.x - 8), Rand.Range(8, base.SingleMap.Size.z - 8));
         if (this.IsGoodCenterLocation(this.centerLocation))
         {
             break;
         }
     }
 }
Beispiel #7
0
 private void FindGoodCenterLocation()
 {
     if (base.SingleMap.Size.x <= 16 || base.SingleMap.Size.z <= 16)
     {
         throw new Exception("Map too small for flashstorm.");
     }
     for (int i = 0; i < 10; i++)
     {
         centerLocation = new IntVec2(Rand.Range(8, base.SingleMap.Size.x - 8), Rand.Range(8, base.SingleMap.Size.z - 8));
         if (IsGoodCenterLocation(centerLocation))
         {
             break;
         }
     }
 }
Beispiel #8
0
 public void SetPosition(Vector2 loc)
 {
     IntVec2 pos = _grid.ToCoordinates(loc);
     if (!pos.Equals(Coordinates))
     {
         SelectedTile = _map.GetTile(pos);
         SelectedTower = null;//todo
         transform.position = _grid.ToWorld(pos);
         Coordinates = pos;
         if (OnPositionChange != null)
         {
             OnPositionChange.Invoke(this);
         }
     }
 }
Beispiel #9
0
        private bool TryFindSpawnCell(CellRect rect, ThingDef thingDef, Rot4 rot, out IntVec3 spawnCell)
        {
            Map     map  = BaseGen.globalSettings.map;
            IntVec3 zero = IntVec3.Zero;
            IntVec2 size = thingDef.size;

            GenAdj.AdjustForRotation(ref zero, ref size, rot);
            CellRect             empty         = CellRect.Empty;
            Predicate <CellRect> basePredicate = delegate(CellRect x)
            {
                if (x.Cells.All((IntVec3 y) => y.Standable(map)))
                {
                    if (!GenSpawn.WouldWipeAnythingWith(x, thingDef, map, (Thing z) => z.def.category == ThingCategory.Building))
                    {
                        return(thingDef.category != ThingCategory.Item || x.CenterCell.GetFirstItem(map) == null);
                    }
                }
                return(false);
            };
            bool flag = false;

            if (thingDef.category == ThingCategory.Building)
            {
                flag = rect.TryFindRandomInnerRectTouchingEdge(size, out empty, (CellRect x) => basePredicate(x) && !BaseGenUtility.AnyDoorAdjacentCardinalTo(x, map) && GenConstruct.TerrainCanSupport(x, map, thingDef));
                if (!flag)
                {
                    flag = rect.TryFindRandomInnerRectTouchingEdge(size, out empty, (CellRect x) => basePredicate(x) && !BaseGenUtility.AnyDoorAdjacentCardinalTo(x, map));
                }
            }
            if (!flag && !rect.TryFindRandomInnerRectTouchingEdge(size, out empty, basePredicate))
            {
                spawnCell = IntVec3.Invalid;
                return(false);
            }
            CellRect.CellRectIterator iterator = empty.GetIterator();
            while (!iterator.Done())
            {
                if (GenAdj.OccupiedRect(iterator.Current, rot, thingDef.size) == empty)
                {
                    spawnCell = iterator.Current;
                    return(true);
                }
                iterator.MoveNext();
            }
            Log.Error("We found a valid rect but we couldn't find the root position. This should never happen.", false);
            spawnCell = IntVec3.Invalid;
            return(false);
        }
Beispiel #10
0
        public void Part1()
        {
            IntVec2           current   = default;
            HashSet <IntVec2> positions = new HashSet <IntVec2>();

            positions.Add(current);

            for (int i = 0; i < _input.Length; i++)
            {
                Move(_input[i], ref current);

                positions.Add(current);
            }

            Assert.Equal(2592, positions.Count);
        }
Beispiel #11
0
        public override void PostSpawnSetup(bool respawningAfterLoad)
        {
            setupDone = true;

            ThingDef def = parent.def;

            size               = def.size;
            isOneCell          = size.z == 1 && size.x == 1;
            compHideFromPlayer = mainComponent.compHideFromPlayer;
            compAffectVision   = parent.TryGetComp <CompAffectVision>();

            lastPosition = iv3Invalid;
            lastRotation = r4Invalid;

            updatePosition();
        }
Beispiel #12
0
        public Day22()
        {
            string[] lines = File.ReadAllLines("Inputs/Day22.txt");
            _bounds = new IntVec2(lines[0].Length, lines.Length);
            _map    = new(_bounds.X * _bounds.Y);
            for (int j = 0; j < _bounds.Y; j++)
            {
                for (int i = 0; i < _bounds.X; i++)
                {
                    _map[new IntVec2(i, j)] = lines[j][i];
                }
            }

            _pos = _bounds / 2;
            _dir = -IntVec2.UnitY;
        }
Beispiel #13
0
            public static Step Parse(string str)
            {
                IntVec2 delta = str[0] switch
                {
                    'U' => IntVec2.UnitY,
                    'D' => - IntVec2.UnitY,
                    'L' => - IntVec2.UnitX,
                    'R' => IntVec2.UnitX,
                    _ => throw new InvalidOperationException("invalid direction")
                };

                int count = int.Parse(str.Substring(1));

                return(new Step(delta, count));
            }
        }
Beispiel #14
0
    public List <Cell> GetMaze(Cell[,] grid, int depth, int steps, int rooms)
    {
        max_depth  = depth;
        steps_back = steps;
        max_rooms  = rooms;
        IntVec2     start_pos  = new IntVec2(Mathf.RoundToInt(grid.GetLength(0) / 2), Mathf.RoundToInt(grid.GetLength(1) / 2));
        List <Cell> cells      = new List <Cell>();
        Cell        first_cell = new Cell(start_pos.x, start_pos.y, Direction.None)
        {
            first_room = true
        };

        grid[first_cell.pos.x, first_cell.pos.y] = first_cell;
        cells.Add(first_cell);
        return(Step(cells, grid, first_cell));
    }
Beispiel #15
0
    private static void circlePlot(int x, int z, HashSet <IntVec2> ret, int plotX, int plotZ, bool fill, int thickness)
    {
        var center = new IntVec2(x, z);

        ret.AddRange(plotOrLine(center, new IntVec2(x + plotX, z + plotZ), fill, thickness));
        if (plotX != 0 || plotZ != 0)
        {
            ret.AddRange(plotOrLine(center, new IntVec2(x - plotX, z - plotZ), fill, thickness));
        }

        if (plotX != 0 && plotZ != 0)
        {
            ret.AddRange(plotOrLine(center, new IntVec2(x + plotX, z - plotZ), fill, thickness));
            ret.AddRange(plotOrLine(center, new IntVec2(x - plotX, z + plotZ), fill, thickness));
        }
    }
Beispiel #16
0
    private static IEnumerable <IntVec2> PlotPoint(int x, int z, int thickness)
    {
        if (thickness == 1)
        {
            return new[] { new IntVec2(x, z) }
        }
        ;
        var negativeReducer = thickness < 0 ? -thickness % 2 == 0 ? 1 : 0 : 0;

        var positiveReducer = thickness > 0 ? thickness % 2 == 0 ? 1 : 0 : 0;
        var step            = Math.Abs(thickness) / 2;
        var corner1         = new IntVec2(x - (step - negativeReducer), z - (step - negativeReducer));
        var corner2         = new IntVec2(x + step - positiveReducer, z + step - positiveReducer);

        return(Rectangle(corner1.x, corner1.y, corner2.x, corner2.y, true, 0, 1));
    }
Beispiel #17
0
    public IntVec2 find(IntVec2 pos, GameState gs, Func <TileItem, bool> f)
    {
        Queue <IntVec2>   searchNodes   = new Queue <IntVec2>();
        HashSet <IntVec2> alreadyQueued = new HashSet <IntVec2>();

        searchNodes.Enqueue(pos);
        alreadyQueued.Add(pos);
        int searched = 0;

        while (searchNodes.Count > 0)
        {
            searched++;
            if (searched > MAX_RANGE)
            {
                return(null);
            }

            IntVec2 toSearch = searchNodes.Dequeue();
            if (gs.getItem(toSearch) != null)
            {
                if (f(gs.getItem(toSearch)))
                {
                    return(toSearch);
                }
            }

            //cant go this way
            if (gs.getItem(toSearch) != null && toSearch != pos)
            {
                continue;
            }

            for (int x = -1; x != 2; ++x)
            {
                for (int y = -1; y != 2; ++y)
                {
                    IntVec2 nloc = new IntVec2(toSearch.x + x, toSearch.y + y);
                    if (!alreadyQueued.Contains(nloc) && !gs.isOOB(nloc))
                    {
                        searchNodes.Enqueue(nloc);
                        alreadyQueued.Add(nloc);
                    }
                }
            }
        }
        return(null);
    }
        private static bool fowInKnownCell(this Thing _this)
        {
#if InternalProfile
            ProfilingUtils.startProfiling("FoWThingUtils.fowInKnownCell");
            try {
#endif
            MapComponentSeenFog mapComponent = _this.Map.getMapComponentSeenFog();
            if (mapComponent != null)
            {
                bool[]  knownCells = mapComponent.knownCells;
                int     mapSizeX   = mapComponent.mapSizeX;
                IntVec3 position   = _this.Position;

                IntVec2 size = _this.def.size;
                if (size.x == 1 && size.z == 1)
                {
                    return(mapComponent.knownCells[(position.z * mapSizeX) + position.x]);
                }
                else
                {
                    CellRect occupiedRect = GenAdj.OccupiedRect(position, _this.Rotation, size);

                    for (int x = occupiedRect.minX; x <= occupiedRect.maxX; x++)
                    {
                        for (int z = occupiedRect.minZ; z <= occupiedRect.maxZ; z++)
                        {
                            if (mapComponent.knownCells[(z * mapSizeX) + x])
                            {
                                return(true);
                            }
                        }
                    }
                }

                return(false);
            }

            return(true);

#if InternalProfile
        }

        finally {
            ProfilingUtils.stopProfiling("FoWThingUtils.fowInKnownCell");
        }
#endif
        }
Beispiel #19
0
        static int AppendArrayVec2(StringBuilder sb, Vector2[] array, string prefix, bool mergeCoincident, out Dictionary <int, int> coincidentIndexMap)
        {
            coincidentIndexMap = new Dictionary <int, int>();

            if (array == null)
            {
                return(0);
            }

            Dictionary <IntVec2, int> common = new Dictionary <IntVec2, int>();
            int index = 0;

            for (int i = 0, c = array.Length; i < c; i++)
            {
                var texture = array[i];
                var key     = new IntVec2(texture);
                int vertexIndex;

                if (mergeCoincident)
                {
                    if (!common.TryGetValue(key, out vertexIndex))
                    {
                        vertexIndex = index++;
                        common.Add(key, vertexIndex);
                    }
                    else
                    {
                        coincidentIndexMap.Add(i, vertexIndex);
                        continue;
                    }
                }
                else
                {
                    vertexIndex = index++;
                }

                coincidentIndexMap.Add(i, vertexIndex);

                sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "{0} {1} {2}",
                                            prefix,
                                            texture.x,
                                            texture.y));
            }

            return(index);
        }
Beispiel #20
0
        public static IntVec3 TryFindSafeLandingSpotCloseToColony(Map map, IntVec2 size, Faction faction = null, int borderWidth = 2)
        {
            size.x += borderWidth;
            size.z += borderWidth;
            tmpColonyBuildings.Clear();
            tmpColonyBuildings.AddRange(map.listerBuildings.allBuildingsColonist);
            if (!tmpColonyBuildings.Any())
            {
                return(CellFinderLoose.RandomCellWith(SpotValidator, map));
            }
            tmpColonyBuildings.Shuffle();
            for (int i = 0; i < tmpColonyBuildings.Count; i++)
            {
                if (TryFindDropSpotNear(tmpColonyBuildings[i].Position, map, out var result, allowFogged: false, canRoofPunch: false, allowIndoors: false, size) && SkyfallerCanLandAt(result, map, size, faction))
                {
                    tmpColonyBuildings.Clear();
                    return(result);
                }
            }
            tmpColonyBuildings.Clear();
            return(CellFinderLoose.RandomCellWith(SpotValidator, map));

            bool SpotValidator(IntVec3 c)
            {
                if (!SkyfallerCanLandAt(c, map, size, faction))
                {
                    return(false);
                }
                if (ModsConfig.RoyaltyActive)
                {
                    List <Thing> list = map.listerThings.ThingsOfDef(ThingDefOf.ActivatorProximity);
                    for (int j = 0; j < list.Count; j++)
                    {
                        if (list[j].Faction != null && list[j].Faction.HostileTo(faction))
                        {
                            CompSendSignalOnPawnProximity compSendSignalOnPawnProximity = list[j].TryGetComp <CompSendSignalOnPawnProximity>();
                            if (compSendSignalOnPawnProximity != null && c.InHorDistOf(list[j].Position, compSendSignalOnPawnProximity.Props.radius + 10f))
                            {
                                return(false);
                            }
                        }
                    }
                }
                return(true);
            }
        }
Beispiel #21
0
        public Day24()
        {
            IntVec2[] input = File.ReadAllLines("Inputs/Day24.txt")
                              .Select(line => line.Split('/'))
                              .Select(tok => new IntVec2(tok[0], tok[1]))
                              .ToArray();

            IntVec2 start = input.Single(p => p.X == 0 || p.Y == 0);

            _initial = new();
            _initial.Add(start);

            _available = new HashSet <IntVec2>(input);
            _available.Remove(start);

            _initialAvailablePort = start.X != 0 ? start.X : start.Y;
        }
Beispiel #22
0
 // Update is called once per frame
 void Update()
 {
     if (mApplyVelocityButton)
     {
         mApplyVelocityButton = false;
         ApplyMomentum();
     }
     if (mPreditciveVelocityButton)
     {
         mPreditciveVelocityButton = false;
         var oldPos      = mMyOnGrid.mPosition;
         var oldVelocity = mVelocity;
         ApplyMomentum();
         mMyOnGrid.mPosition = oldPos;
         mVelocity           = oldVelocity;
     }
 }
Beispiel #23
0
        public override void Tick()
        {
            this.curRotation += rotSpeed % 360f;
            foreach (Pawn pawn in this.tmpPawns)
            {
                if (pawn.IsHashIntervalTick(20) && !pawn.DestroyedOrNull() && pawn.Spawned)
                {
                    Vector3 vector3 = this.DrawPos; // Vector3.Lerp(pawn.Position.ToVector3(), this.DrawPos, lerpSpeed);
                    pawn.Position = vector3.ToIntVec3();
                    pawn.Notify_Teleported();
                    pawn.pather.nextCell = this.DrawPos.ToIntVec3();
                }
            }

            if (this.IsHashIntervalTick(GenTicks.TickRareInterval / 10))
            {
                int     rangeForGrabbingPawns = Mathf.RoundToInt(this.radius * 2);
                IntVec2 rangeIntVec2          = new IntVec2(rangeForGrabbingPawns, rangeForGrabbingPawns);

                foreach (IntVec3 intVec3 in GenAdj.OccupiedRect(this.DrawPos.ToIntVec3(), this.Rotation, rangeIntVec2))
                {
                    if (!intVec3.InBounds(Find.CurrentMap))
                    {
                        continue;
                    }
                    List <Thing> cellThings = Find.CurrentMap.thingGrid.ThingsListAt(intVec3);
                    if (cellThings == null)
                    {
                        continue;
                    }

                    for (int i = 0; i < cellThings.Count; i++)
                    {
                        Thing t = cellThings[i];

                        if (!this.tmpPawns.Contains(t) && t is Pawn p && p.HostileTo(this.Launcher))
                        {
                            this.tmpPawns.Add(p);
                        }
                    }
                }
            }

            base.Tick();
        }
        private bool IsGoodCenterLocation(IntVec2 loc)
        {
            int num  = 0;
            int num2 = (int)(3.14159274f * (float)areaRadius * (float)areaRadius / 2f);

            foreach (IntVec3 potentiallyAffectedCell in GetPotentiallyAffectedCells(loc))
            {
                if (IsGoodLocationForStrike(potentiallyAffectedCell))
                {
                    num++;
                }
                if (num >= num2)
                {
                    break;
                }
            }
            return(num >= num2);
        }
Beispiel #25
0
        public Day20()
        {
            string[] lines = File.ReadAllLines("Inputs/Day20.txt");
            _lookup = lines[0].Select(c => c is '#').ToArray();

            _startBounds = new IntVec2(lines[2].Length, lines.Length - 2);
            _start       = new bool[_startBounds.X, _startBounds.Y];
            for (int j = 2; j < lines.Length; j++)
            {
                for (int i = 0; i < lines[2].Length; i++)
                {
                    if (lines[j][i] is '#')
                    {
                        _start[i, j - 2] = true;
                    }
                }
            }
        }
        // Token: 0x06000015 RID: 21 RVA: 0x0000399C File Offset: 0x00001B9C
        private bool IsPositionValidForBlueprint(IntVec3 cell, IntVec2 size, List <IntVec3> invalidCells)
        {
            var cellRect = new CellRect(cell.x, cell.z, size.x, size.z);
            var list     = new List <IntVec3>(cellRect.Cells);

            foreach (var a in invalidCells)
            {
                foreach (var b in list)
                {
                    if (a == b)
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
        // Token: 0x060000BB RID: 187 RVA: 0x00006660 File Offset: 0x00004860
        private IEnumerable <IntVec3> GetPotentiallyAffectedCells(IntVec2 center)
        {
            int num;

            for (int x = center.x - this.areaRadius; x <= center.x + this.areaRadius; x = num + 1)
            {
                for (int z = center.z - this.areaRadius; z <= center.z + this.areaRadius; z = num + 1)
                {
                    if ((center.x - x) * (center.x - x) + (center.z - z) * (center.z - z) <= this.areaRadius * this.areaRadius)
                    {
                        yield return(new IntVec3(x, 0, z));
                    }
                    num = z;
                }
                num = x;
            }
            yield break;
        }
Beispiel #28
0
    public void collect(GameState gs, IntVec2 pos)
    {
        ExtractedResource r = (gs.getItem(pos) != null && gs.getItem(pos) is ExtractedResource) ? (gs.getItem(pos) as ExtractedResource) : null;

        if (r == null || r.type != type)
        {
            return;
        }

        int to_extract = Math.Min(r.amount, MAX_AMOUNT - r.amount);

        r.amount -= to_extract;
        amount   += to_extract;
        if (r.amount == 0)
        {
            gs.tiles_[pos.x, pos.y] = null;
        }
    }
Beispiel #29
0
    public void deposit(GameState gs, IntVec2 pos)
    {
        Storage r = (gs.getItem(pos) != null && gs.getItem(pos) is Storage) ? (gs.getItem(pos) as Storage) : null;

        if (r == null || r.type != type)
        {
            return;
        }
        switch ((gs.getItem(pos) as Storage).type)
        {
        case Resource.Type.WOOD: gs.player_wood += amount; break;

        case Resource.Type.ORE: gs.player_ore += amount; break;

        case Resource.Type.OIL: gs.player_oil += amount; break;
        }
        amount = 0;
    }
Beispiel #30
0
        private char?GetTurn(IntVec2 current, ref IntVec2 direction)
        {
            IntVec2 leftPoint  = current + -direction.RotateLeft();
            IntVec2 rightPoint = current + -direction.RotateRight();

            if (InBounds(leftPoint) && _map[leftPoint.Y][leftPoint.X] == '#')
            {
                direction = -direction.RotateLeft();
                return('L');
            }
            else if (InBounds(rightPoint) && _map[rightPoint.Y][rightPoint.X] == '#')
            {
                direction = -direction.RotateRight();
                return('R');
            }

            return(null);
        }
Beispiel #31
0
    private MazeCell CreateCell(IntVec2 coord)
    {
        MazeCell newCell = Instantiate(cellPrefab) as MazeCell;

        if (!IsValidCoord(coord))
        {
            Debug.Log("create cell error on coord: " + coord.x + ", " + coord.z);
            Debug.Log("and the size is: " + size.x + ", " + size.z);
        }
        cells[coord.x, coord.z]         = newCell;
        newCell.maze                    = this;
        newCell.patrol                  = null;
        newCell.role                    = "Empty";
        newCell.coord                   = coord;
        newCell.transform.parent        = transform;
        newCell.transform.localPosition = new Vector3(coord.x - size.x * 0.5f + 0.5f, 0f, coord.z - size.z * 0.5f + 0.5f);
        return(newCell);
    }
        private void RenderForbiddenOverlay(Thing t)
        {
            Vector3 drawPos     = t.DrawPos;
            IntVec2 rotatedSize = t.RotatedSize;

            if (rotatedSize.z == 1)
            {
                drawPos.z -= OverlayDrawer.SingleCellForbiddenOffset;
            }
            else
            {
                float   z            = drawPos.z;
                IntVec2 rotatedSize2 = t.RotatedSize;
                drawPos.z = (float)(z - (float)rotatedSize2.z * 0.30000001192092896);
            }
            drawPos.y = (float)(OverlayDrawer.BaseAlt + 0.1875);
            Graphics.DrawMesh(MeshPool.plane05, drawPos, Quaternion.identity, OverlayDrawer.ForbiddenMat, 0);
        }
Beispiel #33
0
        public static Vector3 ExactPosition(this Thing thing)
        {
            float x, z;

            if (thing.def.hasInteractionCell)
            {
                IntVec3 cell = thing.InteractionCell;
                x = 0.5f + cell.x;
                z = 0.5f + cell.z;
            }
            else
            {
                IntVec2 size = thing.def.size;
                IntVec3 cell = thing.Position;
                Rot4    rot  = thing.Rotation;

                x = cell.x;
                z = cell.z;

                if (rot == Rot4.North)
                {
                    x += 0.5f * size.x;
                    z += 0.5f * size.z;
                }
                else if (rot == Rot4.South)
                {
                    x += 0.5f * size.x;
                    z -= -0.5f + 0.5f * size.z;
                }
                else if (rot == Rot4.East)
                {
                    x += 0.5f * size.z;
                    z += 0.5f * size.x;
                }
                else if (rot == Rot4.West)
                {
                    x -= -0.5f + 0.5f * size.z;
                    z += 0.5f * size.x;
                }
            }


            return(new Vector3(x, thing.def.Altitude, z));
        }
Beispiel #34
0
        public Day18()
        {
            string[] input = File.ReadAllLines("Inputs/Day18.txt").ToArray();
            _bounds  = new IntVec2(input[0].Length, input.Length);
            _current = new Cell[_bounds.X, _bounds.Y];
            _next    = (Cell[, ])_current.Clone();

            int j = 0;

            foreach (string s in input)
            {
                int i = 0;
                foreach (char c in s)
                {
                    _current[i++, j] = (Cell)c;
                }
                j++;
            }
        }
Beispiel #35
0
 void Start()
 {
     IntVec2 gridSize = grid.Size;
     pathMap = new bool[gridSize.X, gridSize.Y];
     for (int x = 0; x < gridSize.X; x++)
     {
         for (int y = 0; y < gridSize.Y; y++)
         {
             pathMap[x, y] = true;
         }
     }
     foreach(KeyValuePair<IntVec2, GameObject> tile in tileMap) {
         pathMap[tile.Key.X, tile.Key.Y] = false;
     }
     currentPos = grid.ToCoordinates(transform.position);
     targetPos = grid.ToCoordinates(target.position);
     RecalculatePath();
     tileMap.OnChange += OnMapChanged;
 }
        private bool IsGoodCenterLocation(IntVec2 loc)
        {
            int num  = 0;
            int num2 = (int)(3.14159274f * (float)this.areaRadius * (float)this.areaRadius / 2f);

            foreach (IntVec3 current in this.GetPotentiallyAffectedCells(loc))
            {
                if (this.IsGoodLocationForSpawn(current))
                {
                    num++;
                }
                if (num >= num2)
                {
                    break;
                }
            }

            return(num >= num2 && (IsGoodLocationForSpawn(loc.ToIntVec3)));
        }
Beispiel #37
0
        private IEnumerable <IntVec2> FindSeatsInSight(IntVec2 seat)
        {
            foreach (IntVec2 dir in IntVec2.Zero.Surrounding())
            {
                IntVec2 cand = seat + dir;

                while (InBounds(cand))
                {
                    if (IsSeat(cand))
                    {
                        yield return(cand);

                        break;
                    }

                    cand += dir;
                }
            }
        }
        public override bool TryExecute(IncidentParms parms)
        {
            Predicate<IntVec3> validator = delegate(IntVec3 testedCell)
            {
                if (testedCell.Fogged())
                {
                    return false;
                }
                IntVec2 freeSpaceSize = new IntVec2(16, 16);
                foreach (IntVec3 current in GenAdj.CellsOccupiedBy(testedCell, Rot4.North, freeSpaceSize))
                {
                    if (current.Walkable() == false)
                    {
                        bool result = false;
                        return result;
                    }                    
                    if (Find.RoofGrid.Roofed(current))
                    {
                        bool result = false;
                        return result;
                    }
                }
                return testedCell.CanReachColony();
            };
            IntVec3 landingCell;
            if (CellFinderLoose.TryFindRandomNotEdgeCellWith(20, validator, out landingCell) == false)
            {
                return false;
            }
            string eventText = "   You have detected a strange thing falling from the sky. It is quite bigger than a drop pod and does not emit the standard trading federation emergency call.\n"
                + "You should send someone to scout it but be careful, this stinks mechanoid technology...";
            Find.LetterStack.ReceiveLetter("Artifact", eventText, LetterType.BadNonUrgent, landingCell);
            Thing mechanoidTerraformerIncoming = ThingMaker.MakeThing(Util_MechanoidTerraformer.MechanoidTerraformerIncomingDef);
            mechanoidTerraformerIncoming.SetFactionDirect(Faction.OfMechanoids);
            GenSpawn.Spawn(mechanoidTerraformerIncoming, landingCell);

            return true;
        }
Beispiel #39
0
    private void AddOpenNode(Node from, IntVec2 newPoint, IntVec2 finish, Plane2D directPath)
    {
        Node node = new Node();
        node.point = newPoint;
        node.steps = from.steps + 1;
        node.from = from;

        float distanceToDirectPath = 0.001f * Mathf.Abs (directPath.distanceTo (newPoint));
        float nodeValue = 100 * (newPoint.SubDistance(finish) + node.steps) + distanceToDirectPath;

        Node replacedNode;

        if (openNodes.Add(node, nodeValue, out replacedNode))
        {
            if (replacedNode != null)
            {
                closedNodes.Add(replacedNode.point);
            }
        }
        else
        {
            closedNodes.Add(node.point);
        }
    }
Beispiel #40
0
 public float DistanceTo(IntVec2 point)
 {
     int deltaX = point.X - X;
     int deltaY = point.Y - Y;
     return Mathf.Sqrt(deltaX * deltaX + deltaY * deltaY);
 }
 private int GetBorders(IntVec2 pos)
 {
     int borders = 0;
     borders |= Map.GetTile(pos.Left) == null ? Left : 0;
     borders |= Map.GetTile(pos.Right) == null ? Right : 0;
     borders |= Map.GetTile(pos.Down) == null ? Top : 0;
     borders |= Map.GetTile(pos.Up) == null ? Bottom : 0;
     return borders;
 }
 public void UpdateTile(IntVec2 pos)
 {
     GameObject tile = Map.GetTile(pos);
     if (tile != null)
     {
         int borders = GetBorders(pos);
         brushes[borders].Apply(tile);
     }
 }
Beispiel #43
0
 public void AddTower(IntVec2 pos, GameObject tower)
 {
     TowersList.Add(tower.GetComponent<Tower>());
     towersByPosition.Add(pos, tower.GetComponent<Tower>());
 }
Beispiel #44
0
        // draw loop
        public virtual void Update()
        {
            if (inGame)
            {

                if (Input.GetKeyUp(KeyCode.F11))
                {
                    iconsEnabled = !iconsEnabled;

                    if (iconsEnabled)
                        Messages.Message(Translator.Translate("PSI.Enabled"), MessageSound.Standard);
                    else
                        Messages.Message(Translator.Translate("PSI.Disabled"), MessageSound.Standard);
                }

                worldScale = Screen.height / (2 * Camera.current.orthographicSize);
            }

          //  if (Input.GetKeyUp(KeyCode.RightControl))
            if (false)
            {
                IntVec2 wSize = Find.World.Size;
                float minTemp = float.MaxValue;
                IntVec2 minTempPos = new IntVec2();
                

                for (int x = 0; x < wSize.x; x++)
                for (int z = 0; z < wSize.z; z++)
                {                    
                    
                    WorldSquare ws = Find.World.grid.Get(new IntVec2(x,z));
//                    if (ws.biome == BiomeDefOf.IceSheet)
                    //{
                        //ws.biome = BiomeDefOf.Tundra;
                    ws.temperature -= 1;
                    //}

/*                    if (ws != null)
                    {
                        if (ws.temperature < minTemp && ws.biome.canBuildBase == true)
                        {
                            minTemp = ws.temperature;
                            minTempPos = new IntVec2(x, z);
                            Log.Message(minTemp + "\t" + minTempPos.ToString());                         
                        }
                    }*/
                }
            
            }

        }
Beispiel #45
0
 public bool Contains(IntVec2 pos)
 {
     return GetTile(pos) != null;
 }
Beispiel #46
0
 public GameObject GetTile(IntVec2 point)
 {
     GameObject tile;
     return _tiles.TryGetValue(point, out tile) ? tile : null;
 }
Beispiel #47
0
 public void RemoveTile(GameObject tile)
 {
     IntVec2 key = new IntVec2();
     foreach (KeyValuePair<IntVec2, GameObject> pair in _tiles)
     {
         if (pair.Value == tile)
         {
             key = pair.Key;
             break;
         }
     }
     _tiles.Remove(key);
 }
Beispiel #48
0
 void OnMapChanged(IntVec2 pos, GameObject tile)
 {
     pathMap[pos.X, pos.Y] = tile == null;
     RecalculatePath();
 }
Beispiel #49
0
 public Tower GetTower(IntVec2 pos)
 {
     Tower tower;
     return towersByPosition.TryGetValue(pos, out tower) ? tower : null;
 }
Beispiel #50
0
 public GameObject RemoveTile(IntVec2 pos)
 {
     GameObject tile = GetTile(pos);
     if (tile != null)
     {
         _tiles.Remove(pos);
         if (OnChange != null)
         {
             OnChange.Invoke(pos, null);
         }
         return tile;
     }
     else return null;
 }
        public void PerformLandingTreatment()
        {
            const int periodInTicks = 600;

            if (this.ticksCounter % periodInTicks != 0)
            {
                return;
            }
            IntVec2 foundationsSize = new IntVec2();
            foundationsSize.x = 1 + 2 * this.foundationRange;
            foundationsSize.z = 1 + 2 * this.foundationRange;
            if (this.foundationRange <= foundationRangeMax)
            {
                foreach (IntVec3 cell in GenRadial.RadialCellsAround(this.Position, this.foundationRange, true))
                {
                    Find.TerrainGrid.SetTerrain(cell, TerrainDefOf.Concrete);
                }
                this.foundationRange++;
            }
            else
            {
                for (int rotationIndex = 0; rotationIndex < 4; rotationIndex++)
                {
                    Rot4 rotation = new Rot4(rotationIndex);
                    Find.TerrainGrid.SetTerrain(this.Position + new IntVec3(0, 0, 2).RotatedBy(rotation), TerrainDef.Named("MetalTile"));
                }
                this.ticksCounter = 0;
                this.terraformerState = TerraformerState.Idle;
            }
        }
Beispiel #52
0
	void RecalculateTarget(IntVec2 targetTileCoords)
	{
		// clear tiles
		for (int i = 0; i < countX; i++) {			
			for (int j = 0; j < countY; j++) {				
				tiles [i] [j].moveVector.x = 0;
				tiles [i] [j].moveVector.y = 0;
				tiles [i] [j].distance = 0.0f;
				tiles [i] [j].isCalculated = false;
			}
		}

		tmpCounter = 0;

		List<TmpTileParam> openCells = new List<TmpTileParam> ();

		TmpTileParam param;
		param.prevCoords = targetTileCoords;
		param.coords = targetTileCoords;
		param.distance = 0;
		openCells.Add (param);

		Debug.Log ("RecalculateTarget " + targetTileCoords.x + ", " + targetTileCoords.y);

		while (openCells.Count > 0) {
			TmpTileParam tmp = openCells [0];
			CalculateTile (tmp.prevCoords, tmp.coords, tmp.distance, ref openCells);
			openCells.RemoveAt (0);
		}

		Debug.Log ("tmpCounter " + tmpCounter);
	}
Beispiel #53
0
	bool IsOutOfRange(IntVec2 coords)
	{
		return ((coords.x < 0) || (coords.y < 0) ||
			(coords.x >= countX) || (coords.y >= countY));
	}
Beispiel #54
0
        public static void Calculate(List<Calculation> calculations)
        {
            Stopwatch s = new Stopwatch();
            s.Start();

            int count = calculations.Count;

            IntVec2[] p_p = new IntVec2[count];

            IntVec2[] p_a = new IntVec2[count];
            IntVec2[] p_b = new IntVec2[count];
            IntVec2[] p_c = new IntVec2[count];

            FloatVec3[] c = new FloatVec3[count];

            int[] c_valid = new int[count];

            Parallel.For(0, count, i =>
            {
                var calc = calculations[i];

                p_p[i] = new IntVec2(calc.P);
                p_a[i] = new IntVec2(calc.A);
                p_b[i] = new IntVec2(calc.B);
                p_c[i] = new IntVec2(calc.C);
            });

            mark(s, "memory init");

            ComputeBuffer<IntVec2> _p_p = new ComputeBuffer<IntVec2>(context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, p_p);

            ComputeBuffer<IntVec2> _p_a = new ComputeBuffer<IntVec2>(context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, p_a);

            ComputeBuffer<IntVec2> _p_b = new ComputeBuffer<IntVec2>(context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, p_b);

            ComputeBuffer<IntVec2> _p_c = new ComputeBuffer<IntVec2>(context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, p_c);

            ComputeBuffer<FloatVec3> _c = new ComputeBuffer<FloatVec3>(context, ComputeMemoryFlags.WriteOnly, c.Length);
            ComputeBuffer<int> _c_valid = new ComputeBuffer<int>(context, ComputeMemoryFlags.WriteOnly, c_valid.Length);

            mark(s, "memory buffer init");

            ComputeKernel kernel = program.CreateKernel("Barycentric");
            kernel.SetMemoryArgument(0, _p_p);

            kernel.SetMemoryArgument(1, _p_a);

            kernel.SetMemoryArgument(2, _p_b);

            kernel.SetMemoryArgument(3, _p_c);

            kernel.SetMemoryArgument(4, _c);
            kernel.SetMemoryArgument(5, _c_valid);

            mark(s, "memory init 2");

            ComputeEventList eventList = new ComputeEventList();

            ComputeCommandQueue commands = new ComputeCommandQueue(context, context.Devices[0], ComputeCommandQueueFlags.None);

            commands.Execute(kernel, null, new long[] { count }, null, eventList);

            mark(s, "execute");

            commands.ReadFromBuffer(_c, ref c, false, eventList);
            commands.ReadFromBuffer(_c_valid, ref c_valid, false, eventList);
            commands.Finish();

            mark(s, "read 1");

            Parallel.For(0, count, i =>
            {
                var calc = calculations[i];
                calc.Coords = new BarycentricCoordinates(c[i].U,c[i].V,c[i].W);

                if (c_valid[i] == 1)
                {
                    lock (calc.Tri)
                        calc.Tri.Points.Add(new DrawPoint(calc.Coords, calc.P));
                }
            });

            mark(s, "read 2");

            // cleanup commands
            commands.Dispose();

            // cleanup events
            foreach (ComputeEventBase eventBase in eventList)
            {
                eventBase.Dispose();
            }
            eventList.Clear();

            // cleanup kernel
            kernel.Dispose();

            _p_p.Dispose();

            _p_a.Dispose();
            _p_b.Dispose();
            _p_c.Dispose();

            _c.Dispose();
            _c_valid.Dispose();

            mark(s, "dispose");
        }
Beispiel #55
0
 public static List<CompHopper> FindHoppers( IntVec3 thingCenter, Rot4 thingRot, IntVec2 thingSize )
 {
     // Find hoppers for building
     var hoppers = new List<CompHopper>();
     var occupiedCells = GenAdj.OccupiedRect(thingCenter, thingRot, thingSize);
     foreach ( var cell in GenAdj.CellsAdjacentCardinal(thingCenter, thingRot, thingSize).
         Where(c => c.InBounds()).ToList() )
     {
         var hopper = FindHopper( cell );
         if (
             ( hopper != null ) &&
             ( occupiedCells.Cells.Contains( hopper.Building.Position + hopper.Building.Rotation.FacingCell ) )
         )
         {
             // Hopper is adjacent and rotated correctly
             hoppers.Add(hopper);
         }
     }
     // Return list of hoppers connected to this building
     return hoppers;
 }
Beispiel #56
0
	void CalculateTile(IntVec2 prevTileCoords, IntVec2 tileCoords, float distance, ref List<TmpTileParam> openCells)
	{
		//if (distance > 10)
		//	return;

		//TileSettings tile = tiles [tileCoords.x] [tileCoords.y];
		//TileSettings * tmp = &(tiles [tileCoords.x] [tileCoords.y]);
		if (tiles [tileCoords.x] [tileCoords.y].isCalculated &
			(tiles [tileCoords.x] [tileCoords.y].distance < distance))
			return;


		tmpCounter++;

		tiles [tileCoords.x] [tileCoords.y].isCalculated = true;

		if (tiles [tileCoords.x] [tileCoords.y].isCollide) {
			return;
		}

		tiles [tileCoords.x] [tileCoords.y].moveVector.x = prevTileCoords.x - tileCoords.x;
		tiles [tileCoords.x] [tileCoords.y].moveVector.y = prevTileCoords.y - tileCoords.y;
		//@todo: use distance!

		//Debug.Log (tmpCounter + ". CalculateTile " + tileCoords.x + ", " + tileCoords.y);

		bool leftLimit = tileCoords.x > 0;
		bool rightLimit = tileCoords.x < (countX - 1);
		bool downLimit = tileCoords.y > 0;
		bool upLimit = tileCoords.y < (countY - 1);

		///////
		if (leftLimit & upLimit) {
			IntVec2 left;
			left.x = tileCoords.x - 1;
			left.y = tileCoords.y + 1;

			TmpTileParam param;
			param.prevCoords = tileCoords;
			param.coords = left;
			param.distance = distance + 1.5f;	
		}

		if (rightLimit & upLimit) {
			IntVec2 left;
			left.x = tileCoords.x + 1;
			left.y = tileCoords.y + 1;

			TmpTileParam param;
			param.prevCoords = tileCoords;
			param.coords = left;
			param.distance = distance + 1.5f;	
		}

		if (leftLimit & downLimit) {
			IntVec2 left;
			left.x = tileCoords.x - 1;
			left.y = tileCoords.y - 1;

			TmpTileParam param;
			param.prevCoords = tileCoords;
			param.coords = left;
			param.distance = distance + 1.5f;	
		}

		if (rightLimit & downLimit) {
			IntVec2 left;
			left.x = tileCoords.x + 1;
			left.y = tileCoords.y - 1;

			TmpTileParam param;
			param.prevCoords = tileCoords;
			param.coords = left;
			param.distance = distance + 1.5f;	
		}

		//////////

		if (leftLimit) {
			
			IntVec2 left;
			left.x = tileCoords.x - 1;
			left.y = tileCoords.y;

			TmpTileParam param;
			param.prevCoords = tileCoords;
			param.coords = left;
			param.distance = distance + 1;

			openCells.Add (param);
		}
		if (rightLimit) {
			IntVec2 right;
			right.x = tileCoords.x + 1;
			right.y = tileCoords.y;	

			TmpTileParam param;
			param.prevCoords = tileCoords;
			param.coords = right;
			param.distance = distance + 1;

			openCells.Add (param);
		}
		if (downLimit) {
			IntVec2 down;
			down.x = tileCoords.x;
			down.y = tileCoords.y - 1;	

			TmpTileParam param;
			param.prevCoords = tileCoords;
			param.coords = down;
			param.distance = distance + 1;

			openCells.Add (param);
		}
		if (upLimit) {
			IntVec2 up;
			up.x = tileCoords.x;
			up.y = tileCoords.y + 1;	

			TmpTileParam param;
			param.prevCoords = tileCoords;
			param.coords = up;
			param.distance = distance + 1;

			openCells.Add (param);
		}
	}
Beispiel #57
0
 public int SqrDistance(IntVec2 point)
 {
     int deltaX = point.X - X;
     int deltaY = point.Y - Y;
     return deltaX * deltaX + deltaY * deltaY;
 }
 public void UpdateNeighbours(IntVec2 pos)
 {
     UpdateTile(pos.Left);
     UpdateTile(pos.Right);
     UpdateTile(pos.Up);
     UpdateTile(pos.Down);
 }
Beispiel #59
0
 public int SubDistance(IntVec2 point)
 {
     int deltaX = point.X - X;
     int deltaY = point.Y - Y;
     return Math.Abs(deltaX) + Math.Abs(deltaY);
 }