コード例 #1
0
        // Link a building with a facility
        // affectedDef must have CompAffectedByFacilities
        // facilityDef must have CompFacility
        public static bool LinkFacility( ThingDef affectedDef, ThingDef facilityDef )
        {
            // Get comps
            var affectedComp = affectedDef.GetCompProperties<CompProperties_AffectedByFacilities>();
            var facilityComp = facilityDef.GetCompProperties<CompProperties_Facility>();
            if(
                ( affectedComp == null )||
                ( facilityComp == null )
            )
            {
                // Bad call
                return false;
            }

            // Add the facility to the building
            affectedComp.linkableFacilities.AddUnique( facilityDef );

            // Is the facility in the dictionary?
            if( !facilityComps.ContainsKey( facilityDef ) )
            {
                // Add the facility to the dictionary
                facilityComps.Add( facilityDef, facilityComp );
            }

            // Building is [now] linked to the facility
            return true;
        }
コード例 #2
0
 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());
 }
コード例 #3
0
ファイル: CompRecipeModify.cs プロジェクト: BBream/Vehicle
        public ThingDef FullCopyUnfinishedThingDef(ThingDef unfinishedThingDef)
        {
            if (unfinishedThingDef == null)
                return null;

            ThingDef copy = new ThingDef();

            copy.defName = unfinishedThingDef.defName;
            copy.label = unfinishedThingDef.label;
            copy.thingClass = unfinishedThingDef.thingClass;
            copy.category = unfinishedThingDef.category;
            copy.label = unfinishedThingDef.label;
            copy.graphicData = unfinishedThingDef.graphicData;
            copy.altitudeLayer = unfinishedThingDef.altitudeLayer;
            copy.useHitPoints = unfinishedThingDef.useHitPoints;
            copy.isUnfinishedThing = unfinishedThingDef.isUnfinishedThing;
            copy.selectable = unfinishedThingDef.selectable;
            copy.tradeability = unfinishedThingDef.tradeability;
            copy.drawerType = unfinishedThingDef.drawerType;
            copy.statBases = GenList.ListFullCopyOrNull(unfinishedThingDef.statBases);
            copy.comps = GenList.ListFullCopyOrNull(unfinishedThingDef.comps);
            copy.alwaysHaulable = unfinishedThingDef.alwaysHaulable;
            copy.rotatable = unfinishedThingDef.rotatable;
            copy.pathCost = unfinishedThingDef.pathCost;
            copy.thingCategories = GenList.ListFullCopyOrNull(unfinishedThingDef.thingCategories);
            copy.stuffCategories = GenList.ListFullCopyOrNull(unfinishedThingDef.stuffCategories);

            return copy;
        }
コード例 #4
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;
        }
コード例 #5
0
        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);
        }
コード例 #6
0
        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 ) );
            }
        }
コード例 #7
0
 /// <summary>
 /// Draws a target highlight on Hopper user
 /// </summary>
 /// <param name="def"></param>
 /// <param name="center"></param>
 /// <param name="rot"></param>
 public override void DrawGhost(ThingDef def, IntVec3 center, Rot4 rot)
 {
     Thing hopperUser = CompHopper.FindHopperUser( center + rot.FacingCell );
     if ( (hopperUser != null) && !hopperUser.OccupiedRect().Cells.Contains( center ) )
     {
         GenDraw.DrawTargetHighlight( hopperUser );
     }
 }
コード例 #8
0
        public static bool IsSeedForPlant(ThingDef seedDef, ThingDef plantDef)
        {
            ThingDef_PlantWithSeeds customPlantDef = plantDef as ThingDef_PlantWithSeeds;
            if (customPlantDef != null)
                return seedDef == customPlantDef.SeedDef;

            return false;
        }
コード例 #9
0
 /// <summary>
 /// Draws a target highlight on all connectable Hoppers around target
 /// </summary>
 /// <param name="def"></param>
 /// <param name="center"></param>
 /// <param name="rot"></param>
 public override void DrawGhost( ThingDef def, IntVec3 center, Rot4 rot )
 {
     List<CompHopper> hoppers = CompHopperUser.FindHoppers( center, rot, def.Size );
     foreach( var hopper in hoppers )
     {
         GenDraw.DrawTargetHighlight( hopper.parent );
     }
 }
コード例 #10
0
        public static IEnumerable<ThingDef> ImpliedUnfinishedDefs()
        {
            foreach (var sourceDef in DefDatabase<RecipeDef>.AllDefs.Where(def =>
                def.UsesUnfinishedThing && def.unfinishedThingDef.defName == "UnfinishedThing").ToList())
            {
                var firstProductDef = sourceDef.products.FirstOrDefault().thingDef;

                var newDef = new ThingDef
                {
                    defName = firstProductDef.defName + "Unfinished",
                    label = "unfinished " + firstProductDef.label,
                    description = "Unfinished " + firstProductDef.label + ".",
                    thingClass = typeof (RA_UnfinishedThing),
                    category = ThingCategory.Item,
                    altitudeLayer = AltitudeLayer.Item,
                    stackLimit = 1,
                    pathCost = 15,
                    alwaysHaulable = true,
                    drawGUIOverlay = true,
                    useHitPoints = true,
                    selectable = true,
                    isUnfinishedThing = true,
                    thingCategories = new List<ThingCategoryDef>(),
                    stuffCategories = firstProductDef.stuffCategories,
                    graphicData = new GraphicData()
                };

                newDef.graphicData.CopyFrom(firstProductDef.graphicData);
                newDef.graphicData.drawSize = Vector2.one;

                // assigns MinifiedThings ThingCategory
                CrossRefLoader.RegisterListWantsCrossRef(newDef.thingCategories, "UnfinishedThings");

                newDef.comps.Add(new CompProperties_Forbiddable());

                newDef.SetStatBaseValue(StatDefOf.MaxHitPoints,
                    firstProductDef.statBases.StatListContains(StatDefOf.MaxHitPoints)
                        ? firstProductDef.BaseMaxHitPoints
                        : 100);
                newDef.SetStatBaseValue(StatDefOf.Flammability,
                    firstProductDef.statBases.StatListContains(StatDefOf.Flammability)
                        ? firstProductDef.BaseFlammability
                        : 1);
                newDef.SetStatBaseValue(StatDefOf.MarketValue,
                    firstProductDef.statBases.StatListContains(StatDefOf.MarketValue)
                        ? firstProductDef.BaseMarketValue
                        : 100);
                newDef.SetStatBaseValue(StatDefOf.Beauty,
                    firstProductDef.statBases.StatListContains(StatDefOf.Beauty)
                        ? firstProductDef.GetStatValueAbstract(StatDefOf.Beauty) - 5
                        : -2);

                // assign new minified def to the source ThingDef
                sourceDef.unfinishedThingDef = newDef;

                yield return newDef;
            }
        }
コード例 #11
0
 public void AddItem(ThingDef def, int amount)
 {
     if(Contains(def))
     {
         AddToExisting(def, amount);
         return;
     }
     AddNew(def, amount);
 }
コード例 #12
0
 public static Toil SpawnThingDefOfCountAt( ThingDef of, int count, IntVec3 at )
 {
     return new Toil
     {
         initAction = delegate
         {
             Common.SpawnThingDefOfCountAt( of, count, at );
         }
     };
 }
コード例 #13
0
 public static void SpawnThingDefOfCountAt( ThingDef of, int count, IntVec3 at )
 {
     while( count > 0 )
     {
         Thing newStack = ThingMaker.MakeThing( of, null );
         newStack.stackCount = Math.Min( count, of.stackLimit );
         GenSpawn.Spawn( newStack, at );
         count -= newStack.stackCount;
     }
 }
コード例 #14
0
 public static Toil ReplaceThingWithThingDefOfCount( Thing oldThing, ThingDef of, int count )
 {
     return new Toil
     {
         initAction = delegate
         {
             Common.ReplaceThingWithThingDefOfCount( oldThing, of, count );
         }
     };
 }
コード例 #15
0
 public static bool Spawn(ThingDef thingDef, int numberToSpawn, IntVec3 initialPos, int radiusMax)
 {
     int num = numberToSpawn;
     while (num > 0)
     {
         IntVec3 pos = initialPos + GenRadial.RadialPattern[count];
         if (pos.Standable() && pos.InBounds())
         {
             List<Thing> list = Find.ThingGrid.ThingsListAt(pos);
             if (list.Count != 0)
             {
                 foreach (Thing thing in list)
                 {
                     //Thing thing = Find.ThingGrid.ThingAt(pos, thingDef);
                     if (thing.def.defName == thingDef.defName)
                     {
                         if (!(thing.stackCount == thing.def.stackLimit))
                         {
                             int remainder = thing.def.stackLimit - thing.stackCount;
                             if (num >= remainder)
                             {
                                 AddToExistingStack(thing, remainder);
                                 num -= remainder;
                             }
                             else
                             {
                                 AddToExistingStack(thing, num);
                                 num = 0;
                             }
                         }
                     } //If foundThing not the same, leave
                 }
             }
             else
             {
                 MakeNewStack(thingDef, num, pos);
                 num = 0;
             }
         }
         count++;
         if (count > radiusMax)
         {
             break;
         }
     } //End of loop
     count = 0;
     if (num == 0)
     {
         return true;
     }
     else
     {
         return false;
     }
 }
コード例 #16
0
 public bool Contains(ThingDef def)
 {
     foreach(ListItem item in this.allStoredItemsList)
     {
         if(item.thing.defName == def.defName)
         {
             return true;
         }
     }
     return false;
 }
コード例 #17
0
        public override void DrawGhost( ThingDef def, IntVec3 center, Rot4 rot )
        {
            base.DrawGhost( def, center, rot );

            var room = center.GetRoom();
            if ( room == null || room.UsesOutdoorTemperature )
            {
                return;
            }
            GenDraw.DrawFieldEdges( room.Cells.ToList(), GenTemperature.ColorRoomHot );
        }
コード例 #18
0
    public static float PointsPerAnimal( ThingDef animalDef )
    {
        float cost = 10;

        cost += (animalDef.race.meleeDamage*1.8f) + (animalDef.maxHealth * 0.23f);

         //Bias up boomrats for fire explosive
        if( animalDef.label == "Boomrat" )
            cost += 30;

        return cost;
    }
コード例 #19
0
 public static void AddToList( List<ResourceAmount> list, ThingDef thingDef, int countToAdd )
 {
     for( int index = 0; index < list.Count; ++index )
     {
         if( list[ index ].thingDef == thingDef )
         {
             list[ index ] = new ResourceAmount( list[ index ].thingDef, list[ index ].count + countToAdd );
             return;
         }
     }
     list.Add( new ResourceAmount( thingDef, countToAdd ) );
 }
コード例 #20
0
 public static void ReplaceThingWithThingDefOfCount( Thing oldThing, ThingDef of, int count )
 {
     IntVec3 at = oldThing.Position;
     oldThing.Destroy();
     while( count > 0 )
     {
         Thing newStack = ThingMaker.MakeThing( of, null );
         newStack.stackCount = Math.Min( count, of.stackLimit );
         GenSpawn.Spawn( newStack, at );
         count -= newStack.stackCount;
     }
 }
コード例 #21
0
 public bool HasEnoughOf(ThingDef def, int amount)
 {
     int amountAvailable = 0;
     foreach (var t in AllAvailableResources)
     {
         if (t.def == def)
         {
             //Log.Message("Found some");
             amountAvailable += t.stackCount;
         }
     }
     return amountAvailable >= amount ? true : false;
 }
コード例 #22
0
        public void PlaceFrameForBuild(BuildableDef sourceDef, IntVec3 center, Rot4 rotation, Faction faction, ThingDef stuff)
        {
            var frame = (Frame)ThingMaker.MakeThing(sourceDef.frameDef, stuff);
            frame.SetFactionDirect(faction);

            foreach (var resource in frame.MaterialsNeeded())
            {
                var resource1 = ThingMaker.MakeThing(resource.thingDef);
                resource1.stackCount = (int)Math.Round(resource.count * Properties.upgradeDiscountMultiplier);
                frame.resourceContainer.TryAdd(resource1);
            }
            frame.workDone = (int)Math.Round(frame.def.entityDefToBuild.GetStatValueAbstract(StatDefOf.WorkToMake, frame.Stuff) * Properties.upgradeDiscountMultiplier);
            GenSpawn.Spawn(frame, center, rotation);
        }
コード例 #23
0
ファイル: CompAddon_Static.cs プロジェクト: isistoy/DevLib
 public static bool IsValidOpenSlotFor(this CompAddonsHost hostComp, ThingDef addonDef, IntVec3 loc)
 {
     AddonSlot slot = hostComp.slots
          .Where(x =>
              !x.occupied
              && x.linkableAddonDefs.Contains(addonDef)
              && (loc == (hostComp.parent.Position + x.offset.RotatedBy(hostComp.parent.Rotation))))
          .FirstOrDefault();
     if (slot == null)
     {
         return false;
     }
     return true;
 }
コード例 #24
0
        public override void DrawGhost( ThingDef def, IntVec3 center, Rot4 rot )
        {
            var vecNorth = center + IntVec3.North.RotatedBy( rot );
            if ( !vecNorth.InBounds() )
            {
                return;
            }

            GenDraw.DrawFieldEdges( new List< IntVec3 >() {vecNorth}, Color.white );
            var room = vecNorth.GetRoom();
            if ( room == null || room.UsesOutdoorTemperature )
            {
                return;
            }
            GenDraw.DrawFieldEdges( room.Cells.ToList(), GenTemperature.ColorRoomHot );
        }
コード例 #25
0
        public override void DrawGhost( ThingDef def, IntVec3 center, Rot4 rot )
        {
            var vecSouth = center + IntVec3.South.RotatedBy( rot );
            var vecSouthEast = vecSouth + IntVec3.East.RotatedBy( rot );
            if (!vecSouth.InBounds() || !vecSouthEast.InBounds())
            {
                return;
            }

            GenDraw.DrawFieldEdges( new List< IntVec3 >() {vecSouth, vecSouthEast}, GenTemperature.ColorSpotCold );
            var room = vecSouth.GetRoom();
            if (room == null || room.UsesOutdoorTemperature)
            {
                return;
            }
            GenDraw.DrawFieldEdges( room.Cells.ToList(), GenTemperature.ColorRoomCold );
        }
コード例 #26
0
 /// <summary>
 /// Draws a target highlight on Hopper user or connection cell
 /// </summary>
 /// <param name="def"></param>
 /// <param name="center"></param>
 /// <param name="rot"></param>
 public override void DrawGhost( ThingDef def, IntVec3 center, Rot4 rot )
 {
     var connectionCell = center + rot.FacingCell;
     var hopperUser = CompHopper.FindHopperUser( connectionCell );
     var thingUser = hopperUser == null ? (Thing) null : hopperUser.parent;
     if(
         ( thingUser != null )&&
         ( !thingUser.OccupiedRect().Cells.Contains( center ) )
     )
     {
         GenDraw.DrawFieldEdges( thingUser.OccupiedRect().Cells.ToList() );
         GenDraw.DrawTargetHighlight( thingUser );
     }
     else
     {
         GenDraw.DrawTargetHighlight( connectionCell );
     }
 }
コード例 #27
0
        public override void DrawGhost( ThingDef def, IntVec3 center, Rot4 rot )
        {
            base.DrawGhost( def, center, rot );

            var vecNorth = center + IntVec3.North.RotatedBy( rot );
            if (!vecNorth.InBounds())
            {
                return;
            }

            GenDraw.DrawFieldEdges( new List< IntVec3 > {vecNorth}, new Color( 1f, 0.7f, 0f, 0.5f ) );
            var room = vecNorth.GetRoom();
            if (room == null || room.UsesOutdoorTemperature)
            {
                return;
            }
            GenDraw.DrawFieldEdges( room.Cells.ToList(), new Color( 1f, 0.7f, 0f, 0.5f ) );
        }
コード例 #28
0
        // predict possible market value for spawned items
        public static float PredictBaseMarketValue(ThingDef thingDef, CompCraftedValue_Properties compProps)
        {
            var recipe = DefDatabase<RecipeDef>.GetNamed("Make" + thingDef.defName);

            var workValue = thingDef.GetStatValueAbstract(StatDefOf.WorkToMake) * compProps.valuePerWorkFactor;

            var randomIngredientsValue = recipe.ingredients.Sum(ingredient => ingredient.filter.AllowedThingDefs.RandomElement().BaseMarketValue * ingredient.GetBaseCount());

            var minIngredientsValue = recipe.ingredients.Sum(ingredient =>
                ingredient.filter.AllowedThingDefs.Min(def => def.BaseMarketValue) * ingredient.GetBaseCount());
            var maxIngredientsValue = recipe.ingredients.Sum(ingredient =>
                ingredient.filter.AllowedThingDefs.Max(def => def.BaseMarketValue) * ingredient.GetBaseCount());

            var profitCoefficient = maxIngredientsValue != minIngredientsValue
                ? (float)Math.Pow(maxIngredientsValue - minIngredientsValue, 1 - compProps.profitFactor)
                : 0f;

            return profitCoefficient * (randomIngredientsValue - minIngredientsValue) + workValue + minIngredientsValue;
        }
コード例 #29
0
 public static Toil MakeAndSpawnThingRandomRange(ThingDef def, int min, int max)
 {
     Toil toil = new Toil();
     toil.initAction = () =>
     {
         int num = Rand.Range(min,max);
         List<Thing> things = new List<Thing>();
         while (num > 0)
         {
             Thing thing = ThingMaker.MakeThing(def);
             int num2 = UnityEngine.Mathf.Min(num, def.stackLimit);
             thing.stackCount = num2;
             num -= num2;
             things.Add(thing);
         }
         IntVec3 pos = toil.GetActor().jobs.curJob.targetA.Cell;
         foreach (var thing in things)
         {
             GenSpawn.Spawn(thing, pos);
         }
     };
     return toil;
 }
コード例 #30
0
        /// <summary>
        /// Read parameters from XML file
        /// </summary>
        /// <returns>True if parameters are in order, false otherwise</returns>
        public bool getParameters()
        {
            ThingDef_ProjectileFrag projectileDef = this.def as ThingDef_ProjectileFrag;
            if (projectileDef.fragAmountSmall + projectileDef.fragAmountMedium + projectileDef.fragAmountLarge > 0
                && projectileDef.fragRange > 0
                && projectileDef.fragProjectileSmall != null
                && projectileDef.fragProjectileMedium != null
                && projectileDef.fragProjectileLarge != null)
            {
                this.fragAmountSmall = projectileDef.fragAmountSmall;
                this.fragAmountMedium = projectileDef.fragAmountMedium;
                this.fragAmountLarge = projectileDef.fragAmountLarge;

                this.fragRange = projectileDef.fragRange;

                this.fragProjectileSmall = projectileDef.fragProjectileSmall;
                this.fragProjectileMedium = projectileDef.fragProjectileMedium;
                this.fragProjectileLarge = projectileDef.fragProjectileLarge;

                return true;
            }
            return false;
        }
コード例 #31
0
        protected override void Impact(Thing hitThing)
        {
            Map map = base.Map;

            base.Impact(hitThing);
            BattleLogEntry_RangedImpact battleLogEntry_RangedImpact = new BattleLogEntry_RangedImpact(this.launcher, hitThing, this.intendedTarget.Thing, ThingDef.Named("Gun_Autopistol"), this.def, this.targetCoverDef);

            Find.BattleLog.Add(battleLogEntry_RangedImpact);
            if (hitThing != null)
            {
                DamageDef  damageDef        = this.def.projectile.damageDef;
                float      amount           = (float)base.DamageAmount;
                float      armorPenetration = base.ArmorPenetration;
                float      y            = this.ExactRotation.eulerAngles.y;
                Thing      launcher     = this.launcher;
                ThingDef   equipmentDef = this.equipmentDef;
                DamageInfo dinfo        = new DamageInfo(damageDef, amount, armorPenetration, y, launcher, null, null, DamageInfo.SourceCategory.ThingOrUnknown, this.intendedTarget.Thing);
                hitThing.TakeDamage(dinfo).AssociateWithLog(battleLogEntry_RangedImpact);
                Pawn pawn = hitThing as Pawn;
                if (pawn != null && pawn.stances != null && pawn.BodySize <= this.def.projectile.StoppingPower + 0.001f)
                {
                    pawn.stances.StaggerFor(95);
                }
                if (this.def.defName == "AA_FrostWeb")
                {
                    DamageInfo dinfo2 = new DamageInfo(DamageDefOf.Frostbite, amount / 2, armorPenetration, y, launcher, null, null, DamageInfo.SourceCategory.ThingOrUnknown, this.intendedTarget.Thing);
                    hitThing.TakeDamage(dinfo2).AssociateWithLog(battleLogEntry_RangedImpact);
                }
                if (this.def.defName == "AA_FireWeb")
                {
                    DamageInfo dinfo2 = new DamageInfo(DamageDefOf.Burn, amount / 2, armorPenetration, y, launcher, null, null, DamageInfo.SourceCategory.ThingOrUnknown, this.intendedTarget.Thing);
                    hitThing.TakeDamage(dinfo2).AssociateWithLog(battleLogEntry_RangedImpact);
                }
                if (this.def.defName == "AA_AcidicWeb")
                {
                    DamageInfo dinfo2 = new DamageInfo(DefDatabase <DamageDef> .GetNamed("AA_AcidSpit", true), amount / 2, armorPenetration, y, launcher, null, null, DamageInfo.SourceCategory.ThingOrUnknown, this.intendedTarget.Thing);
                    hitThing.TakeDamage(dinfo2).AssociateWithLog(battleLogEntry_RangedImpact);
                }
                if (this.def.defName == "AA_ExplodingWeb")
                {
                    DamageInfo dinfo2 = new DamageInfo(DamageDefOf.Bomb, amount / 2, armorPenetration, y, launcher, null, null, DamageInfo.SourceCategory.ThingOrUnknown, this.intendedTarget.Thing);
                    hitThing.TakeDamage(dinfo2).AssociateWithLog(battleLogEntry_RangedImpact);
                }
            }
            else
            {
                SoundDefOf.BulletImpact_Ground.PlayOneShot(new TargetInfo(base.Position, map, false));
                FleckMaker.Static(this.ExactPosition, map, FleckDefOf.ShotHit_Dirt, 1f);
                if (base.Position.GetTerrain(map).takeSplashes)
                {
                    FleckMaker.WaterSplash(this.ExactPosition, map, Mathf.Sqrt((float)base.DamageAmount) * 1f, 4f);
                }
            }
        }
コード例 #32
0
ファイル: Storage.cs プロジェクト: SeanLeeLKY/MD2-Source
        private void AddToExisting(ThingDef def, int amount)
        {
            ListItem item = GetItemFromDef(def);

            item.amount += amount;
        }
コード例 #33
0
 public static IEnumerable <Thing> GetMeditationFociAffectedByBuilding(Map map, ThingDef def, Faction faction, IntVec3 pos, Rot4 rotation)
 {
     if (!CountsAsArtificialBuilding(def, faction))
     {
         yield break;
     }
     foreach (Thing item in map.listerThings.ThingsMatching(ThingRequest.ForGroup(ThingRequestGroup.MeditationFocus)))
     {
         CompMeditationFocus compMeditationFocus = item.TryGetComp <CompMeditationFocus>();
         if (compMeditationFocus != null && compMeditationFocus.WillBeAffectedBy(def, faction, pos, rotation))
         {
             yield return(item);
         }
     }
 }
コード例 #34
0
 public void TryRevive(bool ForcedRevive = false)
 {
     reviveIntervalTicks = -1;
     reviveTried         = true;
     Rand.PushState();
     if (Rand.Chance(ReanimateChance) || ForcedRevive)
     {
         List <Hediff> hediffs = unhealableHediffs;
         ResurrectionUtility.Resurrect(Pawn);
         if (originalWeapon == null && Pawn.kindDef.weaponTags.Count > 0)
         {
             ThingDef thingDef = ThingDef.Named(Pawn.kindDef.weaponTags[0]);
             Thing    thing2   = GenClosest.ClosestThingReachable(Pawn.Position, Pawn.Map, ThingRequest.ForDef(thingDef), PathEndMode.InteractionCell, TraverseParms.For(Pawn, Danger.Deadly, TraverseMode.ByPawn, false));
             this.originalWeapon = (ThingWithComps)thing2;
         }
         if (originalWeapon != null)
         {
             ThingWithComps thing = originalWeapon;
             if (thing.Spawned)
             {
                 thing.DeSpawn();
             }
             if (Pawn.inventory.innerContainer.Contains(thing))
             {
                 Pawn.inventory.innerContainer.Remove(thing);
             }
             Pawn.equipment.AddEquipment(thing);
         }
         if (secondryWeapon != null)
         {
             ThingWithComps thing = secondryWeapon;
             if (thing.Spawned)
             {
                 thing.DeSpawn();
             }
             if (Pawn.inventory.innerContainer.Contains(thing))
             {
                 Pawn.inventory.innerContainer.Remove(thing);
             }
             //    pawn.equipment.AdMechAddOffHandEquipment(thing);
         }
         if (!ForcedRevive)
         {
             //    bool revives = true;
             foreach (Hediff item in hediffs)
             {
                 if (!Pawn.health.hediffSet.PartIsMissing(item.Part))
                 {
                     if (Pawn.health.WouldDieAfterAddingHediff(item))
                     {
                         //    revives = false;
                     }
                     if (Pawn.health.WouldBeDownedAfterAddingHediff(item))
                     {
                         //    revives = false;
                     }
                     Pawn.health.AddHediff(item);
                 }
             }
         }
         ThrowNecronGlow(Pos.ToVector3(), Map, 5f);
         FleckMaker.Static(Pos, Map, FleckDefOf.ExplosionFlash, 3f);
         //    log.message(string.Format("{0} revive {1}",pawn, str));
     }
     else
     {
         //    log.message(string.Format("{0} revive {1}", pawn, str));
     }
     Rand.PopState();
 }
コード例 #35
0
        public static void Explosion(IntVec3 center, Map map, float radius, DamageDef damType, Thing instigator, SoundDef explosionSound = null, ThingDef projectile = null, ThingDef source = null, ThingDef postExplosionSpawnThingDef = null, float postExplosionSpawnChance = 0f, int postExplosionSpawnThingCount = 1, bool applyDamageToExplosionCellsNeighbors = false, ThingDef preExplosionSpawnThingDef = null, float preExplosionSpawnChance = 0f, int preExplosionSpawnThingCount = 1)
        {
            System.Random rnd = new System.Random();
            int           modDamAmountRand = GenMath.RoundRandom(rnd.Next(1, projectile.projectile.GetDamageAmount(1, null)));

            if (map == null)
            {
                Log.Warning("Tried to do explosion in a null map.");
                return;
            }

            Explosion explosion = (Explosion)GenSpawn.Spawn(ThingDefOf.Explosion, center, map);

            explosion.damageFalloff                        = false;
            explosion.chanceToStartFire                    = 0.0f;
            explosion.armorPenetration                     = 10;
            explosion.Position                             = center;
            explosion.radius                               = radius;
            explosion.damType                              = damType;
            explosion.instigator                           = instigator;
            explosion.damAmount                            = ((projectile == null) ? GenMath.RoundRandom((float)damType.defaultDamage) : modDamAmountRand);
            explosion.weapon                               = source;
            explosion.preExplosionSpawnThingDef            = preExplosionSpawnThingDef;
            explosion.preExplosionSpawnChance              = preExplosionSpawnChance;
            explosion.preExplosionSpawnThingCount          = preExplosionSpawnThingCount;
            explosion.postExplosionSpawnThingDef           = postExplosionSpawnThingDef;
            explosion.postExplosionSpawnChance             = postExplosionSpawnChance;
            explosion.postExplosionSpawnThingCount         = postExplosionSpawnThingCount;
            explosion.applyDamageToExplosionCellsNeighbors = applyDamageToExplosionCellsNeighbors;
            //map.GetComponent<ExplosionManager>().StartExplosion(explosion, explosionSound);
            explosion.StartExplosion(explosionSound, null);
        }
コード例 #36
0
 public static bool IsMineableRock(this ThingDef td)
 {
     return(td.mineable && !td.IsSmoothed);
 }
コード例 #37
0
        //public static Blueprint_Build PlaceBlueprintForBuild(BuildableDef sourceDef, IntVec3 center, Map map, Rot4 rotation, Faction faction, ThingDef stuff)
        public static void Prefix(ref Blueprint_Build __result, BuildableDef sourceDef, IntVec3 center, Map map, Rot4 rotation, Faction faction, ThingDef stuff)
        {
            if (faction != Faction.OfPlayer)
            {
                return;
            }

            foreach (IntVec3 cell in GenAdj.CellsOccupiedBy(center, rotation, sourceDef.Size))
            {
                if (map.designationManager.DesignationAt(cell, DesignationDefOf.Mine) != null)
                {
                    continue;
                }

                if (sourceDef is ThingDef thingDef)
                {
                    foreach (Thing mineThing in map.thingGrid.ThingsAt(cell).Where(t => t.IsMineableRock()))
                    {
                        if (!DontMineSmoothingRock.ToBeSmoothed(mineThing, thingDef))
                        {
                            map.designationManager.AddDesignation(new Designation(mineThing, DesignationDefOf.Mine));

                            if (mineThing.def.building?.mineableYieldWasteable ?? false)
                            {
                                TutorUtility.DoModalDialogIfNotKnown(ConceptDefOf.BuildersTryMine);
                            }
                        }
                    }
                }
            }
        }
コード例 #38
0
        protected override void Impact(Thing hitThing)
        {
            base.Impact(hitThing);

            ThingDef def    = this.def;
            Pawn     victim = null;

            if (!this.initialized)
            {
                this.pawn = this.launcher as Pawn;
                CompAbilityUserMagic   comp        = pawn.GetComp <CompAbilityUserMagic>();
                MagicPowerSkill        pwr         = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_Repulsion.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_Repulsion_pwr");
                MagicPowerSkill        ver         = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_Repulsion.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_Repulsion_ver");
                ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef();
                pwrVal = pwr.level;
                verVal = ver.level;
                if (pawn.story.traits.HasTrait(TorannMagicDefOf.Faceless))
                {
                    MightPowerSkill mpwr = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_pwr");
                    MightPowerSkill mver = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_ver");
                    pwrVal = mpwr.level;
                    verVal = mver.level;
                }
                this.arcaneDmg = comp.arcaneDmg;
                if (settingsRef.AIHardMode && !pawn.IsColonist)
                {
                    pwrVal = 3;
                    verVal = 3;
                }
                this.strikeDelay       = this.strikeDelay - verVal;
                this.radius            = this.def.projectile.explosionRadius;
                this.duration          = Mathf.RoundToInt(this.radius * this.strikeDelay);
                this.initialized       = true;
                this.targets           = GenRadial.RadialCellsAround(base.Position, strikeNum, false);
                this.casterSensitivity = this.pawn.GetStatValue(StatDefOf.PsychicSensitivity, false);
                cellList = targets.ToList <IntVec3>();
            }

            if (Find.TickManager.TicksGame % this.strikeDelay == 0)
            {
                int     force = Mathf.RoundToInt((10 + (2 * pwrVal) - strikeNum) * casterSensitivity);
                IntVec3 curCell;
                for (int i = 0; i < cellList.Count; i++)
                {
                    curCell = cellList[i];
                    Vector3 angle = GetVector(base.Position, curCell);
                    TM_MoteMaker.ThrowArcaneWaveMote(curCell.ToVector3(), this.Map, .3f * (curCell - base.Position).LengthHorizontal, .1f, .05f, .3f, 0, 3, (Quaternion.AngleAxis(90, Vector3.up) * angle).ToAngleFlat(), (Quaternion.AngleAxis(90, Vector3.up) * angle).ToAngleFlat());
                    if (curCell.IsValid && curCell.InBounds(this.Map))
                    {
                        victim = curCell.GetFirstPawn(this.Map);
                        if (victim != null && !victim.Dead)
                        {
                            Vector3 launchVector      = GetVector(base.Position, victim.Position);
                            IntVec3 projectedPosition = victim.Position + (force * launchVector).ToIntVec3();
                            if (projectedPosition.IsValid && projectedPosition.InBounds(this.Map))
                            {
                                if (Rand.Chance(TM_Calc.GetSpellSuccessChance(pawn, victim, true)))
                                {
                                    damageEntities(victim, force * (.2f * verVal), DamageDefOf.Blunt);
                                    LaunchFlyingObect(projectedPosition, victim, force);
                                }
                            }
                        }
                    }
                }
                strikeNum++;
                IEnumerable <IntVec3> newTargets = GenRadial.RadialCellsAround(base.Position, strikeNum, false);
                try
                {
                    cellList = newTargets.Except(targets).ToList <IntVec3>();
                }
                catch
                {
                    cellList = newTargets.ToList <IntVec3>();
                }
                targets = newTargets;
            }
        }
コード例 #39
0
        public void LaunchFlyingObect(IntVec3 targetCell, Pawn pawn, int force)
        {
            bool flag = targetCell != null && targetCell != default(IntVec3);

            if (flag)
            {
                if (pawn != null && pawn.Position.IsValid && pawn.Spawned && pawn.Map != null && !pawn.Downed && !pawn.Dead)
                {
                    if (ModCheck.Validate.GiddyUp.Core_IsInitialized())
                    {
                        ModCheck.GiddyUp.ForceDismount(pawn);
                    }
                    FlyingObject_Spinning flyingObject = (FlyingObject_Spinning)GenSpawn.Spawn(ThingDef.Named("FlyingObject_Spinning"), pawn.Position, pawn.Map);
                    flyingObject.speed = 25 + force;
                    flyingObject.Launch(pawn, targetCell, pawn);
                }
            }
        }
コード例 #40
0
        public override void DrawGhost(ThingDef def, IntVec3 center, Rot4 rot, Color ghostCol, Thing thing = null)
        {
            Map visibleMap = Find.CurrentMap;

            GenDraw.DrawFieldEdges(Building_TMPortal.PortableCellsAround(center, visibleMap));
        }
コード例 #41
0
        private static float FriendlyFireConeTargetScoreOffset(IAttackTarget target, IAttackTargetSearcher searcher, Verb verb)
        {
            Pawn  pawn = searcher.Thing as Pawn;
            float result;

            if (pawn == null)
            {
                result = 0f;
            }
            else if (pawn.RaceProps.intelligence < Intelligence.ToolUser)
            {
                result = 0f;
            }
            else if (pawn.RaceProps.IsMechanoid)
            {
                result = 0f;
            }
            else
            {
                Verb_Shoot verb_Shoot = verb as Verb_Shoot;
                if (verb_Shoot == null)
                {
                    result = 0f;
                }
                else
                {
                    ThingDef defaultProjectile = verb_Shoot.verbProps.defaultProjectile;
                    if (defaultProjectile == null)
                    {
                        result = 0f;
                    }
                    else if (defaultProjectile.projectile.flyOverhead)
                    {
                        result = 0f;
                    }
                    else
                    {
                        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.DistanceInterceptChance(report.ShootLine.Source.ToVector3Shifted(), c, ((Thing)target).Position);
                            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;
                                    }
                                }
                            }
                        }
                        result = num;
                    }
                }
            }
            return(result);
        }
コード例 #42
0
        static void Postfix(ref IEnumerable <TerrainMovementPawnRestrictions> __result, ThingDef race)
        {
            List <TerrainMovementPawnRestrictions> newResults = new List <TerrainMovementPawnRestrictions>();

            foreach (var ext in __result)
            {
                newResults.Add(ext);
            }
            var modExtensions = race.modExtensions;

            if (modExtensions != null)
            {
                foreach (DefModExtension ext in modExtensions)
                {
                    if (ext is AquaticExtension)
                    {
                        // First water rules
                        AquaticExtension aqext = ext as AquaticExtension;
                        TerrainMovementPawnRestrictions tmext = new TerrainMovementPawnRestrictions();
                        tmext.defaultMovementAllowed = false;
                        tmext.stayOnTerrainTag       = SwimmingLoader.WaterTag;
                        if (aqext.saltWaterOnly)
                        {
                            tmext.stayOffTerrainTag = SwimmingLoader.FreshWaterTag;
                        }
                        else if (aqext.freshWaterOnly)
                        {
                            tmext.stayOffTerrainTag = SwimmingLoader.SaltWaterTag;
                        }
                        newResults.Add(tmext);

                        // Second water rule to avoid bridges
                        tmext = new TerrainMovementPawnRestrictions();
                        tmext.defaultMovementAllowed = false;
                        tmext.stayOffTerrainTag      = SwimmingLoader.BridgeTag;
                        newResults.Add(tmext);
                    }
                }
            }
            __result = newResults;
        }
コード例 #43
0
ファイル: Storage.cs プロジェクト: SeanLeeLKY/MD2-Source
 private void AddNew(ThingDef def, int amount)
 {
     this.allStoredItemsList.Add(new ListItem(def, amount));
 }
コード例 #44
0
        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            Map map = (Map)parms.target;
            List <TargetInfo> list        = new List <TargetInfo>();
            List <Thing>      list3       = ThingSetMakerDefOf.Meteorite.root.Generate();
            ThingDef          shipPartDef = def?.mechClusterBuilding;
            IntVec3           intVec      = FindDropPodLocation(map, (IntVec3 spot) => CanPlaceAt(spot));

            if (intVec == IntVec3.Invalid)
            {
                return(false);
            }
            float       points = Mathf.Max(parms.points * 0.9f, 300f);
            List <Pawn> list2  = PawnGroupMakerUtility.GeneratePawns(new PawnGroupMakerParms
            {
                groupKind = PawnGroupKindDefOf.Combat,
                tile      = map.Tile,
                faction   = Faction.OfMechanoids,
                points    = points
            }).ToList();
            Thing thing = ThingMaker.MakeThing(shipPartDef);

            thing.SetFaction(Faction.OfMechanoids);
            LordMaker.MakeNewLord(Faction.OfMechanoids, new LordJob_SleepThenMechanoidsDefend(new List <Thing>
            {
                thing
            }, Faction.OfMechanoids, 28f, intVec, canAssaultColony: false, isMechCluster: false), map, list2);
            DropPodUtility.DropThingsNear(intVec, map, list2.Cast <Thing>());
            foreach (Pawn item in list2)
            {
                item.TryGetComp <CompCanBeDormant>()?.ToSleep();
            }
            list.AddRange(list2.Select((Pawn p) => new TargetInfo(p)));
            GenSpawn.Spawn(SkyfallerMaker.MakeSkyfaller(ThingDefOf.MeteoriteIncoming, thing), intVec, map);
            list.Add(new TargetInfo(intVec, map));
            SendStandardLetter(parms, list);
            return(true);

            bool CanPlaceAt(IntVec3 loc)
            {
                CellRect cellRect = GenAdj.OccupiedRect(loc, Rot4.North, shipPartDef.Size);

                if (loc.Fogged(map) || !cellRect.InBounds(map))
                {
                    return(false);
                }
                if (!DropCellFinder.SkyfallerCanLandAt(loc, map, shipPartDef.Size))
                {
                    return(false);
                }
                foreach (IntVec3 item2 in cellRect)
                {
                    RoofDef roof = item2.GetRoof(map);
                    if (roof != null && roof.isNatural)
                    {
                        return(false);
                    }
                }
                return(GenConstruct.CanBuildOnTerrain(shipPartDef, loc, map, Rot4.North));
            }
        }
コード例 #45
0
        protected override void Impact(Thing hitThing)
        {
            Map map = base.Map;

            base.Impact(hitThing);
            ThingDef def = this.def;

            Pawn pawn   = this.launcher as Pawn;
            Pawn victim = hitThing as Pawn;

            CompAbilityUserMight comp = pawn.GetComp <CompAbilityUserMight>();
            MightPowerSkill      pwr  = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_AntiArmor.FirstOrDefault((MightPowerSkill x) => x.label == "TM_AntiArmor_pwr");
            MightPowerSkill      ver  = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_AntiArmor.FirstOrDefault((MightPowerSkill x) => x.label == "TM_AntiArmor_ver");
            MightPowerSkill      str  = comp.MightData.MightPowerSkill_global_strength.FirstOrDefault((MightPowerSkill x) => x.label == "TM_global_strength_pwr");

            ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef();
            pwrVal = pwr.level;
            verVal = ver.level;
            if (settingsRef.AIHardMode && !pawn.IsColonistPlayerControlled)
            {
                pwrVal = 3;
                verVal = 3;
            }
            this.Initialize(base.Position, pawn);

            if (victim != null && !victim.Dead && Rand.Chance(this.launcher.GetStatValue(StatDefOf.ShootingAccuracy, true)))
            {
                int dmg;
                if (value > 1000)
                {
                    value -= 1000;
                    dmg    = (this.def.projectile.damageAmountBase) + (int)((16.5f + (value / 150)) * (1 + .05f * str.level));
                }
                else
                {
                    dmg = (this.def.projectile.damageAmountBase) + (int)((value / 60) * (1 + .05f * str.level));
                }

                if (!victim.RaceProps.IsFlesh)
                {
                    MoteMaker.ThrowMicroSparks(victim.Position.ToVector3(), map);
                    damageEntities(victim, null, dmg, DamageDefOf.Bullet);
                    MoteMaker.MakeStaticMote(victim.Position, pawn.Map, ThingDefOf.Mote_ExplosionFlash, 4f);
                    damageEntities(victim, null, dmg * (1 + pwrVal), DamageDefOf.Bullet);
                    MoteMaker.ThrowMicroSparks(victim.Position.ToVector3(), map);
                    for (int i = 0; i < 1 + verVal; i++)
                    {
                        GenExplosion.DoExplosion(newPos, map, Rand.Range((.1f) * (1 + verVal), (.3f) * (1 + verVal)), DamageDefOf.Bomb, this.launcher, (this.def.projectile.damageAmountBase / 4) * (1 + verVal), SoundDefOf.BulletImpactMetal, def, this.equipmentDef, null, 0f, 1, false, null, 0f, 1, 0f, true);
                        GenExplosion.DoExplosion(newPos, map, Rand.Range((.2f) * (1 + verVal), (.4f) * (1 + verVal)), DamageDefOf.Stun, this.launcher, (this.def.projectile.damageAmountBase / 2) * (1 + verVal), SoundDefOf.BulletImpactMetal, def, this.equipmentDef, null, 0f, 1, false, null, 0f, 1, 0f, true);
                        newPos = GetNewPos(newPos, pawn.Position.x <= victim.Position.x, pawn.Position.z <= victim.Position.z, false, 0, 0, xProb, 1 - xProb);
                        MoteMaker.ThrowMicroSparks(victim.Position.ToVector3(), base.Map);
                        MoteMaker.ThrowDustPuff(newPos, map, Rand.Range(1.2f, 2.4f));
                    }
                }
                else
                {
                    damageEntities(victim, null, dmg, DamageDefOf.Bullet);
                }
            }
            else
            {
                Log.Message("No valid target for anti armor shot or missed");
            }
        }
コード例 #46
0
        public override void PawnDied(Corpse corpse)
        {
            float radius;

            if (corpse.InnerPawn.ageTracker.CurLifeStageIndex == 0)
            {
                radius = 1.9f;
            }
            else if (corpse.InnerPawn.ageTracker.CurLifeStageIndex == 1)
            {
                radius = 4.9f;
            }
            else
            {
                radius = 6.9f;
            }
            GenExplosion.DoExplosion(corpse.Position, corpse.Map, radius, DamageDefOf.Stun, corpse.InnerPawn, -1, -1, null, null, null, null, ThingDef.Named("Gas_Smoke"), .7f, 1, false, null, 0f, 1);
        }
コード例 #47
0
        public override GizmoResult GizmoOnGUI(Vector2 topLeft, float maxWidth)
        {
            var gizmoRect = new Rect(topLeft.x, topLeft.y, GetWidth(maxWidth), MinGizmoSize);

            if (Mouse.IsOver(gizmoRect))
            {
                LessonAutoActivator.TeachOpportunity(SidearmsDefOf.Concept_SimpleSidearmsBasic, OpportunityType.Important);
            }

            var contentRect = gizmoRect.ContractedBy(ContentPadding);

            Widgets.DrawWindowBackground(gizmoRect);

            var globalInteracted = false;

            interactedWeapon       = null;
            interactedWeaponMemory = null;
            interactedRanged       = false;
            interactedUnarmed      = false;

            GoldfishModule pawnMemory = GoldfishModule.GetGoldfishForPawn(parent);
            //if (pawnMemory == null)
            //    return new GizmoResult(GizmoState.Clear);

            int i = 0;

            for (i = 0; i < rangedWeapons.Count; i++)
            {
                var  iconOffset = new Vector2((IconSize * i) + IconGap * (i - 1) + LockPanelWidth, 0);
                bool interacted = DrawIconForWeapon(pawnMemory, rangedWeapons[i], contentRect, iconOffset);
                if (interacted)
                {
                    interactedWeapon = rangedWeapons[i];
                }
                if (interacted)
                {
                    interactedRanged = true;
                }
                globalInteracted |= interacted;
            }

            int j = 0;

            if (pawnMemory != null)
            {
                foreach (ThingDef def in rangedWeaponMemories)
                {
                    if (!parent.hasWeaponSomewhere(def))
                    {
                        var  iconOffset = new Vector2((IconSize * (i + j)) + IconGap * ((i + j) - 1) + LockPanelWidth, 0);
                        bool interacted = DrawIconForWeaponMemory(pawnMemory, def, contentRect, iconOffset);
                        if (interacted)
                        {
                            interactedWeaponMemory = def;
                        }
                        if (interacted)
                        {
                            interactedRanged = true;
                        }
                        globalInteracted |= interacted;
                        j++;
                    }
                }
            }

            for (i = 0; i < meleeWeapons.Count; i++)
            {
                var  iconOffset = new Vector2((IconSize * i) + IconGap * (i - 1) + LockPanelWidth, IconSize + IconGap);
                bool interacted = DrawIconForWeapon(pawnMemory, meleeWeapons[i], contentRect, iconOffset);
                if (interacted)
                {
                    interactedWeapon = meleeWeapons[i];
                }
                if (interacted)
                {
                    interactedRanged = false;
                }
                globalInteracted |= interacted;
            }

            j = 0;
            if (pawnMemory != null)
            {
                foreach (ThingDef def in meleeWeaponMemories)
                {
                    if (!parent.hasWeaponSomewhere(def))
                    {
                        var  iconOffset = new Vector2((IconSize * (i + j)) + IconGap * ((i + j) - 1) + LockPanelWidth, IconSize + IconGap);
                        bool interacted = DrawIconForWeaponMemory(pawnMemory, def, contentRect, iconOffset);
                        if (interacted)
                        {
                            interactedWeaponMemory = def;
                        }
                        if (interacted)
                        {
                            interactedRanged = false;
                        }
                        globalInteracted |= interacted;
                        j++;
                    }
                }
            }

            var unarmedIconOffset = new Vector2((IconSize * (i + j)) + IconGap * ((i + j) - 1) + LockPanelWidth, IconSize + IconGap);

            interactedUnarmed = DrawIconForUnarmed(parent, contentRect, unarmedIconOffset);
            globalInteracted |= interactedUnarmed;

            Rect locksPanel = new Rect(gizmoRect.x + ContentPadding, gizmoRect.y, LockPanelWidth - ContentPadding, MinGizmoSize);
            //locksPanel = locksPanel.ContractedBy(LockPanelPadding);

            SwapControlsHandler handler = SwapControlsHandler.GetHandlerForPawn(parent);

            Rect lockPanel     = new Rect(locksPanel.x, locksPanel.y + (locksPanel.height / 2f) - locksPanel.width - LockIconsOffset, locksPanel.width, locksPanel.width);
            Rect locklockPanel = new Rect(locksPanel.x, locksPanel.y + (locksPanel.height / 2f) + LockIconsOffset, locksPanel.width, locksPanel.width);

            DrawLock(handler, lockPanel);
            UIHighlighter.HighlightOpportunity(lockPanel, "SidearmListButton");
            DrawLocklock(handler, locklockPanel);
            UIHighlighter.HighlightOpportunity(locklockPanel, "SidearmListButton");

            UIHighlighter.HighlightOpportunity(gizmoRect, "SidearmList");

            DrawGizmoLabel(defaultLabel, gizmoRect);
            return(globalInteracted ? new GizmoResult(GizmoState.Interacted, Event.current) : new GizmoResult(GizmoState.Clear));
        }
コード例 #48
0
            static IEnumerable <StatDrawEntry> Postfix(IEnumerable <StatDrawEntry> values, ThingDef __instance, StatRequest req)
            {
                CompLootAffixableThing comp = null;

                if (req.Thing is ThingWithComps thing)
                {
                    comp = thing.TryGetComp <CompLootAffixableThing>();
                }

                // Cycle through the entries
                foreach (StatDrawEntry value in values)
                {
                    // Give it to the comp to meddle with
                    if (comp != null)
                    {
                        comp.SpecialDisplayStatsInjectors(value);
                    }

                    yield return(value);
                }

                // Go back to the old set.  Iterators cannot have refs, so we have to replace this with reflection.
                if (!Base.origVerbPropertiesCache.ContainsKey(__instance.defName))
                {
                    if (comp != null && !req.Thing.def.Verbs.NullOrEmpty())
                    {
                        Log.Error("Old VerbProperties lost from SpecialDisplayStats swap!");
                    }
                    yield break;
                }

                // [Reflection] thing.verbs = Base.origVerbPropertiesCache[__instance.defName];
                FieldInfo verbsField = AccessTools.Field(typeof(ThingDef), "verbs");

                verbsField.SetValue(__instance, Base.origVerbPropertiesCache[__instance.defName]);
            }
コード例 #49
0
        protected override void Impact(Thing hitThing)
        {
            Map map = base.Map;

            base.Impact(hitThing);
            ThingDef def    = this.def;
            Pawn     victim = hitThing as Pawn;

            Pawn pawn = this.launcher as Pawn;

            ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef();

            if (pawn.story.traits.HasTrait(TorannMagicDefOf.Faceless))
            {
                MightPowerSkill mpwr = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_pwr");
                MightPowerSkill mver = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_ver");
                pwrVal         = mpwr.level;
                verVal         = mver.level;
                this.arcaneDmg = pawn.GetComp <CompAbilityUserMight>().mightPwr;
            }
            else
            {
                CompAbilityUserMagic comp = pawn.GetComp <CompAbilityUserMagic>();
                pwr            = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_LightningCloud.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_LightningCloud_pwr");
                ver            = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_LightningCloud.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_LightningCloud_ver");
                pwrVal         = pwr.level;
                verVal         = ver.level;
                this.arcaneDmg = comp.arcaneDmg;
            }

            if (settingsRef.AIHardMode && !pawn.IsColonist)
            {
                pwrVal = 3;
                verVal = 3;
            }
            radius = (int)this.def.projectile.explosionRadius + (1 * verVal);

            CellRect cellRect = CellRect.CenteredOn(base.Position, radius - 3);

            cellRect.ClipInsideMap(map);
            IntVec3 randomCell = cellRect.RandomCell;

            duration = 900 + (verVal * 120);

            if (this.primed == true)
            {
                if (((this.shockDelay + this.lastStrike) < this.age))
                {
                    for (int i = 0; i < 3; i++)
                    {
                        randomCell = cellRect.RandomCell;
                        if (randomCell.InBounds(map))
                        {
                            victim = randomCell.GetFirstPawn(map);
                            if (victim != null)
                            {
                                if (Rand.Chance(TM_Calc.GetSpellSuccessChance(pawn, victim) - .3f))
                                {
                                    damageEntities(victim, Mathf.RoundToInt((this.def.projectile.GetDamageAmount(1, null) + pwrVal) * this.arcaneDmg));
                                }
                            }
                        }
                    }

                    Vector3 loc2 = base.Position.ToVector3Shifted();
                    Vector3 loc  = randomCell.ToVector3Shifted();

                    bool rand1 = Rand.Range(0, 100) < 3;
                    bool rand2 = Rand.Range(0, 100) < 16;
                    if (rand1)
                    {
                        MoteMaker.ThrowSmoke(loc2, map, radius);
                        SoundDefOf.Ambient_AltitudeWind.sustainFadeoutTime.Equals(30.0f);
                    }
                    if (rand2)
                    {
                        MoteMaker.ThrowSmoke(loc, map, 4f);
                    }

                    MoteMaker.ThrowMicroSparks(loc, map);
                    MoteMaker.ThrowLightningGlow(loc, map, 2f);

                    strikeInt++;
                    this.lastStrike = this.age;
                    this.shockDelay = Rand.Range(1, 5);

                    bool flag1 = this.age <= duration;
                    if (!flag1)
                    {
                        this.primed = false;
                    }
                }
            }
        }
コード例 #50
0
 public void Aura(IntVec3 pos, Map map, CompProperties_ReactiveDefense props)
 {
     if (props.aura != null)
     {
         for (int i = pos.x - props.auraSize; i <= pos.x + props.auraSize; i++)
         {
             for (int j = pos.z - props.auraSize; j <= pos.z + props.auraSize; j++)
             {
                 IntVec3 temp = new IntVec3(i, 0, j);
                 if (temp != pos && temp.InBounds(map))
                 {
                     ThingDef        particle  = ThingDef.Named(props.aura);
                     List <ThingDef> thingdefs = new List <ThingDef>();
                     foreach (Thing t in temp.GetThingList(map))
                     {
                         thingdefs.Add(t.def);
                     }
                     if (particle.GetCompProperties <CompProperties_AuraParticle>() != null && temp.GetFirstBuilding(map) == null && !thingdefs.Contains(ThingDef.Named(props.aura)))
                     {
                         particle.GetCompProperties <CompProperties_AuraParticle>().duration = props.duration;
                         GenSpawn.Spawn(ThingDef.Named(props.aura), temp, map);
                     }
                 }
             }
         }
     }
 }
コード例 #51
0
        /// <summary>
        /// Gets an appropriate drawColor for this def.
        /// Will use a default stuff or DrawColor, if defined.
        /// </summary>
        /// <param name="def"></param>
        /// <returns></returns>
        public static Color IconColor(this Def def)
        {
            // check cache
            if (_cachedIconColors.ContainsKey(def))
            {
                return(_cachedIconColors[def]);
            }

            // otherwise try to determine icon
            var bdef = def as BuildableDef;
            var tdef = def as ThingDef;
            var pdef = def as PawnKindDef;
            var rdef = def as RecipeDef;

            // get product color for recipes
            if (rdef != null)
            {
                if (!rdef.products.NullOrEmpty())
                {
                    _cachedIconColors.Add(def, rdef.products.First().thingDef.IconColor());
                    return(_cachedIconColors[def]);
                }
            }

            // get color from final lifestage for pawns
            if (pdef != null)
            {
                _cachedIconColors.Add(def, pdef.lifeStages.Last().bodyGraphicData.color);
                return(_cachedIconColors[def]);
            }

            if (bdef == null)
            {
                // if we reach this point, def.IconTexture() would return null. Just store and return white to make sure we don't get weird errors down the line.
                _cachedIconColors.Add(def, Color.white);
                return(_cachedIconColors[def]);
            }

            // built def != listed def
            if (
                (tdef != null) &&
                (tdef.entityDefToBuild != null)
                )
            {
                _cachedIconColors.Add(def, tdef.entityDefToBuild.IconColor());
                return(_cachedIconColors[def]);
            }

            // graphic.color set?
            if (bdef.graphic != null)
            {
                _cachedIconColors.Add(def, bdef.graphic.color);
                return(_cachedIconColors[def]);
            }

            // stuff used?
            if (
                (tdef != null) &&
                tdef.MadeFromStuff
                )
            {
                ThingDef stuff = GenStuff.DefaultStuffFor(tdef);
                _cachedIconColors.Add(def, stuff.stuffProps.color);
                return(_cachedIconColors[def]);
            }

            // all else failed.
            _cachedIconColors.Add(def, Color.white);
            return(_cachedIconColors[def]);
        }
コード例 #52
0
        private void MakeArtOrder(float chance, float price, int delay, ThingDef artType, ThingDef artStuff)
        {
            price -= prepayment;

            Order_Art_RogerEdmonson order = new Order_Art_RogerEdmonson(chance / 100, price, delay, artType, artStuff);

            trader.Order = order;

            Find.LetterStack.ReceiveLetter("MakeBodyPartOrder_Title".Translate(), "MakeBodyPartOrder_Desc".Translate($"{group}_group".Translate(), delay), LetterDefOf.PositiveEvent);
        }
コード例 #53
0
        protected override bool TryCastShot()
        {
            Pawn caster = base.CasterPawn;

            CompAbilityUserMagic comp = caster.GetComp <CompAbilityUserMagic>();

            verVal        = comp.MagicData.MagicPowerSkill_Shapeshift.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_Shapeshift_ver").level;
            pwrVal        = comp.MagicData.MagicPowerSkill_Shapeshift.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_Shapeshift_pwr").level;
            effVal        = comp.MagicData.MagicPowerSkill_Shapeshift.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_Shapeshift_eff").level;
            this.duration = Mathf.RoundToInt((this.duration + (360 * effVal)) * comp.arcaneDmg);
            bool flag = caster != null && !caster.Dead;

            if (flag)
            {
                CompPolymorph compPoly = caster.GetComp <CompPolymorph>();
                if (compPoly != null && compPoly.Original != null && compPoly.TicksLeft > 0)
                {
                    compPoly.Temporary = true;
                    compPoly.TicksLeft = 0;
                }
                else
                {
                    FactionDef fDef = TorannMagicDefOf.TM_SummonedFaction;
                    if (caster.Faction != null)
                    {
                        fDef = caster.Faction.def;
                    }
                    SpawnThings spawnThing = new SpawnThings();
                    spawnThing.factionDef = fDef;
                    spawnThing.spawnCount = 1;
                    spawnThing.temporary  = false;

                    GetPolyMinMax(caster);

                    spawnThing = TM_Action.AssignRandomCreatureDef(spawnThing, this.min, this.max);
                    if (spawnThing.def == null || spawnThing.kindDef == null)
                    {
                        spawnThing.def     = ThingDef.Named("Rat");
                        spawnThing.kindDef = PawnKindDef.Named("Rat");
                        Log.Message("random creature was null");
                    }

                    Pawn polymorphedPawn = TM_Action.PolymorphPawn(this.CasterPawn, caster, caster, spawnThing, caster.Position, true, duration, caster.Faction);

                    if (this.effVal >= 3)
                    {
                        polymorphedPawn.GetComp <CompPolymorph>().Temporary = false;
                    }

                    MoteMaker.ThrowSmoke(polymorphedPawn.DrawPos, caster.Map, 2);
                    MoteMaker.ThrowMicroSparks(polymorphedPawn.DrawPos, caster.Map);
                    MoteMaker.ThrowHeatGlow(polymorphedPawn.Position, caster.Map, 2);
                    //caster.DeSpawn();

                    HealthUtility.AdjustSeverity(polymorphedPawn, HediffDef.Named("TM_ShapeshiftHD"), .5f + (1f * pwrVal));
                }

                //SoundInfo info = SoundInfo.InMap(new TargetInfo(caster.Position, caster.Map, false), MaintenanceType.None);
                //info.pitchFactor = 1.0f;
                //info.volumeFactor = 1.0f;
                //TorannMagicDefOf.TM_FastReleaseSD.PlayOneShot(info);
                //TM_MoteMaker.ThrowGenericMote(ThingDef.Named("Mote_PowerWave"), caster.DrawPos, caster.Map, .8f, .2f, .1f, .1f, 0, 1f, 0, Rand.Chance(.5f) ? 0 : 180);
            }
            return(true);
        }
コード例 #54
0
        private static bool DrawIconForWeaponMemory(GoldfishModule pawnMemory, ThingDef weapon, Rect contentRect, Vector2 iconOffset)
        {
            var     iconTex  = weapon.uiIcon;
            Graphic g        = weapon.graphicData.Graphic;
            Color   color    = getColor(weapon);
            Color   colorTwo = getColor(weapon);
            Graphic g2       = weapon.graphicData.Graphic.GetColoredVersion(g.Shader, color, colorTwo);

            var iconRect = new Rect(contentRect.x + iconOffset.x, contentRect.y + iconOffset.y, IconSize, IconSize);

            string label = weapon.label;

            Texture2D drawPocket;

            if (pawnMemory.IsCurrentPrimary(weapon.defName))
            {
                drawPocket = TextureResources.drawPocketMemoryPrimary;
            }
            else
            {
                drawPocket = TextureResources.drawPocketMemory;
            }

            TooltipHandler.TipRegion(iconRect, string.Format("DrawSidearm_gizmoTooltipMemory".Translate(), weapon.label));
            MouseoverSounds.DoRegion(iconRect, SoundDefOf.Mouseover_Command);
            if (Mouse.IsOver(iconRect))
            {
                LessonAutoActivator.TeachOpportunity(SidearmsDefOf.Concept_SidearmsMissing, OpportunityType.GoodToKnow);
                if (pawnMemory.IsCurrentPrimary(weapon.defName))
                {
                    LessonAutoActivator.TeachOpportunity(SidearmsDefOf.Concept_SidearmsPrimary, OpportunityType.GoodToKnow);
                }
                GUI.color = iconMouseOverColor;
                GUI.DrawTexture(iconRect, drawPocket);
            }
            else
            {
                GUI.color = iconBaseColor;
                GUI.DrawTexture(iconRect, drawPocket);
            }

            Texture resolvedIcon;

            if (!weapon.uiIconPath.NullOrEmpty())
            {
                resolvedIcon = weapon.uiIcon;
            }
            else
            {
                resolvedIcon = g2.MatSingle.mainTexture;
            }
            GUI.color = color;
            GUI.DrawTexture(iconRect, resolvedIcon);
            GUI.color = Color.white;

            UIHighlighter.HighlightOpportunity(iconRect, "SidearmMissing");
            if (pawnMemory.IsCurrentPrimary(weapon.defName))
            {
                UIHighlighter.HighlightOpportunity(iconRect, "SidearmPrimary");
            }

            if (Widgets.ButtonInvisible(iconRect, true))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #55
0
        private void DrawArtsOrders(Rect rect)
        {
            CalculateArtValues();

            Text.Anchor = TextAnchor.MiddleCenter;
            Rect buttonRect = new Rect(rect.x + 10, rect.y, rect.width - 20, 25);

            if (GUIUtils.DrawCustomButton(buttonRect, "RogerEdmonson_OrderWindow_SelectStuff".Translate(artStuff.label), Color.white))
            {
                List <FloatMenuOption> options = new List <FloatMenuOption>();
                foreach (var stuff in DefDatabase <ThingDef> .AllDefs)
                {
                    if (stuff.IsStuff && stuff.stuffProps.CanMake(artType))
                    {
                        options.Add(new FloatMenuOption(stuff.label, delegate
                        {
                            artStuff = stuff;
                        }));
                    }
                }

                Find.WindowStack.Add(new FloatMenu(options));
            }
            buttonRect.y += 30;
            if (GUIUtils.DrawCustomButton(buttonRect, "RogerEdmonson_OrderWindow_SelectArtType".Translate(artType.label), Color.white))
            {
                List <FloatMenuOption> options = new List <FloatMenuOption>();
                foreach (var art in DefDatabase <ThingDef> .AllDefs)
                {
                    if (art.IsArt)
                    {
                        options.Add(new FloatMenuOption(art.label, delegate
                        {
                            artType = art;
                        }));
                    }
                }

                Find.WindowStack.Add(new FloatMenu(options));
            }
            Text.Anchor = TextAnchor.UpperLeft;

            Rect intRect = new Rect(rect.x + 10, rect.y + 60, 250, 25);

            Widgets.Label(intRect, "RogerEdmonson_OrderWindow_Range".Translate());
            intRect.x    += 255;
            intRect.width = rect.width - 275;
            Widgets.TextFieldNumeric(intRect, ref delay, ref delayBuff, 1);

            Rect fullLabel = new Rect(rect.x + 10, rect.y + 90, rect.width - 10, 300);

            Widgets.Label(fullLabel, "RogerEdmonson_OrderWindow_ArtFull".Translate(totalValue, chance.ToString("f2"), prepayment));
            TooltipHandler.TipRegion(fullLabel, "RogerEdmonson_OrderWindow_ArtFull2".Translate(artType.label, baseValue, artStuff.BaseMarketValue, delay, trader.ArriveTime, artType.costStuffCount, totalValue, prepayment
                                                                                               , chance.ToString("f2"), baseChance));

            Text.Anchor = TextAnchor.MiddleCenter;
            if (GUIUtils.DrawCustomButton(new Rect(rect.x + 10, rect.height - 40, rect.width - 20, 30), "RogerEdmonson_OrderWindow_CreateOrder".Translate(), trader.Order == null ? Color.white : Color.gray))
            {
                if (trader.Order != null)
                {
                    Messages.Message("RogerEdmonson_OrderWindow_Only1Order".Translate(), MessageTypeDefOf.NeutralEvent, false);
                }
                else
                {
                    if (TakePrePayment(prepayment))
                    {
                        MakeArtOrder(chance, totalValue, delay, artType, artStuff);
                    }
                }
            }
            if (trader.Order != null)
            {
                if (GUIUtils.DrawCustomButton(new Rect(rect.x + 10, rect.height, rect.width - 20, 30), "DarkNetButtons_CancelOrder".Translate(), Color.white))
                {
                    trader.DeclineOrder();
                }
            }
            Text.Anchor = TextAnchor.UpperLeft;
        }
コード例 #56
0
 public void Notify_BeginRepel(Pawn targetPawn, IntVec3 baseRepelVector, float maxRepelDistance, int baseRepelDurationInTicks, out float outRepelDistance, out ThingDef obstacleDef)
 {
     this.targetPawn           = targetPawn;
     this.initialRepelPosition = targetPawn.Position;
     this.repelVector          = baseRepelVector;
     // Compute repel distance.
     obstacleDef = GetObstacleDefAndComputeRepelDistance(targetPawn.Position, this.repelVector, maxRepelDistance, out this.repelDistance);
     this.repelDurationInTicks = (int)((float)baseRepelDurationInTicks * (this.repelDistance / maxRepelDistance));
     outRepelDistance          = this.repelDistance;
     // At least stun the target during repel.
     targetPawn.stances.stunner.StunFor((int)this.repelDurationInTicks);
 }
コード例 #57
0
 public override bool HandlesThingDef(ThingDef thingDef)
 {
     return(thingDef == this.thingDef);
 }
コード例 #58
0
ファイル: Storage.cs プロジェクト: SeanLeeLKY/MD2-Source
 private ListItem GetItemFromDef(ThingDef def)
 {
     return((from t in this.allStoredItemsList
             where t.thing.defName == def.defName
             select t).First());
 }
コード例 #59
0
        public static void _Postfix(ref bool __state, ref bool __result, Pawn getter, Pawn eater, bool desperate, ref Thing foodSource, ref ThingDef foodDef, bool canRefillDispenser, bool canUseInventory, bool allowForbidden, bool allowCorpse)
        {
            if (__state)
            {
                return;
            }

            try
            {
                __result = Internal(getter, eater, desperate, out foodSource, out foodDef, canRefillDispenser, canUseInventory, allowForbidden, allowCorpse);
                return;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("{0}: Exception when fetching. (getter={1} eater={2})\n{3}\n{4}", ModCore.modname, getter, eater, ex, ex.StackTrace), ex);
            }
        }
コード例 #60
0
        internal static bool Internal(Pawn getter, Pawn eater, bool desperate, out Thing foodSource, out ThingDef foodDef, bool canRefillDispenser = true, bool canUseInventory = true, bool allowForbidden = false, bool allowCorpse = true, Policy forcedPolicy = null)
        {
            List <FoodSourceRating> FoodListForPawn;

            FoodSearchCache.PawnEntry pawnEntry;

            if (!FoodSearchCache.TryGetEntryForPawn(getter, eater, out pawnEntry, allowForbidden))
            {
                Policy policy;

                if (forcedPolicy != null)
                {
                    policy = forcedPolicy;
                }
                else
                {
                    policy = PolicyUtils.GetPolicyAssignedTo(eater, getter);
                }

                bool foundFood = FoodUtils.MakeRatedFoodListForPawn(getter.Map, eater, getter, policy, out FoodListForPawn, canUseInventory, allowForbidden);

                pawnEntry = FoodSearchCache.AddPawnEntry(getter, eater, FoodListForPawn);
            }

            bool flagAllowHunt  = (getter == eater && eater.RaceProps.predator && !eater.health.hediffSet.HasTendableInjury());
            bool flagAllowPlant = (getter == eater);

            // C# 5 :'(
            var foodSourceRating = pawnEntry.GetBestFoodEntry(flagAllowPlant, allowCorpse, flagAllowHunt);

            if (foodSourceRating != null)
            {
                foodSource = foodSourceRating.FoodSource;
            }
            else
            {
                foodSource = null;
            }

            if (foodSource == null)              // ** If no food source is found set food Definition to null and return
            {
                foodDef = null;
                return(false);
            }

            foodDef = RimWorld.FoodUtility.GetFinalIngestibleDef(foodSource);             // ** Set food definition of food source and return
            return(true);

            //bool flag = getter.RaceProps.ToolUser && getter.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation);
            //Thing thing = null;
            //if (canUseInventory)
            //{
            //	if (flag)
            //	{
            //		thing = RimWorld.FoodUtility.BestFoodInInventory(getter, null, FoodPreferability.MealAwful, FoodPreferability.MealLavish, 0f, false);
            //	}
            //	if (thing != null)
            //	{
            //		if (getter.Faction != Faction.OfPlayer)
            //		{
            //			foodSource = thing;
            //			foodDef = RimWorld.FoodUtility.GetFinalIngestibleDef(foodSource);
            //			return true;
            //		}
            //		CompRottable compRottable = thing.TryGetComp<CompRottable>();
            //		if (compRottable != null && compRottable.Stage == RotStage.Fresh && compRottable.TicksUntilRotAtCurrentTemp < 30000)
            //		{
            //			foodSource = thing;
            //			foodDef = RimWorld.FoodUtility.GetFinalIngestibleDef(foodSource);
            //			return true;
            //		}
            //	}
            //}
            //bool allowPlant = getter == eater;
        }