Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of ShopkeeperRules v0.1.0
plugins/ShopkeeperRules/ShopkeeperRules.dll
Decompiled 3 hours agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Runtime.Versioning; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using RepoMods.Shared; using TMPro; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("saya")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: AssemblyInformationalVersion("0.1.0")] [assembly: AssemblyProduct("ShopkeeperRules")] [assembly: AssemblyTitle("ShopkeeperRules")] [assembly: AssemblyVersion("0.1.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace RepoMods.Shared { internal sealed class RepoConfigLocalization { private sealed class ChoiceLabels(Translation[]? japanese, Translation[]? english) { internal Translation[]? Japanese { get; } = japanese; internal Translation[]? English { get; } = english; } [DataContract] internal sealed class Catalog { [DataMember(Name = "sections")] public Translation[]? Sections { get; set; } [DataMember(Name = "settings")] public Setting[] Settings { get; set; } = Array.Empty<Setting>(); [DataMember(Name = "toggle")] public Translation[]? Toggle { get; set; } } [DataContract] internal sealed class Setting { [DataMember(Name = "section")] public string Section { get; set; } = string.Empty; [DataMember(Name = "key")] public string Key { get; set; } = string.Empty; [DataMember(Name = "label")] public string? Label { get; set; } [DataMember(Name = "choices")] public Translation[]? Choices { get; set; } } [DataContract] internal sealed class Translation { [DataMember(Name = "key")] public string Key { get; set; } = string.Empty; [DataMember(Name = "label")] public string? Label { get; set; } } internal const string RepoConfigGuid = "nickklmao.repoconfig"; private const string MenuLibGuid = "nickklmao.menulib"; private static RepoConfigLocalization? _active; private readonly ConfigFile _config; private readonly ManualLogSource _log; private readonly Harmony _harmony; private readonly Catalog? _japanese; private readonly Catalog? _english; private readonly MethodInfo _createEntries; private readonly Func<string, string> _displayName; private readonly Func<string?> _localeCode; private readonly Type _rowType; private readonly Type _labelType; private readonly Type _sliderType; private readonly Type _toggleType; private readonly Dictionary<Type, FieldInfo> _settingLabels; private readonly FieldInfo _categoryLabel; private readonly FieldInfo _leftToggle; private readonly FieldInfo _rightToggle; private readonly FieldInfo _sliderValue; private readonly FieldInfo _sliderText; private readonly FieldInfo _maskedSliderText; private readonly PropertyInfo _sliderOptions; private readonly MethodInfo _updateSliderText; private readonly ConditionalWeakTable<Component, ChoiceLabels> _choices = new ConditionalWeakTable<Component, ChoiceLabels>(); private bool _failed; private RepoConfigLocalization(BaseUnityPlugin plugin, Catalog? japanese, Catalog? english, Assembly repoConfig, Assembly menuLib, Func<string?> localeCode) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown _config = plugin.Config; _log = Logger.CreateLogSource(plugin.Info.Metadata.Name + " REPOConfig"); _harmony = new Harmony(plugin.Info.Metadata.GUID + ".repoconfig-localization"); _japanese = japanese; _english = english; _localeCode = localeCode; Type type = repoConfig.GetType("REPOConfig.ConfigMenu", throwOnError: true); _createEntries = Method(type, "CreateModEntries", MenuType(menuLib, "REPOPopupPage"), typeof(ConfigEntryBase[])); _displayName = (Func<string, string>)Method(type, "FixNaming", typeof(string)).CreateDelegate(typeof(Func<string, string>)); _rowType = MenuType(menuLib, "REPOElement"); _labelType = MenuType(menuLib, "REPOLabel"); _sliderType = MenuType(menuLib, "REPOSlider"); _toggleType = MenuType(menuLib, "REPOToggle"); Type type2 = MenuType(menuLib, "REPOInputField"); _settingLabels = new Dictionary<Type, FieldInfo> { [_sliderType] = Field(_sliderType, "labelTMP"), [_toggleType] = Field(_toggleType, "labelTMP"), [type2] = Field(type2, "labelTMP") }; _categoryLabel = Field(_labelType, "labelTMP"); _leftToggle = Field(_toggleType, "leftButtonTMP"); _rightToggle = Field(_toggleType, "rightButtonTMP"); _sliderValue = Field(_sliderType, "value"); _sliderText = Field(_sliderType, "valueTMP"); _maskedSliderText = Field(_sliderType, "maskedValueTMP"); _sliderOptions = AccessTools.DeclaredProperty(_sliderType, "stringOptions") ?? throw new MissingMemberException(_sliderType.FullName, "stringOptions"); _updateSliderText = Method(_sliderType, "UpdateBarText"); } internal static void Start(BaseUnityPlugin plugin, Catalog? english = null) { if (!Chainloader.PluginInfos.TryGetValue("nickklmao.repoconfig", out var value) || !Chainloader.PluginInfos.TryGetValue("nickklmao.menulib", out var value2)) { return; } RepoConfigLocalization repoConfigLocalization = null; try { Type type = Type.GetType("UnityEngine.Localization.Settings.LocalizationSettings, Unity.Localization"); Catalog catalog = (((object)type == null) ? null : ReadJapaneseCatalog(plugin.Info.Location)); if (catalog != null || english != null) { repoConfigLocalization = new RepoConfigLocalization(plugin, catalog, english, ((object)value.Instance).GetType().Assembly, ((object)value2.Instance).GetType().Assembly, ((object)type == null) ? ((Func<string>)(() => (string?)null)) : CreateLocaleReader(type)); repoConfigLocalization._harmony.Patch((MethodBase)repoConfigLocalization._createEntries, (HarmonyMethod)null, Hook("AfterCreateEntries"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); if (HasChoices(catalog) || HasChoices(english)) { repoConfigLocalization._harmony.Patch((MethodBase)repoConfigLocalization._updateSliderText, (HarmonyMethod)null, Hook("AfterUpdateSliderText"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } _active = repoConfigLocalization; } } catch (Exception ex) { if (repoConfigLocalization != null) { repoConfigLocalization._harmony.UnpatchSelf(); } (repoConfigLocalization?._log ?? Logger.CreateLogSource(plugin.Info.Metadata.Name + " REPOConfig")).LogWarning((object)("Localization could not start (" + ex.GetType().Name + "); using REPOConfig defaults.")); } } private static Catalog? ReadJapaneseCatalog(string pluginPath) { string path = Path.ChangeExtension(pluginPath, ".repoconfig.ja.json"); if (!File.Exists(path)) { return null; } using FileStream stream = File.OpenRead(path); object result; if (new DataContractJsonSerializer(typeof(Catalog)).ReadObject(stream) is Catalog catalog) { Setting[] settings = catalog.Settings; if (settings != null && settings.Length > 0) { result = catalog; goto IL_004f; } } result = null; goto IL_004f; IL_004f: return (Catalog?)result; } private static bool HasChoices(Catalog? catalog) { return catalog?.Settings.Any(delegate(Setting setting) { Translation[] choices = setting.Choices; return choices != null && choices.Length > 0; }) ?? false; } internal static void Stop() { RepoConfigLocalization? active = _active; _active = null; if (active != null) { active._harmony.UnpatchSelf(); } } private static Func<string?> CreateLocaleReader(Type settings) { PropertyInfo selected = settings.GetProperty("SelectedLocale", BindingFlags.Static | BindingFlags.Public) ?? throw new MissingMemberException(settings.FullName, "SelectedLocale"); PropertyInfo identifier = selected.PropertyType.GetProperty("Identifier") ?? throw new MissingMemberException(selected.PropertyType.FullName, "Identifier"); PropertyInfo code = identifier.PropertyType.GetProperty("Code") ?? throw new MissingMemberException(identifier.PropertyType.FullName, "Code"); return delegate { object value = selected.GetValue(null); return (value == null) ? null : (code.GetValue(identifier.GetValue(value)) as string); }; } private static void AfterCreateEntries(Component __0, ConfigEntryBase[] __1) { RepoConfigLocalization active = _active; if (active == null || active._failed || __1.Length == 0 || __1[0].ConfigFile != active._config) { return; } try { string a = active._localeCode(); Catalog catalog = ((string.Equals(a, "ja-JP", StringComparison.OrdinalIgnoreCase) || string.Equals(a, "ja", StringComparison.OrdinalIgnoreCase)) ? active._japanese : null); if (catalog != null || active._english != null) { active.TranslatePage(__0, __1, catalog); } } catch (Exception ex) { active._failed = true; active._log.LogWarning((object)("Localization could not update the menu (" + ex.GetType().Name + ").")); } } private void TranslatePage(Component page, ConfigEntryBase[] entries, Catalog? japanese) { ILookup<string, IGrouping<string, ConfigEntryBase>> lookup = (from entry in entries group entry by entry.Definition.Section).ToLookup<IGrouping<string, ConfigEntryBase>, string>((IGrouping<string, ConfigEntryBase> section) => _displayName(section.Key), StringComparer.Ordinal); IGrouping<string, ConfigEntryBase> grouping = null; Component[] componentsInChildren = page.GetComponentsInChildren(_rowType, true); foreach (Component val in componentsInChildren) { Type type = ((object)val).GetType(); if (type == _labelType) { TMP_Text val2 = ReadText(_categoryLabel, val); if (val2 != null) { grouping = Unique(lookup[val2.text]); SetText(val2, FindLabel(japanese?.Sections, grouping?.Key) ?? FindLabel(_english?.Sections, grouping?.Key)); continue; } } if (grouping == null || !_settingLabels.TryGetValue(type, out FieldInfo value)) { continue; } TMP_Text label = ReadText(value, val); if (label == null) { continue; } ConfigEntryBase val3 = Unique(grouping.Where((ConfigEntryBase item) => _displayName(item.Definition.Key) == label.text)); if (val3 == null) { continue; } Setting setting = FindSetting(japanese, val3.Definition); Setting setting2 = FindSetting(_english, val3.Definition); SetText(label, setting?.Label ?? setting2?.Label); if (type == _toggleType) { Translation[] array = japanese?.Toggle; if (array != null) { TranslateToggle(val, _leftToggle, array); TranslateToggle(val, _rightToggle, array); } } if (!(type == _sliderType)) { continue; } Translation[] array2 = setting?.Choices; if (array2 == null || array2.Length <= 0) { array2 = setting2?.Choices; if (array2 == null || array2.Length <= 0) { continue; } } _choices.Add(val, new ChoiceLabels(setting?.Choices, setting2?.Choices)); _updateSliderText.Invoke(val, null); } } private static void TranslateToggle(Component row, FieldInfo field, Translation[] toggles) { TMP_Text val = ReadText(field, row); if (val != null) { SetText(val, FindLabel(toggles, val.text)); } } private static Setting? FindSetting(Catalog? catalog, ConfigDefinition definition) { return catalog?.Settings.FirstOrDefault((Setting item) => item.Section == definition.Section && item.Key == definition.Key); } private static void AfterUpdateSliderText(Component __instance) { RepoConfigLocalization active = _active; if (active != null && !active._failed && active._choices.TryGetValue(__instance, out ChoiceLabels value) && active._sliderOptions.GetValue(__instance) is string[] array && array.Length > 0) { int num = Convert.ToInt32((float)active._sliderValue.GetValue(__instance)); string key = ((num >= 0 && num < array.Length) ? array[num] : array[0]); string label = FindLabel(value.Japanese, key) ?? FindLabel(value.English, key); SetText(ReadText(active._sliderText, __instance), label); SetText(ReadText(active._maskedSliderText, __instance), label); } } private static T? Unique<T>(IEnumerable<T> matches) where T : class { using IEnumerator<T> enumerator = matches.GetEnumerator(); if (!enumerator.MoveNext()) { return null; } T current = enumerator.Current; return enumerator.MoveNext() ? null : current; } private static string? FindLabel(Translation[]? translations, string? key) { return translations?.FirstOrDefault((Translation translation) => translation.Key == key)?.Label; } private static TMP_Text? ReadText(FieldInfo field, Component row) { object? value = field.GetValue(row); return (TMP_Text?)((value is TMP_Text) ? value : null); } private static void SetText(TMP_Text? text, string? label) { if (text != null && !string.IsNullOrWhiteSpace(label)) { text.text = label; } } private static Type MenuType(Assembly assembly, string name) { return assembly.GetType("MenuLib.MonoBehaviors." + name, throwOnError: true); } private static MethodInfo Method(Type type, string name, params Type[] parameters) { return AccessTools.DeclaredMethod(type, name, parameters, (Type[])null) ?? throw new MissingMethodException(type.FullName, name); } private static FieldInfo Field(Type type, string name) { return AccessTools.DeclaredField(type, name) ?? throw new MissingFieldException(type.FullName, name); } private static HarmonyMethod Hook(string name) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown return new HarmonyMethod(typeof(RepoConfigLocalization), name, (Type[])null); } } } namespace ShopkeeperRules { internal static class AppraisalPatches { private static readonly FieldInfo Attempts = PatchTools.Field(typeof(ShopKeeper), "itemDiscountAttempts"); private static readonly MethodInfo ClampAttempts = AccessTools.DeclaredMethod(typeof(Mathf), "Clamp", new Type[3] { typeof(int), typeof(int), typeof(int) }, (Type[])null) ?? throw new MissingMethodException("Clamp"); internal static readonly Func<ShopKeeper, bool> IsInReaction = (Func<ShopKeeper, bool>)PatchTools.Method(typeof(ShopKeeper), "InItemReactionFlow").CreateDelegate(typeof(Func<ShopKeeper, bool>)); private static readonly MethodInfo RandomInt = AccessTools.DeclaredMethod(typeof(Random), "Range", new Type[2] { typeof(int), typeof(int) }, (Type[])null) ?? throw new MissingMethodException("Range"); internal static void Apply(Harmony harmony) { PatchTools.PatchKeeper(harmony, "ItemPresentationCanStart", Hook("CanPresent")); PatchTools.PatchKeeper(harmony, "ItemPresentationTargetValid", null, First("ReplaceAttemptLimit")); PatchTools.PatchKeeper(harmony, "ItemNoticeStart", null, First("ReplaceAttemptLimit"), Hook("AfterNoticeStart")); PatchTools.PatchKeeper(harmony, "TryStartItemDiscount", null, First("ReplaceAttemptLimit")); PatchTools.PatchKeeper(harmony, "ItemDenyPhysics", null, First("ReplaceAttemptLimit")); PatchTools.PatchKeeper(harmony, "UpdateStateRPC", null, First("ReplaceCounterClamp")); PatchTools.PatchKeeper(harmony, "ItemVerdictPositiveGet", null, First("ReplaceVerdictRoll")); PatchTools.PatchKeeper(harmony, "ItemMeleeAttackTrySetup", Hook("CanAttack")); PatchTools.PatchKeeper(harmony, "ItemDislikeAffectApply", Hook("CanDestroyItem")); PatchTools.PatchKeeper(harmony, "ItemDiscountApply", Hook("BeforeDiscount"), null, null, Hook("RestoreDiscount")); } private static void AfterNoticeStart(ShopKeeper __instance) { Plugin.CaptureAppraisal(__instance); } private static void BeforeDiscount(ShopKeeper __instance, ref Vector2 ___itemLikeDiscountRange, ref int ___itemLikeDiscountMinimumValue, out (Vector2? Range, int? Minimum) __state) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) __state = default((Vector2?, int?)); AppraisalRules appraisalRules = Plugin.AppraisalFor(__instance); if (appraisalRules != null) { if (appraisalRules.DiscountMinimumPercent != 50 || appraisalRules.DiscountMaximumPercent != 70) { __state.Range = ___itemLikeDiscountRange; ___itemLikeDiscountRange = new Vector2((float)appraisalRules.DiscountMinimumPercent / 100f, (float)appraisalRules.DiscountMaximumPercent / 100f); } if (appraisalRules.MinimumDiscountK != 5) { __state.Minimum = ___itemLikeDiscountMinimumValue; ___itemLikeDiscountMinimumValue = appraisalRules.MinimumDiscountK * 1000; } } } private static void RestoreDiscount(ref Vector2 ___itemLikeDiscountRange, ref int ___itemLikeDiscountMinimumValue, (Vector2? Range, int? Minimum) __state) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) var (val, _) = __state; if (val.HasValue) { Vector2 valueOrDefault = val.GetValueOrDefault(); ___itemLikeDiscountRange = valueOrDefault; } int? item = __state.Minimum; if (item.HasValue) { int valueOrDefault2 = item.GetValueOrDefault(); ___itemLikeDiscountMinimumValue = valueOrDefault2; } } private static HarmonyMethod Hook(string name) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown return new HarmonyMethod(typeof(AppraisalPatches), name, (Type[])null); } private static HarmonyMethod First(string name) { return PatchTools.BeforeOtherMods(typeof(AppraisalPatches), name); } private static MethodInfo Local(string name) { return PatchTools.Method(typeof(AppraisalPatches), name); } private static bool CanPresent(ShopKeeper __instance, ref bool __result) { AppraisalRules? appraisalRules = Plugin.AppraisalFor(__instance); if (appraisalRules == null || appraisalRules.Enabled) { return true; } __result = false; return false; } private static bool CanAttack(ShopKeeper __instance, ref bool __result) { AppraisalRules? appraisalRules = Plugin.AppraisalFor(__instance); if (appraisalRules == null || appraisalRules.AllowMelee) { return true; } __result = false; return false; } private static bool CanDestroyItem(ShopKeeper __instance) { return Plugin.AppraisalFor(__instance)?.AllowDestruction ?? true; } private static int AttemptLimit(ShopKeeper keeper) { return Plugin.AppraisalFor(keeper)?.Limit ?? 3; } private static IEnumerable<CodeInstruction> ReplaceAttemptLimit(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); bool flag = false; int num = 0; foreach (CodeInstruction instruction in instructions) { if (flag && PatchTools.LoadsThree(instruction)) { PatchTools.InsertWithLabels(list, instruction, new CodeInstruction(OpCodes.Ldarg_0, (object)null)); instruction.opcode = OpCodes.Call; instruction.operand = Local("AttemptLimit"); num++; } flag = instruction.opcode == OpCodes.Ldfld && object.Equals(instruction.operand, Attempts); list.Add(instruction); } PatchTools.RequireMatches(__originalMethod, num, 1); return list; } private static int CounterMaximum(ShopKeeper keeper) { if (Plugin.RulesFor(keeper) != null) { return 100; } return 3; } private static IEnumerable<CodeInstruction> ReplaceCounterClamp(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod) { //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(instructions); List<CodeInstruction> list2 = new List<CodeInstruction>(); int num = 0; for (int i = 0; i < list.Count; i++) { CodeInstruction val = list[i]; if (i + 2 < list.Count && PatchTools.LoadsThree(val) && list[i + 1].opcode == OpCodes.Call && object.Equals(list[i + 1].operand, ClampAttempts) && list[i + 2].opcode == OpCodes.Stfld && object.Equals(list[i + 2].operand, Attempts)) { PatchTools.InsertWithLabels(list2, val, new CodeInstruction(OpCodes.Ldarg_0, (object)null)); val.opcode = OpCodes.Call; val.operand = Local("CounterMaximum"); num++; } list2.Add(val); } PatchTools.RequireMatches(__originalMethod, num, 1); return list2; } private static int DrawVerdict(int minimum, int maximum, ShopKeeper keeper) { AppraisalRules appraisalRules = Plugin.AppraisalFor(keeper); if (appraisalRules == null) { return Random.Range(minimum, maximum); } if (appraisalRules.SuccessPercent == 0f) { return 1; } if (appraisalRules.SuccessPercent == 100f) { return 0; } return (!appraisalRules.Approves(Random.value)) ? 1 : 0; } private static IEnumerable<CodeInstruction> ReplaceVerdictRoll(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); int num = 0; foreach (CodeInstruction instruction in instructions) { if (instruction.opcode == OpCodes.Call && object.Equals(instruction.operand, RandomInt)) { PatchTools.InsertWithLabels(list, instruction, new CodeInstruction(OpCodes.Ldarg_0, (object)null)); instruction.operand = Local("DrawVerdict"); num++; } list.Add(instruction); } PatchTools.RequireMatches(__originalMethod, num, 1); return list; } } internal static class EnforcementPatches { private static readonly Dictionary<string, (Activity Activity, int Calls)> ActivityMethods = new Dictionary<string, (Activity, int)> { ["PlayerShotGun"] = (Activity.Gunfire, 1), ["PlayerLaserTick"] = (Activity.LaserFire, 1), ["PlayerActivatedExplosive"] = (Activity.Explosives, 1), ["PlayerActivatedMine"] = (Activity.Explosives, 1), ["PlayerExplosiveDetonated"] = (Activity.Explosives, 1), ["PlayerStaffCast"] = (Activity.StaffUse, 1), ["PlayerMeleeHitPhysObject"] = (Activity.MeleeOnObjects, 1), ["PlayerDriftingTick"] = (Activity.DriftAndRam, 1), ["PlayerVehicleImpactHitPlayer"] = (Activity.DriftAndRam, 2), ["PlayerPhysObjectHitPlayer"] = (Activity.ObjectHitsPlayer, 2), ["PlayerDamagedPlayer"] = (Activity.PlayerHits, 4), ["PlayerCarryThrust"] = (Activity.HeldPlayerStruggle, 2) }; private static readonly MethodInfo AddScore = PatchTools.Method(typeof(ShopKeeper), "AddRuckusScore"); private static readonly FieldInfo VanillaWarnings = PatchTools.Field(typeof(ShopKeeper), "angryScoreThresholds"); private static readonly MethodInfo GunfireNotification = PatchTools.Method(typeof(SemiFunc), "PlayerShopKeeperShotGunHost"); private static readonly MethodInfo ExplosionNotification = PatchTools.Method(typeof(SemiFunc), "PlayerShopKeeperExplosionDetonatedHost"); private static readonly Action<PlayerAvatar> NotifyGunfire = (Action<PlayerAvatar>)GunfireNotification.CreateDelegate(typeof(Action<PlayerAvatar>)); private static readonly Action<PlayerAvatar> NotifyExplosion = (Action<PlayerAvatar>)ExplosionNotification.CreateDelegate(typeof(Action<PlayerAvatar>)); internal static void Apply(Harmony harmony) { foreach (string key in ActivityMethods.Keys) { PatchTools.PatchKeeper(harmony, key, Hook("BeforeActivity"), First("ScaleActivityPoints")); } PatchTools.PatchKeeper(harmony, "AddRuckusScore", Hook("CanWarn"), First("ReplaceThresholds")); PatchTools.PatchKeeper(harmony, "CheckPendingRuckusActions", Hook("CanWarn"), First("ReplaceThresholds")); PatchTools.PatchKeeper(harmony, "ExcusePendingWarningsOnWake", null, First("ReplaceThresholds")); PatchTools.PatchKeeper(harmony, "ResolveRuckusPunishment", null, First("ReplaceThresholds")); PatchTools.PatchKeeper(harmony, "ResolveRuckusPunishmentFailed", null, First("ReplaceThresholds")); PatchTools.PatchKeeper(harmony, "WarnPlayer", Hook("CanWarn")); PatchTools.PatchKeeper(harmony, "TriggerAngryObservation", Hook("CanWarn")); PatchTools.PatchKeeper(harmony, "ShootAtPlayer", Hook("CanPunish")); harmony.Patch((MethodBase)PatchTools.Method(typeof(ItemGunLaser), "OnStateShootStart"), (HarmonyMethod)null, (HarmonyMethod)null, First("RouteLaserStart"), (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)PatchTools.Method(typeof(ItemCartLaser), "StateShooting"), (HarmonyMethod)null, (HarmonyMethod)null, First("RouteLaserStart"), (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)PatchTools.Method(typeof(SlowProjectile), "SlowProjectileNearPlayerRuckusCheck"), (HarmonyMethod)null, (HarmonyMethod)null, First("RouteStaffImpact"), (HarmonyMethod)null, (HarmonyMethod)null); } private static HarmonyMethod Hook(string name) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown return new HarmonyMethod(typeof(EnforcementPatches), name, (Type[])null); } private static HarmonyMethod First(string name) { return PatchTools.BeforeOtherMods(typeof(EnforcementPatches), name); } private static MethodInfo Local(string name) { return PatchTools.Method(typeof(EnforcementPatches), name); } private static bool BeforeActivity(ShopKeeper __instance, MethodBase __originalMethod) { return Plugin.RulesFor(__instance)?.Enforcement.AllowsActivity(ActivityMethods[__originalMethod.Name].Activity) ?? true; } private static bool CanWarn(ShopKeeper __instance) { return Plugin.RulesFor(__instance)?.Enforcement.AllowsWarnings ?? true; } private static bool CanPunish(ShopKeeper __instance) { return Plugin.RulesFor(__instance)?.Enforcement.AllowsPunishment ?? true; } private static float Scale(float score, ShopKeeper keeper, Activity activity) { return Plugin.RulesFor(keeper)?.Enforcement.Scale(activity, score) ?? score; } private static void NotifyLaserStart(PlayerAvatar player) { NotifyAlternateActivity(player, Activity.LaserFire, Activity.Gunfire, 100f, NotifyGunfire); } private static void NotifyStaffImpact(PlayerAvatar player) { NotifyAlternateActivity(player, Activity.StaffUse, Activity.Explosives, 200f, NotifyExplosion); } private static void NotifyAlternateActivity(PlayerAvatar player, Activity activity, Activity nativeActivity, float points, Action<PlayerAvatar> nativeNotification) { ShopKeeper instance = ShopKeeper.instance; EnforcementRules enforcementRules = Plugin.RulesFor(instance)?.Enforcement; if (enforcementRules == null || enforcementRules.Percent(activity) == enforcementRules.Percent(nativeActivity)) { nativeNotification(player); } else if (Object.op_Implicit((Object)(object)player) && enforcementRules.AllowsActivity(activity)) { AddScore.Invoke(instance, new object[2] { player, enforcementRules.Scale(activity, points) }); } } private static IEnumerable<CodeInstruction> RouteLaserStart(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod) { return RouteNotification(instructions, __originalMethod, GunfireNotification, Local("NotifyLaserStart")); } private static IEnumerable<CodeInstruction> RouteStaffImpact(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod) { return RouteNotification(instructions, __originalMethod, ExplosionNotification, Local("NotifyStaffImpact")); } private static IEnumerable<CodeInstruction> RouteNotification(IEnumerable<CodeInstruction> instructions, MethodBase original, MethodInfo nativeNotification, MethodInfo replacement) { int num = 0; List<CodeInstruction> list = new List<CodeInstruction>(); foreach (CodeInstruction instruction in instructions) { if (instruction.opcode == OpCodes.Call && object.Equals(instruction.operand, nativeNotification)) { instruction.operand = replacement; num++; } list.Add(instruction); } PatchTools.RequireMatches(original, num, 1); return list; } private static IEnumerable<CodeInstruction> ScaleActivityPoints(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod) { //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Expected O, but got Unknown //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Expected O, but got Unknown //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Expected O, but got Unknown (Activity Activity, int Calls) tuple = ActivityMethods[__originalMethod.Name]; Activity item = tuple.Activity; int item2 = tuple.Calls; List<CodeInstruction> list = new List<CodeInstruction>(); int num = 0; foreach (CodeInstruction instruction in instructions) { if ((instruction.opcode == OpCodes.Call || instruction.opcode == OpCodes.Callvirt) && object.Equals(instruction.operand, AddScore)) { PatchTools.InsertWithLabels(list, instruction, new CodeInstruction(OpCodes.Ldarg_0, (object)null)); list.Add(new CodeInstruction(OpCodes.Ldc_I4, (object)(int)item)); list.Add(new CodeInstruction(OpCodes.Call, (object)Local("Scale"))); num++; } list.Add(instruction); } PatchTools.RequireMatches(__originalMethod, num, item2); return list; } private static float[] WarningScores(ShopKeeper keeper) { return Plugin.RulesFor(keeper)?.Enforcement.WarningScores ?? ((float[])VanillaWarnings.GetValue(null)); } private static float PunishmentScore(ShopKeeper keeper) { return Plugin.RulesFor(keeper)?.Enforcement.EffectivePunishmentScore ?? 1000f; } private static float ScoreAfterPunishment(ShopKeeper keeper) { return Plugin.RulesFor(keeper)?.Enforcement.ScoreAfterPunishment ?? 800f; } private static float ScoreAfterMiss(ShopKeeper keeper) { return Plugin.RulesFor(keeper)?.Enforcement.ScoreAfterMiss ?? 950f; } private static IEnumerable<CodeInstruction> ReplaceThresholds(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod) { //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Expected O, but got Unknown string name = __originalMethod.Name; bool flag = ((name == "AddRuckusScore" || name == "CheckPendingRuckusActions") ? true : false); bool flag2 = flag; bool flag3 = flag2 || name == "ExcusePendingWarningsOnWake"; bool flag4 = flag2 || name == "ResolveRuckusPunishment"; bool flag5 = name == "ResolveRuckusPunishmentFailed"; int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; List<CodeInstruction> list = new List<CodeInstruction>(); foreach (CodeInstruction instruction in instructions) { string text = null; if (flag3 && instruction.opcode == OpCodes.Ldsfld && object.Equals(instruction.operand, VanillaWarnings)) { text = "WarningScores"; num++; } else if (instruction.opcode == OpCodes.Ldc_R4 && instruction.operand is float num5) { if (flag2 && num5 == 1000f) { text = "PunishmentScore"; num2++; } else if (flag4 && num5 == 800f) { text = "ScoreAfterPunishment"; num3++; } else if (flag5 && num5 == 950f) { text = "ScoreAfterMiss"; num4++; } } if (text != null) { PatchTools.InsertWithLabels(list, instruction, new CodeInstruction(OpCodes.Ldarg_0, (object)null)); instruction.opcode = OpCodes.Call; instruction.operand = Local(text); } list.Add(instruction); } PatchTools.RequireMatches(__originalMethod, num, flag2 ? 4 : (flag3 ? 2 : 0)); PatchTools.RequireMatches(__originalMethod, num2, flag2 ? 1 : 0); PatchTools.RequireMatches(__originalMethod, num3, flag4 ? 1 : 0); PatchTools.RequireMatches(__originalMethod, num4, flag5 ? 1 : 0); return list; } } internal static class EnglishSettings { internal static RepoConfigLocalization.Catalog Labels { get; } = new RepoConfigLocalization.Catalog { Sections = new RepoConfigLocalization.Translation[2] { new RepoConfigLocalization.Translation { Key = "Violations", Label = "Shop Violations" }, new RepoConfigLocalization.Translation { Key = "Discounts", Label = "Item Discounts" } }, Settings = new RepoConfigLocalization.Setting[23] { new RepoConfigLocalization.Setting { Section = "Violations", Key = "MaxResponse", Label = "Max Response", Choices = new RepoConfigLocalization.Translation[3] { new RepoConfigLocalization.Translation { Key = "WarnAndShoot", Label = "Warn and Shoot" }, new RepoConfigLocalization.Translation { Key = "WarnOnly", Label = "Warn Only" }, new RepoConfigLocalization.Translation { Key = "DoNothing", Label = "Do Nothing" } } }, new RepoConfigLocalization.Setting { Section = "Violations", Key = "GunfirePercent", Label = "Gunfire %" }, new RepoConfigLocalization.Setting { Section = "Violations", Key = "LaserFirePercent", Label = "Laser Fire %" }, new RepoConfigLocalization.Setting { Section = "Violations", Key = "ExplosivesPercent", Label = "Explosives %" }, new RepoConfigLocalization.Setting { Section = "Violations", Key = "StaffUsePercent", Label = "Staff Use %" }, new RepoConfigLocalization.Setting { Section = "Violations", Key = "MeleeOnObjectsPercent", Label = "Melee on Objects %" }, new RepoConfigLocalization.Setting { Section = "Violations", Key = "DriftAndRamPercent", Label = "Drift & Ram %" }, new RepoConfigLocalization.Setting { Section = "Violations", Key = "ObjectHitsPlayerPercent", Label = "Object Hits Player %" }, new RepoConfigLocalization.Setting { Section = "Violations", Key = "PlayerHitsPercent", Label = "Player Hits %" }, new RepoConfigLocalization.Setting { Section = "Violations", Key = "HeldPlayerStrugglePercent", Label = "Held Player Struggle %" }, new RepoConfigLocalization.Setting { Section = "Violations", Key = "WarnStage1At", Label = "Warn Stage 1 At" }, new RepoConfigLocalization.Setting { Section = "Violations", Key = "WarnStage2At", Label = "Warn Stage 2 At" }, new RepoConfigLocalization.Setting { Section = "Violations", Key = "WarnStage3At", Label = "Warn Stage 3 At" }, new RepoConfigLocalization.Setting { Section = "Violations", Key = "WarnStage4At", Label = "Warn Stage 4 At" }, new RepoConfigLocalization.Setting { Section = "Violations", Key = "KeeperShootsAt", Label = "Keeper Shoots At" }, new RepoConfigLocalization.Setting { Section = "Discounts", Key = "AllowDiscounts", Label = "Allow Discounts" }, new RepoConfigLocalization.Setting { Section = "Discounts", Key = "TriesPerShop", Label = "Tries per Shop" }, new RepoConfigLocalization.Setting { Section = "Discounts", Key = "SuccessChancePercent", Label = "Success Chance %" }, new RepoConfigLocalization.Setting { Section = "Discounts", Key = "MinDiscountPercent", Label = "Min Discount %" }, new RepoConfigLocalization.Setting { Section = "Discounts", Key = "MaxDiscountPercent", Label = "Max Discount %" }, new RepoConfigLocalization.Setting { Section = "Discounts", Key = "MinDiscountK", Label = "Min Discount $K" }, new RepoConfigLocalization.Setting { Section = "Discounts", Key = "RefusedWeapon", Label = "Refused Weapon", Choices = new RepoConfigLocalization.Translation[2] { new RepoConfigLocalization.Translation { Key = "MayAttack", Label = "May Attack" }, new RepoConfigLocalization.Translation { Key = "NoAttack", Label = "No Attack" } } }, new RepoConfigLocalization.Setting { Section = "Discounts", Key = "RefusedItem", Label = "Refused Item", Choices = new RepoConfigLocalization.Translation[2] { new RepoConfigLocalization.Translation { Key = "BreakLater", Label = "Break Later" }, new RepoConfigLocalization.Translation { Key = "NoBreak", Label = "No Break" } } } } }; } internal static class PatchTools { internal static MethodInfo Method(Type type, string name) { return AccessTools.DeclaredMethod(type, name, (Type[])null, (Type[])null) ?? throw new MissingMethodException(type.FullName, name); } internal static FieldInfo Field(Type type, string name) { return AccessTools.DeclaredField(type, name) ?? throw new MissingFieldException(type.FullName, name); } internal static void PatchKeeper(Harmony harmony, string name, HarmonyMethod? prefix = null, HarmonyMethod? transpiler = null, HarmonyMethod? postfix = null, HarmonyMethod? finalizer = null) { harmony.Patch((MethodBase)Method(typeof(ShopKeeper), name), prefix, postfix, transpiler, finalizer, (HarmonyMethod)null); } internal static HarmonyMethod BeforeOtherMods(Type type, string name) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown return new HarmonyMethod(type, name, (Type[])null) { priority = 800 }; } internal static void InsertWithLabels(List<CodeInstruction> output, CodeInstruction original, CodeInstruction first) { first.labels.AddRange(original.labels); original.labels.Clear(); first.blocks.AddRange(original.blocks); original.blocks.Clear(); output.Add(first); } internal static void RequireMatches(MethodBase method, int actual, int expected) { if (actual != expected) { throw new InvalidOperationException($"{method.DeclaringType?.Name}.{method.Name}: expected {expected} matching instructions, found {actual}."); } } internal static bool LoadsThree(CodeInstruction instruction) { if (!(instruction.opcode == OpCodes.Ldc_I4_3) && (!(instruction.opcode == OpCodes.Ldc_I4_S) || Convert.ToInt32(instruction.operand) != 3)) { if (instruction.opcode == OpCodes.Ldc_I4) { return object.Equals(instruction.operand, 3); } return false; } return true; } } [BepInPlugin("saya.ShopkeeperRules", "Shopkeeper Rules", "0.1.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public sealed class Plugin : BaseUnityPlugin { private sealed class ShopVisit { internal AppraisalRules? ActiveAppraisal; } public const string PluginGuid = "saya.ShopkeeperRules"; public const string PluginName = "Shopkeeper Rules"; public const string PluginVersion = "0.1.0"; private readonly Harmony _harmony = new Harmony("saya.ShopkeeperRules"); private readonly Harmony _violations = new Harmony("saya.ShopkeeperRules.violations"); private readonly Harmony _discounts = new Harmony("saya.ShopkeeperRules.discounts"); private readonly ConditionalWeakTable<ShopKeeper, ShopVisit> _visits = new ConditionalWeakTable<ShopKeeper, ShopVisit>(); private ShopSettings _settings; private static Plugin? _instance; private static bool IsHost { get { if (Object.op_Implicit((Object)(object)GameManager.instance)) { return SemiFunc.IsMasterClientOrSingleplayer(); } return false; } } private void Awake() { //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Expected O, but got Unknown ((Component)this).transform.SetParent((Transform)null); ((Object)((Component)this).gameObject).hideFlags = (HideFlags)61; Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject); _settings = new ShopSettings(((BaseUnityPlugin)this).Config); ((BaseUnityPlugin)this).Config.SettingChanged += OnSettingChanged; _instance = this; bool flag = false; bool flag2 = false; try { PatchTools.PatchKeeper(_harmony, "Start", new HarmonyMethod(typeof(Plugin), "BeginShop", (Type[])null)); flag = TryApply(_violations, EnforcementPatches.Apply, "Shop Violations"); flag2 = TryApply(_discounts, AppraisalPatches.Apply, "Item Discounts"); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("Shopkeeper Rules could not bind the shopkeeper game methods: " + ex.GetBaseException().Message)); } if (!flag && !flag2) { ((BaseUnityPlugin)this).Config.SettingChanged -= OnSettingChanged; _harmony.UnpatchSelf(); _instance = null; ((Behaviour)this).enabled = false; } else { SuccessPercentMenu.Apply(_harmony, ((BaseUnityPlugin)this).Logger); RepoConfigLocalization.Start((BaseUnityPlugin)(object)this, EnglishSettings.Labels); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Shopkeeper Rules 0.1.0 loaded. Settings can be changed during a shop visit."); } } private bool TryApply(Harmony harmony, Action<Harmony> apply, string category) { try { apply(harmony); return true; } catch (Exception ex) { harmony.UnpatchSelf(); ((BaseUnityPlugin)this).Logger.LogError((object)("The " + category + " settings have no effect. Another mod or a game update changed the game code they rely on: " + ex.GetBaseException().Message)); return false; } } internal static bool IsSuccessPercentEntry(ConfigEntry<float> entry) { return _instance?._settings.IsSuccessPercentEntry(entry) ?? false; } private ShopVisit? VisitFor(ShopKeeper? keeper) { if (!Object.op_Implicit((Object)(object)keeper) || !IsHost || !_visits.TryGetValue(keeper, out ShopVisit value)) { return null; } return value; } internal static ShopRules? RulesFor(ShopKeeper? keeper) { Plugin instance = _instance; if (instance?.VisitFor(keeper) == null) { return null; } return instance._settings.Current; } internal static AppraisalRules? AppraisalFor(ShopKeeper keeper) { Plugin instance = _instance; ShopVisit shopVisit = instance?.VisitFor(keeper); if (instance == null || shopVisit == null) { return null; } if (shopVisit.ActiveAppraisal != null && !AppraisalPatches.IsInReaction(keeper)) { shopVisit.ActiveAppraisal = null; } return shopVisit.ActiveAppraisal ?? instance._settings.Current.Appraisal; } internal static void CaptureAppraisal(ShopKeeper keeper) { Plugin instance = _instance; ShopVisit shopVisit = instance?.VisitFor(keeper); if (instance != null && shopVisit != null && AppraisalPatches.IsInReaction(keeper)) { ShopVisit shopVisit2 = shopVisit; if (shopVisit2.ActiveAppraisal == null) { shopVisit2.ActiveAppraisal = instance._settings.Current.Appraisal; } } } private static void BeginShop(ShopKeeper __instance) { Plugin instance = _instance; if (instance != null && IsHost && Object.op_Implicit((Object)(object)RunManager.instance) && SemiFunc.RunIsShop() && !instance._visits.TryGetValue(__instance, out ShopVisit _)) { instance._visits.Add(__instance, new ShopVisit()); } } private void OnSettingChanged(object sender, EventArgs args) { _settings.Invalidate(); } private void OnDestroy() { if (_instance == this) { ((BaseUnityPlugin)this).Config.SettingChanged -= OnSettingChanged; RepoConfigLocalization.Stop(); _violations.UnpatchSelf(); _discounts.UnpatchSelf(); _harmony.UnpatchSelf(); _instance = null; } } } internal enum ResponseLimit { WarnAndShoot, WarnOnly, DoNothing } internal enum Activity { Gunfire, LaserFire, Explosives, StaffUse, MeleeOnObjects, DriftAndRam, ObjectHitsPlayer, PlayerHits, HeldPlayerStruggle } internal sealed class EnforcementRules { private ResponseLimit Limit { get; } private int[] ActivityPercents { get; } internal float[] WarningScores { get; } internal float PunishmentScore { get; } internal bool AllowsWarnings => Limit != ResponseLimit.DoNothing; internal bool AllowsPunishment => Limit == ResponseLimit.WarnAndShoot; internal float EffectivePunishmentScore { get { if (!AllowsPunishment) { return float.PositiveInfinity; } return PunishmentScore; } } internal float ScoreAfterPunishment => Math.Max(0f, PunishmentScore - 200f); internal float ScoreAfterMiss => Math.Max(0f, PunishmentScore - 50f); internal EnforcementRules(ResponseLimit responseLimit, int[] activityPercents, int[] warnings, int punishmentScore) { Limit = responseLimit; ActivityPercents = activityPercents; WarningScores = Array.ConvertAll(warnings, (Converter<int, float>)((int score) => score)); Array.Sort(WarningScores); PunishmentScore = Math.Max(punishmentScore, WarningScores[WarningScores.Length - 1] + 1f); } internal int Percent(Activity activity) { return ActivityPercents[(int)activity]; } internal bool AllowsActivity(Activity activity) { if (AllowsWarnings) { return Percent(activity) > 0; } return false; } internal float Scale(Activity activity, float points) { return points * ((float)Percent(activity) / 100f); } } internal sealed class AppraisalRules { internal const float DefaultSuccessPercent = 33.3f; internal const int NativeAttemptLimit = 3; internal const int MaximumAttemptLimit = 100; internal const int NativeMinimumDiscountK = 5; internal const int MaximumMinimumDiscountK = 100; internal const int DollarsPerDiscountUnit = 1000; internal const int NativeDiscountMinimumPercent = 50; internal const int NativeDiscountMaximumPercent = 70; internal bool Enabled { get; } internal int Limit { get; } internal float SuccessPercent { get; } internal int DiscountMinimumPercent { get; } internal int DiscountMaximumPercent { get; } internal int MinimumDiscountK { get; } internal bool AllowMelee { get; } internal bool AllowDestruction { get; } public AppraisalRules(bool enabled, int limit, float successPercent, int discountMinimumPercent, int discountMaximumPercent, int minimumDiscountK, bool allowMelee, bool allowDestruction) { Enabled = enabled; Limit = limit; SuccessPercent = successPercent; DiscountMinimumPercent = Math.Min(discountMinimumPercent, discountMaximumPercent); DiscountMaximumPercent = Math.Max(discountMinimumPercent, discountMaximumPercent); MinimumDiscountK = minimumDiscountK; AllowMelee = allowMelee; AllowDestruction = allowDestruction; base..ctor(); } internal static float RoundSuccessPercent(float percent) { if (!float.IsNaN(percent)) { return MathF.Round(Math.Clamp(percent, 0f, 100f) * 10f, MidpointRounding.AwayFromZero) / 10f; } return 33.3f; } internal bool Approves(float roll) { if (SuccessPercent != 100f) { if (SuccessPercent > 0f) { return roll < SuccessPercent / 100f; } return false; } return true; } } internal sealed class ShopRules(EnforcementRules enforcement, AppraisalRules appraisal) { internal EnforcementRules Enforcement { get; } = enforcement; internal AppraisalRules Appraisal { get; } = appraisal; } internal enum MeleeRefusalAction { MayAttack, NoAttack } internal enum ItemRefusalAction { BreakLater, NoBreak } internal sealed class ShopSettings { private sealed class SuccessPercentRange : AcceptableValueRange<float> { public SuccessPercentRange() : base(0f, 100f) { } public override object Clamp(object value) { return AppraisalRules.RoundSuccessPercent((float)value); } } private const string Violations = "Violations"; private const string Discounts = "Discounts"; private readonly ConfigEntry<ResponseLimit> _response; private readonly ConfigEntry<int>[] _activities; private readonly ConfigEntry<int>[] _warningScores; private readonly ConfigEntry<int> _punishmentScore; private readonly ConfigEntry<bool> _appraisalEnabled; private readonly ConfigEntry<int> _attempts; private readonly ConfigEntry<float> _successRate; private readonly ConfigEntry<int> _lowDiscount; private readonly ConfigEntry<int> _highDiscount; private readonly ConfigEntry<int> _minimumDiscountK; private readonly ConfigEntry<MeleeRefusalAction> _melee; private readonly ConfigEntry<ItemRefusalAction> _destruction; private ShopRules? _current; internal ShopRules Current => _current ?? (_current = Snapshot()); internal ShopSettings(ConfigFile config) { //IL_0191: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Expected O, but got Unknown _response = config.Bind<ResponseLimit>("Violations", "MaxResponse", ResponseLimit.WarnAndShoot, "Strongest response to shop violations. Changes apply during the current shop visit."); _activities = new ConfigEntry<int>[Enum.GetValues(typeof(Activity)).Length]; foreach (Activity value in Enum.GetValues(typeof(Activity))) { _activities[(int)value] = Amount(config, "Violations", $"{value}Percent", 100, 0, 300, "Percent of the game's violation points for this action. At 0 the action is not counted as a violation."); } _warningScores = new ConfigEntry<int>[4]; for (int i = 0; i < _warningScores.Length; i++) { _warningScores[i] = Amount(config, "Violations", $"WarnStage{i + 1}At", (i + 1) * 200, 1, 10000, "Violation points at which the shopkeeper gives this warning. The four stages are used in increasing order."); } _punishmentScore = Amount(config, "Violations", "KeeperShootsAt", 1000, 1, 10001, "Violation points at which the shopkeeper shoots. A value at or below the last warning stage counts as 1 point above it."); _appraisalEnabled = config.Bind<bool>("Discounts", "AllowDiscounts", true, "Whether players can ask the shopkeeper for a discount. A request already underway keeps the settings it started with."); _attempts = Amount(config, "Discounts", "TriesPerShop", 3, 1, 100, "Discount tries shared by all players in one shop. Changing it keeps the tries already used."); _successRate = config.Bind<float>("Discounts", "SuccessChancePercent", 33.3f, new ConfigDescription("Chance that a discount try succeeds, in steps of 0.1.", (AcceptableValueBase)(object)new SuccessPercentRange(), new object[1] { "REPOConfigStep=0.1" })); _lowDiscount = Amount(config, "Discounts", "MinDiscountPercent", 50, 0, 100, "Lower end of the discount for an accepted item."); _highDiscount = Amount(config, "Discounts", "MaxDiscountPercent", 70, 0, 100, "Upper end of the discount for an accepted item."); _minimumDiscountK = Amount(config, "Discounts", "MinDiscountK", 5, 0, 100, "Smallest discount in thousands of dollars, limited to the item's price."); _melee = config.Bind<MeleeRefusalAction>("Discounts", "RefusedWeapon", MeleeRefusalAction.MayAttack, "Whether the shopkeeper may hit the player with a melee weapon it refused."); _destruction = config.Bind<ItemRefusalAction>("Discounts", "RefusedItem", ItemRefusalAction.BreakLater, "Whether a refused item breaks a little later."); } internal bool IsSuccessPercentEntry(ConfigEntry<float> entry) { return entry == _successRate; } private static ConfigEntry<int> Amount(ConfigFile config, string section, string key, int value, int minimum, int maximum, string description) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown return config.Bind<int>(section, key, value, new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueRange<int>(minimum, maximum), Array.Empty<object>())); } internal void Invalidate() { _current = null; } private ShopRules Snapshot() { return new ShopRules(new EnforcementRules(Enum.IsDefined(typeof(ResponseLimit), _response.Value) ? _response.Value : ResponseLimit.WarnAndShoot, Array.ConvertAll(_activities, (ConfigEntry<int> entry) => entry.Value), Array.ConvertAll(_warningScores, (ConfigEntry<int> entry) => entry.Value), _punishmentScore.Value), new AppraisalRules(_appraisalEnabled.Value, _attempts.Value, _successRate.Value, _lowDiscount.Value, _highDiscount.Value, _minimumDiscountK.Value, _melee.Value == MeleeRefusalAction.MayAttack, _destruction.Value == ItemRefusalAction.BreakLater)); } } internal static class SuccessPercentMenu { private static Type? _sliderType; private static PropertyInfo? _precision; private static MethodInfo? _updateBarText; internal static void Apply(Harmony harmony, ManualLogSource logger) { //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Expected O, but got Unknown if (!Chainloader.PluginInfos.TryGetValue("nickklmao.repoconfig", out var value) || !Chainloader.PluginInfos.TryGetValue("nickklmao.menulib", out var value2)) { return; } try { Type type = ((object)value.Instance).GetType().Assembly.GetType("REPOConfig.Strategies.FloatConfigEntryStrategy", throwOnError: true); _sliderType = ((object)value2.Instance).GetType().Assembly.GetType("MenuLib.MonoBehaviors.REPOSlider", throwOnError: true); _precision = AccessTools.DeclaredProperty(_sliderType, "precision") ?? throw new MissingMemberException(_sliderType.FullName, "precision"); _updateBarText = PatchTools.Method(_sliderType, "UpdateBarText"); harmony.Patch((MethodBase)PatchTools.Method(type, "Execute"), (HarmonyMethod)null, new HarmonyMethod(typeof(SuccessPercentMenu), "AfterSliderCreated", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception ex) { logger.LogWarning((object)("Could not set the success chance display precision: " + ex.GetBaseException().Message)); } } private static void AfterSliderCreated(ConfigEntry<float> __2, RectTransform __result) { if (Plugin.IsSuccessPercentEntry(__2) && Object.op_Implicit((Object)(object)__result)) { Component component = ((Component)__result).GetComponent(_sliderType); if (Object.op_Implicit((Object)(object)component)) { _precision.SetValue(component, 1); _updateBarText.Invoke(component, null); } } } } }