Exemple #1
0
        private static void PatchGiddyUpCore([NotNull] Harmony harmonyInstance)
        {
            Type isMountableUtils = GenTypes.GetTypeInAnyAssembly("GiddyUpCore.Utilities.IsMountableUtility");

            if (isMountableUtils == null)
            {
                Log.Error("Unable to find type IsMountableUtilities!");
                return;
            }

            Type enumTyp = isMountableUtils.GetNestedType("Reason");

            if (enumTyp == null)
            {
                Log.Error("unable to find type \"IsMountableUtility.Reason\"");
                return;
            }

            MethodInfo methodToPatch = isMountableUtils.GetMethod("isMountable", new[] { typeof(Pawn), enumTyp.MakeByRefType() });

            if (methodToPatch == null)
            {
                Log.Error("PM: unable to patch isMountable! ");
            }
            else
            {
                harmonyInstance.Patch(methodToPatch,
                                      new HarmonyMethod(typeof(GiddyUpPatch).GetMethod(nameof(IsMountablePatch),
                                                                                       BindingFlags.Static
                                                                                       | BindingFlags.NonPublic)));
            }
        }
Exemple #2
0
            static MapDesigner()
            {
                Harmony harmony = new Harmony("zylle.MapDesigner");

                Log.Message("[Map Designer] Initializing.... ");
                harmony.PatchAll();

                if (ModsConfig.RoyaltyActive)
                {
                    try
                    {
                        MethodInfo targetmethod = AccessTools.Method(typeof(RimWorld.GenStep_AnimaTrees), "DesiredTreeCountForMap");
                        //HarmonyMethod postfix = new HarmonyMethod(typeof(MapDesigner).GetMethod("AnimaTreePatch"));
                        HarmonyMethod postfix = new HarmonyMethod(typeof(AnimaTreePatch).GetMethod("Postfix", BindingFlags.NonPublic | BindingFlags.Static));
                        harmony.Patch(targetmethod, null, postfix);
                    }
                    catch
                    {
                        Log.Message("[Map Designer] ERROR: Failed to patch anima trees");
                    }
                }

                if (GenTypes.GetTypeInAnyAssembly("MapReroll.MapPreviewGenerator") != null)
                {
                    Log.Message("Found Map Reroll");
                    HelperMethods.ApplyMapRerollPatches();
                }

                HelperMethods.InitBiomeDefaults();
                HelperMethods.ApplyBiomeSettings();
            }
        internal void PrepareReflection()
        {
            var gizmoGridType = GenTypes.GetTypeInAnyAssembly("InspectGizmoGrid", "RimWorld");

            if (gizmoGridType != null)
            {
                GizmoGridGizmoListField = gizmoGridType.GetField("gizmoList", HugsLibUtility.AllBindingFlags);
            }
            DesignatorGetDesignationMethod = typeof(Designator).GetMethod("get_Designation", HugsLibUtility.AllBindingFlags);
            DesignatorHasDesignateAllFloatMenuOptionField  = typeof(Designator).GetField("hasDesignateAllFloatMenuOption", HugsLibUtility.AllBindingFlags);
            DesignatorGetRightClickFloatMenuOptionsMethod  = typeof(Designator).GetMethod("get_RightClickFloatMenuOptions", HugsLibUtility.AllBindingFlags);
            DraftControllerAutoUndrafterField              = typeof(Pawn_DraftController).GetField("autoUndrafter", HugsLibUtility.AllBindingFlags);
            DesignationCategoryDefResolveDesignatorsMethod = typeof(DesignationCategoryDef).GetMethod("ResolveDesignators", HugsLibUtility.AllBindingFlags);
            GenDrawLineMatMetaOverlay = typeof(GenDraw).GetField("LineMatMetaOverlay", BindingFlags.Static | BindingFlags.NonPublic);
            if (GizmoGridGizmoListField == null || GizmoGridGizmoListField.FieldType != typeof(List <Gizmo>) ||
                DesignatorGetDesignationMethod == null || DesignatorGetDesignationMethod.ReturnType != typeof(DesignationDef) ||
                DesignatorHasDesignateAllFloatMenuOptionField == null || DesignatorHasDesignateAllFloatMenuOptionField.FieldType != typeof(bool) ||
                DesignatorGetRightClickFloatMenuOptionsMethod == null || DesignatorGetRightClickFloatMenuOptionsMethod.ReturnType != typeof(IEnumerable <FloatMenuOption>) ||
                DraftControllerAutoUndrafterField == null || DraftControllerAutoUndrafterField.FieldType != typeof(AutoUndrafter) ||
                DesignationCategoryDefResolveDesignatorsMethod == null || DesignationCategoryDefResolveDesignatorsMethod.GetParameters().Length != 0 ||
                GenDrawLineMatMetaOverlay == null || GenDrawLineMatMetaOverlay.FieldType != typeof(Material)
                )
            {
                AllowToolController.Logger.Error("Failed to reflect required members");
            }
        }
Exemple #4
0
        static void AddField(ModuleDefinition module, NewFieldData newField)
        {
            var fieldType   = GenTypes.GetTypeInAnyAssembly(newField.fieldType);
            var ceFieldType = module.ImportReference(fieldType);

            PrepatcherMod.Info($"Patching in a new field {newField.name} of type {ceFieldType.ToStringSafe()}/{newField.fieldType} in type {newField.targetType}");

            var ceField = new FieldDefinition(
                newField.name,
                FieldAttributes.Public,
                ceFieldType
                );

            if (newField.isStatic)
            {
                ceField.Attributes |= FieldAttributes.Static;
            }

            var targetType = module.GetType(newField.targetType);

            targetType.Fields.Add(ceField);

            if (newField.defaultValue != null)
            {
                WriteFieldInitializers(newField, ceField, fieldType);
            }
        }
        // MendAndRecycle
        public static IEnumerable <CodeInstruction> Transpile_MendAndReycle_JobDriver_Mend_MendToil_TickAction(IEnumerable <CodeInstruction> instructions)
        {
            #if DEBUG
            Log.Message("Transpiler start: Transpile_MendAndReycle.JobDriver_Mend.MendToil.TickAction (1 match)");
            #endif

            var instructionList = instructions.ToList();

            var removeDeadmanSettingFieldInfo = AccessTools.Field(GenTypes.GetTypeInAnyAssembly("MendAndRecycle.Settings", null), "removesDeadman");

            for (int i = 0; i < instructionList.Count; i++)
            {
                var instruction = instructionList[i];

                // If instruction checks for 'remove deadman' setting, add call to our helper method before it
                if (instruction.opcode == OpCodes.Ldsfld && instruction.OperandIs(removeDeadmanSettingFieldInfo))
                {
                    #if DEBUG
                    Log.Message("Transpile_MendAndReycle.JobDriver_Mend.MendToil.TickAction match 1 of 1");
                    #endif

                    yield return(new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(ProfitableWeaponsSettings), "mendingRemoveLootedFlag"))); // ProfitableWeaponsSettings.mendingRemoveLootedFlag

                    yield return(new CodeInstruction(OpCodes.Ldloc_0));                                                                                 // thing

                    yield return(new CodeInstruction(OpCodes.Call, AccessTools.Method(patchType, nameof(RemoveUsedWeaponFlag))));                       // RemoveUsedWeaponFlag(ProfitableWeaponsSettings.mendingRemoveLootedFlag, thing)
                }

                yield return(instruction);
            }
        }
        public override void DefsLoaded()
        {
            hasAlienRace = GenTypes.GetTypeInAnyAssembly("AlienRace.RaceSettings", "AlienRace") != null;

            FB_Factions.RemoveAll(x => true);
            FB_Factions.Add(FactionDef.Named("FactionBlender_Pirate"));
            FB_Factions.Add(FactionDef.Named("FactionBlender_Civil"));

            ProcessSettings();

            DefInjector.InjectMiscToFactions(FB_Factions);

            Logger.Message("Injecting pawn groups to our factions");
            FillFilterLists();
            DefInjector.InjectPawnKindDefsToFactions(FB_Factions);

            if (hasAlienRace)
            {
                Logger.Message("Injecting pawn groups to our race settings");
                DefInjector.InjectPawnKindEntriesToRaceSettings();
            }
            else
            {
                Logger.Message("AlienRace not loaded; no race settings for us!");
            }
        }
        // ReSharper disable once UnusedParameter.Global
        public static MethodInfo TargetMethod(HarmonyInstance inst)
        {
            // get out target type
            gizmoGridType = GenTypes.GetTypeInAnyAssembly("InspectGizmoGrid");
            var method = AccessTools.Method(gizmoGridType, "DrawInspectGizmoGridFor");

            if (gizmoGridType != null)
            {
                const string expectedDesignatorFieldName = "des";
                // get the nested type that stores the reference to the current designator inside the iterator
                designatorReferencerType = gizmoGridType.GetNestedTypes(HugsLibUtility.AllBindingFlags).FirstOrDefault(t => AccessTools.Field(t, expectedDesignatorFieldName) != null);
                if (designatorReferencerType != null)
                {
                    // get the field that stores the current designator
                    holderDesignatorField = AccessTools.Field(designatorReferencerType, expectedDesignatorFieldName);
                }
            }
            commandGroupKeyField = AccessTools.Field(typeof(Command), "groupKey");
            LongEventHandler.ExecuteWhenFinished(() => {
                if (!patchApplied)
                {
                    AllowToolController.Instance.Logger.Warning("InspectGizmoGrid.DrawInspectGizmoGridFor patch failed. Reverse designator context menus are disabled.");
                }
            });
            // make sure we have all required references, fail patch otherwise
            if (method == null || designatorReferencerType == null || holderDesignatorField == null || commandGroupKeyField == null)
            {
                AllowToolController.Instance.Logger.Warning("Could not reflect a required type or field: " + Environment.StackTrace);
                return(null);
            }
            return(method);
        }
Exemple #8
0
        public static void Apply()
        {
            try {
                var workGiverType = GenTypes.GetTypeInAnyAssembly("PickUpAndHaul.WorkGiver_HaulToInventory");
                if (workGiverType == null)
                {
                    return;
                }
                if (!typeof(WorkGiver_HaulGeneral).IsAssignableFrom(workGiverType))
                {
                    throw new Exception("Expected work giver to extend " + nameof(WorkGiver_HaulGeneral));
                }
                if (workGiverType.GetConstructor(Type.EmptyTypes) == null)
                {
                    throw new Exception("Expected work giver to have parameterless constructor");
                }
                var haulWorkGiver = (WorkGiver_HaulGeneral)Activator.CreateInstance(workGiverType);

                WorkGiver_HaulUrgently.JobOnThingDelegate = (pawn, thing, forced) => {
                    if (haulWorkGiver.ShouldSkip(pawn, forced))
                    {
                        return(null);
                    }
                    return(haulWorkGiver.JobOnThing(pawn, thing, forced));
                };

                AllowToolController.Logger.Message("Applied compatibility patch for \"Pick Up And Haul\"");
            } catch (Exception e) {
                AllowToolController.Logger.ReportException(e, null, false, "Pick Up And Haul compatibility layer application");
            }
        }
        static HarmonyPatches()
        {
            #if DEBUG
            Harmony.DEBUG = true;
            #endif

            VFESecurity.harmonyInstance.PatchAll();

            // Anonymous types...
            var bestAttackTargetAnon = typeof(AttackTargetFinder).GetNestedTypes(BindingFlags.NonPublic | BindingFlags.Instance).
                                       Where(t => t.GetMembers(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).Any(m => m.Name.Contains("BestAttackTarget"))).
                                       MaxBy(t => t.GetMembers(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).Count());
            Patch_AttackTargetFinder.manual_BestAttackTarget.firstAnonymousType = bestAttackTargetAnon;
            VFESecurity.harmonyInstance.Patch(AccessTools.Method(typeof(AttackTargetFinder), nameof(AttackTargetFinder.BestAttackTarget)), transpiler: new HarmonyMethod(typeof(Patch_AttackTargetFinder.manual_BestAttackTarget), "Transpiler"));

            // Patch the InitAction for Toils_Combat.GoToCastPosition
            var initActionType = typeof(Toils_Combat).GetNestedTypes(BindingFlags.NonPublic | BindingFlags.Instance).
                                 First(t => t.GetMembers(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).Any(m => m.Name.Contains("GotoCastPosition")));
            VFESecurity.harmonyInstance.Patch(initActionType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).First(), transpiler: new HarmonyMethod(typeof(Patch_Toils_Combat.manual_GoToCastPosition_initAction), "Transpiler"));

            // Why, oh why does this class have to be internal?
            var sectionLayerSunShadows = GenTypes.GetTypeInAnyAssembly("Verse.SectionLayer_SunShadows", "Verse");
            VFESecurity.harmonyInstance.Patch(AccessTools.Method(sectionLayerSunShadows, "Regenerate"), transpiler: new HarmonyMethod(typeof(Patch_SectionLayer_SunShadows.manual_Regenerate), "Transpiler"));

            //VFESecurity.harmonyInstance.Patch(AccessTools.Method(typeof(JobGiver_Work), nameof(JobGiver_Work.TryIssueJobPackage)),
            //    prefix: new HarmonyMethod(typeof(HarmonyPatches),
            //    nameof(TestPrefix)),
            //    postfix: new HarmonyMethod(typeof(HarmonyPatches),
            //    nameof(TestPostfix)));
        }
Exemple #10
0
        public static void OnDefsLoaded()
        {
            const string doorsModName         = "Doors Expanded mod",
                         doorExpandedTypeName = "DoorsExpanded.Building_DoorExpanded",
                         openIntFieldName     = "openInt",
                         doorRemoteTypeName   = "DoorsExpanded.Building_DoorRemote",
                         curtainDoorDefName   = "HeronCurtainTribal",
                         jailDoorDefName      = "PH_DoorJail";
            var doorExpandedType = GenTypes.GetTypeInAnyAssembly(doorExpandedTypeName);

            if (doorExpandedType != null)
            {
                var logger = RemoteTechController.Instance.Logger;
                try {
                    if (!typeof(Building).IsAssignableFrom(doorExpandedType))
                    {
                        throw new Exception($"Expected {doorExpandedTypeName} to extend {typeof(Building).Name}");
                    }
                    var openIntField = doorExpandedType.GetField(openIntFieldName, BindingFlags.Instance | BindingFlags.NonPublic);
                    if (openIntField == null || openIntField.FieldType != typeof(bool))
                    {
                        throw new Exception($"Expected {doorExpandedTypeName} to have field {openIntFieldName}");
                    }
                    var doorRemoteType = GenTypes.GetTypeInAnyAssembly(doorRemoteTypeName);
                    if (doorRemoteType == null || !doorExpandedType.IsAssignableFrom(doorRemoteType))
                    {
                        throw new Exception($"Expected type {doorRemoteTypeName}, extending {doorExpandedTypeName}");
                    }

                    void LogDefWarning(string defName) => logger.Warning($"Expected to find def {defName} in {doorsModName}");

                    var curtainDoorDef = DefDatabase <ThingDef> .GetNamedSilentFail(curtainDoorDefName);

                    if (curtainDoorDef == null)
                    {
                        LogDefWarning(curtainDoorDefName);
                    }
                    var jailDoorDef = DefDatabase <ThingDef> .GetNamedSilentFail(jailDoorDefName);

                    if (jailDoorDef == null)
                    {
                        LogDefWarning(jailDoorDefName);
                    }

                    var isOpenGetter = CreateGetterForField(openIntField);

                    GasCloud.TraversibleBuildings.Add(doorExpandedType, (building, _) => {
                        var def = building.def;
                        return(def == curtainDoorDef || def == jailDoorDef || isOpenGetter(building));
                    });
                    GasCloud.TraversibleBuildings.Add(doorRemoteType,
                                                      (building, _) => isOpenGetter(building)
                                                      );

                    logger.Message($"Applied compatibility layer for {doorsModName}");
                } catch (Exception e) {
                    logger.Error($"Failed to apply compatibility layer for {doorsModName}: {e}");
                }
            }
        }
Exemple #11
0
 static RimCuisine2()
 {
     if (ModCompatibilityCheck.RimCuisine2BottlingAndBooze)
     {
         RCBBDefOf = GenTypes.GetTypeInAnyAssembly("RimCuisineBBDrugPolicies.RCBBDefOf", "RimCuisineBBDrugPolicies");
     }
 }
Exemple #12
0
        static HarmonyCompOversizedWeapon()
        {
            enabled_AlienRaces     = ModsConfig.ActiveModsInLoadOrder.Any((ModMetaData m) => m.PackageIdPlayerFacing == "erdelf.HumanoidAlienRaces");
            enabled_rooloDualWield = ModsConfig.ActiveModsInLoadOrder.Any((ModMetaData m) => m.PackageIdPlayerFacing == "Roolo.DualWield");

            var harmony = new Harmony("rimworld.Ogliss.comps.oversized");

            harmony.PatchAll(Assembly.GetExecutingAssembly());
            MethodInfo target = AccessTools.Method(GenTypes.GetTypeInAnyAssembly("DualWield.Harmony.PawnRenderer_DrawEquipmentAiming", "DualWield.Harmony"), "DrawEquipmentAimingOverride", null, null);

            if (target == null && enabled_rooloDualWield)
            {
                Log.Warning("Target: DualWield.Harmony.PawnRenderer_DrawEquipmentAiming.DrawEquipmentAimingOverride Not found");
            }
            MethodInfo patch = typeof(Harmony_PawnRenderer_DrawEquipmentAimingOverride_Transpiler).GetMethod("Transpiler");

            if (patch == null && enabled_rooloDualWield)
            {
                Log.Warning("Patch is null Harmony_PawnRenderer_DrawEquipmentAimingOverride_Transpiler.Transpiler");
            }
            if (target != null && patch != null && enabled_rooloDualWield)
            {
                if (harmony.Patch(target, null, null, new HarmonyMethod(patch)) == null)
                {
                    Log.Warning("OgsCompOversizedWeapon: DualWield Patch Failed to apply");
                }
            }
            harmony.Patch(AccessTools.Method(typeof(Thing), "get_DefaultGraphic"), null,
                          new HarmonyMethod(typeof(HarmonyCompOversizedWeapon), nameof(get_DefaultGraphic_PostFix)));
        }
Exemple #13
0
        static Main()
        {
            var harmony = new Harmony("com.ogliss.rimworld.mod.PerfectlyGenericItem");

            harmony.PatchAll(Assembly.GetExecutingAssembly());
            string modname = "Perfectly Generic Item: ";
            // Fluffys Stuff Floors compatability
            string     tname  = "StuffedFloors.Controller";
            string     nspace = "StuffedFloors";
            string     mname  = "GetStuffDefsFor";
            MethodInfo target = AccessTools.Method(GenTypes.GetTypeInAnyAssembly(tname, nspace), mname, new Type[] { typeof(StuffCategoryDef) }, null);

            if (target != null)
            {
                Type       t      = typeof(Main);
                string     pmname = "StuffedFloors_GetStuffDefsFor_Postfix";
                MethodInfo patch  = t.GetMethod(pmname);
                if (patch == null)
                {
                    Log.Warning("Patch is null " + t.Name.ToString() + "." + pmname);
                }
                else
                {
                    if (harmony.Patch(target, new HarmonyMethod(patch)) == null)
                    {
                        Log.Warning(modname + tname + " Patch Failed to apply");
                    }
                }
            }
        }
        private static void FactionControlFix()
        {
            try
            {
                var controller = GenTypes.GetTypeInAnyAssembly("FactionControl.Controller", "FactionControl");

                var fieldSeparation    = controller.GetField("minFactionSeparation", BindingFlags.Static | BindingFlags.Public);
                var fieldFactionSprawl = controller.GetField("maxFactionSprawl", BindingFlags.Static | BindingFlags.Public);
                var fieldPirateSprawl  = controller.GetField("pirateSprawl", BindingFlags.Static | BindingFlags.Public);

                // Check if not initialized
                if (((double)fieldSeparation.GetValue(null)).Equals(0))
                {
                    Log.Message($"Found Faction Control mod. Fixing its values to avoid problems.");
                    double tiles    = Math.Sqrt(Find.WorldGrid.TilesCount);
                    double factions = Math.Sqrt(Find.FactionManager.AllFactionsVisible.Count() - 1);
                    fieldSeparation.SetValue(null, tiles / (factions * 2));
                    var defaultFactionGrouping = 0.5; // use default; good enough for not breaking everything
                    fieldFactionSprawl.SetValue(null, tiles / (factions * defaultFactionGrouping));
                    fieldPirateSprawl.SetValue(null, tiles / (factions * defaultFactionGrouping));
                }
            }
            catch (Exception e)
            {
                Log.Warning($"Something went wrong when trying to initialize FactionControl.Controller:\n{e.Message}\n{e.StackTrace}");
            }
        }
        public bool Passes(object toCheck)
        {
            //Log.Message(toCheck.GetType().ToString());
            //Log.Message(Data.ToString());

            switch (Condition)
            {
                case _ConditionType.IsType:
                {
                    var dataType = Data as Type ?? Data.GetType();
                    return dataType.IsInstanceOfType(toCheck);
                }
                case _ConditionType.IsTypeStringMatch:
                    return toCheck.GetType().ToString() == (string)toCheck;
                case _ConditionType.ThingHasComp:
                {
                    if (toCheck is ThingWithComps t)
                    {
                        var dataType = Data is string typeName ? GenTypes.GetTypeInAnyAssembly(typeName) : Data as Type;
                        if (dataType != null)
                        {
                            var comps = t.AllComps;
                            for (int i = 0, count = comps.Count; i < count; i++)
                            {
                                if (dataType.IsAssignableFrom(comps[i].GetType()))
                                    return true;
                            }
                        }
                    }
                    return false;
                }
                default:
                    throw new ArgumentException("Unrecognized condition type " + Condition);
            }
        }
 protected override bool ApplyWorker(XmlDocument xml)
 {
     if (GenTypes.GetTypeInAnyAssembly("RT_Fuse.CompRTFuse") != null)
     {
         return(base.ApplyWorker(xml));
     }
     return(true);
 }
Exemple #17
0
        public static Type GetRWType(string typeName)
        {
            const string ns        = "RWLayout.alpha2";
            Type         valueType = GenTypes.GetTypeInAnyAssembly(typeName, ns);

            valueType ??= GenTypes.GetTypeInAnyAssembly($"{ns}.{typeName}", ns);
            return(valueType);
        }
Exemple #18
0
 static CE_Compat()
 {
     IsCEInstalled = ModLister.GetActiveModWithIdentifier("CETeam.CombatExtended") != null;
     if (IsCEInstalled)
     {
         AmmoDefType = GenTypes.GetTypeInAnyAssembly("CombatExtended.AmmoDef");
         method      = GenTypes.GetTypeInAnyAssembly("CombatExtended.AmmoUtility")?.GetMethod("GetProjectileReadout", BindingFlags.Public | BindingFlags.Static);
     }
 }
        static HarmonyPatches()
        {
            // Unlimited range
            int            range = 200;
            List <IntVec3> list  = new List <IntVec3>();

            for (int i = -range; i < range; i++)
            {
                for (int j = -range; j < range; j++)
                {
                    list.Add(new IntVec3(i, 0, j));
                }
            }
            list.Sort(delegate(IntVec3 A, IntVec3 B)
            {
                float num  = A.LengthHorizontalSquared;
                float num2 = B.LengthHorizontalSquared;
                if (num < num2)
                {
                    return(-1);
                }
                return((num != num2) ? 1 : 0);
            });

            GenRadial.RadialPattern = new IntVec3[list.Count];
            float[] radii = new float[list.Count];

            for (int k = 0; k < list.Count; k++)
            {
                GenRadial.RadialPattern[k] = list[k];
                radii[k] = list[k].LengthHorizontal;
            }
            AccessTools.Field(typeof(GenRadial), "RadialPatternRadii").SetValue(null, radii);

#if DEBUG
            Harmony.DEBUG = true;
#endif

            VFESecurity.harmonyInstance.PatchAll();

            // Anonymous types...
            var bestAttackTargetAnon = typeof(AttackTargetFinder).GetNestedTypes(BindingFlags.NonPublic | BindingFlags.Instance).
                                       Where(t => t.GetMembers(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).Any(m => m.Name.Contains("BestAttackTarget"))).
                                       MaxBy(t => t.GetMembers(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).Count());
            Patch_AttackTargetFinder.manual_BestAttackTarget.firstAnonymousType = bestAttackTargetAnon;
            VFESecurity.harmonyInstance.Patch(AccessTools.Method(typeof(AttackTargetFinder), nameof(AttackTargetFinder.BestAttackTarget)), transpiler: new HarmonyMethod(typeof(Patch_AttackTargetFinder.manual_BestAttackTarget), "Transpiler"));

            // Patch the InitAction for Toils_Combat.GoToCastPosition
            var initActionType = typeof(Toils_Combat).GetNestedTypes(BindingFlags.NonPublic | BindingFlags.Instance).
                                 First(t => t.GetMembers(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).Any(m => m.Name.Contains("GotoCastPosition")));
            VFESecurity.harmonyInstance.Patch(initActionType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).First(), transpiler: new HarmonyMethod(typeof(Patch_Toils_Combat.manual_GoToCastPosition_initAction), "Transpiler"));

            // Why, oh why does this class have to be internal?
            var sectionLayerSunShadows = GenTypes.GetTypeInAnyAssembly("Verse.SectionLayer_SunShadows", "Verse");
            VFESecurity.harmonyInstance.Patch(AccessTools.Method(sectionLayerSunShadows, "Regenerate"), transpiler: new HarmonyMethod(typeof(Patch_SectionLayer_SunShadows.manual_Regenerate), "Transpiler"));
        }
Exemple #20
0
 static HumanoidAlienRaces()
 {
     // Add types from humanoid alien races
     if (ModCompatibilityCheck.HumanoidAlienRaces)
     {
         ThingDef_AlienRace = GenTypes.GetTypeInAnyAssembly("AlienRace.ThingDef_AlienRace", "AlienRace");
         AlienSettings      = ThingDef_AlienRace.GetNestedType("AlienSettings", BindingFlags.Public | BindingFlags.Instance);
         HairSettings       = GenTypes.GetTypeInAnyAssembly("AlienRace.HairSettings", "AlienRace");
     }
 }
Exemple #21
0
            // Token: 0x06000043 RID: 67 RVA: 0x00002FE4 File Offset: 0x000011E4
            static RimCities()
            {
                bool rimCities = ModCompatibilityCheck.RimCities;

                if (rimCities)
                {
                    Type typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly("Cities.GenCity", "Cities");
                    NonPublicMethods.RimCities.GenCity_RandomCityFaction = (Func <Predicate <Faction>, Faction>)Delegate.CreateDelegate(typeof(Func <Predicate <Faction>, Faction>), AccessTools.Method(typeInAnyAssembly, "RandomCityFaction", null, null));
                }
            }
Exemple #22
0
            static RimCities()
            {
                if (ModCompatibilityCheck.RimCities)
                {
                    var genCity = GenTypes.GetTypeInAnyAssembly("Cities.GenCity", "Cities");

                    GenCity_RandomCityFaction = (Func <Predicate <Faction>, Faction>)
                                                Delegate.CreateDelegate(typeof(Func <Predicate <Faction>, Faction>), AccessTools.Method(genCity, "RandomCityFaction"));
                }
            }
Exemple #23
0
 public Type GetTypeIfEnabled()
 {
     if (IsEnabled())
     {
         return(GenTypes.GetTypeInAnyAssembly(typeName));
     }
     else
     {
         return(null);
     }
 }
Exemple #24
0
        public InfoCollector()
        {
            RelevantRooms = new Dictionary <Room, RoomInfo>();
            MaxStatCount  = 0;
            MaxStatSize   = 0;

            var envInspector = GenTypes.GetTypeInAnyAssembly("EnvironmentInspectDrawer");

            _roomLabelGetter =
                envInspector?.GetMethod("GetRoomRoleLabel", BindingFlags.Static | BindingFlags.NonPublic);
        }
Exemple #25
0
 private void ApplyDeterministicGenerationPatches()
 {
     DeterministicGenerationPatcher.InstrumentMethodForDeterministicGeneration(
         AccessTools.Method(GenTypes.GetTypeInAnyAssembly("Rimworld.BeachMaker"), "Init"),
         ((Action <Map>)DeterministicGenerationPatcher.DeterministicBeachSetup).Method, HarmonyInst);
     DeterministicGenerationPatcher.InstrumentMethodForDeterministicGeneration(
         AccessTools.Method(typeof(TerrainPatchMaker), "Init"),
         ((Action <Map>)DeterministicGenerationPatcher.DeterministicPatchesSetup).Method, HarmonyInst);
     DeterministicGenerationPatcher.InstrumentMethodForDeterministicGeneration(
         AccessTools.Method(typeof(GenStep_Terrain), "GenerateRiver"),
         ((Action <Map>)DeterministicGenerationPatcher.DeterministicRiverSetup).Method, HarmonyInst);
 }
        public static bool GetOrganRejectionSetting()
        {
            //only set rejectionEnabled to true if the mod loads successfully and we can retrieve the value from settings
            bool rejectionEnabled = false;

            var rbseModType = GenTypes.GetTypeInAnyAssembly("RBSE.Mod", "RBSE");

            if (rbseModType != null)
            {
                var rbseMod = LoadedModManager.GetMod(rbseModType);

                if (rbseMod != null)
                {
                    //The RBSE.Settings class is not available w/ public modifier. Use Reflection to get the Type
                    var rbseSettingsType = rbseModType.Assembly.GetType("RBSE.Settings");
                    if (rbseSettingsType != null)
                    {
                        var settings = typeof(Mod)?.GetMethod(nameof(Mod.GetSettings), Type.EmptyTypes)?.MakeGenericMethod(rbseSettingsType)?.Invoke(rbseMod, new object[0]);
                        if (settings != null)
                        {
                            var toggleActiveRejection = settings?.GetType()?.GetField("ToggleActiveRejection", AccessTools.all)?.GetValue(settings);
                            if (toggleActiveRejection != null)
                            {
                                QEEMod.TryLog("toggleActiveRejection value: " + toggleActiveRejection);
                                rejectionEnabled = (bool)toggleActiveRejection;
                            }
                            else
                            {
                                QEEMod.TryLog("Problem retrieving toggleActiveRejection ModSetting value from RBSE mod. Organ rejection hediff will not be added.");
                            }
                        }
                        else
                        {
                            QEEMod.TryLog("Error making generic GetSettings() method for RBSE compatibility. Organ rejection hediff will not be added.");
                        }
                    }
                    else
                    {
                        QEEMod.TryLog("RBSE class 'RBSE.Settings' not found. Organ rejection hediff will not be added.");
                    }
                }
                else
                {
                    QEEMod.TryLog("GetMod() returned null for RBSE. Organ rejection hediff will not be added.");
                }
            }
            else
            {
                QEEMod.TryLog("Class 'RBSE.Mod' not found. Organ rejection hediff will not be added.");
            }

            return(rejectionEnabled);
        }
 static ReflectedMethods()
 {
     // Convert DualWield.Ext_Pawn_EquipmentTracker.TryGetOffHandEquipment to a delegate
     if (ModCompatibilityCheck.DualWield)
     {
         TryGetOffHandEquipment = (FuncOut <Pawn_EquipmentTracker, ThingWithComps, bool>)Delegate.CreateDelegate(
             typeof(FuncOut <Pawn_EquipmentTracker, ThingWithComps, bool>),
             AccessTools.Method(
                 GenTypes.GetTypeInAnyAssembly("DualWield.Ext_Pawn_EquipmentTracker", "DualWield"),
                 "TryGetOffHandEquipment"));
     }
 }
        public static void SetupIfNeeded(Harmony harmony)
        {
            //TODO: Improve this finding logic?
            if (LoadedModManager.RunningModsListForReading.FirstOrDefault((ModContentPack mod) => mod.PackageIdPlayerFacing.Equals("Madeline.ModMismatchFormatter")) != null)
            {
                Log.Message("Compat patch with Better ModMismatch Window");

                MethodBase    funcBeginReading = GenTypes.GetTypeInAnyAssembly("Madeline.ModMismatchFormatter.MetaHeaderUtility").GetMethod("BeginReading");
                HarmonyMethod transpiler       = new HarmonyMethod(typeof(Compat_BetterModMismatchWindow).GetMethod("BeginReading_Transpiler"));

                harmony.Patch(funcBeginReading, null, null, transpiler, null);
            }
        }
        public static void PCCompat_IncludeCompToSave()
        {
            Type t_PawnCompRules = GenTypes.GetTypeInAnyAssembly("EdB.PrepareCarefully.DefaultPawnCompRules");

            try
            {
                if (t_PawnCompRules != null)
                {
                    EdB.PrepareCarefully.DefaultPawnCompRules.rulesForSaving.IncludeComp("ButterfishHairModdingPlus.HairColor2_Comp");
                }
            }
            catch (TypeLoadException) { }
        }
        void InitializeHelpSuport()
        {
            var type = GenTypes.GetTypeInAnyAssembly("HelpTab.IHelpDefView");

            if (type != null)
            {
                modHelp = DefDatabase <MainButtonDef> .GetNamed("ModHelp", false);

                helpWindow_JumpTo = type.GetMethod("JumpTo", new Type[] { typeof(Def) });

                helpTreeLoaded = true;
            }
        }