Example #1
0
        protected override void MoveThingTo([NotNull] Thing thing, IntVec3 beltDest)
        {
            OnBeginMove(thing, beltDest);

            // Slides only output to underground
            BeltComponent belt = null;
            var belts = beltDest.GetBeltUndergroundComponents();
            var lift = belts.Find( b => b.IsLift() && b.outputDirection == this.outputDirection );
            var under = belts.Find( tuc => tuc.IsUndercover() );
            if( ( lift != null )&&
                ( ( lift.BeltPhase == Phase.Active )||
                    ( under == null ) ) )
                // Use the lift unless it's unpowered and there is an undertaker
                belt = lift;
            else
                belt = under;

            //  Check if there is a belt, if it is empty, and also check if it is active !
            if (belt == null || !belt.ItemContainer.Empty || belt.BeltPhase != Phase.Active)
            {
                return;
            }

            ItemContainer.TransferItem(thing, belt.ItemContainer);

            // Need to check if it is a receiver or not ...
            belt.ThingOrigin = parent.Position;
        }
        public static AirNet NetAt( IntVec3 pos, NetLayer layer )
        {
            if(!AirNetTicker.doneInit)
                AirNetTicker.Initialize();

            return netGrid[(int)layer][CellIndices.CellToIndex( pos )];
        }
 protected void GetFacingCell(ref Pawn facingPawn, ref IntVec3 facingCell)
 {
     List<Pawn> nearbyPawns = new List<Pawn>();
     foreach (Pawn colonist in Find.MapPawns.FreeColonists)
     {
         if (colonist == this.pawn)
         {
             continue;
         }
         if (colonist.Position.InHorDistOf(this.pawn.Position, 2f))
         {
             nearbyPawns.Add(colonist);
         }
     }
     if (nearbyPawns.NullOrEmpty())
     {
         facingPawn = null;
         facingCell = this.pawn.Position + new IntVec3(0, 0, 1).RotatedBy(new Rot4(Rand.Range(0, 4)));
     }
     else
     {
         facingPawn = nearbyPawns.RandomElement();
         facingCell = facingPawn.Position;
     }
 }
 public override void DesignateSingleCell(IntVec3 c)
 {
     List<Thing> thingList = c.GetThingList();
     foreach (var thing in thingList)
         if (thing.def.category == ThingCategory.Item && !Find.Reservations.IsReserved(thing, Faction.OfColony))
             designations.Add(new Designation(thing, DesignationDefOf.Haul));
 }
 public override bool AllowVerbCast(IntVec3 root, TargetInfo targ)
 {
     if (this.wearer.equipment.Primary != null)
     {
         if (this.wearer.equipment.Primary.def.IsMeleeWeapon)
         {
             return true;
         }
         if (this.wearer.equipment.Primary.def.defName.Equals("Gun_Pistol"))
         {
             return true;
         }
         if (this.wearer.equipment.Primary.def.defName.Equals("Gun_PDW"))
         {
             return true;
         }
         if (this.wearer.equipment.Primary.def.defName.Equals("Gun_HeavySMG"))
         {
             return true;
         }
         if (this.wearer.equipment.Primary.def.weaponTags.Contains("MedievalShields_ValidSidearm"))
         {
             return true;
         }
     }
     return root.AdjacentTo8Way(targ.Cell);
 }
Example #6
0
        public static bool IsCellOpenForSowingPlantOfType(IntVec3 cell, ThingDef plantDef)
        {
            IPlantToGrowSettable plantToGrowSettable = GetPlayerSetPlantForCell(cell);
            if (plantToGrowSettable == null || !plantToGrowSettable.CanAcceptSowNow())
                return false;

            ThingDef plantDefToGrow = plantToGrowSettable.GetPlantDefToGrow();
            if (plantDefToGrow == null || plantDefToGrow != plantDef)
                return false;

            // check if there's already a plant occupying the cell
            if (cell.GetPlant() != null)
                return false;

            // check if there are nearby cells which block growth
            if (GenPlant.AdjacentSowBlocker(plantDefToGrow, cell) != null)
                return false;

            // check through all the things in the cell which might block growth
            foreach (Thing tempThing in Find.ThingGrid.ThingsListAt(cell))
                if (tempThing.def.BlockPlanting)
                    return false;

            if (!plantDefToGrow.CanEverPlantAt(cell) || !GenPlant.GrowthSeasonNow(cell))
                return false;

            return true;
        }
        public override string GetReport()
        {
            Vehicle_Cart cart = TargetThingA as Vehicle_Cart;

            IntVec3 destLoc = new IntVec3(-1000, -1000, -1000);
            string destName = null;
            SlotGroup destGroup = null;

            if (pawn.jobs.curJob.targetB != null)
            {
                destLoc = pawn.jobs.curJob.targetB.Cell;
                destGroup = StoreUtility.GetSlotGroup(destLoc);
            }

            if (destGroup != null)
                destName = destGroup.parent.SlotYielderLabel();

            string repString;
            if (destName != null)
                repString = "ReportDismountingOn".Translate(cart.LabelCap, destName);
            else
                repString = "ReportDismounting".Translate(cart.LabelCap);

            return repString;
        }
		public override AcceptanceReport CanDesignateCell(IntVec3 c) {
			if (mode == OperationMode.AllOfDef) {
				return TryGetItemOrPawnUnderCursor() != null;
			} else {
				return base.CanDesignateCell(c);
			}
		}
Example #9
0
        public override void DesignateSingleCell(IntVec3 c)
        {
            Job jobNew = new Job(DefDatabase<JobDef>.GetNamed("Standby"), c, 4800);
            driver.jobs.StartJob(jobNew, JobCondition.Incompletable);

            DesignatorManager.Deselect();
        }
        /// <summary>
        /// Try to get a valid cell to spawn a new cluster anywhere on the map.
        /// </summary>
        public static void TryGetRandomClusterSpawnCell(ThingDef_ClusterPlant plantDef, int newDesiredClusterSize, bool checkTemperature, out IntVec3 spawnCell)
        {
            spawnCell = IntVec3.Invalid;

            Predicate<IntVec3> validator = delegate(IntVec3 cell)
            {
                // Check a plant can be spawned here.
                if (GenClusterPlantReproduction.IsValidPositionToGrowPlant(plantDef, cell) == false)
                {
                    return false;
                }
                // Check there is no third cluster nearby.
                if (GenClusterPlantReproduction.IsClusterAreaClear(plantDef, newDesiredClusterSize, cell) == false)
                {
                    return false;
                }
                return true;
            };

            bool validCellIsFound = CellFinderLoose.TryGetRandomCellWith(validator, 1000, out spawnCell);
            if (validCellIsFound == false)
            {
                // Just for robustness, TryGetRandomCellWith set result to IntVec3.Invalid if no valid cell is found.
                spawnCell = IntVec3.Invalid;
            }
        }
 public Job HaulGarbageAsideJob(IntVec3 cell, Pawn pawn)
 {
     return Find.ThingGrid.ThingsListAtFast(cell)
             .Where(thing => thing.def.BlockPlanting && thing.def.EverHaulable)
             .Select(thing => HaulAIUtility.HaulAsideJobFor(pawn, thing))
             .FirstOrDefault();
 }
Example #12
0
        public override AcceptanceReport AllowsPlacing( BuildableDef checkingDef, IntVec3 loc, Rot4 rot )
        {
            var Restrictions = checkingDef.RestrictedPlacement_Properties();
            #if DEBUG
            if( Restrictions == null ){
                CCL_Log.Error( "PlaceWorker_RestrictedCount unable to get properties!", checkingDef.defName );
                return AcceptanceReport.WasRejected;
            }
            #endif

            var thingDef = checkingDef as ThingDef;
            #if DEBUG
            if( thingDef == null )
            {
                CCL_Log.Error( "PlaceWorker_RestrictedCount unable to get cast BuildableDef to ThingDef!", checkingDef.defName );
                return AcceptanceReport.WasRejected;
            }
            #endif

            // Get the current count of instances and blueprints of
            int count = Find.ListerThings.ThingsOfDef( thingDef ).Count
                + Find.ListerThings.ThingsOfDef( thingDef.blueprintDef ).Count;

            return count < Restrictions.MaxCount
                ? AcceptanceReport.WasAccepted
                    : "MessagePlacementCountRestricted".Translate( Restrictions.MaxCount );
        }
		public override void DesignateSingleCell(IntVec3 loc) {
			if (ProcessCell(loc) > 0) {
				FinalizeDesignationSucceeded();
			} else {
				FinalizeDesignationFailed();
			}
		}
 private bool GetNearbyPlantingSite(IntVec3 originPos, out IntVec3 newSite)
 {
     return GenCellFinder.TryFindRandomMapCellNearWith(originPos, 5,
         (IntVec3 tempCell) => Utils_Plants.IsCellOpenForSowingPlantOfType(tempCell, CurJob.plantDefToSow) &&
         GetActor().CanReserveAndReach(tempCell, PathEndMode.Touch, GetActor().NormalMaxDanger()),
         out newSite);
 }
        /// <summary>
        /// Checks if a new force field generator can be built at this location.
        /// - must not be too near from another force field generator (or it would perturb other fields).
        /// </summary>
        public override AcceptanceReport AllowsPlacing(BuildableDef checkingDef, IntVec3 loc, Rot4 rot)
        {
            // Check if another force field generator is not too close.
            List<Thing> forceFieldGeneratorList = new List<Thing>();
            IEnumerable<Thing> list = Find.ListerThings.ThingsOfDef(ThingDef.Named("ForceFieldGenerator"));
            foreach (Thing generator in list)
            {
                forceFieldGeneratorList.Add(generator);
            }
            list = Find.ListerThings.ThingsOfDef(ThingDef.Named("ForceFieldGenerator").blueprintDef);
            foreach (Thing generator in list)
            {
                forceFieldGeneratorList.Add(generator);
            }
            list = Find.ListerThings.ThingsOfDef(ThingDef.Named("ForceFieldGenerator").frameDef);
            foreach (Thing generator in list)
            {
                forceFieldGeneratorList.Add(generator);
            }

            foreach (Thing generator in forceFieldGeneratorList)
            {
                if (generator.Position.InHorDistOf(loc, minDistanceBetweenTwoForceFieldGenerators))
                {
                    return new AcceptanceReport("An other force field generator is too close (would generate perturbations).");
                }
            }

            // Display effect zone.
            List<IntVec3> coveredCells = Building_ForceFieldGenerator.GetCoveredCells(loc, rot);
            GenDraw.DrawFieldEdges(coveredCells);

            return true;
        }
 public override void DrawGhost(ThingDef def, IntVec3 center, Rot4 rot)
 {
     GenDraw.DrawFieldEdges(
         FindUtil.SquareAreaAround(center, Mathf.RoundToInt(def.specialDisplayRadius))
             .Where(cell => cell.Walkable() && cell.InBounds())
             .ToList());
 }
Example #17
0
        public override AcceptanceReport AllowsPlacing(BuildableDef checkingDef, IntVec3 loc, Rot4 rot)
        {
            bool flag = false;
            List<Thing> list = Find.ThingGrid.ThingsListAt(loc);
            if (list.Count > 0)
            {
                foreach (Thing current in list)
                {
                    if (current.def.category == ThingCategory.Building)
                    {
                        if (current.def.holdsRoof && current.def.coversFloor && current.def.altitudeLayer == AltitudeLayer.BuildingTall && current.def.passability == Traversability.Impassable)
                        {

                            flag = true;
                            break;
                        }
                    }
                }
            }
            else
            {
                flag = false;
            }
            AcceptanceReport result;
            if (flag)
            {
                result = true;
            }
            else
            {
                result = "Need to be placed on a colony wall";
            }
            return result;
        }
        public override AcceptanceReport AllowsPlacing( BuildableDef checkingDef, IntVec3 loc, Rot4 rot )
        {
            ThingDef def = checkingDef as ThingDef;

            var Restrictions = def.GetCompProperties( typeof( RestrictedPlacement_Comp ) ) as RestrictedPlacement_Properties;
            if( Restrictions == null ){
                Log.Error( "Could not get restrictions!" );
                return (AcceptanceReport)false;
            }

            // Override steam-geyser restriction
            if( ( Restrictions.RestrictedThing.FindIndex( r => r == ThingDefOf.SteamGeyser ) >= 0 )&&
                ( ThingDefOf.GeothermalGenerator != ( checkingDef as ThingDef ) ) ){
                var newGeo = checkingDef as ThingDef;
                ThingDefOf.GeothermalGenerator = newGeo;
            }

            foreach( Thing t in loc.GetThingList() ){
                if( ( Restrictions.RestrictedThing.Find( r => r == t.def ) != null )&&
                    ( t.Position == loc ) )
                    return (AcceptanceReport)true;
            }

            return "MessagePlacementNotHere".Translate();
        }
 protected bool IsValidCellToWander(IntVec3 cell)
 {
     if (cell.Standable() == false)
     {
         return false;
     }
     if (this.pawn.CanReach(new TargetInfo(cell), PathEndMode.OnCell, Danger.None) == false)
     {
         return false;
     }
     foreach (Thing thing in cell.GetThingList())
     {
         if (thing is Fire)
         {
             return false;
         }
     }
     if (cell.GetRoom() != this.TargetLocA.GetRoom())
     {
         return false;
     }
     if (Find.PawnDestinationManager.DestinationIsReserved(cell))
     {
         return false;
     }
     return true;
 }
 public override AcceptanceReport AllowsPlacing(BuildableDef checkingDef, IntVec3 loc, Rot4 rot, Thing thingToIgnore = null)
 {
     IEnumerable<IntVec3> cells = GenAdj.CellsAdjacent8Way(loc, rot, checkingDef.Size).Union<IntVec3>(GenAdj.CellsOccupiedBy(loc, rot, checkingDef.Size));
     foreach (IntVec3 cell in cells)
     {
         List<Thing> things = Map.thingGrid.ThingsListAt(cell);
         foreach (Thing thing in things)
         {
             if (thing.TryGetComp<CompRTQuantumStockpile>() != null
                 || thing.TryGetComp<CompRTQuantumChunkSilo>() != null)
             {
                 return "PlaceWorker_RTNoQSOverlap".Translate();
             }
             else if (thing.def.entityDefToBuild != null)
             {
                 ThingDef thingDef = thing.def.entityDefToBuild as ThingDef;
                 if (null != thingDef &&
                     null != thingDef.comps &&
                     null != thingDef.comps.Find(x => typeof(CompRTQuantumStockpile) == x.compClass))
                 {
                     return "PlaceWorker_RTNoQSOverlap".Translate();
                 }
             }
         }
     }
     return true;
 }
        /// <summary>
        /// Display the scan range of built mobile mineral sonar and the max scan range at the tested position.
        /// Allow placement nearly anywhere.
        /// </summary>
        public override AcceptanceReport AllowsPlacing(BuildableDef checkingDef, IntVec3 loc, Rot4 rot)
        {
            IEnumerable<Building> mobileMineralSonarList = Find.ListerBuildings.AllBuildingsColonistOfDef(ThingDef.Named("MobileMineralSonar"));

            if (mobileMineralSonarList != null)
            {
                foreach (Building mobileMineralSonar in mobileMineralSonarList)
                {
                    (mobileMineralSonar as Building_MobileMineralSonar).DrawMaxScanRange();
                }
            }

            ResearchProjectDef mmsResearch = ResearchProjectDef.Named("ResearchMobileMineralSonarEnhancedScan");
            if (Find.ResearchManager.GetProgress(mmsResearch) >= mmsResearch.CostApparent)
            {
                Material scanRange30 = MaterialPool.MatFrom("Effects/ScanRange30");
                Vector3 scanRangeScale30 = new Vector3(60f, 1f, 60f);
                Matrix4x4 scanRangeMatrix30 = default(Matrix4x4);
                // The 10f offset on Y axis is mandatory to be over the fog of war.
                scanRangeMatrix30.SetTRS(loc.ToVector3Shifted() + new Vector3(0f, 10f, 0f) + Altitudes.AltIncVect, (0f).ToQuat(), scanRangeScale30);
                Graphics.DrawMesh(MeshPool.plane10, scanRangeMatrix30, scanRange30, 0);
            }
            else
            {
                Material scanRange50 = MaterialPool.MatFrom("Effects/ScanRange50");
                Vector3 scanRangeScale50 = new Vector3(100f, 1f, 100f);
                Matrix4x4 scanRangeMatrix50 = default(Matrix4x4);
                // The 10f offset on Y axis is mandatory to be over the fog of war.
                scanRangeMatrix50.SetTRS(loc.ToVector3Shifted() + new Vector3(0f, 10f, 0f) + Altitudes.AltIncVect, (0f).ToQuat(), scanRangeScale50);
                Graphics.DrawMesh(MeshPool.plane10, scanRangeMatrix50, scanRange50, 0);
            }

            return true;
        }
Example #22
0
        //Constructor
        public ShieldField(Building_Shield shieldBuilding, IntVec3 pos, int shieldMaxShieldStrength, int shieldInitialShieldStrength, int shieldShieldRadius, int shieldRechargeTickDelay, int shieldRecoverWarmup, bool shieldBlockIndirect, bool shieldBlockDirect, bool shieldFireSupression, bool shieldInterceptDropPod, bool shieldStructuralIntegrityMode, float colourRed, float colourGreen, float colourBlue)
        {
            this.shieldBuilding = shieldBuilding;
            position = pos;
            //shieldCurrentStrength = 0;
            this.shieldMaxShieldStrength = shieldMaxShieldStrength;
            this.shieldInitialShieldStrength = shieldInitialShieldStrength;
            this.shieldShieldRadius = shieldShieldRadius;
            this.shieldRechargeTickDelay = shieldRechargeTickDelay;
            this.shieldRecoverWarmup = shieldRecoverWarmup;

            this.shieldBlockIndirect = shieldBlockIndirect;

            this.shieldBlockDirect = shieldBlockDirect;

            this.shieldFireSupression = shieldFireSupression;
            this.shieldInterceptDropPod = shieldInterceptDropPod;
            this.shieldStructuralIntegrityMode = shieldStructuralIntegrityMode;

            this.colourRed = colourRed;
            this.colourGreen = colourGreen;
            this.colourBlue = colourBlue;

            //this.SIFBuildings = SIFBuildings;
            //this.setupValidBuildings();
        }
		private void UpdateAffectedCellsInRect(IntVec3 pos1, IntVec3 pos2) {
			affectedCells.Clear();
			// estabilish bounds
			int minX, maxX, minZ, maxZ;
			if (pos1.x <= pos2.x) {
				minX = pos1.x;
				maxX = pos2.x;
			} else {
				minX = pos2.x;
				maxX = pos1.x;
			}
			if (pos1.z <= pos2.z) {
				minZ = pos1.z;
				maxZ = pos2.z;
			} else {
				minZ = pos2.z;
				maxZ = pos1.z;
			}

			// check all items against bounds
			var allTheThings = Find.ListerThings.AllThings;
			for (var i = 0; i < allTheThings.Count; i++) {
				var thing = allTheThings[i];
				var thingPos = thing.Position;
				if (thing.def.selectable && thingPos.x >= minX && thingPos.x <= maxX && thingPos.z >= minZ && thingPos.z <= maxZ && filterCallback(thing)) {
					affectedCells.Add(thingPos);
				}
			}
		}
        public static void GenerateSmallRoomWeaponRoom(IntVec3 areaSouthWestOrigin, int zoneAbs, int zoneOrd, Rot4 rotation, ref OG_OutpostData outpostData)
        {
            IntVec3 origin = Zone.GetZoneOrigin(areaSouthWestOrigin, zoneAbs, zoneOrd);
            IntVec3 rotatedOrigin = Zone.GetZoneRotatedOrigin(areaSouthWestOrigin, zoneAbs, zoneOrd, rotation);

            OG_Common.GenerateEmptyRoomAt(rotatedOrigin + new IntVec3(smallRoomWallOffset, 0, smallRoomWallOffset).RotatedBy(rotation), Genstep_GenerateOutpost.zoneSideSize - 2 * smallRoomWallOffset, Genstep_GenerateOutpost.zoneSideSize - 2 * smallRoomWallOffset, rotation, TerrainDefOf.Concrete, TerrainDef.Named("MetalTile"), ref outpostData);

            // Spawn weapon racks, weapons and lamps.
            Building_Storage rack = OG_Common.TrySpawnThingAt(ThingDefOf.EquipmentRack, ThingDefOf.Steel, rotatedOrigin + new IntVec3(smallRoomWallOffset + 1, 0, smallRoomWallOffset + 1).RotatedBy(rotation), true, new Rot4(Rot4.North.AsInt + rotation.AsInt), ref outpostData)as Building_Storage;
            TrySpawnWeaponOnRack(rack);
            rack.GetStoreSettings().filter.SetAllow(ThingCategoryDef.Named("WeaponsMelee"), false);
            rack.GetStoreSettings().Priority = StoragePriority.Critical;
            rack = OG_Common.TrySpawnThingAt(ThingDefOf.EquipmentRack, ThingDefOf.Steel, rotatedOrigin + new IntVec3(smallRoomWallOffset + 4, 0, smallRoomWallOffset + 1).RotatedBy(rotation), true, new Rot4(Rot4.North.AsInt + rotation.AsInt), ref outpostData) as Building_Storage;
            TrySpawnWeaponOnRack(rack);
            rack.GetStoreSettings().filter.SetAllow(ThingCategoryDef.Named("WeaponsMelee"), false);
            rack.GetStoreSettings().Priority = StoragePriority.Critical;
            rack = OG_Common.TrySpawnThingAt(ThingDefOf.EquipmentRack, ThingDefOf.Steel, rotatedOrigin + new IntVec3(smallRoomWallOffset + 2, 0, smallRoomWallOffset + 5).RotatedBy(rotation), true, new Rot4(Rot4.South.AsInt + rotation.AsInt), ref outpostData) as Building_Storage;
            TrySpawnWeaponOnRack(rack);
            rack.GetStoreSettings().filter.SetAllow(ThingCategoryDef.Named("WeaponsMelee"), false);
            rack.GetStoreSettings().Priority = StoragePriority.Critical;
            rack = OG_Common.TrySpawnThingAt(ThingDefOf.EquipmentRack, ThingDefOf.Steel, rotatedOrigin + new IntVec3(smallRoomWallOffset + 5, 0, smallRoomWallOffset + 5).RotatedBy(rotation), true, new Rot4(Rot4.South.AsInt + rotation.AsInt), ref outpostData) as Building_Storage;
            TrySpawnWeaponOnRack(rack);
            rack.GetStoreSettings().filter.SetAllow(ThingCategoryDef.Named("WeaponsMelee"), false);
            rack.GetStoreSettings().Priority = StoragePriority.Critical;
            OG_Common.TrySpawnLampAt(rotatedOrigin + new IntVec3(smallRoomWallOffset + 1, 0, smallRoomWallOffset + 3).RotatedBy(rotation), Color.white, ref outpostData);
            OG_Common.TrySpawnLampAt(rotatedOrigin + new IntVec3(smallRoomWallOffset + 5, 0, smallRoomWallOffset + 3).RotatedBy(rotation), Color.white, ref outpostData);
            // Spawn vertical alley and door.
            for (int zOffset = smallRoomWallOffset; zOffset <= Genstep_GenerateOutpost.zoneSideSize - smallRoomWallOffset; zOffset++)
            {
                Find.TerrainGrid.SetTerrain(rotatedOrigin + new IntVec3(Genstep_GenerateOutpost.zoneSideCenterOffset, 0, zOffset).RotatedBy(rotation), TerrainDef.Named("PavedTile"));
            }
            OG_Common.SpawnDoorAt(rotatedOrigin + new IntVec3(Genstep_GenerateOutpost.zoneSideCenterOffset, 0, Genstep_GenerateOutpost.zoneSideSize - smallRoomWallOffset - 1).RotatedBy(rotation), ref outpostData);
        }
Example #25
0
 public override AcceptanceReport CanDesignateCell(IntVec3 loc)
 {
     if (loc.CanReach(vehicle, PathEndMode.OnCell, TraverseMode.ByPawn, Danger.Deadly))
         return true;
     else
         return new AcceptanceReport(txtCannotMove.Translate());
 }
        public void TrySpawnExplosionThing(ThingDef thingDef, IntVec3 cell)
        {
            if (thingDef == null)
            {
                return;
            }
            if (thingDef.thingClass == typeof (LiquidFuel))
            {
                var liquidFuel = (LiquidFuel) Find.ThingGrid.ThingAt(cell, thingDef);
                if (liquidFuel != null)
                {
                    liquidFuel.Refill();
                    return;
                }
            }

            // special skyfaller spawning
            if (thingDef == ThingDef.Named("CobbleSlate"))
            {
                var impactResultThing = ThingMaker.MakeThing(ThingDef.Named("CobbleSlate"));
                impactResultThing.stackCount = Rand.RangeInclusive(1, 10);
                GenPlace.TryPlaceThing(impactResultThing, cell, ThingPlaceMode.Near);
                return;
            }

            GenSpawn.Spawn(thingDef, cell);
        }
        public static void GenerateMediumRoomPrison(IntVec3 areaSouthWestOrigin, int zoneAbs, int zoneOrd, Rot4 rotation, ref OG_OutpostData outpostData)
        {
            IntVec3 origin = Zone.GetZoneOrigin(areaSouthWestOrigin, zoneAbs, zoneOrd);
            IntVec3 rotatedOrigin = Zone.GetZoneRotatedOrigin(areaSouthWestOrigin, zoneAbs, zoneOrd, rotation);

            OG_Common.GenerateEmptyRoomAt(rotatedOrigin + new IntVec3(0, 0, 1).RotatedBy(rotation), 5, 9, rotation, TerrainDefOf.Concrete, null, ref outpostData);
            OG_Common.GenerateEmptyRoomAt(rotatedOrigin + new IntVec3(4, 0, 1).RotatedBy(rotation), 3, 9, rotation, TerrainDefOf.Concrete, null, ref outpostData);
            OG_Common.GenerateEmptyRoomAt(rotatedOrigin + new IntVec3(6, 0, 1).RotatedBy(rotation), 5, 9, rotation, TerrainDefOf.Concrete, null, ref outpostData);

            // Spawn prisoner beds.
            OG_Common.TrySpawnThingAt(ThingDef.Named("Bed"), ThingDefOf.Steel, rotatedOrigin + new IntVec3(1, 0, 8).RotatedBy(rotation), true, new Rot4(Rot4.South.AsInt + rotation.AsInt), ref outpostData);
            OG_Common.TrySpawnThingAt(ThingDef.Named("Stool"), ThingDefOf.Steel, rotatedOrigin + new IntVec3(2, 0, 8).RotatedBy(rotation), true, new Rot4(Rot4.South.AsInt + rotation.AsInt), ref outpostData);
            OG_Common.TrySpawnThingAt(ThingDef.Named("Bed"), ThingDefOf.Steel, rotatedOrigin + new IntVec3(3, 0, 8).RotatedBy(rotation), true, new Rot4(Rot4.South.AsInt + rotation.AsInt), ref outpostData);
            OG_Common.TrySpawnThingAt(ThingDef.Named("Bed"), ThingDefOf.Steel, rotatedOrigin + new IntVec3(7, 0, 2).RotatedBy(rotation), true, new Rot4(Rot4.North.AsInt + rotation.AsInt), ref outpostData);
            OG_Common.TrySpawnThingAt(ThingDef.Named("Stool"), ThingDefOf.Steel, rotatedOrigin + new IntVec3(8, 0, 2).RotatedBy(rotation), true, new Rot4(Rot4.North.AsInt + rotation.AsInt), ref outpostData);
            OG_Common.TrySpawnThingAt(ThingDef.Named("Bed"), ThingDefOf.Steel, rotatedOrigin + new IntVec3(9, 0, 2).RotatedBy(rotation), true, new Rot4(Rot4.North.AsInt + rotation.AsInt), ref outpostData);

            // Spawn lamps, heaters and coolers.
            OG_Common.TrySpawnLampAt(rotatedOrigin + new IntVec3(3, 0, 2).RotatedBy(rotation), Color.white, ref outpostData);
            OG_Common.TrySpawnLampAt(rotatedOrigin + new IntVec3(7, 0, 8).RotatedBy(rotation), Color.white, ref outpostData);
            OG_Common.TrySpawnHeaterAt(rotatedOrigin + new IntVec3(1, 0, 2).RotatedBy(rotation), ref outpostData);
            OG_Common.TrySpawnHeaterAt(rotatedOrigin + new IntVec3(9, 0, 8).RotatedBy(rotation), ref outpostData);
            OG_Common.SpawnCoolerAt(rotatedOrigin + new IntVec3(0, 0, 2).RotatedBy(rotation), new Rot4(Rot4.West.AsInt + rotation.AsInt), ref outpostData);
            OG_Common.SpawnCoolerAt(rotatedOrigin + new IntVec3(10, 0, 8).RotatedBy(rotation), new Rot4(Rot4.East.AsInt + rotation.AsInt), ref outpostData);

            // Spawn vertical alley and door.
            for (int zOffset = 0; zOffset <= 10; zOffset++)
            {
                Find.TerrainGrid.SetTerrain(rotatedOrigin + new IntVec3(5, 0, zOffset).RotatedBy(rotation), TerrainDef.Named("PavedTile"));
            }
            OG_Common.SpawnDoorAt(rotatedOrigin + new IntVec3(4, 0, 3).RotatedBy(rotation), ref outpostData);
            OG_Common.SpawnDoorAt(rotatedOrigin + new IntVec3(6, 0, 7).RotatedBy(rotation), ref outpostData);
            OG_Common.SpawnDoorAt(rotatedOrigin + new IntVec3(5, 0, 1).RotatedBy(rotation), ref outpostData);
            OG_Common.SpawnDoorAt(rotatedOrigin + new IntVec3(5, 0, 9).RotatedBy(rotation), ref outpostData);
        }
    public void InstantiateVoxels(int startx, int starty, int startz, int width, int height, int depth)
    {
        Width = width;
        Height = height;
        Depth = depth;

        Voxels = new Voxel[Width, Height, Depth];

        float voxelSize = VoxelWorld.Inst.PhysicalVoxelSize;
        float halfVoxel = voxelSize * 0.5f;

        for (int x = 0; x < Width; ++x)
        {
            for (int y = 0; y < Height; ++y)
            {
                for (int z = 0; z < Depth; ++z)
                {
                    IntVec3 pos = new IntVec3(startx + x, starty + y, startz + z);
                    BoxCollider collider = gameObject.AddComponent<BoxCollider>();
                    collider.center = new Vector3(pos.X + halfVoxel, pos.Y + halfVoxel, pos.Z + halfVoxel);
                    collider.size = new Vector3(voxelSize, voxelSize, voxelSize);
                    Voxel voxel = new Voxel(this, VoxelType.Air, pos, collider);
                    Voxels[x, y, z] = voxel;
                    ColliderToVoxel[collider] = voxel;
                }
            }
        }
    }
        public override void DrawGhost( ThingDef def, IntVec3 center, Rot4 rot )
        {
            var vecNorth = center + IntVec3.North.RotatedBy( rot );
            var vecSouth = center + IntVec3.South.RotatedBy( rot );
            if ( !vecNorth.InBounds() || !vecSouth.InBounds() )
            {
                return;
            }

            GenDraw.DrawFieldEdges( new List< IntVec3 >
            {
                vecNorth
            }, new Color( 1f, 0.7f, 0f, 0.5f ) );
            GenDraw.DrawFieldEdges( new List< IntVec3 >
            {
                vecSouth
            }, Color.white );

            var controlledRoom = vecNorth.GetRoom();
            var otherRoom = vecSouth.GetRoom();

            if ( controlledRoom == null || otherRoom == null )
            {
                return;
            }

            if ( !controlledRoom.UsesOutdoorTemperature )
            {
                GenDraw.DrawFieldEdges( controlledRoom.Cells.ToList(), new Color( 1f, 0.7f, 0f, 0.5f ) );
            }
        }
        public override AcceptanceReport  AllowsPlacing(BuildableDef checkingDef, IntVec3 loc, Rot4 rot)
        {
            string reason = "";
            bool canBePlacedHere = Building_LaserFencePylon.CanPlaceNewPylonHere(loc, out reason);
            if (canBePlacedHere == false)
            {
                return new AcceptanceReport(reason);
            }
            
            // Display potential placing positions.
            foreach (Thing pylon in Find.ListerThings.ThingsOfDef(ThingDef.Named("LaserFencePylon").blueprintDef))
            {
                if (pylon.Position.InHorDistOf(loc, 6f))
                {
                    Building_LaserFencePylon.DrawPotentialPlacePositions(pylon.Position);
                }
            }
            foreach (Thing pylon in Find.ListerThings.ThingsOfDef(ThingDef.Named("LaserFencePylon").frameDef))
            {
                if (pylon.Position.InHorDistOf(loc, 6f))
                {
                    Building_LaserFencePylon.DrawPotentialPlacePositions(pylon.Position);
                }
            }
            foreach (Thing pylon in Find.ListerThings.ThingsOfDef(ThingDef.Named("LaserFencePylon")))
            {
                if (pylon.Position.InHorDistOf(loc, 6f))
                {
                    Building_LaserFencePylon.DrawPotentialPlacePositions(pylon.Position);
                }
            }

            return true;
        }
Example #31
0
        public override void PassingParameters(ResolveParams rp)
        {
            string defChair = "DiningChair";
            string defLamp  = "Jecrell_GasLamp";

            ThingDef lampDef      = Cthulhu.Utility.IsIndustrialAgeLoaded() ? ThingDef.Named(defLamp) : ThingDefOf.TorchLamp;
            ThingDef lampStuffDef = Cthulhu.Utility.IsIndustrialAgeLoaded() ? ThingDefOf.Steel : null;

            Map      map      = BaseGen.globalSettings.map;
            bool     @bool    = Rand.Bool;
            bool     hasLamp  = false;
            ThingDef thingDef = ThingDefOf.Bed;
            ThingDef chairDef = ThingDef.Named(defChair);

            foreach (IntVec3 current in rp.rect)
            {
                if (@bool)
                {
                    if (current.x % 3 != 0 || current.z % 3 != 0)
                    {
                        continue;
                    }
                }
                else if (current.x % 3 != 0 || current.z % 3 != 0)
                {
                    continue;
                }
                Rot4 rot = (!@bool) ? Rot4.South : Rot4.West;
                if (!GenSpawn.WouldWipeAnythingWith(current, rot, thingDef, map, (Thing x) => x.def.category == ThingCategory.Building))
                {
                    bool flag = false;
                    foreach (IntVec3 current2 in GenAdj.CellsOccupiedBy(current, rot, thingDef.Size))
                    {
                        if (BaseGenUtility.AnyDoorAdjacentCardinalTo(current2, map))
                        {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag)
                    {
                        ///Bed
                        ThingDef stuff = null;
                        if (thingDef.MadeFromStuff)
                        {
                            stuff = ThingDefOf.WoodLog;
                        }
                        Thing thing = ThingMaker.MakeThing(thingDef, stuff);
                        thing.SetFaction(rp.faction, null);
                        GenSpawn.Spawn(thing, current, map, rot);

                        if (thing != null)
                        {
                            if (thing.Spawned && thing.Position.InBounds(map))
                            {
                                CellRect thingRect = thing.OccupiedRect();
                                if (thingRect != null)
                                {
                                    thingRect = thingRect.ExpandedBy(1);
                                    List <IntVec3> possibleCells = new List <IntVec3>();
                                    possibleCells.AddRange(thingRect.GetEdgeCells(Rot4.North));
                                    possibleCells.AddRange(thingRect.GetEdgeCells(Rot4.South));
                                    possibleCells.AddRange(thingRect.GetEdgeCells(Rot4.East));
                                    possibleCells.AddRange(thingRect.GetEdgeCells(Rot4.West));
                                    possibleCells.Remove(Cthulhu.Utility.GetCornerPos(thingRect, 0));
                                    possibleCells.Remove(Cthulhu.Utility.GetCornerPos(thingRect, 1));
                                    possibleCells.Remove(Cthulhu.Utility.GetCornerPos(thingRect, 2));
                                    possibleCells.Remove(Cthulhu.Utility.GetCornerPos(thingRect, 3));

                                    IntVec3 spawnPos = IntVec3.Invalid;
                                    spawnPos = possibleCells.FirstOrDefault((IntVec3 x) => x.InBounds(map) && x.Walkable(map));
                                    if (spawnPos != null)
                                    {
                                        possibleCells.Remove(spawnPos);
                                        Thing thing2 = ThingMaker.MakeThing(chairDef, stuff);
                                        thing2.SetFaction(rp.faction, null);
                                        GenSpawn.Spawn(thing2, spawnPos, map, rot.Opposite);
                                    }
                                    if (!hasLamp)
                                    {
                                        hasLamp  = true;
                                        spawnPos = possibleCells.FirstOrDefault((IntVec3 x) => x.InBounds(map) && x.Walkable(map));
                                        if (spawnPos != null)
                                        {
                                            possibleCells.Remove(spawnPos);
                                            Thing thing3 = ThingMaker.MakeThing(lampDef, lampStuffDef);
                                            thing3.SetFaction(rp.faction, null);
                                            GenSpawn.Spawn(thing3, spawnPos, map, rot.Opposite);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //List<int> corners = new List<int>() { 0, 1, 2, 3 };
            //foreach (int corner in corners.InRandomOrder<int>())
            //{
            //    IntVec3 loc = Cthulhu.Utility.GetCornerPos(rp.rect.ContractedBy(1), corner);
            //    if (!GenSpawn.WouldWipeAnythingWith(loc, Rot4.South, lampDef, map, (Thing x) => x.def.category == ThingCategory.Building))
            //    {
            //        ThingDef singleThingDef3 = (Cthulhu.Utility.IsIndustrialAgeLoaded()) ? lampDef : ThingDefOf.TorchLamp;
            //        Thing thing3 = ThingMaker.MakeThing(singleThingDef3, ThingDefOf.Steel);
            //        GenSpawn.Spawn(thing3, loc, map);
            //        break;
            //    }
            //}
        }
Example #32
0
 public override void DesignateSingleCell(IntVec3 loc)
 {
     DesignateThing(TopDesignatableThing(loc));
 }
Example #33
0
        private void DoDamage(IntVec3 c, float damageFactor, bool CorC)
        {
            ISOTHIS.tmpThings.Clear();
            ISOTHIS.tmpThings.AddRange(c.GetThingList(base.Map));
            Vector3 vector = c.ToVector3Shifted();
            Vector2 b      = new Vector2(vector.x, vector.z);

            //float num = -this.realPosition.AngleTo(b) + 180f;
            for (int i = 0; i < ISOTHIS.tmpThings.Count; i++)
            {
                BattleLogEntry_RangedImpact battleLogEntry_RangedImpact = null;
                switch (ISOTHIS.tmpThings[i].def.category)
                {
                case ThingCategory.Pawn:
                {
                    Pawn pawn = (Pawn)ISOTHIS.tmpThings[i];
                    battleLogEntry_RangedImpact = new BattleLogEntry_RangedImpact
                                                      (this.launcher, pawn, this.intendedTarget.Thing, this.equipmentDef, this.def, this.targetCoverDef);
                    Find.BattleLog.Add(battleLogEntry_RangedImpact);
                    if (pawn.RaceProps.baseHealthScale < 1f)
                    {
                        damageFactor *= pawn.RaceProps.baseHealthScale;
                    }
                    if (pawn.RaceProps.Animal)
                    {
                        damageFactor *= 0.75f;
                    }
                    if (pawn.Downed)
                    {
                        damageFactor *= 0.2f;
                    }
                    break;
                }

                case ThingCategory.Item:
                    damageFactor *= 0.68f;
                    break;

                case ThingCategory.Building:
                    damageFactor *= 0.8f;
                    break;

                case ThingCategory.Plant:
                    damageFactor *= 1.7f;
                    break;
                }
                //int amount = Mathf.Max(GenMath.RoundRandom(30f * damageFactor), 1);

                int   amount    = Mathf.RoundToInt(Mathf.Max(damageFactor * 2, 10));
                Thing arg_184_0 = ISOTHIS.tmpThings[i];
                //Verse.Log.Message(amount.ToString() + "da", false);
                if (CorC)
                {
                    arg_184_0.TakeDamage(new DamageInfo(DamageDefOf.Crush, amount, this.ArmorPenetration * 2, 0, launcher, null, this.def, DamageInfo.SourceCategory.ThingOrUnknown, null)).AssociateWithLog(battleLogEntry_RangedImpact);
                }
                else
                {
                    arg_184_0.TakeDamage(new DamageInfo(DamageDefOf.Cut, amount, this.ArmorPenetration, 0, launcher, null, this.def, DamageInfo.SourceCategory.ThingOrUnknown, null)).AssociateWithLog(battleLogEntry_RangedImpact);
                }
            }
            ISOTHIS.tmpThings.Clear();
        }
Example #34
0
        // Added targetThing to parameters so we can calculate its height
        private bool CanHitCellFromCellIgnoringRange(Vector3 shotSource, IntVec3 targetLoc, Thing targetThing = null)
        {
            // Vanilla checks
            if (verbProps.mustCastOnOpenGround && (!targetLoc.Standable(caster.Map) || caster.Map.thingGrid.CellContains(targetLoc, ThingCategory.Pawn)))
            {
                return(false);
            }
            if (verbProps.requireLineOfSight)
            {
                // Calculate shot vector
                Vector3 targetPos;
                if (targetThing != null)
                {
                    Vector3 targDrawPos = targetThing.DrawPos;
                    targetPos = new Vector3(targDrawPos.x, new CollisionVertical(targetThing).Max, targDrawPos.z);
                    var targPawn = targetThing as Pawn;
                    if (targPawn != null)
                    {
                        targetPos += targPawn.Drawer.leaner.LeanOffset * 0.6f;
                    }
                }
                else
                {
                    targetPos = targetLoc.ToVector3Shifted();
                }
                Ray shotLine = new Ray(shotSource, (targetPos - shotSource));

                // Create validator to check for intersection with partial cover
                var aimMode = CompFireModes?.CurrentAimMode;

                Predicate <IntVec3> CanShootThroughCell = (IntVec3 cell) =>
                {
                    Thing cover = cell.GetFirstPawn(caster.Map) ?? cell.GetCover(caster.Map);

                    if (cover != null && cover != ShooterPawn && cover != caster && cover != targetThing && !cover.IsPlant() && !(cover is Pawn && cover.HostileTo(caster)))
                    {
                        // Skip this check entirely if we're doing suppressive fire and cell is adjacent to target
                        if ((VerbPropsCE.ignorePartialLoSBlocker || aimMode == AimMode.SuppressFire) && cover.def.Fillage != FillCategory.Full)
                        {
                            return(true);
                        }

                        Bounds bounds = CE_Utility.GetBoundsFor(cover);

                        // Simplified calculations for adjacent cover for gameplay purposes
                        if (cover.def.Fillage != FillCategory.Full && cover.AdjacentTo8WayOrInside(caster))
                        {
                            // Sanity check to prevent stuff behind us blocking LoS
                            var cellTargDist = cell.DistanceTo(targetLoc);
                            var shotTargDist = shotSource.ToIntVec3().DistanceTo(targetLoc);

                            if (shotTargDist > cellTargDist)
                            {
                                return(cover is Pawn || bounds.size.y < shotSource.y);
                            }
                        }

                        // Check for intersect
                        if (bounds.IntersectRay(shotLine))
                        {
                            if (Controller.settings.DebugDrawPartialLoSChecks)
                            {
                                caster.Map.debugDrawer.FlashCell(cell, 0, bounds.extents.y.ToString());
                            }
                            return(false);
                        }

                        if (Controller.settings.DebugDrawPartialLoSChecks)
                        {
                            caster.Map.debugDrawer.FlashCell(cell, 0.7f, bounds.extents.y.ToString());
                        }
                    }

                    return(true);
                };

                // Add validator to parameters
                foreach (IntVec3 curCell in SightUtility.GetCellsOnLine(shotSource, targetLoc.ToVector3(), caster.Map))
                {
                    if (Controller.settings.DebugDrawPartialLoSChecks)
                    {
                        caster.Map.debugDrawer.FlashCell(curCell, 0.4f);
                    }
                    if (curCell != shotSource.ToIntVec3() && curCell != targetLoc && !CanShootThroughCell(curCell))
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Example #35
0
        private bool CanHitFromCellIgnoringRange(Vector3 shotSource, LocalTargetInfo targ, out IntVec3 goodDest)
        {
            if (targ.Thing != null)
            {
                if (targ.Thing.Map != caster.Map)
                {
                    goodDest = IntVec3.Invalid;
                    return(false);
                }
                tempDestList.Clear();
                tempDestList.Add(targ.Cell);

                foreach (var dest in tempDestList)
                {
                    if (CanHitCellFromCellIgnoringRange(shotSource, dest, targ.Thing))
                    {   // if any of the locations the target is at or can lean to for shooting can be shot by the shooter then lets have the shooter shoot.
                        goodDest = dest;
                        return(true);
                    }
                }
            }
            else if (CanHitCellFromCellIgnoringRange(shotSource, targ.Cell, targ.Thing))
            {
                goodDest = targ.Cell;
                return(true);
            }
            goodDest = IntVec3.Invalid;
            return(false);
        }
Example #36
0
        public static bool Prefix(ref IAttackTarget __result, List <IAttackTarget> ___tmpTargets, List <Pair <IAttackTarget, float> > ___availableShootingTargets,
                                  List <float> ___tmpTargetScores, List <bool> ___tmpCanShootAtTarget, List <IntVec3> ___tempDestList, List <IntVec3> ___tempSourceList,
                                  IAttackTargetSearcher searcher, TargetScanFlags flags, Predicate <Thing> validator = null, float minDist = 0f, float maxDist = 9999f, IntVec3 locus     = default(IntVec3),
                                  float maxTravelRadiusFromLocus = float.MaxValue, bool canBashDoors = false, bool canTakeTargetsCloserThanEffectiveMinRange   = true, bool canBashFences = false)
        {
            bool result = true;

            if (!recursiveTrap && multiMapSearch)
            {
                recursiveTrap = true;
                Map     oldMap             = searcher.Thing.Map;
                IntVec3 oldPosition        = searcher.Thing.Position;
                bool    dontCheckForStairs = searcher.Thing is Building;
                foreach (var map in ZUtils.GetAllMapsInClosestOrder(searcher.Thing, oldMap, oldPosition, dontCheckForStairs: dontCheckForStairs))
                {
                    if (map != oldMap)
                    {
                        if (ZUtils.ZTracker.GetZIndexFor(map) < ZUtils.ZTracker.GetZIndexFor(oldMap))
                        {
                            CanBeSeenOverFast_Patch.checkLevels = true;
                            CanBeSeenOverFast_Patch.upperMap    = oldMap;
                            CanBeSeenOverFast_Patch.lowerMap    = map;
                            CanBeSeenOverFast_Patch.caster      = searcher.Thing;
                        }
                        var target = AttackTargetFinder.BestAttackTarget(searcher, flags, validator, minDist,
                                                                         maxDist, locus, maxTravelRadiusFromLocus, canBashDoors, canTakeTargetsCloserThanEffectiveMinRange, canBashFences);
                        //ZLogger.Message(searcher.Thing + " - 1: " + ZUtils.ZTracker.GetMapInfo(searcher.Thing.Map) + " - result: " + target);
                        if (target != null)
                        {
                            __result = target;
                            result   = false;
                            break;
                        }
                    }
                }
                //ZLogger.Message("1 Trying to get " + searcher.Thing + " back to " + oldMap + " - " + oldPosition);
                ZUtils.TeleportThing(searcher.Thing, oldMap, oldPosition);
                recursiveTrap = false;
                CanBeSeenOverFast_Patch.checkLevels = false;
                CanBeSeenOverFast_Patch.upperMap    = null;
                CanBeSeenOverFast_Patch.lowerMap    = null;
                CanBeSeenOverFast_Patch.caster      = null;
            }
            return(result);
        }
Example #37
0
        static Job Cleaning_Opportunity(Job currJob, IntVec3 cell, Pawn pawn, int Limit)
        {
            if (Utility.IncapableOfCleaning(pawn))
            {
                return(null);
            }

            Thing   target = null;
            IntVec3 source = pawn.Position;

            Thing building = currJob.targetA.Thing;

            if (building != null)
            {
                if (currJob.targetB != null)
                {
                    target = currJob.targetB.Thing;
                }

                if (target == null && currJob.targetQueueB != null && currJob.targetQueueB.Count > 0)
                {
                    target = currJob.targetQueueB[0].Thing;
                }
            }
            if (target != null)
            {
                float stot = 0; //source to target
                float stob = 0; //source to building
                float btot = 0; //building to target
                bool  b    = false;
                if (Settings.calculate_full_path)
                {
                    PawnPath pawnPath = target.Map.pathFinder.FindPath(source, target, TraverseParms.For(TraverseMode.PassDoors, Danger.None), PathEndMode.Touch);
                    if (!pawnPath.Found)
                    {
                        pawnPath.ReleaseToPool();
                        return(null);
                    }
                    stot = pawnPath.TotalCost;
                    pawnPath.ReleaseToPool();

                    pawnPath = building.Map.pathFinder.FindPath(source, building, TraverseParms.For(TraverseMode.PassDoors, Danger.None), PathEndMode.Touch);
                    if (!pawnPath.Found)
                    {
                        pawnPath.ReleaseToPool();
                        return(null);
                    }
                    stob = pawnPath.TotalCost;
                    pawnPath.ReleaseToPool();

                    pawnPath = target.Map.pathFinder.FindPath(building.Position, target, TraverseParms.For(TraverseMode.PassDoors, Danger.None), PathEndMode.Touch);
                    if (!pawnPath.Found)
                    {
                        pawnPath.ReleaseToPool();
                        return(null);
                    }
                    btot = pawnPath.TotalCost;
                    pawnPath.ReleaseToPool();

                    b = stob > 500 && stot / (stob + btot) < 0.7f;
                }
                else
                {
                    stot = Mathf.Sqrt(source.DistanceToSquared(target.Position));
                    stob = Mathf.Sqrt(source.DistanceToSquared(building.Position));
                    btot = Mathf.Sqrt(building.Position.DistanceToSquared(target.Position));
                    b    = stob > 10 && stot / (stob + btot) < 0.7f;
                }
                if (b)
                {
                    return(null);
                }
            }

            return(MakeCleaningJob(pawn, currJob.targetA, Limit));
        }
Example #38
0
 public override AcceptanceReport CanDesignateCell(IntVec3 c)
 {
     return(GenConstruct.CanPlaceBlueprintAt(entDef, c, placingRot, base.Map, DebugSettings.godMode, null, null, stuffDef));
 }
 public virtual void DoCellSteadyEffects(IntVec3 c, Map map)
 {
 }
Example #40
0
 private static bool CanPlaceBlueprintAt(IntVec3 root, Rot4 rot, ThingDef buildingDef, Map map)
 {
     return(GenConstruct.CanPlaceBlueprintAt(buildingDef, root, rot, map).Accepted);
 }
Example #41
0
        public override bool ModifyCarriedThingDrawPos(ref Vector3 drawPos, ref bool behind, ref bool flip)
        {
            IntVec3 cell = job.GetTarget(TargetIndex.B).Cell;

            return(ModifyCarriedThingDrawPosWorker(ref drawPos, ref behind, ref flip, cell, pawn));
        }
Example #42
0
 public LordJob_MechanoidsDefendShip(Thing shipPart, Faction faction, float defendRadius, IntVec3 defSpot)
 {
     this.shipPart     = shipPart;
     this.faction      = faction;
     this.defendRadius = defendRadius;
     this.defSpot      = defSpot;
 }
        public override void MapComponentTick()
        {
            base.MapComponentTick();
            if (Controller.Settings.waterFreezes.Equals(false))
            {
                return;
            }
            int   num  = Mathf.RoundToInt((float)this.map.Area * 0.00005f);
            int   area = this.map.Area;
            float cellTemp;

            for (int i = 0; i < num; i++)
            {
                this.cycleIndex++;
                if (this.cycleIndex >= area)
                {
                    this.cycleIndex = 0;
                }
                IntVec3 c          = this.map.cellsInRandomOrder.Get(this.cycleIndex);
                var     terrainDef = map.terrainGrid.TerrainAt(c);
                if (!GenTemperature.TryGetTemperatureForCell(c, map, out cellTemp))
                {
                    cellTemp = 0f;
                }
                float shallowChance    = (cellTemp * cellTemp) / 100f;
                float deepChance       = (cellTemp * cellTemp * 0.2f) / 100f;
                float permafrostChance = deepChance;
                if (permafrostChance > 0.2f)
                {
                    permafrostChance = 0.2f;
                }
                if (cellTemp < 0f)
                {
                    if (terrainDef.defName == "WaterShallow" || terrainDef.defName == "IceST")
                    {
                        int freezable = 0;
                        for (int k = -1; k < 2; k++)
                        {
                            for (int j = -1; j < 2; j++)
                            {
                                int x = c.x + k;
                                int z = c.z + j;
                                if ((k == 0 && j == 1) || (k == 0 && j == -1) || (k == 1 && j == 0) || (k == -1 && j == 0))
                                {
                                    if (x > 0 && x < this.map.Size.x && z > 0 && z < this.map.Size.z)
                                    {
                                        IntVec3 newSpot = new IntVec3(x, 0, z);
                                        if (!map.terrainGrid.TerrainAt(newSpot).defName.Contains("Water") && map.terrainGrid.TerrainAt(newSpot).defName != "Marsh" && map.terrainGrid.TerrainAt(newSpot).defName != "BridgeMarsh" && map.terrainGrid.TerrainAt(newSpot).defName != "Bridge")
                                        {
                                            freezable++;
                                        }
                                    }
                                }
                            }
                        }
                        if (Rand.Value < shallowChance * freezable)
                        {
                            List <Thing> thingList = c.GetThingList(map);
                            for (int j = 0; j < thingList.Count; j++)
                            {
                                Thing item = thingList[j];
                                if (item.def.defName == "Fishing Spot" || item.def.defName == "ZARS_FishingSpot")
                                {
                                    item.Destroy(DestroyMode.Vanish);
                                }
                            }
                            string iceType;
                            if (terrainDef.defName == "WaterShallow")
                            {
                                iceType = "IceST";
                            }
                            else
                            {
                                iceType = "IceS";
                            }
                            map.terrainGrid.SetTerrain(c, TerrainDef.Named(iceType));
                        }
                    }
                    if (terrainDef.defName == "WaterDeep" || terrainDef.defName == "IceDT")
                    {
                        int freezable = 0;
                        for (int k = -1; k < 2; k++)
                        {
                            for (int j = -1; j < 2; j++)
                            {
                                int x = c.x + k;
                                int z = c.z + j;
                                if ((k == 0 && j == 1) || (k == 0 && j == -1) || (k == 1 && j == 0) || (k == -1 && j == 0))
                                {
                                    if (x > 0 && x < this.map.Size.x && z > 0 && z < this.map.Size.z)
                                    {
                                        IntVec3 newSpot = new IntVec3(x, 0, z);
                                        if (!map.terrainGrid.TerrainAt(newSpot).defName.Contains("Water") && map.terrainGrid.TerrainAt(newSpot).defName != "Marsh" && map.terrainGrid.TerrainAt(newSpot).defName != "BridgeMarsh" && map.terrainGrid.TerrainAt(newSpot).defName != "Bridge")
                                        {
                                            freezable++;
                                        }
                                    }
                                }
                            }
                        }
                        if (Rand.Value < deepChance * freezable)
                        {
                            List <Thing> thingList = c.GetThingList(map);
                            for (int j = 0; j < thingList.Count; j++)
                            {
                                Thing item = thingList[j];
                                if (item.def.defName == "Fishing Spot" || item.def.defName == "ZARS_FishingSpot")
                                {
                                    item.Destroy(DestroyMode.Vanish);
                                }
                            }
                            string iceType;
                            if (terrainDef.defName == "WaterDeep")
                            {
                                iceType = "IceDT";
                            }
                            else
                            {
                                iceType = "IceD";
                            }
                            map.terrainGrid.SetTerrain(c, TerrainDef.Named(iceType));
                        }
                    }
                    if (terrainDef.defName == "Marsh" || terrainDef.defName == "IceMarshT")
                    {
                        int freezable = 0;
                        for (int k = -1; k < 2; k++)
                        {
                            for (int j = -1; j < 2; j++)
                            {
                                int x = c.x + k;
                                int z = c.z + j;
                                if ((k == 0 && j == 1) || (k == 0 && j == -1) || (k == 1 && j == 0) || (k == -1 && j == 0))
                                {
                                    if (x > 0 && x < this.map.Size.x && z > 0 && z < this.map.Size.z)
                                    {
                                        IntVec3 newSpot = new IntVec3(x, 0, z);
                                        if (!map.terrainGrid.TerrainAt(newSpot).defName.Contains("Water") && map.terrainGrid.TerrainAt(newSpot).defName != "Marsh" && map.terrainGrid.TerrainAt(newSpot).defName != "BridgeMarsh" && map.terrainGrid.TerrainAt(newSpot).defName != "Bridge")
                                        {
                                            freezable++;
                                        }
                                    }
                                }
                            }
                        }
                        if (Rand.Value < shallowChance * freezable)
                        {
                            List <Thing> thingList = c.GetThingList(map);
                            for (int j = 0; j < thingList.Count; j++)
                            {
                                Thing item = thingList[j];
                                if (item.def.defName == "Fishing Spot" || item.def.defName == "ZARS_FishingSpot")
                                {
                                    item.Destroy(DestroyMode.Vanish);
                                }
                            }
                            string iceType;
                            if (terrainDef.defName == "Marsh")
                            {
                                iceType = "IceMarshT";
                            }
                            else
                            {
                                iceType = "IceMarsh";
                            }
                            map.terrainGrid.SetTerrain(c, TerrainDef.Named(iceType));
                        }
                    }
                    if ((terrainDef.defName == "Soil" || terrainDef.defName == "Gravel" || terrainDef.defName == "MossyTerrain") && map.Biome.defName.Contains("Permafrost"))
                    {
                        int freezable = 0;
                        for (int k = -1; k < 2; k++)
                        {
                            for (int j = -1; j < 2; j++)
                            {
                                int x = c.x + k;
                                int z = c.z + j;
                                if ((k == 0 && j == 1) || (k == 0 && j == -1) || (k == 1 && j == 0) || (k == -1 && j == 0))
                                {
                                    if (x > 0 && x < this.map.Size.x && z > 0 && z < this.map.Size.z)
                                    {
                                        IntVec3 newSpot = new IntVec3(x, 0, z);
                                        if (map.terrainGrid.TerrainAt(newSpot).defName == "Ice")
                                        {
                                            freezable++;
                                        }
                                    }
                                }
                            }
                        }
                        if (Rand.Value < (permafrostChance / 8) * freezable)
                        {
                            List <Thing> thingList = c.GetThingList(map);
                            for (int j = 0; j < thingList.Count; j++)
                            {
                                Thing item = thingList[j];
                                if (item.def.thingClass == typeof(Plant))
                                {
                                    item.Destroy(DestroyMode.Vanish);
                                }
                            }
                            map.terrainGrid.SetTerrain(c, TerrainDef.Named("Ice"));
                        }
                    }
                }
                if (cellTemp > -4f)
                {
                    if (terrainDef.defName == "IceS" || terrainDef.defName == "IceD" || terrainDef.defName == "IceST" || terrainDef.defName == "IceDT")
                    {
                        int quickThaw = 1;
                        for (int k = -1; k < 2; k++)
                        {
                            for (int j = -1; j < 2; j++)
                            {
                                int x = c.x + k;
                                int z = c.z + j;
                                if ((k == 0 && j == 1) || (k == 0 && j == -1) || (k == 1 && j == 0) || (k == -1 && j == 0))
                                {
                                    if (x > 0 && x < this.map.Size.x && z > 0 && z < this.map.Size.z)
                                    {
                                        IntVec3 newSpot = new IntVec3(x, 0, z);
                                        if (!terrainDef.label.Contains("Thin"))
                                        {
                                            if (map.terrainGrid.TerrainAt(newSpot).defName.Contains("Water") || map.terrainGrid.TerrainAt(newSpot).defName == "Marsh" || map.terrainGrid.TerrainAt(newSpot).label.Contains("Thin"))
                                            {
                                                quickThaw++;
                                            }
                                        }
                                        else
                                        {
                                            if (map.terrainGrid.TerrainAt(newSpot).defName.Contains("Water") || map.terrainGrid.TerrainAt(newSpot).defName == "Marsh")
                                            {
                                                quickThaw++;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (quickThaw == 1)
                        {
                            if (Rand.Value < 0.67f)
                            {
                                quickThaw = 0;
                            }
                        }
                        if (Rand.Value < (shallowChance * quickThaw))
                        {
                            string waterType;
                            if (terrainDef.defName == "IceST")
                            {
                                waterType = "WaterShallow";
                            }
                            else if (terrainDef.defName == "IceS")
                            {
                                waterType = "IceST";
                            }
                            else if (terrainDef.defName == "IceDT")
                            {
                                waterType = "WaterDeep";
                            }
                            else
                            {
                                waterType = "IceDT";
                            }
                            if (waterType.Contains("Water"))
                            {
                                map.snowGrid.SetDepth(c, 0f);
                            }
                            map.terrainGrid.SetTerrain(c, TerrainDef.Named(waterType));
                        }
                    }
                    if (terrainDef.defName.Contains("IceMarsh"))
                    {
                        int quickThaw = 1;
                        for (int k = -1; k < 2; k++)
                        {
                            for (int j = -1; j < 2; j++)
                            {
                                int x = c.x + k;
                                int z = c.z + j;
                                if ((k == 0 && j == 1) || (k == 0 && j == -1) || (k == 1 && j == 0) || (k == -1 && j == 0))
                                {
                                    if (x > 0 && x < this.map.Size.x && z > 0 && z < this.map.Size.z)
                                    {
                                        IntVec3 newSpot = new IntVec3(x, 0, z);
                                        if (!terrainDef.label.Contains("Thin"))
                                        {
                                            if (map.terrainGrid.TerrainAt(newSpot).defName.Contains("Water") || map.terrainGrid.TerrainAt(newSpot).defName == "Marsh" || map.terrainGrid.TerrainAt(newSpot).label.Contains("Thin"))
                                            {
                                                quickThaw++;
                                            }
                                        }
                                        else
                                        {
                                            if (map.terrainGrid.TerrainAt(newSpot).defName.Contains("Water") || map.terrainGrid.TerrainAt(newSpot).defName == "Marsh")
                                            {
                                                quickThaw++;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (quickThaw == 1)
                        {
                            if (Rand.Value < 0.67f)
                            {
                                quickThaw = 0;
                            }
                        }
                        if (Rand.Value < (shallowChance * quickThaw))
                        {
                            string waterType;
                            if (terrainDef.defName == "IceMarsh")
                            {
                                waterType = "IceMarshT";
                            }
                            else
                            {
                                waterType = "Marsh";
                                map.snowGrid.SetDepth(c, 0f);
                            }
                            map.terrainGrid.SetTerrain(c, TerrainDef.Named(waterType));
                        }
                    }
                    if (terrainDef.defName == "Ice" && map.Biome.defName.Contains("Permafrost"))
                    {
                        int quickThaw = 0;
                        for (int k = -1; k < 2; k++)
                        {
                            for (int j = -1; j < 2; j++)
                            {
                                int x = c.x + k;
                                int z = c.z + j;
                                if ((k == 0 && j == 1) || (k == 0 && j == -1) || (k == 1 && j == 0) || (k == -1 && j == 0))
                                {
                                    if (x > 0 && x < this.map.Size.x && z > 0 && z < this.map.Size.z)
                                    {
                                        IntVec3 newSpot = new IntVec3(x, 0, z);
                                        if (!map.terrainGrid.TerrainAt(newSpot).defName.Contains("Ice"))
                                        {
                                            quickThaw++;
                                        }
                                    }
                                }
                            }
                        }
                        if (Rand.Value < ((permafrostChance / 4) * quickThaw))
                        {
                            map.terrainGrid.SetTerrain(c, TerrainDef.Named("Gravel"));
                        }
                    }
                }
            }
        }
Example #44
0
            static bool Prefix(ref Pawn_JobTracker_Crutch __instance, Job newJob, bool fromQueue)
            {
                try
                {
                    if (__instance == null || __instance._pawn == null || !__instance._pawn.IsColonistPlayerControlled || newJob == null || newJob.def == null)
                    {
                        return(true);
                    }

                    if (Settings.fun_police && __instance._pawn.needs?.joy != null && __instance._pawn.needs.joy.CurLevel < 0.8f)
                    {
                        CompJoyToppedOff c = __instance._pawn.TryGetComp <CompJoyToppedOff>();
                        if (c != null)
                        {
                            c.JoyToppedOff = false;
                        }
                    }

                    if (!Settings.clean_before_work && !Settings.hauling_over_bills)
                    {
                        return(true);
                    }

                    if (!newJob.def.allowOpportunisticPrefix && newJob.def != JobDefOf.SpectateCeremony)
                    {
                        return(true);
                    }

                    Job job = null;

                    if (newJob.def == JobDefOf.DoBill)
                    {
                        if (Settings.hauling_over_bills)
                        {
                            job = Hauling_Opportunity(newJob, __instance._pawn);
                        }
                    }
                    else if (!fromQueue && !newJob.playerForced && newJob.targetA != null && newJob.targetA.Cell != null)
                    {
                        IntVec3 cell = newJob.targetA.Cell;

                        if (!cell.IsValid || cell.IsForbidden(__instance._pawn) || __instance._pawn.Downed)
                        {
                            return(true);
                        }
                        if (Settings.clean_before_work &&
                            (
                                newJob.def == JobDefOf.PrisonerAttemptRecruit ||
                                newJob.def == JobDefOf.PrisonerConvert ||
                                newJob.def == JobDefOf.PrisonerEnslave ||
                                newJob.def == JobDefOf.SpectateCeremony ||
                                newJob.targetA.Thing != null && newJob.targetA.Thing.GetType().IsSubclassOf(typeof(Building)) && newJob.def != JobDefOf.PlaceNoCostFrame && newJob.def != JobDefOf.FinishFrame ||
                                newJob.def.joyKind != null
                            ) &&
                            !HealthAIUtility.ShouldBeTendedNowByPlayer(__instance._pawn))
                        {
                            job = Cleaning_Opportunity(newJob, cell, __instance._pawn, Settings.op_clean_num);
                        }
                    }

                    if (job != null)
                    {
                        if (Settings.add_to_que)
                        {
                            __instance.jobQueue.EnqueueFirst(newJob);
                        }
                        __instance.jobQueue.EnqueueFirst(job);
                        return(false);
                    }
                }
                catch (Exception e)
                {
                    Log.Warning($"CommonSense: opportunistic task skipped due to error ({e.Message}) ({__instance._pawn}, {newJob})");
                }
                return(true);
            }
Example #45
0
 // Token: 0x0600738E RID: 29582 RVA: 0x002893F0 File Offset: 0x002875F0
 public static void PlaceTravelingTunnelers(List <ActiveDropPodInfo> dropPods, IntVec3 near, Map map)
 {
     TransportPodsArrivalActionUtility.RemovePawnsFromWorldPawns(dropPods);
     for (int i = 0; i < dropPods.Count; i++)
     {
         IntVec3 c;
         DropCellFinder.TryFindDropSpotNear(near, map, out c, false, true, true, null);
         TunnelRaidUtility.MakeTunnelAt(c, map, dropPods[i]);
     }
 }
Example #46
0
 public LordToil_PrepareCaravan_GatherSlavesShip(IntVec3 meetingPoint)
 {
     this.meetingPoint = meetingPoint;
 }
 internal bool <> m__1(IntVec3 x)
 {
     return(x.x == this.rp.rect.maxX);
 }
 internal bool <> m__2(IntVec3 x)
 {
     return(x.z == this.rp.rect.minZ);
 }
        public void GetAffectedPawns(IntVec3 center, Map map)
        {
            Pawn    victim = null;
            IntVec3 curCell;
            IEnumerable <IntVec3> targets = GenRadial.RadialCellsAround(center, this.def.projectile.explosionRadius, true);

            for (int i = 0; i < targets.Count(); i++)
            {
                curCell = targets.ToArray <IntVec3>()[i];
                if (curCell.InBounds(map) && curCell.IsValid)
                {
                    victim = curCell.GetFirstPawn(map);
                }

                if (victim != null && victim.Faction == this.caster.Faction && !victim.Dead)
                {
                    if (verVal >= 1)
                    {
                        HealthUtility.AdjustSeverity(victim, HediffDef.Named("TM_HediffTimedInvulnerable"), 1f);
                    }
                    if (verVal >= 2)
                    {
                        Pawn pawn       = victim;
                        bool flag       = pawn != null && !pawn.Dead && !TM_Calc.IsUndead(pawn);
                        bool undeadFlag = pawn != null && !pawn.Dead && TM_Calc.IsUndead(pawn);
                        if (flag)
                        {
                            int num = 3;
                            using (IEnumerator <BodyPartRecord> enumerator = pawn.health.hediffSet.GetInjuredParts().GetEnumerator())
                            {
                                while (enumerator.MoveNext())
                                {
                                    BodyPartRecord rec   = enumerator.Current;
                                    bool           flag2 = num > 0;

                                    if (flag2)
                                    {
                                        int num2 = 1;
                                        IEnumerable <Hediff_Injury> arg_BB_0 = pawn.health.hediffSet.GetHediffs <Hediff_Injury>();
                                        Func <Hediff_Injury, bool>  arg_BB_1;

                                        arg_BB_1 = ((Hediff_Injury injury) => injury.Part == rec);

                                        foreach (Hediff_Injury current in arg_BB_0.Where(arg_BB_1))
                                        {
                                            bool flag4 = num2 > 0;
                                            if (flag4)
                                            {
                                                bool flag5 = current.CanHealNaturally() && !current.IsPermanent();
                                                if (flag5)
                                                {
                                                    //current.Heal((float)((int)current.Severity + 1));
                                                    if (!this.caster.IsColonist)
                                                    {
                                                        current.Heal(20.0f); // power affects how much to heal
                                                    }
                                                    else
                                                    {
                                                        current.Heal((5.0f * this.caster.TryGetComp <CompAbilityUserMagic>().arcaneDmg)); // power affects how much to heal
                                                    }
                                                    TM_MoteMaker.ThrowRegenMote(pawn.Position.ToVector3Shifted(), pawn.Map, .6f);
                                                    TM_MoteMaker.ThrowRegenMote(pawn.Position.ToVector3Shifted(), pawn.Map, .4f);
                                                    num--;
                                                    num2--;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (verVal >= 3)
                    {
                        HealthUtility.AdjustSeverity(victim, HediffDef.Named("BestowMightHD"), 1f);
                    }
                }
                if (victim != null && !victim.Dead && TM_Calc.IsUndead(victim))
                {
                    TM_Action.DamageUndead(victim, Rand.Range(5f, 12f), this.launcher);
                }
                targets.GetEnumerator().MoveNext();
            }
        }
 internal bool <> m__0(IntVec3 x)
 {
     return(x.x == this.rp.rect.minX);
 }
        // Token: 0x06003F20 RID: 16160 RVA: 0x001D9208 File Offset: 0x001D7608
        private static float FriendlyFireConeTargetScoreOffset(IAttackTarget target, IAttackTargetSearcher searcher, Verb verb)
        {
            Pawn pawn = searcher.Thing as Pawn;

            if (pawn == null)
            {
                return(0f);
            }
            if (pawn.RaceProps.intelligence < Intelligence.ToolUser)
            {
                return(0f);
            }
            if (pawn.RaceProps.IsMechanoid)
            {
                return(0f);
            }
            Verb_Shoot verb_Shoot = verb as Verb_Shoot;

            if (verb_Shoot == null)
            {
                return(0f);
            }
            ThingDef defaultProjectile = verb_Shoot.verbProps.defaultProjectile;

            if (defaultProjectile == null)
            {
                return(0f);
            }
            if (defaultProjectile.projectile.flyOverhead)
            {
                return(0f);
            }
            Map                   map    = pawn.Map;
            ShotReport            report = ShotReport.HitReportFor(pawn, verb, (Thing)target);
            float                 a      = VerbUtility.CalculateAdjustedForcedMiss(verb.verbProps.forcedMissRadius, report.ShootLine.Dest - report.ShootLine.Source);
            float                 radius = Mathf.Max(a, 1.5f);
            IntVec3               dest2  = report.ShootLine.Dest;
            IEnumerable <IntVec3> source = from dest in GenRadial.RadialCellsAround(dest2, radius, true)
                                           where dest.InBounds(map)
                                           select dest;
            IEnumerable <ShootLine> source2 = from dest in source
                                              select new ShootLine(report.ShootLine.Source, dest);
            IEnumerable <IntVec3> source3    = source2.SelectMany((ShootLine line) => line.Points().Concat(line.Dest).TakeWhile((IntVec3 pos) => pos.CanBeSeenOverFast(map)));
            IEnumerable <IntVec3> enumerable = source3.Distinct <IntVec3>();
            float num = 0f;

            foreach (IntVec3 c in enumerable)
            {
                float num2 = VerbUtility.InterceptChanceFactorFromDistance(report.ShootLine.Source.ToVector3Shifted(), c);
                if (num2 > 0f)
                {
                    List <Thing> thingList = c.GetThingList(map);
                    for (int i = 0; i < thingList.Count; i++)
                    {
                        Thing thing = thingList[i];
                        if (thing is IAttackTarget && thing != target)
                        {
                            float num3;
                            if (thing == searcher)
                            {
                                num3 = 40f;
                            }
                            else if (thing is Pawn)
                            {
                                num3 = ((!thing.def.race.Animal) ? 18f : 7f);
                            }
                            else
                            {
                                num3 = 10f;
                            }
                            num3 *= num2;
                            if (searcher.Thing.HostileTo(thing))
                            {
                                num3 *= 0.6f;
                            }
                            else
                            {
                                num3 *= -1f;
                            }
                            num += num3;
                        }
                    }
                }
            }
            return(num);
        }
 // ignore fogged cells unless dev mode is on
 private bool BlockedByFog(IntVec3 cell, Map map)
 {
     return(map.fogGrid.IsFogged(cell) && !DebugSettings.godMode);
 }
        // Token: 0x06003F17 RID: 16151 RVA: 0x001D8758 File Offset: 0x001D6B58
        public static IAttackTarget BestAttackTarget(IAttackTargetSearcher searcher, TargetScanFlags flags, Predicate <Thing> validator = null, float minDist = 0f, float maxDist = 9999f, IntVec3 locus = default(IntVec3), float maxTravelRadiusFromLocus = 3.40282347E+38f, bool canBash = false, bool canTakeTargetsCloserThanEffectiveMinRange = true)
        {
            Thing searcherThing = searcher.Thing;
            Pawn  searcherPawn  = searcher as Pawn;
            Verb  verb          = searcher.CurrentEffectiveVerb;

            if (verb == null)
            {
                Log.Error("BestAttackTarget with " + searcher.ToStringSafe <IAttackTargetSearcher>() + " who has no attack verb.", false);
                return(null);
            }
            bool  onlyTargetMachines = verb.IsEMP();
            float minDistSquared     = minDist * minDist;
            float num = maxTravelRadiusFromLocus + verb.verbProps.range;
            float maxLocusDistSquared         = num * num;
            Func <IntVec3, bool> losValidator = null;

            if ((byte)(flags & TargetScanFlags.LOSBlockableByGas) != 0)
            {
                losValidator = delegate(IntVec3 vec3)
                {
                    Gas gas = vec3.GetGas(searcherThing.Map);
                    return(gas == null || !gas.def.gas.blockTurretTracking);
                };
            }
            Predicate <IAttackTarget> innerValidator = delegate(IAttackTarget t)
            {
                Thing thing = t.Thing;
                if (t == searcher)
                {
                    return(false);
                }
                if (minDistSquared > 0f && (float)(searcherThing.Position - thing.Position).LengthHorizontalSquared < minDistSquared)
                {
                    return(false);
                }
                if (!canTakeTargetsCloserThanEffectiveMinRange)
                {
                    float num2 = verb.verbProps.EffectiveMinRange(thing, searcherThing);
                    if (num2 > 0f && (float)(searcherThing.Position - thing.Position).LengthHorizontalSquared < num2 * num2)
                    {
                        return(false);
                    }
                }
                if (maxTravelRadiusFromLocus < 9999f && (float)(thing.Position - locus).LengthHorizontalSquared > maxLocusDistSquared)
                {
                    return(false);
                }

                /*
                 * if (!searcherThing.HostileTo(thing))
                 * {
                 *  return false;
                 * }
                 */
                if (validator != null && !validator(thing))
                {
                    return(false);
                }
                if (searcherPawn != null)
                {
                    Lord lord = searcherPawn.GetLord();
                    if (lord != null && !lord.LordJob.ValidateAttackTarget(searcherPawn, thing))
                    {
                        return(false);
                    }
                }
                if ((byte)(flags & TargetScanFlags.NeedLOSToAll) != 0 && !searcherThing.CanSee(thing, losValidator))
                {
                    if (t is Pawn)
                    {
                        if ((byte)(flags & TargetScanFlags.NeedLOSToPawns) != 0)
                        {
                            return(false);
                        }
                    }
                    else if ((byte)(flags & TargetScanFlags.NeedLOSToNonPawns) != 0)
                    {
                        return(false);
                    }
                }
                if ((byte)(flags & TargetScanFlags.NeedThreat) != 0 && t.ThreatDisabled(searcher))
                {
                    return(false);
                }
                Pawn pawn = t as Pawn;
                if (onlyTargetMachines && pawn != null && pawn.RaceProps.IsFlesh)
                {
                    return(false);
                }
                if ((byte)(flags & TargetScanFlags.NeedNonBurning) != 0 && thing.IsBurning())
                {
                    return(false);
                }
                if (searcherThing.def.race != null && searcherThing.def.race.intelligence >= Intelligence.Humanlike)
                {
                    CompExplosive compExplosive = thing.TryGetComp <CompExplosive>();
                    if (compExplosive != null && compExplosive.wickStarted)
                    {
                        return(false);
                    }
                }
                if (thing.def.size.x == 1 && thing.def.size.z == 1)
                {
                    if (thing.Position.Fogged(thing.Map))
                    {
                        return(false);
                    }
                }
                else
                {
                    bool flag2 = false;
                    CellRect.CellRectIterator iterator = thing.OccupiedRect().GetIterator();
                    while (!iterator.Done())
                    {
                        if (!iterator.Current.Fogged(thing.Map))
                        {
                            flag2 = true;
                            break;
                        }
                        iterator.MoveNext();
                    }
                    if (!flag2)
                    {
                        return(false);
                    }
                }
                return(true);
            };

            if (XenomorphTargetFinder.HasRangedAttack(searcher))
            {
                XenomorphTargetFinder.tmpTargets.Clear();
                XenomorphTargetFinder.tmpTargets.AddRange(searcherThing.Map.attackTargetsCache.GetPotentialTargetsFor(searcher));
                if ((byte)(flags & TargetScanFlags.NeedReachable) != 0)
                {
                    Predicate <IAttackTarget> oldValidator = innerValidator;
                    innerValidator = ((IAttackTarget t) => oldValidator(t) && XenomorphTargetFinder.CanReach(searcherThing, t.Thing, canBash));
                }
                bool flag = false;
                for (int i = 0; i < XenomorphTargetFinder.tmpTargets.Count; i++)
                {
                    IAttackTarget attackTarget = XenomorphTargetFinder.tmpTargets[i];
                    if (attackTarget.Thing.Position.InHorDistOf(searcherThing.Position, maxDist) && innerValidator(attackTarget) && XenomorphTargetFinder.CanShootAtFromCurrentPosition(attackTarget, searcher, verb))
                    {
                        flag = true;
                        break;
                    }
                }
                IAttackTarget result;
                if (flag)
                {
                    XenomorphTargetFinder.tmpTargets.RemoveAll((IAttackTarget x) => !x.Thing.Position.InHorDistOf(searcherThing.Position, maxDist) || !innerValidator(x));
                    result = XenomorphTargetFinder.GetRandomShootingTargetByScore(XenomorphTargetFinder.tmpTargets, searcher, verb);
                }
                else
                {
                    Predicate <Thing> validator2;
                    if ((byte)(flags & TargetScanFlags.NeedReachableIfCantHitFromMyPos) != 0 && (byte)(flags & TargetScanFlags.NeedReachable) == 0)
                    {
                        validator2 = ((Thing t) => innerValidator((IAttackTarget)t) && (XenomorphTargetFinder.CanReach(searcherThing, t, canBash) || XenomorphTargetFinder.CanShootAtFromCurrentPosition((IAttackTarget)t, searcher, verb)));
                    }
                    else
                    {
                        validator2 = ((Thing t) => innerValidator((IAttackTarget)t));
                    }
                    result = (IAttackTarget)GenClosest.ClosestThing_Global(searcherThing.Position, XenomorphTargetFinder.tmpTargets, maxDist, validator2, null);
                }
                XenomorphTargetFinder.tmpTargets.Clear();
                return(result);
            }
            if (searcherPawn != null && searcherPawn.mindState.duty != null && searcherPawn.mindState.duty.radius > 0f && !searcherPawn.InMentalState)
            {
                Predicate <IAttackTarget> oldValidator = innerValidator;
                innerValidator = ((IAttackTarget t) => oldValidator(t) && t.Thing.Position.InHorDistOf(searcherPawn.mindState.duty.focus.Cell, searcherPawn.mindState.duty.radius));
            }
            IntVec3           position         = searcherThing.Position;
            Map               map              = searcherThing.Map;
            ThingRequest      thingReq         = ThingRequest.ForGroup(ThingRequestGroup.AttackTarget);
            PathEndMode       peMode           = PathEndMode.Touch;
            Pawn              searcherPawn2    = searcherPawn;
            Danger            maxDanger        = Danger.Deadly;
            bool              canBash2         = canBash;
            TraverseParms     traverseParams   = TraverseParms.For(searcherPawn2, maxDanger, TraverseMode.ByPawn, canBash2);
            float             maxDist2         = maxDist;
            Predicate <Thing> validator3       = (Thing x) => innerValidator((IAttackTarget)x);
            int               searchRegionsMax = (maxDist <= 800f) ? 40 : -1;
            IAttackTarget     attackTarget2    = (IAttackTarget)GenClosest.ClosestThingReachable(position, map, thingReq, peMode, traverseParams, maxDist2, validator3, null, 0, searchRegionsMax, false, RegionType.Set_Passable, false);

            if (attackTarget2 != null && PawnUtility.ShouldCollideWithPawns(searcherPawn))
            {
                IAttackTarget attackTarget3 = XenomorphTargetFinder.FindBestReachableMeleeTarget(innerValidator, searcherPawn, maxDist, canBash);
                if (attackTarget3 != null)
                {
                    float lengthHorizontal  = (searcherPawn.Position - attackTarget2.Thing.Position).LengthHorizontal;
                    float lengthHorizontal2 = (searcherPawn.Position - attackTarget3.Thing.Position).LengthHorizontal;
                    if (Mathf.Abs(lengthHorizontal - lengthHorizontal2) < 50f)
                    {
                        attackTarget2 = attackTarget3;
                    }
                }
            }
            return(attackTarget2);
        }
        // Token: 0x06003F19 RID: 16153 RVA: 0x001D8C58 File Offset: 0x001D7058
        private static IAttackTarget FindBestReachableMeleeTarget(Predicate <IAttackTarget> validator, Pawn searcherPawn, float maxTargDist, bool canBash)
        {
            maxTargDist = Mathf.Min(maxTargDist, 30f);
            IAttackTarget reachableTarget = null;
            Func <IntVec3, IAttackTarget> bestTargetOnCell = delegate(IntVec3 x)
            {
                List <Thing> thingList = x.GetThingList(searcherPawn.Map);
                for (int i = 0; i < thingList.Count; i++)
                {
                    Thing         thing        = thingList[i];
                    IAttackTarget attackTarget = thing as IAttackTarget;
                    if (attackTarget != null)
                    {
                        if (validator(attackTarget))
                        {
                            if (ReachabilityImmediate.CanReachImmediate(x, thing, searcherPawn.Map, PathEndMode.Touch, searcherPawn))
                            {
                                if (searcherPawn.CanReachImmediate(thing, PathEndMode.Touch) || searcherPawn.Map.attackTargetReservationManager.CanReserve(searcherPawn, attackTarget))
                                {
                                    return(attackTarget);
                                }
                            }
                        }
                    }
                }
                return(null);
            };

            searcherPawn.Map.floodFiller.FloodFill(searcherPawn.Position, delegate(IntVec3 x)
            {
                if (!x.Walkable(searcherPawn.Map))
                {
                    return(false);
                }
                if ((float)x.DistanceToSquared(searcherPawn.Position) > maxTargDist * maxTargDist)
                {
                    return(false);
                }
                if (!canBash)
                {
                    Building_Door building_Door = x.GetEdifice(searcherPawn.Map) as Building_Door;
                    if (building_Door != null && !building_Door.CanPhysicallyPass(searcherPawn))
                    {
                        return(false);
                    }
                }
                return(!PawnUtility.AnyPawnBlockingPathAt(x, searcherPawn, true, false, false));
            }, delegate(IntVec3 x)
            {
                for (int i = 0; i < 8; i++)
                {
                    IntVec3 intVec = x + GenAdj.AdjacentCells[i];
                    if (intVec.InBounds(searcherPawn.Map))
                    {
                        IAttackTarget attackTarget = bestTargetOnCell(intVec);
                        if (attackTarget != null)
                        {
                            reachableTarget = attackTarget;
                            break;
                        }
                    }
                }
                return(reachableTarget != null);
            }, int.MaxValue, false, null);
            return(reachableTarget);
        }
Example #55
0
        /// <summary>
        /// Checks if the shooter can hit the target from a certain position with regards to cover height
        /// </summary>
        /// <param name="root">The position from which to check</param>
        /// <param name="targ">The target to check for line of sight</param>
        /// <returns>True if shooter can hit target from root position, false otherwise</returns>
        public override bool CanHitTargetFrom(IntVec3 root, LocalTargetInfo targ)
        {
            string unused;

            return(CanHitTargetFrom(root, targ, out unused));
        }
Example #56
0
        //See if closestSlot already contains Thing, if not double check the whole storage cell to see if there's an existing stack we want to force our Thing onto
        static void TryFindBestBetterStoreCellForWorker_Postfix(Thing t, Pawn carrier, Map map, Faction faction, SlotGroup slotGroup, ref IntVec3 closestSlot)
        {
            if (slotGroup == null || !slotGroup.parent.Accepts(t))
            {
                //So I don't think I needed this check in 1.0 but clearly this is needed in 1.1
                //HaulToStack.Instance.Logger.Message("slotgroup is null or doesn't accept item");
                return;
            }
            if (!closestSlot.InBounds(map))
            {
                //HaulToStack.Instance.Logger.Message("The original location picked to place item is out of bounds for an unknown reason");
                //HaulToStack.Instance.Logger.Message($"Thing {t.def.defName} Pawn: {carrier.Name}");
                //HaulToStack.Instance.Logger.Message($"Pawn: {carrier.Name}");
                return;
            }

            List <Thing> thingList = closestSlot.GetThingList(map);

            if (thingList.Exists(item => item.def.defName == t.def.defName))
            {
                return;
            }
            else
            {
                //HaulToStack.Instance.Logger.Trace("THE PLACE WE WERE GOING TO HAUL TO DOESN'T HAVE: " + t.def.defName);
                List <IntVec3> cellsList = slotGroup.CellsList;
                foreach (IntVec3 cell in cellsList)
                {
                    if (cell.InBounds(map))
                    {
                        //HaulToStack.Instance.Logger.Message("cell in the provided slotGroup is in bounds");
                        //return;
                        if (cell.GetThingList(map).Exists(item => item.def.defName == t.def.defName))
                        {
                            if (StoreUtility.IsGoodStoreCell(cell, map, t, carrier, faction))
                            {
                                //HaulToStack.Instance.Logger.Trace("FOUND AN EXISTING TILE WITH " + t.def.defName);
                                closestSlot = cell;
                                return;
                            }
                        }
                    }
                    //HaulToStack.Instance.Logger.Message("cell in the provided slotGroup is out of bounds");
                }

                //HaulToStack.Instance.Logger.Trace("TILE WITH EXISTING STACK OF " + t.def.defName + " DOES NOT EXIST, USING PREDETERMINED STACK LOCATION");
                //HaulToStack.Instance.Logger.Trace("----------------------------------------------------------------------------------------------------");
            }
        }
Example #57
0
        public virtual bool CanHitTargetFrom(IntVec3 root, LocalTargetInfo targ, out string report)
        {
            report = "";
            if (caster?.Map == null || !targ.Cell.InBounds(caster.Map) || !root.InBounds(caster.Map))
            {
                report = "Out of bounds";
                return(false);
            }
            // Check target self
            if (targ.Thing != null && targ.Thing == caster)
            {
                if (!verbProps.targetParams.canTargetSelf)
                {
                    report = "Can't target self";
                    return(false);
                }
                return(true);
            }
            // Check thick roofs
            if (Projectile.projectile.flyOverhead)
            {
                RoofDef roofDef = caster.Map.roofGrid.RoofAt(targ.Cell);
                if (roofDef != null && roofDef.isThickRoof)
                {
                    report = "Blocked by roof";
                    return(false);
                }
            }
            if (ShooterPawn != null)
            {
                // Check for capable of violence
                if (ShooterPawn.story != null && ShooterPawn.WorkTagIsDisabled(WorkTags.Violent))
                {
                    report = "IsIncapableOfViolenceLower".Translate(ShooterPawn.Name.ToStringShort);
                    return(false);
                }

                // Check for apparel
                bool isTurretOperator = caster.def.building?.IsTurret ?? false;
                if (ShooterPawn.apparel != null)
                {
                    List <Apparel> wornApparel = ShooterPawn.apparel.WornApparel;
                    foreach (Apparel current in wornApparel)
                    {
                        //pawns can use turrets while wearing shield belts, but the shield is disabled for the duration via Harmony patch (see Harmony-ShieldBelt.cs)
                        if (!current.AllowVerbCast(root, caster.Map, targ, this) && !(current is ShieldBelt && isTurretOperator))
                        {
                            report = "Shooting disallowed by " + current.LabelShort;
                            return(false);
                        }
                    }
                }
            }
            // Check for line of sight
            ShootLine shootLine;

            if (!TryFindCEShootLineFromTo(root, targ, out shootLine))
            {
                float lengthHorizontalSquared = (root - targ.Cell).LengthHorizontalSquared;
                if (lengthHorizontalSquared > verbProps.range * verbProps.range)
                {
                    report = "Out of range";
                }
                else if (lengthHorizontalSquared < verbProps.minRange * verbProps.minRange)
                {
                    report = "Within minimum range";
                }
                else
                {
                    report = "No line of sight";
                }
                return(false);
            }
            return(true);
        }
Example #58
0
        public bool TryFindCEShootLineFromTo(IntVec3 root, LocalTargetInfo targ, out ShootLine resultingLine)
        {
            if (targ.HasThing && targ.Thing.Map != caster.Map)
            {
                resultingLine = default(ShootLine);
                return(false);
            }
            if (verbProps.range <= ShootTuning.MeleeRange) // If this verb has a MAX range up to melee range (NOT a MIN RANGE!)
            {
                resultingLine = new ShootLine(root, targ.Cell);
                return(ReachabilityImmediate.CanReachImmediate(root, targ, caster.Map, PathEndMode.Touch, null));
            }
            CellRect cellRect = (!targ.HasThing) ? CellRect.SingleCell(targ.Cell) : targ.Thing.OccupiedRect();
            float    num      = cellRect.ClosestDistSquaredTo(root);

            if (num > verbProps.range * verbProps.range || num < verbProps.minRange * verbProps.minRange)
            {
                resultingLine = new ShootLine(root, targ.Cell);
                return(false);
            }
            //if (!this.verbProps.NeedsLineOfSight) This method doesn't consider the currently loaded projectile
            if (Projectile.projectile.flyOverhead)
            {
                resultingLine = new ShootLine(root, targ.Cell);
                return(true);
            }

            // First check current cell for early opt-out
            IntVec3 dest;
            var     shotSource = root.ToVector3Shifted();

            shotSource.y = ShotHeight;

            // Adjust for multi-tile turrets
            if (caster.def.building?.IsTurret ?? false)
            {
                shotSource = ShotSource;
            }

            if (CanHitFromCellIgnoringRange(shotSource, targ, out dest))
            {
                resultingLine = new ShootLine(root, dest);
                return(true);
            }
            // For pawns, calculate possible lean locations
            if (CasterIsPawn)
            {
                // Next check lean sources
                ShootLeanUtility.LeanShootingSourcesFromTo(root, cellRect.ClosestCellTo(root), caster.Map, tempLeanShootSources);
                foreach (var leanLoc in tempLeanShootSources)
                {
                    var leanOffset = (leanLoc - root).ToVector3() * 0.5f;

                    if (CanHitFromCellIgnoringRange(shotSource + leanOffset, targ, out dest))
                    {
                        resultingLine = new ShootLine(leanLoc, dest);
                        return(true);
                    }
                }
            }

            resultingLine = new ShootLine(root, targ.Cell);
            return(false);
        }
Example #59
0
        public static bool ModifyCarriedThingDrawPosWorker(ref Vector3 drawPos, ref bool behind, ref bool flip, IntVec3 placeCell, Pawn pawn)
        {
            if (pawn.pather.Moving)
            {
                return(false);
            }
            Thing carriedThing = pawn.carryTracker.CarriedThing;

            if (carriedThing == null || !carriedThing.IngestibleNow)
            {
                return(false);
            }
            if (placeCell.IsValid && placeCell.AdjacentToCardinal(pawn.Position) && placeCell.HasEatSurface(pawn.Map) && carriedThing.def.ingestible.ingestHoldUsesTable)
            {
                drawPos = new Vector3((float)placeCell.x + 0.5f, drawPos.y, (float)placeCell.z + 0.5f);
                return(true);
            }
            if (carriedThing.def.ingestible.ingestHoldOffsetStanding != null)
            {
                HoldOffset holdOffset = carriedThing.def.ingestible.ingestHoldOffsetStanding.Pick(pawn.Rotation);
                if (holdOffset != null)
                {
                    drawPos += holdOffset.offset;
                    behind   = holdOffset.behind;
                    flip     = holdOffset.flip;
                    return(true);
                }
            }
            return(false);
        }
 public bool StackableAt(Thing thing, IntVec3 cell, Map map)
 {
     return(CapacityToStoreThingAt(thing, map, cell) > 0);
 }