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}"); } } }
public RustConstantsWriter(GenTypes genTypes, IdentifierConverter idConverter, RustDocCommentWriter docWriter, DeprecatedWriter deprecatedWriter) { this.genTypes = genTypes; this.idConverter = idConverter; this.docWriter = docWriter; this.deprecatedWriter = deprecatedWriter; }
public InstrCreateGenImpl(GenTypes genTypes, IdentifierConverter idConverter, RustDocCommentWriter docWriter) { this.genTypes = genTypes; this.idConverter = idConverter; this.docWriter = docWriter; sb = new StringBuilder(); }
void ICreatedInstructions.OnCreatedInstructions(GenTypes genTypes, HashSet <EnumValue> filteredCodeValues) { var defs = genTypes.GetObject <InstructionDefs>(TypeIds.InstructionDefs).Defs; infos = defs.Select(a => a.Masm).ToArray(); filtered = true; }
EncoderFlagsEnum(GenTypes genTypes) { if ((uint)EncoderFlags.VvvvvShift + 5 > 32) { throw new InvalidOperationException(); } }
// 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); }
public override void Serialize(GenTypes genTypes, FileWriter writer, StringsTable stringsTable) { writer.WriteFileHeader(); writer.WriteLineNoIndent($"#if {define}"); writer.WriteLine($"namespace {@namespace} {{"); using (writer.Indent()) { writer.WriteLine("static partial class InstrInfos {"); using (writer.Indent()) { writer.WriteLineNoIndent($"#if {CSharpConstants.HasSpanDefine}"); writer.WriteLine("static System.ReadOnlySpan<byte> GetSerializedInstrInfos() =>"); writer.WriteLineNoIndent("#else"); writer.WriteLine("static byte[] GetSerializedInstrInfos() =>"); writer.WriteLineNoIndent("#endif"); using (writer.Indent()) { writer.WriteLine("new byte[] {"); using (writer.Indent()) SerializeTable(writer, stringsTable); writer.WriteLine("};"); } } writer.WriteLine("}"); } writer.WriteLine("}"); writer.WriteLineNoIndent("#endif"); }
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); } }
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))); } }
static HarmonyPatches() { //HarmonyInstance.DEBUG = true; RenameEverything.HarmonyInstance.PatchAll(); // RPG Style Inventory if (ModCompatibilityCheck.RPGStyleInventory) { // Apply the same transpiler used on ITab_Pawn_Gear.DrawThingRow to RPG_GearTab's DrawThingRow var rpgGearTab = GenTypes.GetTypeInAnyAssemblyNew("Sandy_Detailed_RPG_Inventory.Sandy_Detailed_RPG_GearTab", "Sandy_Detailed_RPG_Inventory"); if (rpgGearTab != null) { RenameEverything.HarmonyInstance.Patch(AccessTools.Method(rpgGearTab, "DrawThingRow"), transpiler: new HarmonyMethod(typeof(Patch_ITab_Pawn_Gear.Patch_DrawThingRow), "Transpiler")); } else { Log.Error("Could not find type Sandy_Detailed_RPG_Inventory.Sandy_Detailed_RPG_GearTab in RPG Style Inventory"); } } // Infused if (ModCompatibilityCheck.Infused) { var infusedThingLabelPatch = GenTypes.GetTypeInAnyAssemblyNew("Infused.GenMapUI_DrawThingLabel_Patch", "Infused"); if (infusedThingLabelPatch != null) { RenameEverything.HarmonyInstance.Patch(AccessTools.Method(infusedThingLabelPatch, "Postfix"), transpiler: new HarmonyMethod(typeof(Patch_Infused_GenMapUI_DrawThingLabel_Patch.ManualPatch_Postfix), "Transpiler")); } else { Log.Error("Could not find type Infused.GenMapUI_DrawThingLabel_Patch in Infused"); } } }
static VEF_ReflectionData() { if (VEF_ModCompatibilityCheck.enabled_rooloDualWield) { MB_TryGetOffHandEquipment = AccessTools.Method(type: GenTypes.GetTypeInAnyAssemblyNew("DualWield.Ext_Pawn_EquipmentTracker", "DualWield"), name: "TryGetOffHandEquipment"); } }
static MemorySizeDef[] CreateData(GenTypes genTypes) { var filename = Path.Combine(genTypes.Dirs.GeneratorDir, "Tables", "MemorySizeDefs.txt"); var reader = new MemorySizeDefsReader(genTypes, filename); return(reader.Read()); }
static MemorySizeDef[] CreateDefs(GenTypes genTypes) { var filename = genTypes.Dirs.GetGeneratorFilename("Tables", "MemorySizeDefs.txt"); var reader = new MemorySizeDefsReader(genTypes, filename); return(reader.Read()); }
static TupleTypeInfo[] CreateData(GenTypes genTypes) { var tupleType = genTypes[TypeIds.TupleType]; var result = new List <TupleTypeInfo> { new TupleTypeInfo(tupleType[nameof(TupleType.N1)], 1, 1), new TupleTypeInfo(tupleType[nameof(TupleType.N2)], 2, 2), new TupleTypeInfo(tupleType[nameof(TupleType.N4)], 4, 4), new TupleTypeInfo(tupleType[nameof(TupleType.N8)], 8, 8), new TupleTypeInfo(tupleType[nameof(TupleType.N16)], 16, 16), new TupleTypeInfo(tupleType[nameof(TupleType.N32)], 32, 32), new TupleTypeInfo(tupleType[nameof(TupleType.N64)], 64, 64), new TupleTypeInfo(tupleType[nameof(TupleType.N8b4)], 8, 4), new TupleTypeInfo(tupleType[nameof(TupleType.N16b4)], 16, 4), new TupleTypeInfo(tupleType[nameof(TupleType.N32b4)], 32, 4), new TupleTypeInfo(tupleType[nameof(TupleType.N64b4)], 64, 4), new TupleTypeInfo(tupleType[nameof(TupleType.N16b8)], 16, 8), new TupleTypeInfo(tupleType[nameof(TupleType.N32b8)], 32, 8), new TupleTypeInfo(tupleType[nameof(TupleType.N64b8)], 64, 8), }.ToArray(); if (result.Length != tupleType.Values.Length) { throw new InvalidOperationException(); } if (result.Select(a => a.Value).ToHashSet().Count != tupleType.Values.Length) { throw new InvalidOperationException(); } Array.Sort(result, (a, b) => a.Value.Value.CompareTo(b.Value.Value)); return(result); }
// 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); } }
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(); }
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"); } }
internal static void InitializeEnumCountTypes(GenTypes genTypes) { if (toEnumCountName.Count != 0 || toEnumCountNameInitd) { throw new InvalidOperationException(); } foreach (var enumType in genTypes.AllEnumTypes) { if (!enumType.IsPublic || enumType.IsFlags) { continue; } if (!VerifyPublicEnumValues(enumType)) { throw new InvalidOperationException($"All values 0..max (exclusive) must be valid enum values"); } var rawName = enumType.RawName; string enumCountName; if (rawName.Contains('_', StringComparison.Ordinal)) { enumCountName = rawName + "_" + "EnumCount"; } else { enumCountName = rawName + "EnumCount"; } toEnumCountName.Add(enumType.TypeId, enumCountName); } toEnumCountNameInitd = true; }
public static void Prefix() { Log.Message("Loading Screen Manager :: Call Static CCtors :: Start"); Manager.currentStage = LoadingStage.FinishUp; Manager.numStaticConstructorsToCall = GenTypes.AllTypesWithAttribute <StaticConstructorOnStartup>().Count(); }
static OpCodeOperandKindDef[] CreateDefs(GenTypes genTypes) { var filename = genTypes.Dirs.GetGeneratorFilename("Tables", "OpCodeOperandKindDefs.txt"); var reader = new OpCodeOperandKindDefsReader(genTypes, filename); return(reader.Read()); }
public static bool PreCallAll() { Log.Message("Static constructors? Oh, sit down, vanilla, I'll do it myself. Starting now, at " + DateTime.Now.ToLongTimeString(), true); _toRun = GenTypes.AllTypesWithAttribute <StaticConstructorOnStartup>().ToList(); BetterLoadingMain.LoadingScreen.StartCoroutine(StaticConstructAll()); Log.Message("[BetterLoading] Overriding LongEventHandler's toExecuteWhenFinished", true); var result = LongEventHandlerMirror.ToExecuteWhenFinished; Log.Message($"[BetterLoading] Got list of pending actions: {result}. Removing up to and including the static constructor call...", true); var staticCallIdx = result.FindIndex(i => i.Method.DeclaringType?.Name == "PlayDataLoader" && i.Method.Name.Contains("m__2")); Log.Message($"[BetterLoading] (Which is at index {staticCallIdx} of {result.Count})", true); result = result.Skip(staticCallIdx + 1).Take(int.MaxValue).ToList(); //Remove the static constructor call _queue = result; Log.Message($"[BetterLoading] Updating field in LEH to a new list of size {result.Count}...", true); LongEventHandlerMirror.ToExecuteWhenFinished = new List <Action>(); LongEventHandler.QueueLongEvent(WaitForStaticCtors, null, true, null); return(false); }
public static void AddComments(GenTypes genTypes, string unitTestDir) { var removed = genTypes.GetObject <HashSet <EnumValue> >(TypeIds.RemovedCodeValues).Select(a => a.RawName).ToHashSet(); var docs = new Dictionary <string, string>(StringComparer.Ordinal); bool checkedIt = false; const char sepChar = '|'; var defs = genTypes.GetObject <InstructionDefs>(TypeIds.InstructionDefs).Defs; var toInstrInfo = defs.ToDictionary(a => a.OpCodeInfo.Code.RawName, a => a.InstrInfo, StringComparer.Ordinal); var toOpCodeInfo = defs.ToDictionary(a => a.OpCodeInfo.Code.RawName, a => a.OpCodeInfo, StringComparer.Ordinal); var sb = new StringBuilder(); foreach (var line in File.ReadLines(Path.Combine(unitTestDir, "Encoder", "OpCodeInfos.txt"))) { if (line.Length == 0 || line[0] == '#') { continue; } var parts = line.Split(','); if (parts.Length != 8) { throw new InvalidOperationException("Invalid file"); } var name = parts[0].Trim(); if (removed.Contains(name)) { continue; } var opCodeStr = parts[5].Trim(); var instructionStr = parts[6].Trim(); if (name == "Add_rm8_r8") { // Verify that we read the correct columns, in case someone reorders them... if (opCodeStr != "00 /r" || instructionStr != $"ADD r/m8{sepChar} r8") { throw new InvalidOperationException("Wrong columns!"); } checkedIt = true; } instructionStr = instructionStr.Replace(sepChar, ','); var docStr = $"#(c:{instructionStr})##(p:)##(c:{opCodeStr})##(p:)##(c:{GetCpuid(toInstrInfo[name])})##(p:)##(c:{GetMode(sb, toOpCodeInfo[name])})#"; docs.Add(name, docStr); } if (!checkedIt) { throw new InvalidOperationException(); } foreach (var enumValue in genTypes[TypeIds.Code].Values) { if (!string.IsNullOrEmpty(enumValue.Documentation)) { continue; } if (!docs.TryGetValue(enumValue.RawName, out var doc)) { throw new InvalidOperationException($"Couldn't find enum {enumValue.RawName}"); } enumValue.Documentation = doc; } }
InstructionDefs(GenTypes genTypes) { var filename = Path.Combine(genTypes.Dirs.GeneratorDir, "Tables", "InstructionDefs.txt"); defs = new InstructionDefsReader(genTypes, filename).Read(); genTypes.AddObject(TypeIds.InstructionDefs, this); }
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"); } }
public static Dictionary <string, DefInfo> CollectDefInfos() { var dict = new Dictionary <string, DefInfo>(); int TypeHash(Type type) => GenText.StableStringHash(type.FullName); dict["ThingComp"] = GetDefInfo(Sync.thingCompTypes, TypeHash); dict["Designator"] = GetDefInfo(Sync.designatorTypes, TypeHash); dict["WorldObjectComp"] = GetDefInfo(Sync.worldObjectCompTypes, TypeHash); dict["IStoreSettingsParent"] = GetDefInfo(Sync.storageParents, TypeHash); dict["IPlantToGrowSettable"] = GetDefInfo(Sync.plantToGrowSettables, TypeHash); foreach (var defType in GenTypes.AllLeafSubclasses(typeof(Def))) { if (defType.Assembly != typeof(Game).Assembly) { continue; } if (IgnoredVanillaDefTypes.Contains(defType)) { continue; } var defs = GenDefDatabase.GetAllDefsInDatabaseForDef(defType); dict.Add(defType.Name, GetDefInfo(defs, d => GenText.StableStringHash(d.defName))); } return(dict); }
public override bool Prepare(Node node) { if (!base.Prepare(node)) { return(false); } var DebugLevel = node.DebugLevel; var DebugMessage = node.DebugMessage; var targets = Targets(node.inputPorts); FieldToStat = new Dictionary <FieldInfo, StatDef>(); StatDefOfFieldInfo = new List <FieldInfo>(); foreach (Type type in GenTypes.AllTypesWithAttribute <DefOf>()) { foreach (FieldInfo field in type.GetFields().Where(t => t.FieldType == typeof(StatDef))) { if (targets.GetData <StatDef>().FirstOrFallback(t => field.Name.Equals(t.defName)) is StatDef stat) { StatDefOfFieldInfo.Add(field); FieldToStat.Add(field, stat); } } } if (DebugLevel > 1) { DebugMessage.AppendLine($"Initialize stage: From [{defName}]: StatSearch method:\nFieldToStat:"); FieldToStat.Do(t => DebugMessage.AppendLine($"{t.Key} : {t.Value} [{t.Key.DeclaringType}]")); } return(true); }
static HarmonyPatches() { Harmony harmony = new Harmony("LongerCFloor.ProxyHeat"); CompTemperatureSource.gasCompType = AccessTools.TypeByName("GasNetwork.CompGasTrader"); if (CompTemperatureSource.gasCompType != null) { CompTemperatureSource.methodInfoGasOn = AccessTools.PropertyGetter(CompTemperatureSource.gasCompType, "GasOn"); } harmony.PatchAll(); if (ModLister.HasActiveModWithName("Brrr and Phew (Continued)")) { var prefix = AccessTools.Method(typeof(HarmonyPatches), nameof(HarmonyPatches.TryGiveJobPrefix)); var postfix = AccessTools.Method(typeof(HarmonyPatches), nameof(HarmonyPatches.TryGiveJobPostfix)); foreach (var type in GenTypes.AllSubclasses(typeof(ThinkNode_JobGiver))) { if (type.Namespace == "Brrr") { var method = AccessTools.Method(type, "TryGiveJob"); harmony.Patch(method, new HarmonyMethod(prefix), new HarmonyMethod(postfix)); } } var genNewRRJobMethod = AccessTools.Method("Brrr.BrrrGlobals:GenNewRRJob"); harmony.Patch(genNewRRJobMethod, new HarmonyMethod(typeof(HarmonyPatches), nameof(HarmonyPatches.GenNewRRJobPrefix))); var meth_JobGiver_Brrr_TryGiveJob = AccessTools.Method("Brrr.JobGiver_Brrr:TryGiveJob"); harmony.Patch(meth_JobGiver_Brrr_TryGiveJob, null, null, new HarmonyMethod(typeof(HarmonyPatches), nameof(HarmonyPatches.JobGiver_BrrrTranspiler))); var meth_JobGiver_Phew_TryGiveJob = AccessTools.Method("Brrr.JobGiver_Phew:TryGiveJob"); harmony.Patch(meth_JobGiver_Phew_TryGiveJob, null, null, new HarmonyMethod(typeof(HarmonyPatches), nameof(HarmonyPatches.JobGiver_PhewTranspiler))); } }
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!"); } }
static RegisterDef[] CreateData(GenTypes genTypes) { var filename = genTypes.Dirs.GetGeneratorFilename("Tables", "RegisterDefs.txt"); var reader = new RegisterDefsReader(genTypes, filename); return(reader.Read()); }
public static void FindSettingsDependentFields() { #if DEBUG Log.Message("Finding settings dependant fields"); #endif var traverses = new List <Traverse>(); var markedTypes = GenTypes.AllTypesWithAttribute <NVHasSettingsDependentFieldAttribute>(); foreach (var type in markedTypes) { var fields = AccessTools.GetDeclaredFields(type) .FindAll(fi => fi.HasAttribute <NVSettingsDependentFieldAttribute>()); #if DEBUG Log.Message($"Type: {type}"); #endif foreach (var info in fields) { var traverse = new Traverse(type); traverse = traverse.Field(info.Name); #if DEBUG Log.Message($"Field: {info.Name}"); #endif traverses.Add(traverse); } } SettingsDependentFieldTraverses = traverses; }