Exemple #1
0
        public static void AffectGoodwillWithSpacerFaction(Faction faction, Faction other, float goodwillChange)
        {
            if (goodwillChange > 0f && ((faction.IsPlayer && FactionBaseUtility.IsPlayerAttackingAnyFactionBaseOf(other)) || (other.IsPlayer && FactionBaseUtility.IsPlayerAttackingAnyFactionBaseOf(faction))))
            {
                return;
            }
            float           value           = other.GoodwillWith(faction) + goodwillChange;
            FactionRelation factionRelation = other.RelationWith(faction, false);

            factionRelation.goodwill = Mathf.Clamp(value, -100f, 100f);

            if (!faction.HostileTo(other) && faction.GoodwillWith(other) < -80f)
            {
                faction.SetHostileTo(other, true);
                if (Current.ProgramState == ProgramState.Playing && Find.TickManager.TicksGame > 100 && other == Faction.OfPlayer)
                {
                    Find.LetterStack.ReceiveLetter("LetterLabelRelationsChangeBad".Translate(), "RelationsBrokenDown".Translate(new object[]
                    {
                        faction.Name
                    }), LetterType.BadNonUrgent, null);
                }
            }
            if (faction.HostileTo(other) && faction.GoodwillWith(other) > 0f)
            {
                faction.SetHostileTo(other, false);
                if (Current.ProgramState == ProgramState.Playing && Find.TickManager.TicksGame > 100 && other == Faction.OfPlayer)
                {
                    Find.LetterStack.ReceiveLetter("LetterLabelRelationsChangeGood".Translate(), "RelationsWarmed".Translate(new object[]
                    {
                        faction.Name
                    }), LetterType.BadNonUrgent, null);
                }
            }
        }
Exemple #2
0
        // ===================== Goodwill management =====================
        public static bool AffectFactionGoodwillWithOther(Faction faction, Faction other, float goodwillChange)
        {
            float           num             = faction.GoodwillWith(other);
            float           value           = num + goodwillChange;
            FactionRelation factionRelation = faction.RelationWith(other, false);

            factionRelation.goodwill = Mathf.Clamp(value, -100f, 100f);
            if (!faction.HostileTo(other) && faction.GoodwillWith(other) < -80f)
            {
                SetFactionHostileToOther(faction, other, true);
                if (Current.ProgramState == ProgramState.Playing && Find.TickManager.TicksGame > 100 && other == Faction.OfPlayer)
                {
                    Find.LetterStack.ReceiveLetter("LetterLabelRelationsChangeBad".Translate(), "RelationsBrokenDown".Translate(new object[]
                    {
                        faction.Name
                    }), LetterDefOf.NegativeEvent, null);
                }
            }
            if (faction.HostileTo(other) && faction.GoodwillWith(other) >= 0f)
            {
                SetFactionHostileToOther(faction, other, false);
                if (Current.ProgramState == ProgramState.Playing && Find.TickManager.TicksGame > 100 && other == Faction.OfPlayer)
                {
                    Find.LetterStack.ReceiveLetter("LetterLabelRelationsChangeGood".Translate(), "RelationsWarmed".Translate(new object[]
                    {
                        faction.Name
                    }), LetterDefOf.PositiveEvent, null);
                }
            }
            return(faction.def.appreciative && (goodwillChange > 0f || factionRelation.goodwill != num));
        }
        public override void WorldComponentTick()
        {
            base.WorldComponentTick();

            if (Settings.useAllyFaction)
            {
                if (Find.TickManager.TicksGame % UPDATE_ALLY_FACTION_TICKS == 0)
                {
                    // update ally faction relations to owner faction relations
                    Faction allyFaction = Find.FactionManager.FirstFactionOfDef(DefDatabase <FactionDef> .GetNamed("RimSpawnersFriendlyFaction"));
                    allyFaction.hostileFromMemberCapture = false;

                    FactionRelation playerFactionRelation = allyFaction.RelationWith(Faction.OfPlayer);
                    if (!playerFactionRelation.kind.Equals(FactionRelationKind.Ally))
                    {
                        playerFactionRelation.goodwill = 100;
                        playerFactionRelation.kind     = FactionRelationKind.Ally;
                    }

                    foreach (Faction otherFaction in Find.FactionManager.AllFactions)
                    {
                        if (!otherFaction.IsPlayer && !otherFaction.Equals(allyFaction))
                        {
                            FactionRelation otherFactionRelation = otherFaction.RelationWith(allyFaction);
                            otherFactionRelation.goodwill = otherFaction.PlayerGoodwill;
                            otherFactionRelation.kind     = otherFaction.PlayerRelationKind;

                            FactionRelation allyFactionRelation = allyFaction.RelationWith(otherFaction);
                            allyFactionRelation.goodwill = otherFactionRelation.goodwill;
                            allyFactionRelation.kind     = otherFactionRelation.kind;
                        }
                    }
                }
            }
        }
Exemple #4
0
        public static void Postfix(Faction __instance, Faction other)
        {
            var currentFactionDefExtension = FactionDefExtension.Get(__instance.def);
            var otherFactionDefExtension   = FactionDefExtension.Get(other.def);

            var currentToOtherFactionGoodwill = currentFactionDefExtension?.startingGoodwillByFactionDefs?.Find(x => x.factionDef == other.def);
            var otherToCurrentFactionGoodwill = otherFactionDefExtension?.startingGoodwillByFactionDefs?.Find(x => x.factionDef == __instance.def);

            // If at least one of the factions references the other via custom values in the FactionDefExtension
            if (currentToOtherFactionGoodwill != null || otherToCurrentFactionGoodwill != null)
            {
                // Get the lowest range of goodwill possible between factions
                int?currentToOtherFactionGoodwillMin = currentToOtherFactionGoodwill?.Min;
                int?currentToOtherFactionGoodwillMax = currentToOtherFactionGoodwill?.Max;
                int?otherToCurrentFactionGoodwillMin = otherToCurrentFactionGoodwill?.Min;
                int?otherToCurrentFactionGoodwillMax = otherToCurrentFactionGoodwill?.Max;

                int mutualGoodwillMin = MinOfNullableInts(currentToOtherFactionGoodwillMin, otherToCurrentFactionGoodwillMin);

                int mutualGoodwillMax = MinOfNullableInts(currentToOtherFactionGoodwillMax, otherToCurrentFactionGoodwillMax);

                // Generate a random goodwill value within the range
                int finalMutualGoodWill = Rand.RangeInclusive(mutualGoodwillMin, mutualGoodwillMax);

                // Assign mutual faction relations
                FactionRelationKind kind = (finalMutualGoodWill > -10) ? ((finalMutualGoodWill < 75) ? FactionRelationKind.Neutral : FactionRelationKind.Ally) : FactionRelationKind.Hostile;

                FactionRelation factionRelation = __instance.RelationWith(other, false);
                factionRelation.baseGoodwill = finalMutualGoodWill;
                factionRelation.kind         = kind;
                FactionRelation factionRelation2 = other.RelationWith(__instance, false);
                factionRelation2.baseGoodwill = finalMutualGoodWill;
                factionRelation2.kind         = kind;
            }
        }
Exemple #5
0
        private static bool TrySetRelationKind(Faction self, Faction other, FactionRelationKind kind, bool canSendLetter = true)
        {
            FactionRelation factionRelation = self.RelationWith(other);

            if (factionRelation.kind == kind)
            {
                return(true);
            }
            if (!self.HasGoodwill)
            {
                self.SetRelationDirect(other, kind, canSendLetter);
                return(true);
            }
            switch (kind)
            {
            case FactionRelationKind.Hostile:
                self.TryAffectGoodwillWith(other, -75 - factionRelation.baseGoodwill, canSendMessage: false, canSendLetter);
                return(factionRelation.kind == FactionRelationKind.Hostile);

            case FactionRelationKind.Neutral:
                self.TryAffectGoodwillWith(other, -factionRelation.baseGoodwill, canSendMessage: false, canSendLetter);
                return(factionRelation.kind == FactionRelationKind.Neutral);

            case FactionRelationKind.Ally:
                self.TryAffectGoodwillWith(other, 75 - factionRelation.baseGoodwill, canSendMessage: false, canSendLetter);
                return(factionRelation.kind == FactionRelationKind.Ally);

            default:
                throw new NotSupportedException(kind.ToString());
            }
        }
Exemple #6
0
 /// <summary>
 /// Checks to see if relation is within certain value. If not sets to highest or lowest possiable.
 /// </summary>
 /// <param name="relation"></param>
 void Validate(FactionRelation relation)
 {
     if (relation.opinion < -100)
     {
         relation.opinion = -100;
     }
     else if (relation.opinion > 100)
     {
         relation.opinion = 100;
     }
 }
Exemple #7
0
        public override void SpawnSetup()
        {
            base.SpawnSetup();

            RemoveAfterLeave = false;

            comp = this.GetComponent <SiegeCampSiteComp>();

            caravanAction = new CaravanVisitAction_SiegeCamp(this);

            relation = Faction.RelationWith(Faction.OfPlayer);
        }
Exemple #8
0
 /// <summary>
 /// Creates a singular relation
 /// </summary>
 /// <param name="a"></param>
 /// <param name="b"></param>
 public void CreateFactionRelation(Faction a, Faction b)
 {
     if ((int)a != (int)b)
     {
         if (!DoesFactionRelationExist(a, b))
         {
             FactionRelation fr = new FactionRelation();
             fr.faction1 = a;
             fr.faction2 = b;
             factionRelations.Add(fr);
         }
     }
 }
Exemple #9
0
 public void SendRelations(Character character)
 {
     if (_relations.Count == 0)
     {
         character.SendPacket(new SCFactionRelationListPacket());
     }
     else
     {
         var factions = _relations.ToArray();
         for (var i = 0; i < factions.Length; i += 200)
         {
             var temp = new FactionRelation[factions.Length - i <= 200 ? factions.Length - i : 200];
             Array.Copy(factions, i, temp, 0, temp.Length);
             character.SendPacket(new SCFactionRelationListPacket(temp));
         }
     }
 }
        protected Faction CreateFaction(FactionDef def)
        {
            Faction faction = Faction.OfPlayer;

            if (def != Faction.OfPlayer.def)
            {
                faction = new Faction()
                {
                    def = def
                };
                FactionRelation rel = new FactionRelation();
                rel.other    = Faction.OfPlayer;
                rel.goodwill = 50;
                (typeof(Faction).GetField("relations", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(faction) as List <FactionRelation>).Add(rel);
            }
            return(faction);
        }
Exemple #11
0
        public static void TenantCaptured(Pawn pawn, Pawn byPawn)
        {
            if (pawn.HostileTo(Find.FactionManager.OfPlayer))
            {
                return;
            }
            string text = "TenantCaptured".Translate(pawn.Named("PAWN"));

            text = text.AdjustedFor(pawn);
            string label = "Captured".Translate() + ": " + pawn.LabelShortCap;

            Find.LetterStack.ReceiveLetter(label, text, LetterDefOf.NeutralEvent, pawn);
            Tenant tenantComp = pawn.GetTenantComponent();

            tenantComp.IsTenant = false;
            pawn.GetTenantComponent().CapturedTenant = true;
            pawn.SetFaction(tenantComp.HiddenFaction);

            if (pawn.Faction.HostileTo(Find.FactionManager.OfPlayer))
            {
                if (Rand.Value < 0.25f || tenantComp.Wanted)
                {
                    MapComponent_Tenants.GetComponent(byPawn.Map).CapturedTenantsToAvenge.Add(pawn);
                    IncidentParms parms = StorytellerUtility.DefaultParmsNow(IncidentCategoryDefOf.ThreatBig, byPawn.Map);
                    parms.raidStrategy = RaidStrategyDefOf.Retribution;
                    parms.forced       = true;
                    Find.Storyteller.incidentQueue.Add(IncidentDefOf.RetributionForCaptured, Find.TickManager.TicksGame + Rand.Range(15000, 90000), parms, 240000);
                }
            }
            else
            {
                if (Rand.Value < 0.66f || tenantComp.Wanted)
                {
                    if (tenantComp.HiddenFaction.def != FactionDefOf.Ancients)
                    {
                        FactionRelation relation = pawn.Faction.RelationWith(Find.FactionManager.OfPlayer);
                        relation.goodwill = relation.goodwill - SettingsHelper.LatestVersion.OutragePenalty;
                        Messages.Message("TenantFactionOutrage".Translate(pawn.Faction, SettingsHelper.LatestVersion.OutragePenalty, pawn.Named("PAWN")), MessageTypeDefOf.NegativeEvent);
                    }
                }
            }
        }
Exemple #12
0
        public override void PreForceReform(MapParent mapParent)
        {
            if (comp.CachedRelations != null)
            {
                for (int i = 0; i < comp.CachedRelations.Count; i++)
                {
                    FactionRelation rel  = comp.CachedRelations[i];
                    Faction         fact = comp.CachedFactions[i];
                    fact.TrySetRelationKind(rel.other, rel.kind);
                }

                comp.CachedRelations.Clear();
                comp.CachedFactions.Clear();
            }

            QuestsManager.Communications.RemoveCommunication(comp.Dialog);
            comp.Dialog = null;

            base.PreForceReform(mapParent);
        }
        private void CacheAndChangeRelations(DoomsdayUltimatumComp comp)
        {
            comp.CachedRelations = new List <FactionRelation>();
            comp.CachedFactions  = new List <Faction>();
            foreach (var faction in comp.HelpingFactions)
            {
                foreach (var faction2 in comp.HelpingFactions)
                {
                    if (faction2 == faction)
                    {
                        continue;
                    }

                    FactionRelation mainRelation = faction.RelationWith(faction2);
                    if (mainRelation != null)
                    {
                        FactionRelation relation = new FactionRelation();
                        relation.other = mainRelation.other;
                        relation.kind  = mainRelation.kind;

                        comp.CachedRelations.Add(relation);
                        comp.CachedFactions.Add(faction);

                        faction.TrySetRelationKind(faction2, FactionRelationKind.Ally);
                    }
                }

                FactionRelation withPlayer = faction.RelationWith(Faction.OfPlayer);
                if (withPlayer != null)
                {
                    FactionRelation relation = new FactionRelation();
                    relation.other = withPlayer.other;
                    relation.kind  = withPlayer.kind;

                    comp.CachedRelations.Add(relation);
                    comp.CachedFactions.Add(faction);

                    faction.TrySetRelationKind(Faction.OfPlayer, FactionRelationKind.Ally);
                }
            }
        }
Exemple #14
0
        private void RemoveFaction()
        {
            if (selectedFaction == null)
            {
                Messages.Message($"Select faction", MessageTypeDefOf.NeutralEvent, false);
                return;
            }

            List <Settlement> toDelete = (Find.WorldObjects.Settlements.Where(sett => sett.Faction == selectedFaction)).ToList();

            foreach (var del in toDelete)
            {
                Find.WorldObjects.Remove(del);
            }

            if (Find.WorldPawns.Contains(selectedFaction.leader))
            {
                Find.WorldPawns.RemoveAndDiscardPawnViaGC(selectedFaction.leader);
            }

            FieldInfo relations = typeof(Faction).GetField("relations", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            Find.FactionManager.Remove(selectedFaction);

            foreach (var fac in Find.FactionManager.AllFactions)
            {
                var factionRelation = relations.GetValue(fac) as List <FactionRelation>;
                for (int i = 0; i < factionRelation.Count; i++)
                {
                    FactionRelation rel = factionRelation[i];
                    if (rel.other == selectedFaction)
                    {
                        factionRelation.Remove(rel);
                    }
                }
            }

            Messages.Message($"Faction deleted", MessageTypeDefOf.NeutralEvent, false);
        }
Exemple #15
0
            private static bool Prefix(Faction __instance, Faction other, ref FactionRelation __result, bool allowNull = false)
            {
                if (other == __instance)
                {
                    return(true);
                }
                List <FactionRelation> fr = Traverse.Create(root: __instance).Field(name: "relations").GetValue <List <FactionRelation> >();

                for (int i = 0; i < fr.Count; i++)
                {
                    if (fr[i].other == other)
                    {
                        __result = fr[i];
                        return(false);
                    }
                }
                if (!allowNull)
                {
                    WorldUtility.CreateFactionRelation(__instance, other);
                    //Log.Message("forced faction relation between " + __instance.Name + " and " + other.Name);
                }
                return(true);
            }
        public override void PostExposeData(object obj)
        {
            if (Scribe.mode == LoadSaveMode.PostLoadInit)
            {
                Map map = obj as Map;
                if (map != null)
                {
                    if (map.retainedCaravanData == null)
                    {
                        map.retainedCaravanData = new RetainedCaravanData(map);
                    }
                    if (map.wildAnimalSpawner == null)
                    {
                        map.wildAnimalSpawner = new WildAnimalSpawner(map);
                    }
                    if (map.wildPlantSpawner == null)
                    {
                        map.wildPlantSpawner = new WildPlantSpawner(map);
                    }
                }
                Thing thing = obj as Thing;
                if (thing != null && thing.def.useHitPoints && thing.MaxHitPoints != thing.HitPoints && Mathf.Abs((float)thing.HitPoints / (float)thing.MaxHitPoints - 0.617f) < 0.02f && thing.Stuff == ThingDefOf.WoodLog)
                {
                    thing.HitPoints = thing.MaxHitPoints;
                }
                Pawn pawn = obj as Pawn;
                if (pawn != null && !pawn.Destroyed && !pawn.Dead && pawn.needs == null)
                {
                    Log.Error(pawn.ToStringSafe() + " has null needs tracker even though he's not dead. Fixing...");
                    pawn.needs = new Pawn_NeedsTracker(pawn);
                    pawn.needs.SetInitialLevels();
                }
                History history = obj as History;
                if (history != null && history.archive == null)
                {
                    history.archive = new Archive();
                }
                WorldInfo worldInfo = obj as WorldInfo;
                if (worldInfo != null && worldInfo.persistentRandomValue == 0)
                {
                    worldInfo.persistentRandomValue = Rand.Int;
                }
                Caravan caravan = obj as Caravan;
                if (caravan != null)
                {
                    if (caravan.forage == null)
                    {
                        caravan.forage = new Caravan_ForageTracker(caravan);
                    }
                    if (caravan.needs == null)
                    {
                        caravan.needs = new Caravan_NeedsTracker(caravan);
                    }
                    if (caravan.carryTracker == null)
                    {
                        caravan.carryTracker = new Caravan_CarryTracker(caravan);
                    }
                    if (caravan.beds == null)
                    {
                        caravan.beds = new Caravan_BedsTracker(caravan);
                    }
                }
                PlaySettings playSettings = obj as PlaySettings;
                if (playSettings != null)
                {
                    playSettings.defaultCareForColonyHumanlike = MedicalCareCategory.Best;
                    playSettings.defaultCareForColonyAnimal    = MedicalCareCategory.HerbalOrWorse;
                    playSettings.defaultCareForColonyPrisoner  = MedicalCareCategory.HerbalOrWorse;
                    playSettings.defaultCareForNeutralFaction  = MedicalCareCategory.HerbalOrWorse;
                    playSettings.defaultCareForNeutralAnimal   = MedicalCareCategory.HerbalOrWorse;
                    playSettings.defaultCareForHostileFaction  = MedicalCareCategory.HerbalOrWorse;
                }
            }
            if (Scribe.mode == LoadSaveMode.LoadingVars)
            {
                Hediff hediff = obj as Hediff;
                if (hediff != null)
                {
                    Scribe_Values.Look(ref hediff.temp_partIndexToSetLater, "partIndex", -1);
                }
                Bill_Medical bill_Medical = obj as Bill_Medical;
                if (bill_Medical != null)
                {
                    Scribe_Values.Look(ref bill_Medical.temp_partIndexToSetLater, "partIndex", -1);
                }
                FactionRelation factionRelation = obj as FactionRelation;
                if (factionRelation != null)
                {
                    bool value = false;
                    Scribe_Values.Look(ref value, "hostile", defaultValue: false);
                    if (value || factionRelation.goodwill <= -75)
                    {
                        factionRelation.kind = FactionRelationKind.Hostile;
                    }
                    else if (factionRelation.goodwill >= 75)
                    {
                        factionRelation.kind = FactionRelationKind.Ally;
                    }
                }
                HediffComp_GetsPermanent hediffComp_GetsPermanent = obj as HediffComp_GetsPermanent;
                if (hediffComp_GetsPermanent != null)
                {
                    bool value2 = false;
                    Scribe_Values.Look(ref value2, "isOld", defaultValue: false);
                    if (value2)
                    {
                        hediffComp_GetsPermanent.isPermanentInt = true;
                    }
                }
                if (obj is World)
                {
                    UniqueIDsManager target = null;
                    Scribe_Deep.Look(ref target, "uniqueIDsManager");
                    if (target != null)
                    {
                        Current.Game.uniqueIDsManager = target;
                    }
                }
                WorldFeature worldFeature = obj as WorldFeature;
                if (worldFeature != null && worldFeature.maxDrawSizeInTiles == 0f)
                {
                    Vector2 value3 = Vector2.zero;
                    Scribe_Values.Look(ref value3, "maxDrawSizeInTiles");
                    worldFeature.maxDrawSizeInTiles = value3.x;
                }
            }
            if (Scribe.mode != LoadSaveMode.ResolvingCrossRefs)
            {
                return;
            }
            Hediff hediff2 = obj as Hediff;

            if (hediff2 != null && hediff2.temp_partIndexToSetLater >= 0 && hediff2.pawn != null)
            {
                if (hediff2.temp_partIndexToSetLater == 0)
                {
                    hediff2.Part = hediff2.pawn.RaceProps.body.GetPartAtIndex(hediff2.temp_partIndexToSetLater);
                }
                else
                {
                    hediff2.pawn.health.hediffSet.hediffs.Remove(hediff2);
                }
                hediff2.temp_partIndexToSetLater = -1;
            }
            Bill_Medical bill_Medical2 = obj as Bill_Medical;

            if (bill_Medical2 != null)
            {
                if (bill_Medical2.temp_partIndexToSetLater == 0)
                {
                    bill_Medical2.Part = bill_Medical2.GiverPawn.RaceProps.body.GetPartAtIndex(bill_Medical2.temp_partIndexToSetLater);
                }
                else
                {
                    bill_Medical2.GiverPawn.BillStack.Bills.Remove(bill_Medical2);
                }
                bill_Medical2.temp_partIndexToSetLater = -1;
            }
        }
Exemple #17
0
        public override void DoWindowContents(Rect inRect)
        {
            Text.Font = GameFont.Small;

            Widgets.Label(new Rect(inRect.center.x - 60, 0, 250, 20), Translator.Translate("FactionCreatorTitle"));
            WidgetRow row = new WidgetRow(330, 25);

            if (row.ButtonText(Translator.Translate("RandomizeFaction")))
            {
                newFaction = GenerateFaction();
            }
            if (row.ButtonText(Translator.Translate("RandomizeName")))
            {
                GenerateName(newFaction);
            }
            if (row.ButtonText(Translator.Translate("ClearFaction")))
            {
                newFaction      = null;
                selectedFaction = null;
            }

            int  factionDefSize     = avaliableFactions.Count * 25;
            Rect scrollRectFact     = new Rect(0, 25, 320, inRect.height - 100);
            Rect scrollVertRectFact = new Rect(0, 0, scrollRectFact.x, factionDefSize);

            Widgets.BeginScrollView(scrollRectFact, ref scrollPositionFact, scrollVertRectFact);

            int yButtonPos = 5;

            if (Widgets.ButtonText(new Rect(0, yButtonPos, 320, 20), Translator.Translate("NoText")))
            {
                selectedFaction = null;
            }
            yButtonPos += 25;
            foreach (FactionDef def in avaliableFactions)
            {
                if (Widgets.ButtonText(new Rect(0, yButtonPos, 320, 20), def.label))
                {
                    selectedFaction = def;

                    if (newFaction == null)
                    {
                        newFaction = GenerateFaction();
                    }
                }
                yButtonPos += 22;
            }
            Widgets.EndScrollView();

            Rect scrollRectGlobalFact     = new Rect(330, 50, 380, inRect.height - 20);
            Rect scrollVertRectGlobalFact = new Rect(0, 0, scrollRectGlobalFact.x, 600);

            Widgets.BeginScrollView(scrollRectGlobalFact, ref scrollFieldsPos, scrollVertRectGlobalFact);
            if (newFaction != null)
            {
                Widgets.Label(new Rect(0, 5, 330, 30), $"{Translator.Translate("FactionDefName")} {selectedFaction.label}");

                Widgets.Label(new Rect(0, 35, 150, 30), Translator.Translate("FactionName"));
                newFaction.Name = Widgets.TextField(new Rect(160, 35, 180, 30), newFaction.Name);

                Widgets.Label(new Rect(0, 73, 150, 30), Translator.Translate("FactionDefeated"));
                if (newFaction.defeated)
                {
                    if (Widgets.ButtonText(new Rect(160, 73, 180, 30), Translator.Translate("isDefeatedYES")))
                    {
                        newFaction.defeated = false;
                    }
                }
                else
                {
                    if (Widgets.ButtonText(new Rect(160, 73, 180, 30), Translator.Translate("isDefeatedNO")))
                    {
                        newFaction.defeated = true;
                    }
                }

                Widgets.Label(new Rect(0, 105, 180, 30), Translator.Translate("FactionRelative"));
                int  y                 = 15;
                int  boxY              = 5;
                Rect scrollRectRel     = new Rect(0, 130, 370, 160);
                Rect scrollVertRectRel = new Rect(0, 0, scrollRectRel.x, newFactionRelation.Count * 140);
                Widgets.DrawBox(new Rect(0, 130, 350, 160));
                Widgets.BeginScrollView(scrollRectRel, ref scrollRel, scrollVertRectRel);
                for (int i = 0; i < newFactionRelation.Count; i++)
                {
                    FactionRelation rel = newFactionRelation[i];

                    Widgets.DrawBox(new Rect(2, boxY, 340, 130));

                    Widgets.Label(new Rect(5, y, 315, 30), $"{Translator.Translate("FactionInfoName")} {rel.other.Name}");

                    y += 35;
                    Widgets.Label(new Rect(5, y, 140, 30), Translator.Translate("FactionGoodness"));
                    Widgets.TextFieldNumeric(new Rect(150, y, 130, 30), ref rel.goodwill, ref newFactionGoodwillBuff[i], -10000000000f);

                    y += 35;
                    switch (rel.kind)
                    {
                    case FactionRelationKind.Ally:
                    {
                        if (Widgets.ButtonText(new Rect(5, y, 180, 30), rel.kind.GetLabel()))
                        {
                            rel.kind = FactionRelationKind.Neutral;
                        }
                        break;
                    }

                    case FactionRelationKind.Neutral:
                    {
                        if (Widgets.ButtonText(new Rect(5, y, 180, 30), rel.kind.GetLabel()))
                        {
                            rel.kind = FactionRelationKind.Hostile;
                        }
                        break;
                    }

                    case FactionRelationKind.Hostile:
                    {
                        if (Widgets.ButtonText(new Rect(5, y, 180, 30), rel.kind.GetLabel()))
                        {
                            rel.kind = FactionRelationKind.Ally;
                        }
                        break;
                    }
                    }

                    boxY += 140;
                    y     = boxY + 10;
                }
                Widgets.EndScrollView();

                Widgets.Label(new Rect(0, 315, 180, 30), Translator.Translate("FactionIcon"));
                Widgets.DrawTextureFitted(new Rect(195, 315, 160, 30), selectedFaction.FactionIcon, 1.0f);
                //float.TryParse(Widgets.TextField(new Rect(195, 315, 160, 30), newFaction.centralMelanin.ToString()), out newFaction.centralMelanin);

                Widgets.Label(new Rect(0, 360, 160, 30), Translator.Translate("ColorSpectrum"));
                Widgets.FloatRange(new Rect(195, 360, 130, 30), 42, ref color, 0, 1);
                if (newFaction.def.colorSpectrum != null)
                {
                    Widgets.DrawBoxSolid(new Rect(165, 360, 20, 20), ColorsFromSpectrum.Get(newFaction.def.colorSpectrum, color.max));
                }

                Widgets.Label(new Rect(0, 400, 120, 30), Translator.Translate("FactionLeaderName"));
                leaderName = Widgets.TextField(new Rect(135, 400, 220, 30), leaderName);
            }
            Widgets.EndScrollView();

            if (Widgets.ButtonText(new Rect(0, inRect.height - 30, 320, 20), Translator.Translate("CreateNewFaction")))
            {
                CreateFaction();
            }
        }
 public static void DrawBrowseButtons(float top, float width, float padding, Pawn currentPawn)
 {
     if (currentPawn != null)
     {
         Action action  = null;
         Action action2 = null;
         if (currentPawn.IsColonist)
         {
             if (Find.ListerPawns.FreeColonists.Count <Pawn>() > 1)
             {
                 action = delegate
                 {
                     BrowseButtonDrawer.selector.SelectNextColonist();
                 };
                 action2 = delegate
                 {
                     BrowseButtonDrawer.selector.SelectPreviousColonist();
                 };
             }
         }
         else if (currentPawn.IsPrisonerOfColony)
         {
             if (Find.ListerPawns.PrisonersOfColonyCount > 1)
             {
                 action = delegate
                 {
                     BrowseButtonDrawer.selector.SelectNextPrisoner();
                 };
                 action2 = delegate
                 {
                     BrowseButtonDrawer.selector.SelectPreviousPrisoner();
                 };
             }
         }
         else
         {
             Faction faction = currentPawn.Faction;
             if (faction != null)
             {
                 if (faction != Faction.OfColony)
                 {
                     FactionRelation factionRelation = faction.RelationWith(Faction.OfColony);
                     if (factionRelation != null)
                     {
                         bool hostile = factionRelation.hostile;
                         if (hostile)
                         {
                             if (BrowseButtonDrawer.selector.MoreThanOneHostilePawn)
                             {
                                 action = delegate
                                 {
                                     BrowseButtonDrawer.selector.SelectNextEnemy();
                                 };
                                 action2 = delegate
                                 {
                                     BrowseButtonDrawer.selector.SelectPreviousEnemy();
                                 };
                             }
                         }
                         else if (BrowseButtonDrawer.selector.MoreThanOneVisitorPawn)
                         {
                             action = delegate
                             {
                                 BrowseButtonDrawer.selector.SelectNextVisitor();
                             };
                             action2 = delegate
                             {
                                 BrowseButtonDrawer.selector.SelectPreviousVisitor();
                             };
                         }
                     }
                 }
                 else if (BrowseButtonDrawer.selector.MoreThanOneColonyAnimal)
                 {
                     action = delegate
                     {
                         BrowseButtonDrawer.selector.SelectNextColonyAnimal();
                     };
                     action2 = delegate
                     {
                         BrowseButtonDrawer.selector.SelectPreviousColonyAnimal();
                     };
                 }
             }
         }
         Rect rect = new Rect(0f, 0f, BrowseButtonDrawer.ButtonSize.x, BrowseButtonDrawer.ButtonSize.y);
         if (action != null && action2 != null)
         {
             rect.x = padding - rect.width;
             rect.y = top;
             if (rect.Contains(Event.current.mousePosition))
             {
                 GUI.color = Color.white;
             }
             else
             {
                 GUI.color = BrowseButtonDrawer.ButtonColor;
             }
             GUI.DrawTexture(rect, BrowseButtonDrawer.ButtonTexturePrevious);
             if (Widgets.InvisibleButton(rect))
             {
                 action2();
             }
             rect.x = width - padding;
             rect.y = top;
             if (rect.Contains(Event.current.mousePosition))
             {
                 GUI.color = Color.white;
             }
             else
             {
                 GUI.color = BrowseButtonDrawer.ButtonColor;
             }
             GUI.DrawTexture(rect, BrowseButtonDrawer.ButtonTextureNext);
             if (Widgets.InvisibleButton(rect))
             {
                 action();
             }
         }
     }
 }
Exemple #19
0
 public void AddRelation(Faction faction, FactionRelation rel)
 {
     relations.Add(faction.GUID, rel);
 }
Exemple #20
0
        public static void SetFactionHostileToOther(Faction faction, Faction other, bool hostile)
        {
            FactionRelation factionRelation = faction.RelationWith(other, false);

            if (hostile)
            {
                if ((faction == Util_Faction.MiningCoFaction) &&
                    (other == Faction.OfPlayer))
                {
                    Util_Misc.Partnership.globalGoodwillFeeInSilver = WorldComponent_Partnership.globalGoodwillCostInSilver;
                    Util_Misc.OrbitalHealing.Notify_BecameHostileToColony();
                    foreach (Map map in Find.Maps)
                    {
                        if (map.IsPlayerHome)
                        {
                            List <Building_Spaceship> takeOffRequestList = new List <Building_Spaceship>();
                            foreach (Thing thing in map.listerThings.AllThings)
                            {
                                if (thing is Building_Spaceship)
                                {
                                    takeOffRequestList.Add(thing as Building_Spaceship);
                                }
                            }
                            foreach (Building_Spaceship spaceship in takeOffRequestList)
                            {
                                spaceship.RequestTakeOff();
                            }
                        }
                    }
                }
                if (Current.ProgramState == ProgramState.Playing)
                {
                    foreach (Pawn current in PawnsFinder.AllMapsWorldAndTemporary_Alive.ToList <Pawn>())
                    {
                        if ((current.Faction == faction && current.HostFaction == other) || (current.Faction == other && current.HostFaction == faction))
                        {
                            current.guest.SetGuestStatus(current.HostFaction, true);
                        }
                    }
                }
                if (!factionRelation.hostile)
                {
                    other.RelationWith(faction, false).hostile = true;
                    factionRelation.hostile = true;
                    if (factionRelation.goodwill > -80f)
                    {
                        factionRelation.goodwill = -80f;
                    }
                }
            }
            else
            {
                if (factionRelation.hostile)
                {
                    other.RelationWith(faction, false).hostile = false;
                    factionRelation.hostile = false;
                    if (factionRelation.goodwill < 0f)
                    {
                        factionRelation.goodwill = 0f;
                    }
                }
            }
            if (Current.ProgramState == ProgramState.Playing)
            {
                List <Map> maps = Find.Maps;
                for (int i = 0; i < maps.Count; i++)
                {
                    maps[i].attackTargetsCache.Notify_FactionHostilityChanged(faction, other);
                    LordManager lordManager = maps[i].lordManager;
                    for (int j = 0; j < lordManager.lords.Count; j++)
                    {
                        Lord lord = lordManager.lords[j];
                        if (lord.faction == other)
                        {
                            lord.Notify_FactionRelationsChanged(faction);
                        }
                        else
                        {
                            if (lord.faction == faction)
                            {
                                lord.Notify_FactionRelationsChanged(other);
                            }
                        }
                        if ((lord.faction == Util_Faction.MiningCoFaction) &&
                            (other == Faction.OfPlayer))
                        {
                            lord.ReceiveMemo("BecameHostileToColony");
                        }
                    }
                }
            }
        }
Exemple #21
0
 private static bool Prefix(Faction __instance, List <FactionRelation> ___relations, Faction other, ref FactionRelation __result, bool allowNull = false)
 {
     if (other == __instance)
     {
         return(true);
     }
     for (int i = 0; i < ___relations.Count; i++)
     {
         if (___relations[i].other == other)
         {
             __result = ___relations[i];
             return(false);
         }
     }
     if (!allowNull)
     {
         WorldUtility.CreateFactionRelation(__instance, other);
         //Log.Message("forced faction relation between " + __instance.Name + " and " + other.Name);
     }
     return(true);
 }
Exemple #22
0
        public void Load()
        {
            _systemFactions = new Dictionary <uint, SystemFaction>();
            _relations      = new List <FactionRelation>();
            using (var connection = SQLite.CreateConnection())
            {
                _log.Info("Loading system factions...");
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM system_factions";
                    command.Prepare();
                    using (var sqliteReader = command.ExecuteReader())
                        using (var reader = new SQLiteWrapperReader(sqliteReader))
                        {
                            while (reader.Read())
                            {
                                var faction = new SystemFaction
                                {
                                    Id              = reader.GetUInt32("id"),
                                    Name            = reader.GetString("name"),
                                    OwnerName       = reader.GetString("owner_name"),
                                    UnitOwnerType   = (sbyte)reader.GetInt16("owner_type_id"),
                                    OwnerId         = reader.GetUInt32("owner_id"),
                                    PoliticalSystem = reader.GetByte("political_system_id"),
                                    MotherId        = reader.GetUInt32("mother_id"),
                                    AggroLink       = reader.GetBoolean("aggro_link", true),
                                    GuardHelp       = reader.GetBoolean("guard_help", true),
                                    DiplomacyTarget = reader.GetBoolean("is_diplomacy_tgt", true)
                                };
                                _systemFactions.Add(faction.Id, faction);
                            }
                        }
                }

                _log.Info("Loaded {0} system factions", _systemFactions.Count);
                _log.Info("Loading faction relations...");
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM system_faction_relations";
                    command.Prepare();
                    using (var sqliteReader = command.ExecuteReader())
                        using (var reader = new SQLiteWrapperReader(sqliteReader))
                        {
                            while (reader.Read())
                            {
                                var relation = new FactionRelation
                                {
                                    Id    = reader.GetUInt32("faction1_id"),
                                    Id2   = reader.GetUInt32("faction2_id"),
                                    State = (RelationState)reader.GetByte("state_id")
                                };
                                _relations.Add(relation);

                                var faction = _systemFactions[relation.Id];
                                faction.Relations.Add(relation.Id2, relation);
                                faction = _systemFactions[relation.Id2];
                                faction.Relations.Add(relation.Id, relation);
                            }
                        }
                }

                _log.Info("Loaded {0} faction relations", _relations.Count);
            }
        }
Exemple #23
0
        // ===================== Goodwill management =====================
        public static bool AffectGoodwillWith(Faction faction, Faction other, int goodwillChange, bool canSendMessage = true, bool canSendHostilityLetter = true, string reason = null, GlobalTargetInfo?lookTarget = null)
        {
            if (goodwillChange == 0)
            {
                return(true);
            }
            int num  = faction.GoodwillWith(other);
            int num2 = Mathf.Clamp(num + goodwillChange, -100, 100);

            if (num == num2)
            {
                return(true);
            }
            FactionRelation factionRelation = faction.RelationWith(other, false);

            factionRelation.goodwill = num2;
            bool flag;

            factionRelation.CheckKindThresholds(faction, canSendHostilityLetter, reason, (!lookTarget.HasValue) ? GlobalTargetInfo.Invalid : lookTarget.Value, out flag);
            FactionRelation     factionRelation2 = other.RelationWith(faction, false);
            FactionRelationKind kind             = factionRelation2.kind;

            factionRelation2.goodwill = factionRelation.goodwill;
            factionRelation2.kind     = factionRelation.kind;
            bool flag2;

            if (kind != factionRelation2.kind)
            {
                other.Notify_RelationKindChanged(faction, kind, canSendHostilityLetter, reason, (!lookTarget.HasValue) ? GlobalTargetInfo.Invalid : lookTarget.Value, out flag2);
            }

            if ((faction == Util_Faction.MiningCoFaction) &&
                (other == Faction.OfPlayer) &&
                (factionRelation.kind == FactionRelationKind.Hostile))
            {
                Util_Misc.Partnership.globalGoodwillFeeInSilver = WorldComponent_Partnership.globalGoodwillCostInSilver;
                Util_Misc.OrbitalHealing.Notify_BecameHostileToColony();
                foreach (Map map in Find.Maps)
                {
                    if (map.IsPlayerHome)
                    {
                        List <Building_Spaceship> takeOffRequestList = new List <Building_Spaceship>();
                        foreach (Thing thing in map.listerThings.AllThings)
                        {
                            if (thing is Building_Spaceship)
                            {
                                takeOffRequestList.Add(thing as Building_Spaceship);
                            }
                        }
                        foreach (Building_Spaceship spaceship in takeOffRequestList)
                        {
                            spaceship.RequestTakeOff();
                        }
                    }
                    LordManager lordManager = map.lordManager;
                    for (int j = 0; j < lordManager.lords.Count; j++)
                    {
                        Lord lord = lordManager.lords[j];
                        if (lord.faction == Util_Faction.MiningCoFaction)
                        {
                            lord.ReceiveMemo("BecameHostileToColony");
                        }
                    }
                }
            }

            /*else
             * {
             *  flag2 = false;
             * }
             * if (canSendMessage && !flag && !flag2 && Current.ProgramState == ProgramState.Playing && (faction.IsPlayer || other.IsPlayer))
             * {
             *  Faction faction = (!this.IsPlayer) ? this : other;
             *  string text;
             *  if (!reason.NullOrEmpty())
             *  {
             *      text = "MessageGoodwillChangedWithReason".Translate(faction.name, num.ToString("F0"), factionRelation.goodwill.ToString("F0"), reason);
             *  }
             *  else
             *  {
             *      text = "MessageGoodwillChanged".Translate(faction.name, num.ToString("F0"), factionRelation.goodwill.ToString("F0"));
             *  }
             *  Messages.Message(text, (!lookTarget.HasValue) ? GlobalTargetInfo.Invalid : lookTarget.Value, ((float)goodwillChange <= 0f) ? MessageTypeDefOf.NegativeEvent : MessageTypeDefOf.PositiveEvent, true);
             * }*/
            return(true);
        }
Exemple #24
0
 public void AddRelation(String guid, FactionRelation rel)
 {
     relations.Add(guid, rel);
 }
Exemple #25
0
        private bool doDiploChange()
        {
            Faction faction;
            Faction faction2;

            if (!this.TryFindFaction(IncidentWorker_NPCDiploChange.allowPerm, IncidentWorker_NPCDiploChange.excludeEmpire, out faction))
            {
                return(false);
            }
            if (!this.TryFindFaction2(IncidentWorker_NPCDiploChange.allowIdeoBloc, IncidentWorker_NPCDiploChange.allowPerm, IncidentWorker_NPCDiploChange.excludeEmpire, faction, out faction2))
            {
                return(false);
            }

            if (faction.HostileTo(faction2))
            {
                FactionRelation factionRelation = faction.RelationWith(faction2, false);
                factionRelation.kind = FactionRelationKind.Neutral;
                FactionRelation factionRelation2 = faction2.RelationWith(faction, false);
                factionRelation2.kind = FactionRelationKind.Neutral;

                if (ModsConfig.IdeologyActive)
                {
                    int ideosurrenderroll = Rand.Range(1, 100);
                    if (ideosurrenderroll <= IncidentWorker_NPCDiploChange.ideoSurrenderChance)
                    {
                        List <Settlement> settlements   = Find.WorldObjects.Settlements.ToList <Settlement>();
                        double            faction1count = 0;
                        double            faction2count = 0;

                        for (int i = 0; i < settlements.Count; i++)
                        {
                            if (faction == settlements[i].Faction)
                            {
                                faction1count++;
                            }
                            if (faction2 == settlements[i].Faction)
                            {
                                faction2count++;
                            }
                        }

                        if (faction1count >= (faction2count * 3) && faction1count > 4)
                        {
                            faction2.ideos.SetPrimary(faction.ideos.PrimaryIdeo);
                            faction2.leader.ideo.SetIdeo(faction.ideos.PrimaryIdeo);
                            Find.LetterStack.ReceiveLetter("LabelDDSurrender".Translate(), "DescDDSurrender".Translate(faction.Name, faction2.Name, faction.ideos.PrimaryIdeo.ToString()), LetterDefOf.NeutralEvent, null);
                            return(true);
                        }
                        else if (faction2count >= (faction1count * 3) && faction2count > 4)
                        {
                            faction.ideos.SetPrimary(faction2.ideos.PrimaryIdeo);
                            faction.leader.ideo.SetIdeo(faction2.ideos.PrimaryIdeo);
                            Find.LetterStack.ReceiveLetter("LabelDDSurrender".Translate(), "DescDDSurrender".Translate(faction2.Name, faction.Name, faction2.ideos.PrimaryIdeo.ToString()), LetterDefOf.NeutralEvent, null);
                            return(true);
                        }
                    }
                }
            }
            else
            {
                FactionRelation factionRelation = faction.RelationWith(faction2, false);
                factionRelation.kind = FactionRelationKind.Hostile;
                FactionRelation factionRelation2 = faction2.RelationWith(faction, false);
                factionRelation2.kind = FactionRelationKind.Hostile;
            }

            return(true);
        }
Exemple #26
0
        public override void DoWindowContents(Rect inRect)
        {
            if (selectedFaction == null)
            {
                return;
            }

            Text.Font = GameFont.Small;

            Widgets.Label(new Rect(160, 0, 300, 20), Translator.Translate("FactionEditTitle"));

            Rect scrollRectGlobalFact     = new Rect(0, 30, 390, inRect.height - 30);
            Rect scrollVertRectGlobalFact = new Rect(0, 0, scrollRectGlobalFact.x, 600);

            Widgets.BeginScrollView(scrollRectGlobalFact, ref scrollFieldsPos, scrollVertRectGlobalFact);
            if (selectedFaction != null)
            {
                Widgets.Label(new Rect(0, 5, 330, 30), $"{Translator.Translate("FactionDefName")} {selectedFaction.def.label}");

                Widgets.Label(new Rect(0, 35, 150, 30), Translator.Translate("FactionName"));
                selectedFaction.Name = Widgets.TextField(new Rect(160, 35, 180, 30), selectedFaction.Name);

                Widgets.Label(new Rect(0, 73, 150, 30), Translator.Translate("FactionDefeated"));
                if (selectedFaction.defeated)
                {
                    if (Widgets.ButtonText(new Rect(160, 73, 180, 30), Translator.Translate("isDefeatedYES")))
                    {
                        selectedFaction.defeated = false;
                    }
                }
                else
                {
                    if (Widgets.ButtonText(new Rect(160, 73, 180, 30), Translator.Translate("isDefeatedNO")))
                    {
                        selectedFaction.defeated = true;
                    }
                }

                Widgets.Label(new Rect(0, 105, 180, 30), Translator.Translate("FactionRelative"));
                int  y                 = 15;
                int  boxY              = 5;
                Rect scrollRectRel     = new Rect(0, 130, 370, 160);
                Rect scrollVertRectRel = new Rect(0, 0, scrollRectRel.x, factionRelation.Count * 140);
                Widgets.DrawBox(new Rect(0, 130, 350, 160));
                Widgets.BeginScrollView(scrollRectRel, ref scrollRel, scrollVertRectRel);
                for (int i = 0; i < factionRelation.Count; i++)
                {
                    FactionRelation rel = factionRelation[i];
                    Widgets.DrawBox(new Rect(2, boxY, 340, 130));

                    Widgets.Label(new Rect(5, y, 315, 30), $"{Translator.Translate("FactionInfoName")} {rel.other?.Name}");

                    y += 35;
                    Widgets.Label(new Rect(5, y, 140, 30), Translator.Translate("FactionGoodness"));
                    Widgets.TextFieldNumeric(new Rect(150, y, 130, 30), ref rel.goodwill, ref factionGoodwillBuff[i], -10000000000f);

                    y += 35;
                    switch (rel.kind)
                    {
                    case FactionRelationKind.Ally:
                    {
                        if (Widgets.ButtonText(new Rect(5, y, 180, 30), rel.kind.GetLabel()))
                        {
                            rel.kind = FactionRelationKind.Neutral;
                        }
                        break;
                    }

                    case FactionRelationKind.Neutral:
                    {
                        if (Widgets.ButtonText(new Rect(5, y, 180, 30), rel.kind.GetLabel()))
                        {
                            rel.kind = FactionRelationKind.Hostile;
                        }
                        break;
                    }

                    case FactionRelationKind.Hostile:
                    {
                        if (Widgets.ButtonText(new Rect(5, y, 180, 30), rel.kind.GetLabel()))
                        {
                            rel.kind = FactionRelationKind.Ally;
                        }
                        break;
                    }
                    }

                    boxY += 140;
                    y     = boxY + 10;
                }

                Widgets.EndScrollView();


                if (selectedFaction.def.ExpandingIconTexture != null)
                {
                    Widgets.Label(new Rect(0, 315, 180, 30), Translator.Translate("FactionIcon"));
                    Widgets.DrawTextureFitted(new Rect(195, 315, 160, 30), selectedFaction.def.ExpandingIconTexture, 1.0f);
                }

                Widgets.Label(new Rect(0, 360, 160, 30), Translator.Translate("ColorSpectrum"));
                Widgets.FloatRange(new Rect(195, 360, 130, 30), 42, ref color, 0, 1);
                if (selectedFaction.def.colorSpectrum != null)
                {
                    Widgets.DrawBoxSolid(new Rect(165, 360, 20, 20), ColorsFromSpectrum.Get(selectedFaction.def.colorSpectrum, color.max));
                }

                if (selectedFaction.leader != null)
                {
                    Widgets.Label(new Rect(0, 400, 120, 30), Translator.Translate("FactionLeaderName"));
                    leaderName = Widgets.TextField(new Rect(135, 400, 220, 30), leaderName);
                }
            }
            Widgets.EndScrollView();

            if (Widgets.ButtonText(new Rect(0, inRect.height - 20, 400, 20), Translator.Translate("SaveFaction")))
            {
                SaveFaction();
            }
        }
Exemple #27
0
        private bool doConquest()
        {
            Settlement AttackerBase = RandomSettlement();

            if (AttackerBase == null)
            {
                return(false);
            }
            Faction AttackerFaction = AttackerBase.Faction;

            if (AttackerFaction == null)
            {
                return(false);
            }

            List <Settlement> settlements       = Find.WorldObjects.Settlements.ToList <Settlement>();
            List <Settlement> prox1             = new List <Settlement>();
            List <Settlement> prox2             = new List <Settlement>();
            List <Settlement> prox3             = new List <Settlement>();
            List <Settlement> prox4             = new List <Settlement>();
            List <Settlement> prox5             = new List <Settlement>();
            List <Settlement> prox6             = new List <Settlement>();
            List <Settlement> prox7             = new List <Settlement>();
            double            attackerBaseCount = 0;
            double            totalBaseCount    = 0;

            List <Settlement> attackerSettlementList = new List <Settlement>();

            for (int i = 0; i < settlements.Count; i++)
            {
                Settlement DefenderBase = settlements[i];

                if (DefenderBase.Faction == AttackerBase.Faction)
                {
                    attackerBaseCount++;
                    attackerSettlementList.Add(DefenderBase);
                }

                if (DefenderBase.Faction != null && !DefenderBase.Faction.IsPlayer && DefenderBase.Faction.def.settlementGenerationWeight > 0f && !DefenderBase.def.defName.Equals("City_Faction") && !DefenderBase.def.defName.Equals("City_Abandoned") && !DefenderBase.def.defName.Equals("City_Ghost") && !DefenderBase.def.defName.Equals("City_Citadel"))
                {
                    totalBaseCount++;
                    if (AttackerBase.Faction.HostileTo(DefenderBase.Faction))
                    {
                        int attackDistance = Find.WorldGrid.TraversalDistanceBetween(AttackerBase.Tile, DefenderBase.Tile, true);
                        if (attackDistance < 30)
                        {
                            prox1.Add(DefenderBase);
                        }
                        else if (attackDistance < 60)
                        {
                            prox2.Add(DefenderBase);
                        }
                        else if (attackDistance < 90)
                        {
                            prox3.Add(DefenderBase);
                        }
                        else if (attackDistance < 120)
                        {
                            prox4.Add(DefenderBase);
                        }
                        else if (attackDistance < 150)
                        {
                            prox5.Add(DefenderBase);
                        }
                        else if (attackDistance < 180)
                        {
                            prox6.Add(DefenderBase);
                        }
                        else if (attackDistance < 210)
                        {
                            prox7.Add(DefenderBase);
                        }
                    }
                }
            }

            // Rebellion code
            if (attackerBaseCount >= 10 && attackerBaseCount >= (totalBaseCount * 0.1))
            {
                int num = Rand.Range(1, 100);
                if (num <= (int)(attackerBaseCount / totalBaseCount * 20) || attackerBaseCount >= (totalBaseCount * 0.8))
                {
                    List <Faction> allFactionList = (from x in Find.FactionManager.AllFactionsVisible
                                                     where x.def.settlementGenerationWeight > 0f && !x.def.hidden && !x.IsPlayer && !x.defeated && x != AttackerFaction && x.leader != null && !x.leader.IsPrisoner && !x.leader.Spawned
                                                     select x).ToList <Faction>();
                    for (int i = 0; i < allFactionList.Count; i++)
                    {
                        if (!IncidentWorker_NPCConquest.HasAnyOtherBase(allFactionList[i]))
                        {
                            for (int j = 0; j < attackerSettlementList.Count; j++)
                            {
                                int  num2             = Rand.Range(1, 100);
                                bool resistancechance = num2 < 41;
                                if (resistancechance)
                                {
                                    Settlement rebelSettlement = (Settlement)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.Settlement);
                                    rebelSettlement.SetFaction(allFactionList[i]);
                                    rebelSettlement.Tile = attackerSettlementList[j].Tile;
                                    rebelSettlement.Name = SettlementNameGenerator.GenerateSettlementName(rebelSettlement, null);
                                    Find.WorldObjects.Remove(attackerSettlementList[j]);
                                    Find.WorldObjects.Add(rebelSettlement);
                                }
                            }

                            FactionRelation factionRelation = allFactionList[i].RelationWith(AttackerBase.Faction, false);
                            factionRelation.kind = FactionRelationKind.Hostile;
                            FactionRelation factionRelation2 = AttackerBase.Faction.RelationWith(allFactionList[i], false);
                            factionRelation2.kind = FactionRelationKind.Hostile;
                            Find.LetterStack.ReceiveLetter("LabelRebellion".Translate(), "DescRebellion".Translate(allFactionList[i], AttackerBase.Faction), LetterDefOf.NeutralEvent, null);
                            return(true);
                        }
                    }

                    if (IncidentWorker_NPCConquest.allowCloneFaction && AttackerFaction != Faction.OfEmpire)
                    {
                        Faction clonefaction = FactionGenerator.NewGeneratedFaction(new FactionGeneratorParms(AttackerFaction.def, default(IdeoGenerationParms), null));
                        clonefaction.color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
                        Find.FactionManager.Add(clonefaction);

                        for (int i = 0; i < attackerSettlementList.Count; i++)
                        {
                            int  num3             = Rand.Range(1, 100);
                            bool resistancechance = num3 < 41;
                            if (resistancechance)
                            {
                                Settlement rebelSettlement = (Settlement)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.Settlement);
                                rebelSettlement.SetFaction(clonefaction);
                                rebelSettlement.Tile = attackerSettlementList[i].Tile;
                                rebelSettlement.Name = SettlementNameGenerator.GenerateSettlementName(rebelSettlement, null);
                                Find.WorldObjects.Remove(attackerSettlementList[i]);
                                Find.WorldObjects.Add(rebelSettlement);
                            }
                        }

                        FactionRelation factionRelation = clonefaction.RelationWith(AttackerBase.Faction, false);
                        factionRelation.kind = FactionRelationKind.Hostile;
                        FactionRelation factionRelation2 = AttackerBase.Faction.RelationWith(clonefaction, false);
                        factionRelation2.kind = FactionRelationKind.Hostile;

                        Ideo newIdeo = IdeoGenerator.GenerateIdeo(FactionIdeosTracker.IdeoGenerationParmsForFaction_BackCompatibility(clonefaction.def));
                        clonefaction.ideos.SetPrimary(newIdeo);
                        Find.IdeoManager.Add(newIdeo);
                        clonefaction.leader.ideo.SetIdeo(newIdeo);

                        Find.LetterStack.ReceiveLetter("LabelRebellion".Translate(), "DescRebellion".Translate(clonefaction, AttackerBase.Faction), LetterDefOf.NeutralEvent, null);
                        return(true);
                    }
                }
            }

            // Conquest code
            Settlement FinalDefenderBase;

            if (prox1.Count != 0)
            {
                FinalDefenderBase = prox1.RandomElement <Settlement>();
            }
            else if (prox2.Count != 0)
            {
                FinalDefenderBase = prox2.RandomElement <Settlement>();
            }
            else if (prox3.Count != 0)
            {
                FinalDefenderBase = prox3.RandomElement <Settlement>();
            }
            else if (prox4.Count != 0)
            {
                FinalDefenderBase = prox4.RandomElement <Settlement>();
            }
            else if (prox5.Count != 0)
            {
                FinalDefenderBase = prox5.RandomElement <Settlement>();
            }
            else if (prox6.Count != 0)
            {
                FinalDefenderBase = prox6.RandomElement <Settlement>();
            }
            else if (prox7.Count != 0)
            {
                FinalDefenderBase = prox7.RandomElement <Settlement>();
            }
            else
            {
                return(false);
            }

            if (FinalDefenderBase.HasMap)
            {
                Log.Message("attack target has generated map. Event dropped.");
                return(false);
            }

            // Determine whether to raze or take control, distance-based
            int razeroll = Rand.Range(1, 100);

            if (razeroll <= IncidentWorker_NPCConquest.razeChance)
            {
                if (IncidentWorker_NPCConquest.allowRazeClear)
                {
                    List <DestroyedSettlement> clearRuinTarget = Find.WorldObjects.DestroyedSettlements;
                    for (int i = 0; i < clearRuinTarget.Count; i++)
                    {
                        Find.WorldObjects.Remove(clearRuinTarget[i]);
                    }
                }

                DestroyedSettlement destroyedSettlement = (DestroyedSettlement)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.DestroyedSettlement);
                destroyedSettlement.Tile = FinalDefenderBase.Tile;
                Find.WorldObjects.Remove(FinalDefenderBase);
                Find.WorldObjects.Add(destroyedSettlement);
            }
            else
            {
                Settlement settlementConquest = (Settlement)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.Settlement);
                settlementConquest.SetFaction(AttackerBase.Faction);
                settlementConquest.Tile = FinalDefenderBase.Tile;
                settlementConquest.Name = SettlementNameGenerator.GenerateSettlementName(settlementConquest, null);
                Find.WorldObjects.Remove(FinalDefenderBase);
                Find.WorldObjects.Add(settlementConquest);
            }

            // Defeat check for distance conquest
            if (IncidentWorker_NPCConquest.allowCloneFaction && !HasAnyOtherBase(FinalDefenderBase))
            {
                List <Faction> clonefactioncheck = (from x in Find.FactionManager.AllFactionsVisible
                                                    where !x.def.hidden && !x.IsPlayer && !x.defeated && x != FinalDefenderBase.Faction && x.def == FinalDefenderBase.Faction.def
                                                    select x).ToList <Faction>();
                if (clonefactioncheck.Count > 0)
                {
                    FinalDefenderBase.Faction.defeated = true;
                    Find.LetterStack.ReceiveLetter("LetterLabelFactionBaseDefeated".Translate(), "LetterFactionBaseDefeated_FactionDestroyed".Translate(FinalDefenderBase.Faction.Name), LetterDefOf.NeutralEvent, null);
                }
            }

            int defeatroll = Rand.Range(1, 100);

            if (defeatroll <= IncidentWorker_NPCConquest.defeatChance && !HasAnyOtherBase(FinalDefenderBase))
            {
                FinalDefenderBase.Faction.defeated = true;
                Find.LetterStack.ReceiveLetter("LetterLabelFactionBaseDefeated".Translate(), "LetterFactionBaseDefeated_FactionDestroyed".Translate(FinalDefenderBase.Faction.Name), LetterDefOf.NeutralEvent, null);
            }

            // Alliance code
            if (IncidentWorker_NPCConquest.allowAlliance && Find.World.GetComponent <DiplomacyWorldComponent>().allianceCooldown <= 0)
            {
                List <Faction> alliance = (from x in Find.FactionManager.AllFactionsVisible
                                           where x.def.settlementGenerationWeight > 0f && !x.def.hidden && !x.IsPlayer && !x.defeated && x != AttackerFaction && x.leader != null && !x.leader.IsPrisoner && !x.leader.Spawned
                                           select x).ToList <Faction>();
                List <Faction> finalAlliance = new List <Faction>();

                if (alliance.Count >= 2 && attackerBaseCount >= (totalBaseCount * 0.4) && attackerBaseCount <= (totalBaseCount * 0.6) && attackerBaseCount > 9)
                {
                    for (int i = 0; i < alliance.Count; i++)
                    {
                        int  num         = Rand.Range(1, 100);
                        bool havemysword = num < 81;
                        if (havemysword)
                        {
                            FactionRelation factionRelation = AttackerFaction.RelationWith(alliance[i], false);
                            factionRelation.kind = FactionRelationKind.Hostile;
                            FactionRelation factionRelation2 = alliance[i].RelationWith(AttackerFaction, false);
                            factionRelation2.kind = FactionRelationKind.Hostile;
                            finalAlliance.Add(alliance[i]);
                        }
                    }

                    StringBuilder allianceList = new StringBuilder();
                    for (int x = 0; x < finalAlliance.Count; x++)
                    {
                        for (int y = 0; y < finalAlliance.Count; y++)
                        {
                            if (finalAlliance[y] != finalAlliance[x])
                            {
                                FactionRelation factionRelation3 = finalAlliance[y].RelationWith(finalAlliance[x], false);
                                factionRelation3.kind = FactionRelationKind.Neutral;
                                FactionRelation factionRelation4 = finalAlliance[x].RelationWith(finalAlliance[y], false);
                                factionRelation4.kind = FactionRelationKind.Neutral;
                            }
                        }
                        allianceList.Append(finalAlliance[x].ToString()).Append(", ");
                    }
                    string allianceListString = allianceList.ToString();
                    allianceListString = allianceListString.Trim().TrimEnd(',');

                    Find.LetterStack.ReceiveLetter("LabelAlliance".Translate(), "DescAlliance".Translate(allianceListString, AttackerBase.Faction), LetterDefOf.NeutralEvent, null);
                    Find.World.GetComponent <DiplomacyWorldComponent>().allianceCooldown = 11;
                }
            }

            if (Find.World.GetComponent <DiplomacyWorldComponent>().allianceCooldown > 0)
            {
                Find.World.GetComponent <DiplomacyWorldComponent>().allianceCooldown--;
            }

            return(true);
        }
Exemple #28
0
        public static void Patch_Pawn_Kill(ref Thing __instance, ref DamageInfo?dinfo, ref Hediff exactCulprit)
        {
            //Log.Message(ModData.Settings.ToString());
            //Log.Message("Pawn '" + __instance.LabelCap + "' got killed.");
            //Construct our killfeed announcement.
            if (__instance == null)
            {
                return;
            }

            Pawn pawn = __instance as Pawn;

            if (pawn != null)
            {
                //Log.Message(pawn.def.defName);
                //Log.Message(pawn.Faction.IsPlayer + "");

                KillAnnouncement announcement = new KillAnnouncement
                {
                    victim       = pawn,
                    dinfo        = dinfo,
                    exactCulprit = exactCulprit
                };

                //If the damage info got a value then something killed them normally.
                if (dinfo != null && dinfo.HasValue && dinfo.Value.Instigator != null)
                {
                    //Log.Message("natural death");
                    Thing instigator = dinfo.Value.Instigator;
                    announcement.perpetrator = instigator;

                    //Figure out the context of death.
                    bool victimIsFriendly = false;
                    bool victimIsNeutral  = false;
                    if (announcement.victim.Faction != null)
                    {
                        if (announcement.victim.Faction.IsPlayer)
                        {
                            victimIsFriendly = true;
                        }
                        else
                        {
                            FactionRelation relationWithPlayer = announcement.victim.Faction.RelationWith(Faction.OfPlayer);
                            if (relationWithPlayer.kind == FactionRelationKind.Hostile && relationWithPlayer.goodwill >= 40f)
                            {
                                victimIsFriendly = true;
                            }
                        }
                    }
                    else
                    {
                        victimIsNeutral = true;
                    }

                    //bool perpetratorIsFriendly = false;
                    //bool perpetratorIsNeutral = false;
                    //if (announcement.perpetrator.Faction != null)
                    //{
                    //    if (announcement.perpetrator.Faction.HasName || announcement.perpetrator.Faction.Name == "New Arrivals")
                    //    {
                    //        if (announcement.perpetrator.Faction.IsPlayer)
                    //        {
                    //            //Log.Message("Perpetrator faction is player's");
                    //            perpetratorIsFriendly = true;
                    //        }
                    //        else
                    //        {
                    //            FactionRelation relationWithPlayer = announcement.perpetrator.Faction.RelationWith(Faction.OfPlayer);
                    //            //Log.Message(announcement.perpetrator.Faction.Name);
                    //            if (relationWithPlayer.kind == FactionRelationKind.Hostile && relationWithPlayer.goodwill >= 40f)
                    //            {
                    //                perpetratorIsFriendly = true;
                    //                //Log.Message("Perpetrator faction is hostile");
                    //            }
                    //            else
                    //            {
                    //                //Log.Message("Perpetrator faction is ally");
                    //            }

                    //        }
                    //    }
                    //    else
                    //    {
                    //        //Log.Message("perpetrator faction has no name" + announcement.perpetrator.Faction.Name);
                    //    }
                    //}
                    //else
                    //{
                    //    //Log.Message("perpetrator has no faction");
                    //    perpetratorIsNeutral = true;
                    //}

                    //categorize announcement type
                    announcement.type = KillAnnouncementType.Ignore;

                    if (victimIsFriendly)
                    {
                        if (ModData.Settings.DisplayAllyDeath)
                        {
                            announcement.type = KillAnnouncementType.Ally;
                        }
                    }
                    else
                    {
                        if (victimIsNeutral)
                        {
                            if (ModData.Settings.DisplayWildAnimalDeath)
                            {
                                announcement.type = KillAnnouncementType.WildAnimal;
                            }
                        }
                        else
                        {
                            if (ModData.Settings.DisplayEnemyDeath)
                            {
                                announcement.type = KillAnnouncementType.Enemy;
                            }
                        }
                    }

                    //Log.Message(announcement.type.ToString());

                    //Log.Message(announcement.perpetrator.Position.ToStringSafe());

                    /*if (announcement.perpetrator.HostileTo(Faction.OfPlayer))
                     * {
                     *  announcement.type = KillAnnouncementType.Enemy;
                     * }
                     * else
                     * {
                     *  announcement.type = KillAnnouncementType.Ally;
                     * }*/
                }
                else
                {
                    //Log.Message(announcement.victim.Position.ToStringSafe());
                    announcement.type = KillAnnouncementType.Magic;
                    if (exactCulprit != null)
                    {
                        announcement.flavorText = " died from " + exactCulprit.Label;
                    }
                    else
                    {
                        announcement.flavorText = " died from magic";
                    }
                }


                if (announcement.type != KillAnnouncementType.Ignore)
                {
                    Current.Game.GetComponent <KillFeedGameComponent>().PushAnnouncement(announcement);
                }
            }
        }