mirror of
https://github.com/soarqin/DSP_Mods.git
synced 2026-11-19 17:05:20 +08:00
feat(cheatenabler): add tech downgrade and make the tech modifiers upgradable
Rework `Unlock Tech with Key-Modifiers` into a full upgrade/downgrade feature, ported from the standalone TechTweaks plugin. - Holding Shift / Ctrl / Ctrl+Shift / Alt while clicking a tech adds 1 / 10 / 100 / all levels and unlocks the direct prerequisites, as before. - `Caps Lock` toggles a session downgrade mode; the same modifiers then subtract 1 / 10 / 100 levels or revert the tech to locked. Downgrading walks the dependent techs so no "prerequisite locked, dependent unlocked" state is left behind, and it reverts the upgrade values the tech had applied (`TechFuncRevert`), including the multiplicative, assignment and boolean `UnlockTechFunction` cases, so repeated up/down cycles do not drift. - Toggling downgrade mode reports itself like the other toggles: a realtime tip popup plus the critical warning banner. The banner now shows on its own instead of requiring `Build without condition` or `No collision` to be on, and outranks both in the shared priority chains. - The `?` button in the tech tree shows the full key reference, using the same title and text as the config panel's tip button. While the option is off, the button is absent and `Caps Lock` is inert, so the key cannot collide with other bindings. - The option keeps its original `General/UnlockTech` config entry, so existing configurations carry over. The old unlock-only handler in `Patches/GamePatch.cs` is replaced by `Patches/TechTweaksPatch.cs`, which follows the repository's mod feature lifecycle (per-frame input through the registry's `OnInputUpdate`).
This commit is contained in:
1 parent
6a292e0816
commit
6ced106901
19 files changed
+2072
-143
No files matched your search
@@ -28,6 +28,8 @@
|
||||
## Architecture
|
||||
|
||||
- UXAssist Dark Fog buy-out belt signals keep each item ID, per-Metaverse rate, localization key, and embedded icon path in one definition. Name embedded icon files after the current English item names and synchronize resource includes and loader paths when renaming them. Preserve the legacy signal and saved-stock order. Rates represent equivalent single-material value: a native bundle of 10 Silicon-based Neurons, 10 Negentropy Singularities, and 10 Matter Recombinators per Metaverse corresponds to 30 of any one selected material per Metaverse.
|
||||
- CheatEnabler's tech upgrade / downgrade feature lives under `Patches/Tech`; `TechTweaksPatch` owns the config (reusing `General/UnlockTech`), the `[ModFeature]` lifecycle, the `UITechTree` UI patches and the `UITechNode.OnPointerDown` transpiler, while the click decision, key-modifier decoding, downgrade recursion, UI and the per-function inverse of `GameHistoryData.UnlockTechFunction` stay in their own classes. Per-frame input goes through the registry's `OnInputUpdate`, so no separate `VFInput.OnUpdate` patch is added. `TechFuncRevert` must keep covering every `UnlockTechFunction` case: functions without a drift-free inverse are recomputed from the `Configs.freeMode` base values plus the levels still applied across all techs, never by replaying the whole tech tree, because a replay would re-apply the `func 30/31` station rescaling and the `func 5/38` package resize instead of restoring them.
|
||||
- CheatEnabler's custom critical-warning texts are a single string behind two gates, and every feature that wants one takes part in both priority chains: `WarningSystem_hasCriticalWarning_Transpiler` (an OR chain deciding whether the banner appears at all) and `WarningSystem_UpdateCriticalWarningText_Transpiler` (deciding which text it shows). Tech downgrade mode is first in both so it displays on its own, without either build toggle being on; previously the banner could only appear while `Build without condition` or `No collision` was enabled. Extend the chains instead of overwriting `criticalWarningTexts` from another patch.
|
||||
- `ModFeatureRegistry` discovers dependent-mod features during `Awake`; feature initialization is eager, while UXAssist alone drives the deferred start, input, update, and uninitialization lifecycle. Keep dispatchers internal and idempotent.
|
||||
- Apply config-controlled patches from their owning feature's `Start` and `SettingChanged` handlers. Shared lifecycle helpers must only manage always-on patches and must not override saved option states.
|
||||
- Proto-dependent features must tolerate calls before preload completes and retry via `UXAssist.Common.GameLogic.OnDataLoaded`. Mark changes applied only after capturing valid originals and successfully mutating the proto.
|
||||
|
||||
@@ -3,6 +3,14 @@
|
||||
|
||||
## Changlog
|
||||
|
||||
* 2.4.7
|
||||
* `Unlock Tech with Key-Modifiers` becomes `Quickly upgrade/downgrade tech with key-modifiers`.
|
||||
* Holding `Shift` / `Ctrl` / `Ctrl + Shift` / `Alt` while clicking a tech adds 1 / 10 / 100 / all levels; all direct prerequisites are unlocked as well.
|
||||
* `Caps Lock` toggles downgrade mode; the same modifiers then subtract 1 / 10 / 100 levels, or revert the tech to locked.
|
||||
* Downgrading reverts the tech's upgrade values as well, including multiplicative, assignment, and boolean tech functions, so repeated up/down cycles do not drift.
|
||||
* Toggling downgrade mode reports itself like the other toggles: a realtime tip popup plus a critical warning banner. The banner shows on its own, without requiring `Build without condition` or `No collision` to be on, and outranks both of them while they are.
|
||||
* The `?` button in the tech tree window shows the full upgrade and downgrade key reference, using the same title and text as the config panel's tip button.
|
||||
* While the option is off, neither the `?` button nor the `Caps Lock` toggle is active, so the key cannot collide with other bindings.
|
||||
* 2.4.6
|
||||
* `Architect mode`: Restore unlimited use of buildings, Logistics Bots, Logistics Drones, and Logistics Vessels, and increase the default displayed count from 100 to 999.
|
||||
* `Wind Turbines do global power coverage`: Fix a possible startup crash when enabled.
|
||||
@@ -196,6 +204,14 @@
|
||||
|
||||
## 更新日志
|
||||
|
||||
* 2.4.7
|
||||
* `使用组合键点击解锁科技` 改为 `使用组合键快速升降级科技`。
|
||||
* 按住 `Shift` / `Ctrl` / `Ctrl + Shift` / `Alt` 点击科技,分别提升 1 / 10 / 100 / 全部等级;所有直接前置科技也会被解锁。
|
||||
* `Caps Lock` 切换降级模式,开启后同样的组合键变为降低 1 / 10 / 100 等级,或将科技回退到未解锁。
|
||||
* 降级同时回退科技带来的升级数值,覆盖乘法型、赋值型和布尔型科技函数,因此反复升降级不会产生数值漂移。
|
||||
* 切换降级模式会像其它开关一样提示:实时弹窗 + 严重警告横幅。横幅可独立显示,不需要开启`无条件建造`或`无碰撞`;这两个开启时,降级模式的提示优先显示。
|
||||
* 科技树界面的 `?` 按钮显示完整的升降级组合键说明,标题与文本同 MOD 设置面板的提示按钮一致。
|
||||
* 关闭该选项时,科技界面不显示 `?` 按钮,`Caps Lock` 也不生效,避免与原版其它键位冲突。
|
||||
* 2.4.6
|
||||
* `建筑师模式`:修复建筑、配送运输机、物流运输机和星际物流运输船无法无限使用的问题,默认显示数量由 100 提高至 999。
|
||||
* `风力涡轮机供电覆盖全球`:修复启用后可能导致启动崩溃的问题。
|
||||
|
||||
@@ -23,8 +23,9 @@ public class CheatEnabler : BaseUnityPlugin
|
||||
GamePatch.DevShortcutsEnabled = Config.Bind("General", "DevShortcuts", false, "Enable DevMode shortcuts");
|
||||
GamePatch.AbnormalDisablerEnabled = Config.Bind("General", "DisableAbnormalChecks", false,
|
||||
"disable all abnormal checks");
|
||||
GamePatch.UnlockTechEnabled = Config.Bind("General", "UnlockTech", false,
|
||||
"Unlock clicked tech by holding key-modifilers(Shift/Alt/Ctrl)");
|
||||
TechTweaksPatch.Enabled = Config.Bind("General", "UnlockTech", false,
|
||||
"Unlock clicked tech by holding key-modifilers(Shift/Alt/Ctrl), and downgrade them by holding the " +
|
||||
"same modifiers while downgrade mode is on (toggle it with Caps Lock)");
|
||||
FactoryPatch.ImmediateEnabled = Config.Bind("Build", "ImmediateBuild", false,
|
||||
"Build immediately");
|
||||
FactoryPatch.ArchitectModeEnabled = Config.Bind("Build", "Architect", false,
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<BepInExPluginGuid>org.soardev.cheatenabler</BepInExPluginGuid>
|
||||
<Description>DSP MOD - CheatEnabler</Description>
|
||||
<Version>2.4.6</Version>
|
||||
<Version>2.4.7</Version>
|
||||
<PackageId>CheatEnabler</PackageId>
|
||||
<RootNamespace>CheatEnabler</RootNamespace>
|
||||
<PackHasChangelog>true</PackHasChangelog>
|
||||
|
||||
@@ -35,6 +35,29 @@ public static class Localization
|
||||
public const string DisableAbnormalChecks = "Disable Abnormal Checks";
|
||||
public const string Hotkey = "Hotkey";
|
||||
public const string UnlockTechWithKeyModifiers = "Unlock Tech with Key-Modifiers";
|
||||
public const string UnlockDowngradeTechWithKeyModifiers = "Quickly upgrade/downgrade tech with key-modifiers";
|
||||
public const string TechDowngradeModeOn = "Tech downgrade mode ON!";
|
||||
public const string TechDowngradeModeOff = "Tech downgrade mode OFF!";
|
||||
public const string TechDowngradeModeWarning = "!!Tech downgrade mode is ON!!";
|
||||
public const string TechModifierHelpBody = """
|
||||
Click a tech on the tree while holding:
|
||||
Shift: Tech level + 1
|
||||
Ctrl: Tech level + 10
|
||||
Ctrl + Shift: Tech level + 100
|
||||
Alt: Tech level to MAX
|
||||
|
||||
Note: all direct prerequisites will be unlocked as well.
|
||||
|
||||
Press Caps Lock to toggle Tech Downgrade Mode: the key-modifiers above then decrease tech levels and revert the corresponding upgrade values.
|
||||
Shift: Tech level - 1
|
||||
Ctrl: Tech level - 10
|
||||
Ctrl + Shift: Tech level - 100
|
||||
Alt: revert to locked (level 0)
|
||||
(Shift+Alt and Ctrl+Alt do nothing)
|
||||
|
||||
The features above come from the mod: CheatEnabler
|
||||
""";
|
||||
public const string PackageResizeSkippedOccupiedCells = "Package resize skipped: occupied cells would be removed";
|
||||
public const string DevShortcuts = "Dev Shortcuts";
|
||||
public const string DevShortcutsTips = "Dev Shortcuts Tips";
|
||||
public const string UnlockTechWithKeyModifiersTips = "Unlock Tech with Key-Modifiers Tips";
|
||||
@@ -145,6 +168,47 @@ public static class Localization
|
||||
I18N.Add(DisableAbnormalChecks, "Disable Abnormal Checks", "关闭数据异常检查");
|
||||
I18N.Add(Hotkey, "Hotkey", "快捷键");
|
||||
I18N.Add(UnlockTechWithKeyModifiers, "Unlock Tech with Key-Modifiers", "使用组合键点击解锁科技");
|
||||
I18N.Add(UnlockDowngradeTechWithKeyModifiers, "Quickly upgrade/downgrade tech with key-modifiers", "使用组合键快速升降级科技");
|
||||
I18N.Add(TechDowngradeModeOn, "Tech downgrade mode ON!", "科技降级模式已开启!");
|
||||
I18N.Add(TechDowngradeModeOff, "Tech downgrade mode OFF!", "科技降级模式已关闭!");
|
||||
I18N.Add(TechDowngradeModeWarning, "!!Tech downgrade mode is ON!!", "!!科技降级模式已开启!!");
|
||||
I18N.Add(TechModifierHelpBody, """
|
||||
Click a tech on the tree while holding:
|
||||
Shift: Tech level + 1
|
||||
Ctrl: Tech level + 10
|
||||
Ctrl + Shift: Tech level + 100
|
||||
Alt: Tech level to MAX
|
||||
|
||||
Note: all direct prerequisites will be unlocked as well.
|
||||
|
||||
Press Caps Lock to toggle Tech Downgrade Mode: the key-modifiers above then decrease tech levels and revert the corresponding upgrade values.
|
||||
Shift: Tech level - 1
|
||||
Ctrl: Tech level - 10
|
||||
Ctrl + Shift: Tech level - 100
|
||||
Alt: revert to locked (level 0)
|
||||
(Shift+Alt and Ctrl+Alt do nothing)
|
||||
|
||||
The features above come from the mod: CheatEnabler
|
||||
""", """
|
||||
按住以下组合键点击科技树:
|
||||
Shift:科技等级 +1
|
||||
Ctrl:科技等级 +10
|
||||
Ctrl + Shift:科技等级 +100
|
||||
Alt:科技等级升到最大
|
||||
|
||||
注意:所有直接前置科技也会被解锁。
|
||||
|
||||
按 Caps Lock 开启/关闭科技降级模式:开启后上述组合键变为降低科技等级,并回退对应升级数值。
|
||||
Shift:科技等级 -1
|
||||
Ctrl:科技等级 -10
|
||||
Ctrl + Shift:科技等级 -100
|
||||
Alt:直接回退到未解锁(0 级,锁定)
|
||||
(Shift+Alt 与 Ctrl+Alt 无效果)
|
||||
|
||||
以上功能来源于MOD:CheatEnabler
|
||||
""");
|
||||
I18N.Add(PackageResizeSkippedOccupiedCells, "Package resize skipped: occupied cells would be removed",
|
||||
"背包扩容回退已跳过:有物品的格子会被移除,未缩小背包");
|
||||
I18N.Add(DevShortcuts, "Dev Shortcuts", "开发模式快捷键");
|
||||
I18N.Add(DevShortcutsTips, """
|
||||
Caution: Some function may trigger abnormal check!
|
||||
|
||||
@@ -209,22 +209,32 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
|
||||
[HarmonyPatch(typeof(WarningSystem), nameof(WarningSystem.hasCriticalWarning), MethodType.Getter)]
|
||||
private static IEnumerable<CodeInstruction> WarningSystem_hasCriticalWarning_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
// The original body is `criticalWarnings.Count > 0`. The chain appended here ORs the feature
|
||||
// switches on top of it, in display priority order: whichever one matches first owns the banner,
|
||||
// because UpdateCriticalWarningText bails out before assigning any custom text when this getter is
|
||||
// false. Tech downgrade mode therefore has to come first: it must show on its own, without either
|
||||
// build toggle being on.
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
var label1 = generator.DefineLabel();
|
||||
var label2 = generator.DefineLabel();
|
||||
var downgrade = generator.DefineLabel();
|
||||
var noCondition = generator.DefineLabel();
|
||||
var noCollision = generator.DefineLabel();
|
||||
matcher.End().MatchBack(false,
|
||||
new CodeMatch(OpCodes.Ret)
|
||||
).RemoveInstructions(1);
|
||||
matcher.InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Brfalse, label1),
|
||||
new CodeInstruction(OpCodes.Brfalse, downgrade),
|
||||
new CodeInstruction(OpCodes.Ldc_I4_1),
|
||||
new CodeInstruction(OpCodes.Ret),
|
||||
new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(FactoryPatch), nameof(NoConditionEnabled))).WithLabels(label1),
|
||||
new CodeInstruction(OpCodes.Call, AccessTools.PropertyGetter(typeof(Tech.DowngradeMode), nameof(Tech.DowngradeMode.IsOn))).WithLabels(downgrade),
|
||||
new CodeInstruction(OpCodes.Brfalse, noCondition),
|
||||
new CodeInstruction(OpCodes.Ldc_I4_1),
|
||||
new CodeInstruction(OpCodes.Ret),
|
||||
new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(FactoryPatch), nameof(NoConditionEnabled))).WithLabels(noCondition),
|
||||
new CodeInstruction(OpCodes.Call, AccessTools.PropertyGetter(typeof(ConfigEntry<bool>), nameof(ConfigEntry<bool>.Value))),
|
||||
new CodeInstruction(OpCodes.Brfalse, label2),
|
||||
new CodeInstruction(OpCodes.Brfalse, noCollision),
|
||||
new CodeInstruction(OpCodes.Ldc_I4_1),
|
||||
new CodeInstruction(OpCodes.Ret),
|
||||
new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(FactoryPatch), nameof(NoCollisionEnabled))).WithLabels(label2),
|
||||
new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(FactoryPatch), nameof(NoCollisionEnabled))).WithLabels(noCollision),
|
||||
new CodeInstruction(OpCodes.Call, AccessTools.PropertyGetter(typeof(ConfigEntry<bool>), nameof(ConfigEntry<bool>.Value))),
|
||||
new CodeInstruction(OpCodes.Ret)
|
||||
);
|
||||
@@ -250,7 +260,14 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
|
||||
new CodeInstruction(OpCodes.Ldarg_0),
|
||||
Transpilers.EmitDelegate((WarningSystem w) =>
|
||||
{
|
||||
if (NoConditionEnabled.Value)
|
||||
// Only one of these can own the banner, so they form a display priority chain:
|
||||
// tech downgrade mode (a transient state the player has to notice) outranks the
|
||||
// two build toggles the player turned on deliberately.
|
||||
if (Tech.DowngradeMode.IsOn)
|
||||
{
|
||||
w.criticalWarningTexts = Localization.TechDowngradeModeWarning.Translate() + "\r\n";
|
||||
}
|
||||
else if (NoConditionEnabled.Value)
|
||||
{
|
||||
w.criticalWarningTexts = Localization.BuildWithoutConditionIsEnabled.Translate() + "\r\n";
|
||||
}
|
||||
|
||||
@@ -15,13 +15,11 @@ public static class GamePatch
|
||||
{
|
||||
public static ConfigEntry<bool> DevShortcutsEnabled;
|
||||
public static ConfigEntry<bool> AbnormalDisablerEnabled;
|
||||
public static ConfigEntry<bool> UnlockTechEnabled;
|
||||
|
||||
public static void Init()
|
||||
{
|
||||
DevShortcutsEnabled.SettingChanged += (_, _) => DevShortcuts.Enable(DevShortcutsEnabled.Value);
|
||||
AbnormalDisablerEnabled.SettingChanged += (_, _) => AbnormalDisabler.Enable(AbnormalDisablerEnabled.Value);
|
||||
UnlockTechEnabled.SettingChanged += (_, _) => UnlockTech.Enable(UnlockTechEnabled.Value);
|
||||
GameLogicProc.OnGameEnd += ResetState;
|
||||
}
|
||||
|
||||
@@ -29,13 +27,11 @@ public static class GamePatch
|
||||
{
|
||||
DevShortcuts.Enable(DevShortcutsEnabled.Value);
|
||||
AbnormalDisabler.Enable(AbnormalDisablerEnabled.Value);
|
||||
UnlockTech.Enable(UnlockTechEnabled.Value);
|
||||
}
|
||||
|
||||
public static void Uninit()
|
||||
{
|
||||
GameLogicProc.OnGameEnd -= ResetState;
|
||||
UnlockTech.Enable(false);
|
||||
AbnormalDisabler.Enable(false);
|
||||
DevShortcuts.Enable(false);
|
||||
}
|
||||
@@ -213,127 +209,4 @@ public static class GamePatch
|
||||
}
|
||||
}
|
||||
|
||||
public class UnlockTech : PatchImpl<UnlockTech>
|
||||
{
|
||||
private static void UnlockTechRecursive(GameHistoryData history, [NotNull] TechProto techProto, int maxLevel = 10000)
|
||||
{
|
||||
var techStates = history.techStates;
|
||||
var techID = techProto.ID;
|
||||
if (techStates == null || !techStates.TryGetValue(techID, out var value))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (value.unlocked)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var maxLvl = Math.Min(maxLevel < 0 ? value.curLevel - maxLevel - 1 : maxLevel, value.maxLevel);
|
||||
|
||||
foreach (var preid in techProto.PreTechs)
|
||||
{
|
||||
var preProto = LDB.techs.Select(preid);
|
||||
if (preProto != null)
|
||||
UnlockTechRecursive(history, preProto, techProto.PreTechsMax ? 10000 : -1);
|
||||
}
|
||||
|
||||
foreach (var preid in techProto.PreTechsImplicit)
|
||||
{
|
||||
var preProto = LDB.techs.Select(preid);
|
||||
if (preProto != null)
|
||||
UnlockTechRecursive(history, preProto, techProto.PreTechsMax ? 10000 : -1);
|
||||
}
|
||||
|
||||
if (value.curLevel < techProto.Level) value.curLevel = techProto.Level;
|
||||
while (value.curLevel <= maxLvl)
|
||||
{
|
||||
if (value.curLevel == 0)
|
||||
{
|
||||
foreach (var recipe in techProto.UnlockRecipes)
|
||||
{
|
||||
history.UnlockRecipe(recipe);
|
||||
}
|
||||
}
|
||||
|
||||
for (var j = 0; j < techProto.UnlockFunctions.Length; j++)
|
||||
{
|
||||
history.UnlockTechFunction(techProto.UnlockFunctions[j], techProto.UnlockValues[j], value.curLevel);
|
||||
}
|
||||
|
||||
for (var k = 0; k < techProto.AddItems.Length; k++)
|
||||
{
|
||||
history.GainTechAwards(techProto.AddItems[k], techProto.AddItemCounts[k]);
|
||||
}
|
||||
|
||||
value.curLevel++;
|
||||
}
|
||||
|
||||
value.unlocked = maxLvl >= value.maxLevel;
|
||||
value.curLevel = value.unlocked ? maxLvl : maxLvl + 1;
|
||||
value.hashNeeded = techProto.GetHashNeeded(value.curLevel);
|
||||
value.hashUploaded = value.unlocked ? value.hashNeeded : 0;
|
||||
techStates[techID] = value;
|
||||
history.RegFeatureKey(1000100);
|
||||
history.NotifyTechUnlock(techID, maxLvl, true);
|
||||
}
|
||||
|
||||
private static void OnClickTech(UITechNode node)
|
||||
{
|
||||
var history = GameMain.history;
|
||||
if (VFInput.shift)
|
||||
{
|
||||
if (VFInput.alt) return;
|
||||
if (VFInput.control)
|
||||
UnlockTechRecursive(history, node.techProto, -100);
|
||||
else
|
||||
UnlockTechRecursive(history, node.techProto, -1);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (VFInput.control)
|
||||
{
|
||||
if (!VFInput.alt)
|
||||
UnlockTechRecursive(history, node.techProto, -10);
|
||||
else
|
||||
return;
|
||||
}
|
||||
else if (VFInput.alt)
|
||||
{
|
||||
UnlockTechRecursive(history, node.techProto);
|
||||
}
|
||||
else
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
history.VerifyTechQueue();
|
||||
if (history.currentTech != history.techQueue[0])
|
||||
{
|
||||
history.currentTech = history.techQueue[0];
|
||||
}
|
||||
}
|
||||
// Harmony transpiler: UITechNode_OnPointerDown_Transpiler
|
||||
// Target: UITechNode.OnPointerDown
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(UITechNode), nameof(UITechNode.OnPointerDown))]
|
||||
private static IEnumerable<CodeInstruction> UITechNode_OnPointerDown_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldarg_0),
|
||||
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(UITechNode), nameof(UITechNode.tree))),
|
||||
new CodeMatch(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(UITechTree), nameof(UITechTree.selected)))
|
||||
);
|
||||
var labels = matcher.Labels;
|
||||
matcher.Labels = null;
|
||||
matcher.Insert(
|
||||
new CodeInstruction(OpCodes.Ldarg_0).WithLabels(labels),
|
||||
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(UnlockTech), nameof(UnlockTech.OnClickTech)))
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace CheatEnabler.Patches.Tech;
|
||||
|
||||
/// <summary>
|
||||
/// Session level downgrade mode, toggled with <c>Caps Lock</c>.
|
||||
///
|
||||
/// The flag is intentionally not persisted: it is a per-session switch, so a game restart always comes
|
||||
/// back in the normal (upgrade) mode. The click handler reads <see cref="IsOn"/> at click time, so
|
||||
/// whatever the mode is at that moment wins.
|
||||
///
|
||||
/// Toggling reports itself exactly like the other CheatEnabler toggles (no condition build / no
|
||||
/// collision) do: a realtime tip ahead popup, plus an entry in the critical warning banner. The banner
|
||||
/// entry outranks the other two so the mode cannot be missed while they are on as well.
|
||||
/// </summary>
|
||||
internal static class DowngradeMode
|
||||
{
|
||||
public static bool IsOn { get; private set; }
|
||||
|
||||
/// <summary>Per-frame <c>Caps Lock</c> poll; driven by the mod feature registry input hook.</summary>
|
||||
public static void Update()
|
||||
{
|
||||
if (TechTweaksPatch.Enabled == null || !TechTweaksPatch.Enabled.Value)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (Input.GetKeyDown(KeyCode.CapsLock))
|
||||
{
|
||||
Toggle();
|
||||
}
|
||||
}
|
||||
|
||||
public static void Toggle()
|
||||
{
|
||||
IsOn = !IsOn;
|
||||
|
||||
if (!DSPGame.IsMenuDemo && GameMain.isRunning)
|
||||
{
|
||||
UIRoot.instance.uiGame.generalTips.InvokeRealtimeTipAhead(
|
||||
(IsOn ? Localization.TechDowngradeModeOn : Localization.TechDowngradeModeOff).Translate());
|
||||
GameMain.data?.warningSystem?.UpdateCriticalWarningText();
|
||||
}
|
||||
}
|
||||
|
||||
public static void Reset()
|
||||
{
|
||||
IsOn = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using System;
|
||||
|
||||
namespace CheatEnabler.Patches.Tech;
|
||||
|
||||
/// <summary>
|
||||
/// Entry point injected into <c>UITechNode.OnPointerDown</c>. Decides between "do nothing", "hand over
|
||||
/// to the built-in UnlockTech feature", "upgrade" and "downgrade".
|
||||
/// </summary>
|
||||
internal static class TechClickHandler
|
||||
{
|
||||
public static void OnClickTech(UITechNode node)
|
||||
{
|
||||
// The handler runs inside the game's own click path, so nothing may escape from here and break
|
||||
// the tech tree UI.
|
||||
try
|
||||
{
|
||||
HandleClick(node);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
TechLog.Warn($"click handling failed: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void HandleClick(UITechNode node)
|
||||
{
|
||||
if (node == null || TechTweaksPatch.Enabled == null || !TechTweaksPatch.Enabled.Value)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
TechProto techProto = node.techProto;
|
||||
if (techProto == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
GameHistoryData history = GameMain.history;
|
||||
if (history == null || history.techStates == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!TechKeyCombo.TryDecode(out int steps))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (DowngradeMode.IsOn)
|
||||
{
|
||||
TechDowngrade.Run(history, techProto, steps);
|
||||
}
|
||||
else
|
||||
{
|
||||
TechUnlock.Run(history, techProto, steps);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using HarmonyLib;
|
||||
|
||||
namespace CheatEnabler.Patches.Tech;
|
||||
|
||||
/// <summary>
|
||||
/// Downgrade side - decrease a tech by clicking it with a key-modifier held while downgrade mode is on.
|
||||
///
|
||||
/// The recursion is the mirror image of <see cref="TechUnlock"/>: the unlock walks into the *pre*-techs
|
||||
/// so the tech tree is never left with a gap, the downgrade walks into the *post*-techs so it is never
|
||||
/// left with "prerequisite locked, dependent unlocked".
|
||||
///
|
||||
/// Downgrading is limited to levels the tech actually has applied, never goes below zero and does
|
||||
/// nothing at all for a tech that is not unlocked yet.
|
||||
/// </summary>
|
||||
internal static class TechDowngrade
|
||||
{
|
||||
private static readonly HashSet<int> Visited = new HashSet<int>();
|
||||
|
||||
private static readonly HashSet<int> DirtyFuncs = new HashSet<int>();
|
||||
|
||||
/// <summary>techId -> new curLevel, for every tech touched by the current click.</summary>
|
||||
private static readonly Dictionary<int, int> Touched = new Dictionary<int, int>();
|
||||
|
||||
private static bool _inserterDirty;
|
||||
|
||||
public static void Run(GameHistoryData history, TechProto techProto, int steps)
|
||||
{
|
||||
if (history?.techStates == null || techProto == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!history.techStates.TryGetValue(techProto.ID, out TechState state))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int lastApplied = GetLastAppliedLevel(state);
|
||||
if (lastApplied < techProto.Level)
|
||||
{
|
||||
// Nothing applied yet: clicking a tech that is not unlocked does nothing.
|
||||
return;
|
||||
}
|
||||
|
||||
int target = steps == TechKeyCombo.LevelToMax
|
||||
? techProto.Level - 1
|
||||
: lastApplied - steps;
|
||||
if (target < techProto.Level)
|
||||
{
|
||||
target = techProto.Level - 1;
|
||||
}
|
||||
|
||||
if (target >= lastApplied)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Visited.Clear();
|
||||
DirtyFuncs.Clear();
|
||||
Touched.Clear();
|
||||
_inserterDirty = false;
|
||||
|
||||
DowngradeTo(history, techProto, lastApplied, target);
|
||||
|
||||
foreach (int func in DirtyFuncs)
|
||||
{
|
||||
try
|
||||
{
|
||||
TechFuncRevert.Recompute(history, func);
|
||||
}
|
||||
catch (System.Exception e)
|
||||
{
|
||||
TechLog.Warn($"recomputing tech function {func} failed: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
if (_inserterDirty && history.gameData != null)
|
||||
{
|
||||
history.gameData.OnInserterTechChange();
|
||||
}
|
||||
|
||||
TechUnlock.FinishClick(history);
|
||||
|
||||
RefreshOpenWindow();
|
||||
}
|
||||
|
||||
internal static void MarkDirty(int func) => DirtyFuncs.Add(func);
|
||||
|
||||
internal static void MarkInserterDirty() => _inserterDirty = true;
|
||||
|
||||
/// <summary>
|
||||
/// <c>curLevel</c> means "levels completed plus one" while the tech is being researched, but
|
||||
/// "the max level" once it is unlocked. This helper hides that difference and returns the index of
|
||||
/// the highest level whose <c>UnlockTechFunction</c> calls have already been applied.
|
||||
/// </summary>
|
||||
internal static int GetLastAppliedLevel(TechState state) => state.unlocked ? state.curLevel : state.curLevel - 1;
|
||||
|
||||
internal static bool TryGetLastAppliedLevel(GameHistoryData history, TechProto proto, out int lastApplied)
|
||||
{
|
||||
lastApplied = 0;
|
||||
if (history?.techStates == null || proto == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!history.techStates.TryGetValue(proto.ID, out TechState state))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
lastApplied = GetLastAppliedLevel(state);
|
||||
return lastApplied >= proto.Level;
|
||||
}
|
||||
|
||||
internal static bool HasAnyAppliedLevel(GameHistoryData history, TechProto proto) =>
|
||||
TryGetLastAppliedLevel(history, proto, out int _);
|
||||
|
||||
private static void DowngradeTo(GameHistoryData history, TechProto proto, int lastApplied, int target)
|
||||
{
|
||||
if (!Visited.Add(proto.ID))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!history.techStates.TryGetValue(proto.ID, out TechState state))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (target >= lastApplied)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
bool willBeUnlocked = target >= state.maxLevel;
|
||||
|
||||
RevertDependentTechs(history, proto, willBeUnlocked, target, state.maxLevel);
|
||||
|
||||
for (int level = lastApplied; level > target; level--)
|
||||
{
|
||||
for (int j = 0; j < proto.UnlockFunctions.Length; j++)
|
||||
{
|
||||
// One failing function must not abort the whole downgrade: that would leave the tech
|
||||
// state updated for some techs and stale for others.
|
||||
try
|
||||
{
|
||||
TechFuncRevert.Revert(history, proto.UnlockFunctions[j], proto.UnlockValues[j], level);
|
||||
}
|
||||
catch (System.Exception e)
|
||||
{
|
||||
TechLog.Warn($"reverting tech function {proto.UnlockFunctions[j]} of tech {proto.ID} " +
|
||||
$"at level {level} failed: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Recipes are unlocked when the tech reaches level 0 (see TechUnlock); they are locked again
|
||||
// only when the tech itself becomes locked.
|
||||
if (target < proto.Level)
|
||||
{
|
||||
foreach (int recipe in proto.UnlockRecipes)
|
||||
{
|
||||
LockRecipeIfUnused(history, recipe, proto.ID);
|
||||
}
|
||||
}
|
||||
|
||||
state = history.techStates[proto.ID];
|
||||
state.unlocked = willBeUnlocked;
|
||||
state.curLevel = willBeUnlocked ? state.maxLevel : target + 1;
|
||||
state.hashNeeded = proto.GetHashNeeded(state.curLevel);
|
||||
state.hashUploaded = willBeUnlocked ? state.hashNeeded : 0L;
|
||||
history.techStates[proto.ID] = state;
|
||||
Touched[proto.ID] = state.curLevel;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pulls back every already-unlocked dependent tech whose prerequisite requirement would be
|
||||
/// violated by this downgrade. <c>PreTechsMax</c> demands the prerequisite to be fully unlocked, so
|
||||
/// the dependent is dropped to "not unlocked" (<c>maxLevel - 1</c> applied levels); a prerequisite
|
||||
/// that becomes fully locked forces the dependent to be locked as well.
|
||||
/// </summary>
|
||||
private static void RevertDependentTechs(GameHistoryData history, TechProto proto, bool willBeUnlocked,
|
||||
int target, int maxLevel)
|
||||
{
|
||||
bool preMaxSatisfied = willBeUnlocked && target >= maxLevel;
|
||||
TechProto[] all = LDB.techs.dataArray;
|
||||
|
||||
for (int i = 0; i < all.Length; i++)
|
||||
{
|
||||
TechProto post = all[i];
|
||||
if (post == null || post.ID == proto.ID || !DependsOn(post, proto.ID))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!history.techStates.TryGetValue(post.ID, out TechState postState))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int postLast = GetLastAppliedLevel(postState);
|
||||
if (postLast < post.Level)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Only techs that currently meet their requirement can become illegal.
|
||||
bool currentlyOk = post.PreTechsMax
|
||||
? postState.unlocked && postState.curLevel == postState.maxLevel
|
||||
: postState.unlocked;
|
||||
bool stillOk = post.PreTechsMax ? preMaxSatisfied : willBeUnlocked;
|
||||
if (!currentlyOk || stillOk)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int postTarget = postState.maxLevel - 1;
|
||||
if (postTarget < post.Level)
|
||||
{
|
||||
postTarget = post.Level - 1;
|
||||
}
|
||||
|
||||
if (postTarget >= postLast)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
DowngradeTo(history, post, postLast, postTarget);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool DependsOn(TechProto post, int techId) =>
|
||||
Contains(post.PreTechs, techId) || Contains(post.PreTechsImplicit, techId);
|
||||
|
||||
private static bool Contains(int[] array, int value)
|
||||
{
|
||||
if (array == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < array.Length; i++)
|
||||
{
|
||||
if (array[i] == value)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a recipe from the unlocked set unless another tech that still has levels applied
|
||||
/// unlocks it too. <c>GameHistoryData</c> only exposes <c>UnlockRecipe</c>, so the Set is edited
|
||||
/// directly and the one special recipe id (the delivery package, recipe 122) is reverted by hand.
|
||||
/// </summary>
|
||||
private static void LockRecipeIfUnused(GameHistoryData history, int recipeId, int excludeTechId)
|
||||
{
|
||||
TechProto[] all = LDB.techs.dataArray;
|
||||
for (int i = 0; i < all.Length; i++)
|
||||
{
|
||||
TechProto proto = all[i];
|
||||
if (proto == null || proto.ID == excludeTechId || !HasAnyAppliedLevel(history, proto))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Contains(proto.UnlockRecipes, recipeId))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (history.recipeUnlocked != null)
|
||||
{
|
||||
history.recipeUnlocked.Remove(recipeId);
|
||||
}
|
||||
|
||||
const int dispenserRecipeId = 122;
|
||||
if (recipeId == dispenserRecipeId)
|
||||
{
|
||||
Player player = GameMain.mainPlayer;
|
||||
if (player?.deliveryPackage != null)
|
||||
{
|
||||
player.deliveryPackage.unlocked = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replays the per-node refresh the game performs on an upgrade, without firing the "research
|
||||
/// complete" popup or the scenario hooks (a downgrade is not a research event).
|
||||
/// </summary>
|
||||
private static void RefreshTechTree()
|
||||
{
|
||||
UITechTree window = UIRoot.instance?.uiGame?.techTree;
|
||||
if (window == null || !window.active || Touched.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
MethodInfo refresh = AccessTools.Method(typeof(UITechTree), "OnTechUnlocked",
|
||||
new[] { typeof(int), typeof(int), typeof(bool) });
|
||||
if (refresh == null)
|
||||
{
|
||||
window.RefreshDataValueText();
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var pair in Touched)
|
||||
{
|
||||
refresh.Invoke(window, new object[] { pair.Key, pair.Value, true });
|
||||
}
|
||||
}
|
||||
|
||||
internal static void RefreshOpenWindow() => RefreshTechTree();
|
||||
}
|
||||
@@ -0,0 +1,934 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace CheatEnabler.Patches.Tech
|
||||
{
|
||||
/// <summary>
|
||||
/// F4 - the downgrade side of <c>GameHistoryData.UnlockTechFunction</c>.
|
||||
///
|
||||
/// <para><b>Chosen approach: A (per-function inverse operation), with recomputation for the
|
||||
/// functions where an inverse is either impossible or not drift free.</b></para>
|
||||
///
|
||||
/// <para>Why A rather than B (reset to base plus full replay): a replay has to re-run every side
|
||||
/// effect of <c>UnlockTechFunction</c> on the live game objects. Several of those are ratchets that
|
||||
/// cannot be replayed safely - <c>func 30/31</c> rescale existing logistics station storage
|
||||
/// proportionally through <c>PlanetTransport.OnTechFunctionUnlocked</c>, and <c>func 5/38</c> resize
|
||||
/// the player's package. Replaying them would double-apply the scaling instead of restoring it.
|
||||
/// Inverse operations touch exactly the field that was changed and nothing else, and they need no
|
||||
/// snapshot, so they also survive save/load.</para>
|
||||
///
|
||||
/// <para>Where an inverse is not available the value is recomputed from
|
||||
/// <c>Configs.freeMode</c> - the very table <c>GameHistoryData.SetForNewGame</c> uses to
|
||||
/// initialise the field - plus the set of levels still applied across all techs. That covers the
|
||||
/// multiplicative functions (no float drift, and <c>func 20</c> recovers from the game's 0 clamp,
|
||||
/// which a division can never undo), the assignment functions (a plain subtraction is wrong when
|
||||
/// the value came from a different tech) and the boolean / one-way functions (there is no
|
||||
/// "unset" call in the game).</para>
|
||||
///
|
||||
/// <para>Every case of the original switch (1-45, 61-86, 99 - ids 46-60 and 87-98 do not exist)
|
||||
/// is handled below or explicitly delegated to <see cref="Recompute"/>.</para>
|
||||
/// </summary>
|
||||
internal static class TechFuncRevert
|
||||
{
|
||||
// Base values hard-coded by GameHistoryData.SetForNewGame().
|
||||
private const int BaseInserterStackCountObsolete = 1;
|
||||
private const int BaseInserterStackInput = 2;
|
||||
private const int BaseInserterStackOutput = 1;
|
||||
private const int BaseStorageLevel = 2;
|
||||
private const int BaseLabLevel = 3;
|
||||
private const int BaseStationPilerLevel = 1;
|
||||
private const int BaseDysonNodeAbsorbInterval = 360;
|
||||
|
||||
/// <summary>Function ids already reported as having no known inverse (log-once guard).</summary>
|
||||
private static readonly HashSet<int> UnknownFuncsWarned = new HashSet<int>();
|
||||
|
||||
/// <summary>The game's own rounding of <c>double</c> tech values to <c>int</c>.</summary>
|
||||
internal static int ToInt(double value) => (int)(value > 0.0 ? value + 0.5 : value - 0.5);
|
||||
|
||||
/// <summary>Mirrors <c>Mathf.Round(x * 1000f) / 1000f</c> used by func 21.</summary>
|
||||
private static float Round3Mathf(float value) => Mathf.Round(value * 1000f) / 1000f;
|
||||
|
||||
/// <summary>Mirrors <c>(float)(int)(x * 1000.0 + 0.5) / 1000f</c> used by funcs 61-64, 67 and 71.</summary>
|
||||
private static float Round3Trunc(float value) => (float)(int)((double)value * 1000.0 + 0.5) / 1000f;
|
||||
|
||||
/// <summary>Mirrors <c>(double)(int)(x * 1000.0 + 0.5) / 1000.0</c> used by func 84.</summary>
|
||||
private static double Round3Trunc(double value) => (int)(value * 1000.0 + 0.5) / 1000.0;
|
||||
|
||||
/// <summary>Undo one already applied level of <paramref name="func"/>.</summary>
|
||||
public static void Revert(GameHistoryData history, int func, double value, int level)
|
||||
{
|
||||
Player player = GameMain.mainPlayer;
|
||||
Mecha mecha = player != null ? player.mecha : null;
|
||||
int num = ToInt(value);
|
||||
|
||||
switch (func)
|
||||
{
|
||||
case 1:
|
||||
if (mecha != null)
|
||||
{
|
||||
ConstructionModuleComponent module = mecha.constructionModule;
|
||||
module.droneCount = Math.Max(0, module.droneCount - num);
|
||||
module.droneAliveCount = Math.Max(0, Math.Min(module.droneAliveCount - num, module.droneCount));
|
||||
module.droneIdleCount = Math.Max(0, Math.Min(module.droneIdleCount - num, module.droneCount));
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 2:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.reactorPowerGen -= value;
|
||||
if (mecha.reactorPowerGen < 0.0)
|
||||
{
|
||||
mecha.reactorPowerGen = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 3:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.walkSpeed -= (float)value;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 4: // assignment: recomputed from the techs that still grant it
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 5: // package geometry: recomputed together with func 38
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 6:
|
||||
// coreEnergyCap is additive, coreLevel is an assignment of the tech level -> the
|
||||
// capacity is reverted here and the level is recomputed.
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.coreEnergyCap -= value;
|
||||
if (mecha.coreEnergyCap < 0.0)
|
||||
{
|
||||
mecha.coreEnergyCap = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 7:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.replicateSpeed -= (float)value;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 8: // one-way flag: recomputed
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 9:
|
||||
history.constructionDroneMovement = Math.Max(0, history.constructionDroneMovement - num);
|
||||
break;
|
||||
|
||||
case 10:
|
||||
history.constructionDroneSpeed -= (float)value;
|
||||
break;
|
||||
|
||||
case 11:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.maxSailSpeed -= (float)value;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 12:
|
||||
history.solarSailLife -= (float)value;
|
||||
break;
|
||||
|
||||
case 13: // multiplicative: recomputed (no float drift)
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 14: // assignment: recomputed
|
||||
TechDowngrade.MarkDirty(func);
|
||||
TechDowngrade.MarkInserterDirty();
|
||||
break;
|
||||
|
||||
case 15:
|
||||
history.logisticDroneSpeedScale -= (float)value;
|
||||
break;
|
||||
|
||||
case 16:
|
||||
history.logisticShipSpeedScale -= (float)value;
|
||||
break;
|
||||
|
||||
case 17: // one-way flag: recomputed, and existing warpers are never removed
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 18:
|
||||
history.logisticDroneCarries = Math.Max(0, history.logisticDroneCarries - num);
|
||||
break;
|
||||
|
||||
case 19:
|
||||
history.logisticShipCarries = Math.Max(0, history.logisticShipCarries - num);
|
||||
break;
|
||||
|
||||
case 20: // multiplicative with a 0 clamp: recomputed
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 21:
|
||||
history.miningSpeedScale = Round3Mathf(history.miningSpeedScale - (float)value);
|
||||
break;
|
||||
|
||||
case 22:
|
||||
history.techSpeed = Math.Max(1, history.techSpeed - num);
|
||||
break;
|
||||
|
||||
case 23: // assignment
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 24:
|
||||
history.storageLevel = Math.Max(BaseStorageLevel, history.storageLevel - num);
|
||||
break;
|
||||
|
||||
case 25:
|
||||
history.labLevel = Math.Max(BaseLabLevel, history.labLevel - num);
|
||||
break;
|
||||
|
||||
case 26:
|
||||
history.dysonNodeLatitude -= (float)value;
|
||||
break;
|
||||
|
||||
case 27:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.maxWarpSpeed -= (float)(value * 40000.0);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 28: // assignment
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 29:
|
||||
history.stationPilerLevel = Math.Max(BaseStationPilerLevel, history.stationPilerLevel - num);
|
||||
break;
|
||||
|
||||
case 30:
|
||||
// PlanetTransport.OnTechFunctionUnlocked rescaled every local station's storage when
|
||||
// this was applied; shrinking the *count* back is the inverse the game itself uses
|
||||
// when the field is lowered, so no extra rescale is performed here.
|
||||
history.localStationExtraStorage = Math.Max(0, history.localStationExtraStorage - num);
|
||||
break;
|
||||
|
||||
case 31:
|
||||
history.remoteStationExtraStorage = Math.Max(0, history.remoteStationExtraStorage - num);
|
||||
break;
|
||||
|
||||
case 32:
|
||||
if (player != null && player.deliveryPackage != null)
|
||||
{
|
||||
player.deliveryPackage.colCount = Math.Max(0, player.deliveryPackage.colCount - num);
|
||||
player.deliveryPackage.NotifySizeChange();
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 33:
|
||||
if (player != null && player.deliveryPackage != null)
|
||||
{
|
||||
player.deliveryPackage.stackSizeMultiplier = Math.Max(1, player.deliveryPackage.stackSizeMultiplier - num);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 34:
|
||||
history.logisticCourierSpeedScale -= (float)value;
|
||||
break;
|
||||
|
||||
case 35:
|
||||
history.logisticCourierCarries = Math.Max(0, history.logisticCourierCarries - num);
|
||||
break;
|
||||
|
||||
case 36:
|
||||
history.dispenserDeliveryMaxAngle = Math.Max(0f, history.dispenserDeliveryMaxAngle - (float)value);
|
||||
break;
|
||||
|
||||
case 37: // feature keys: recomputed
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 38:
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 39:
|
||||
TechDowngrade.MarkDirty(func);
|
||||
TechDowngrade.MarkInserterDirty();
|
||||
break;
|
||||
|
||||
case 40:
|
||||
TechDowngrade.MarkDirty(func);
|
||||
TechDowngrade.MarkInserterDirty();
|
||||
break;
|
||||
|
||||
case 41:
|
||||
TechDowngrade.MarkDirty(func);
|
||||
TechDowngrade.MarkInserterDirty();
|
||||
break;
|
||||
|
||||
case 42:
|
||||
case 43:
|
||||
case 44:
|
||||
case 45:
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 61:
|
||||
history.kineticDamageScale = Round3Trunc(history.kineticDamageScale - (float)value);
|
||||
break;
|
||||
|
||||
case 62:
|
||||
history.energyDamageScale = Round3Trunc(history.energyDamageScale - (float)value);
|
||||
break;
|
||||
|
||||
case 63:
|
||||
history.blastDamageScale = Round3Trunc(history.blastDamageScale - (float)value);
|
||||
break;
|
||||
|
||||
case 64:
|
||||
history.magneticDamageScale = Round3Trunc(history.magneticDamageScale - (float)value);
|
||||
break;
|
||||
|
||||
case 65:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.energyShieldRadius = Math.Max(0f, mecha.energyShieldRadius - (float)value);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 66:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.energyShieldCapacity = Math.Max(0L, mecha.energyShieldCapacity - num);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 67:
|
||||
history.combatDroneDamageRatio = Round3Trunc(history.combatDroneDamageRatio - (float)value);
|
||||
break;
|
||||
|
||||
case 68:
|
||||
history.combatDroneROFRatio -= (float)value;
|
||||
break;
|
||||
|
||||
case 69:
|
||||
history.combatDroneDurabilityRatio -= (float)value;
|
||||
break;
|
||||
|
||||
case 70:
|
||||
history.combatDroneSpeedRatio -= (float)value;
|
||||
history.combatShipSpeedRatio -= (float)value;
|
||||
break;
|
||||
|
||||
case 71:
|
||||
history.combatShipDamageRatio = Round3Trunc(history.combatShipDamageRatio - (float)value);
|
||||
break;
|
||||
|
||||
case 72:
|
||||
history.combatShipROFRatio -= (float)value;
|
||||
break;
|
||||
|
||||
case 73:
|
||||
history.combatShipDurabilityRatio -= (float)value;
|
||||
break;
|
||||
|
||||
case 74: // ratio driven value: recomputed
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 75: // one-way flag
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 76: // assignment
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 77:
|
||||
if (mecha != null && mecha.groundCombatModule != null)
|
||||
{
|
||||
mecha.groundCombatModule.fleetCount = Math.Max(0, mecha.groundCombatModule.fleetCount - num);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 78:
|
||||
history.groundFleetPortCount = Math.Max(0, history.groundFleetPortCount - num);
|
||||
break;
|
||||
|
||||
case 79:
|
||||
if (mecha != null && mecha.spaceCombatModule != null)
|
||||
{
|
||||
mecha.spaceCombatModule.fleetCount = Math.Max(0, mecha.spaceCombatModule.fleetCount - num);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 80:
|
||||
history.spaceFleetPortCount = Math.Max(0, history.spaceFleetPortCount - num);
|
||||
break;
|
||||
|
||||
case 81:
|
||||
if (mecha != null)
|
||||
{
|
||||
RescaleHp(mecha, () => mecha.hpMaxUpgrade = Math.Max(0, mecha.hpMaxUpgrade - num));
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 82:
|
||||
// The forward operation is `range *= 1 + value / range`, which is exactly
|
||||
// `range += value`; the inverse is therefore a plain subtraction.
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.laserLocalAttackRange = Math.Max(0f, mecha.laserLocalAttackRange - (float)value);
|
||||
mecha.laserSpaceAttackRange = Math.Max(0f, mecha.laserSpaceAttackRange - (float)value);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 83:
|
||||
RevertLaserDamage(mecha, num);
|
||||
break;
|
||||
|
||||
case 84:
|
||||
if (mecha != null)
|
||||
{
|
||||
RescaleHp(mecha, () =>
|
||||
history.globalHpEnhancement = (float)Round3Trunc(history.globalHpEnhancement - (float)value));
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 85:
|
||||
history.enemyDropScale -= (float)value;
|
||||
break;
|
||||
|
||||
case 86: // one-way flag
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 99: // one-way flag
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
default:
|
||||
// Unknown / newly added function id: warn instead of guessing. Only once per id -
|
||||
// a downgrade can walk thousands of levels and must not flood the log.
|
||||
if (UnknownFuncsWarned.Add(func))
|
||||
{
|
||||
TechLog.Warn($"revert: no inverse known for tech function {func} (value={value}, level={level}); " +
|
||||
"the field was left untouched. A game update may have added a new function.");
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recomputes the functions that cannot be inverted step by step. Called once per downgrade
|
||||
/// click after every level has been reverted.
|
||||
/// </summary>
|
||||
public static void Recompute(GameHistoryData history, int func)
|
||||
{
|
||||
Player player = GameMain.mainPlayer;
|
||||
Mecha mecha = player != null ? player.mecha : null;
|
||||
ModeConfig freeMode = Configs.freeMode;
|
||||
if (freeMode == null)
|
||||
{
|
||||
TechLog.Warn($"recompute of tech function {func} skipped: Configs.freeMode is not available");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (func)
|
||||
{
|
||||
case 5:
|
||||
case 38:
|
||||
ReconcilePackage(history, freeMode);
|
||||
break;
|
||||
|
||||
case 4:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.thrusterLevel = Math.Max(freeMode.mechaThrusterLevel,
|
||||
PickMax(history, func, freeMode.mechaThrusterLevel));
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 6:
|
||||
if (mecha != null)
|
||||
{
|
||||
// func 6 assigns `coreLevel = level` (the tech's own level), not the value.
|
||||
mecha.coreLevel = Math.Max(freeMode.mechaCoreLevel, PickMaxLevel(history, func));
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 8:
|
||||
history.useIonLayer = IsGrantedByAnyTech(history, func) || freeMode.useIonLayer;
|
||||
break;
|
||||
|
||||
case 13:
|
||||
history.solarEnergyLossRate = freeMode.solarEnergyLossRate * ProductOfAppliedValues(history, func);
|
||||
break;
|
||||
|
||||
case 14:
|
||||
history.inserterStackCountObsolete = Math.Max(BaseInserterStackCountObsolete,
|
||||
PickMax(history, func, BaseInserterStackCountObsolete));
|
||||
break;
|
||||
|
||||
case 17:
|
||||
// Never revoke the warp capability from stations that already have warpers: only the
|
||||
// history flag is recalculated. `SetAllStationsMaxWarperCount` has no inverse that
|
||||
// would not destroy existing warpers.
|
||||
history.logisticShipWarpDrive = IsGrantedByAnyTech(history, func) || freeMode.logisticShipWarpDrive;
|
||||
break;
|
||||
|
||||
case 20:
|
||||
float costRate = freeMode.miningCostRate * ProductOfAppliedValues(history, func);
|
||||
// Mirrors the clamp inside GameHistoryData.UnlockTechFunction case 20.
|
||||
if (costRate < TechProto.MINING_COST_CRITICAL_POINT)
|
||||
{
|
||||
costRate = 0f;
|
||||
}
|
||||
|
||||
history.miningCostRate = costRate;
|
||||
break;
|
||||
|
||||
case 23:
|
||||
history.universeObserveLevel = Math.Max(freeMode.universeObserveLevel,
|
||||
PickMax(history, func, freeMode.universeObserveLevel));
|
||||
break;
|
||||
|
||||
case 28:
|
||||
history.blueprintLimit = Math.Max(freeMode.blueprintLimit,
|
||||
PickMax(history, func, freeMode.blueprintLimit));
|
||||
break;
|
||||
|
||||
case 37:
|
||||
RecomputeFeatureKeys(history);
|
||||
break;
|
||||
|
||||
case 39:
|
||||
history.inserterStackOutput = Math.Max(BaseInserterStackOutput,
|
||||
PickMax(history, func, BaseInserterStackOutput));
|
||||
break;
|
||||
|
||||
case 40:
|
||||
history.inserterBidirectional = IsGrantedByAnyTech(history, func);
|
||||
break;
|
||||
|
||||
case 41:
|
||||
history.inserterStackInput = Math.Max(BaseInserterStackInput,
|
||||
PickMax(history, func, BaseInserterStackInput));
|
||||
break;
|
||||
|
||||
case 42:
|
||||
history.beltVerticalConstruction = IsGrantedByAnyTech(history, func);
|
||||
break;
|
||||
|
||||
case 43:
|
||||
// A shorter absorption interval is the upgrade, so the smallest granted value wins.
|
||||
history.dysonNodeAbsorbInterval = PickMin(history, func, BaseDysonNodeAbsorbInterval);
|
||||
break;
|
||||
|
||||
case 44:
|
||||
history.bpReformLimit = PickMax(history, func, 0);
|
||||
break;
|
||||
|
||||
case 45:
|
||||
history.manualPlantVegetation = IsGrantedByAnyTech(history, func);
|
||||
break;
|
||||
|
||||
case 74:
|
||||
RecomputePlanetaryAtField(history, freeMode);
|
||||
break;
|
||||
|
||||
case 75:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.energyShieldUnlocked = IsGrantedByAnyTech(history, func) || freeMode.unlockEnergyShield;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 76:
|
||||
history.autoReconstructSpeed = PickMax(history, func, 0);
|
||||
break;
|
||||
|
||||
case 86:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.energyShieldBurstUnlocked =
|
||||
IsGrantedByAnyTech(history, func) || freeMode.unlockEnergyShieldBurst;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 99:
|
||||
history.missionAccomplished = IsGrantedByAnyTech(history, func);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// func 74 keeps the field expressed as <c>base / ratio</c>; the ratio grows by <c>value</c> per
|
||||
/// level and is rounded to two decimals each time. Rebuilding it from <c>1 + sum(values)</c>
|
||||
/// reproduces exactly what the sequence of forward operations produced, because the rounding is
|
||||
/// a no-op for two-decimal increments.
|
||||
/// </summary>
|
||||
private static void RecomputePlanetaryAtField(GameHistoryData history, ModeConfig freeMode)
|
||||
{
|
||||
double ratio = 1.0;
|
||||
ForEachAppliedFunction(history, 74, (proto, lastApplied, value) =>
|
||||
ratio += value * (lastApplied - proto.Level + 1));
|
||||
ratio = Math.Round(ratio, 2);
|
||||
if (ratio <= 0.0)
|
||||
{
|
||||
ratio = 1.0;
|
||||
}
|
||||
|
||||
long rate = (long)((double)freeMode.planetaryATFieldEnergyRate / ratio + 0.5);
|
||||
history.planetaryATFieldEnergyRate = Math.Max(1L, rate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// func 37 registers <c>1600000 + value</c> as a feature key. A key is kept while any tech that
|
||||
/// grants it still has a level applied, and removed otherwise.
|
||||
/// </summary>
|
||||
private static void RecomputeFeatureKeys(GameHistoryData history)
|
||||
{
|
||||
var allKeys = new HashSet<int>();
|
||||
var stillGranted = new HashSet<int>();
|
||||
TechProto[] all = LDB.techs.dataArray;
|
||||
for (int i = 0; i < all.Length; i++)
|
||||
{
|
||||
TechProto proto = all[i];
|
||||
if (proto?.UnlockFunctions == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int j = 0; j < proto.UnlockFunctions.Length; j++)
|
||||
{
|
||||
if (proto.UnlockFunctions[j] != 37)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int key = 1600000 + ToInt(proto.UnlockValues[j]);
|
||||
allKeys.Add(key);
|
||||
if (TechDowngrade.HasAnyAppliedLevel(history, proto))
|
||||
{
|
||||
stillGranted.Add(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (int key in allKeys)
|
||||
{
|
||||
if (stillGranted.Contains(key))
|
||||
{
|
||||
history.RegFeatureKey(key);
|
||||
}
|
||||
else
|
||||
{
|
||||
history.UnregFeatureKey(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static float ProductOfAppliedValues(GameHistoryData history, int func)
|
||||
{
|
||||
float product = 1f;
|
||||
ForEachAppliedFunction(history, func, (proto, lastApplied, value) =>
|
||||
{
|
||||
int count = lastApplied - proto.Level + 1;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
product *= (float)value;
|
||||
}
|
||||
});
|
||||
return product;
|
||||
}
|
||||
|
||||
private static int PickMax(GameHistoryData history, int func, int fallback)
|
||||
{
|
||||
int best = fallback;
|
||||
bool found = false;
|
||||
ForEachAppliedFunction(history, func, (proto, lastApplied, value) =>
|
||||
{
|
||||
int candidate = ToInt(value);
|
||||
if (!found || candidate > best)
|
||||
{
|
||||
best = candidate;
|
||||
found = true;
|
||||
}
|
||||
});
|
||||
return found ? best : fallback;
|
||||
}
|
||||
|
||||
private static int PickMin(GameHistoryData history, int func, int fallback)
|
||||
{
|
||||
int best = fallback;
|
||||
bool found = false;
|
||||
ForEachAppliedFunction(history, func, (proto, lastApplied, value) =>
|
||||
{
|
||||
int candidate = ToInt(value);
|
||||
if (!found || candidate < best)
|
||||
{
|
||||
best = candidate;
|
||||
found = true;
|
||||
}
|
||||
});
|
||||
return found ? best : fallback;
|
||||
}
|
||||
|
||||
/// <summary>Largest "last applied level" among all techs granting <paramref name="func"/>.</summary>
|
||||
private static int PickMaxLevel(GameHistoryData history, int func)
|
||||
{
|
||||
int best = 0;
|
||||
ForEachAppliedFunction(history, func, (proto, lastApplied, value) =>
|
||||
{
|
||||
if (lastApplied > best)
|
||||
{
|
||||
best = lastApplied;
|
||||
}
|
||||
});
|
||||
return best;
|
||||
}
|
||||
|
||||
private static bool IsGrantedByAnyTech(GameHistoryData history, int func)
|
||||
{
|
||||
bool found = false;
|
||||
ForEachAppliedFunction(history, func, (proto, lastApplied, value) => found = true);
|
||||
return found;
|
||||
}
|
||||
|
||||
internal static void ForEachAppliedFunction(GameHistoryData history, int func, Action<TechProto, int, double> visit)
|
||||
{
|
||||
if (history.techStates == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
TechProto[] all = LDB.techs.dataArray;
|
||||
for (int i = 0; i < all.Length; i++)
|
||||
{
|
||||
TechProto proto = all[i];
|
||||
if (proto?.UnlockFunctions == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!TechDowngrade.TryGetLastAppliedLevel(history, proto, out int lastApplied))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int j = 0; j < proto.UnlockFunctions.Length; j++)
|
||||
{
|
||||
if (proto.UnlockFunctions[j] == func)
|
||||
{
|
||||
visit(proto, lastApplied, proto.UnlockValues[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// func 81 and 84 keep the current HP ratio while <c>hpMaxApplied</c> changes.
|
||||
/// </summary>
|
||||
private static void RescaleHp(Mecha mecha, Action changeMaxUpgrade)
|
||||
{
|
||||
int maxApplied = mecha.hpMaxApplied;
|
||||
float ratio = maxApplied > 0 ? (float)mecha.hp / maxApplied : 1f;
|
||||
changeMaxUpgrade();
|
||||
maxApplied = mecha.hpMaxApplied;
|
||||
mecha.hp = (int)(maxApplied * ratio + 0.5f);
|
||||
if (mecha.hp > maxApplied)
|
||||
{
|
||||
mecha.hp = maxApplied;
|
||||
}
|
||||
|
||||
if (mecha.hp < 1)
|
||||
{
|
||||
mecha.hp = 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// func 83 scales every laser stat by <c>1 + num / laserLocalDamage</c> measured *before* the
|
||||
/// change. The integer rounding makes the transform lossy, so the previous damage value is
|
||||
/// recovered as <c>laserLocalDamage - num</c> and the other stats are divided by the same
|
||||
/// factor.
|
||||
/// </summary>
|
||||
private static void RevertLaserDamage(Mecha mecha, int num)
|
||||
{
|
||||
if (mecha == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int damageAfter = mecha.laserLocalDamage;
|
||||
int damageBefore = damageAfter - num;
|
||||
if (damageBefore < 1)
|
||||
{
|
||||
damageBefore = 1;
|
||||
}
|
||||
|
||||
float inverseFactor = damageAfter > 0 ? (float)damageBefore / damageAfter : 1f;
|
||||
mecha.laserLocalDamage = damageBefore;
|
||||
mecha.laserSpaceDamage = (int)(mecha.laserSpaceDamage * inverseFactor + 0.5f);
|
||||
mecha.laserEnergyCapacity = (int)(mecha.laserEnergyCapacity * inverseFactor + 0.5f);
|
||||
mecha.laserLocalEnergyCost = (int)(mecha.laserLocalEnergyCost * inverseFactor + 0.5f);
|
||||
mecha.laserSpaceEnergyCost = (int)(mecha.laserSpaceEnergyCost * inverseFactor + 0.5f);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// func 5 and func 38 both resize the player's package: func 5 adds whole rows
|
||||
/// (<c>SetSize(size + num * colCount)</c>) and func 38 changes the column count, which re-lays-out
|
||||
/// every row.
|
||||
///
|
||||
/// Neither can be undone by simply calling the game's resize in reverse:
|
||||
/// <c>StorageComponent.SetSize(int, int, int)</c> iterates the *whole* backing array and computes
|
||||
/// <c>row * newcol + col</c>, so shrinking the column count runs past the new size and throws
|
||||
/// <c>IndexOutOfRangeException</c> (verified in game). The geometry is therefore recomputed from
|
||||
/// the base values and the levels still applied, and the grid is re-laid-out cell by cell.
|
||||
///
|
||||
/// If an occupied cell would fall outside the target layout the resize is refused and reported -
|
||||
/// no item is ever destroyed, and the tech level is still reverted.
|
||||
/// </summary>
|
||||
private static void ReconcilePackage(GameHistoryData history, ModeConfig freeMode)
|
||||
{
|
||||
Player player = GameMain.mainPlayer;
|
||||
if (player?.package == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Player.SetForNewGame(): packageColCount = 10, package = Configs.freeMode.playerPackageSize cells.
|
||||
const int baseCols = 10;
|
||||
int baseSize = freeMode.playerPackageSize;
|
||||
if (baseSize <= 0)
|
||||
{
|
||||
baseSize = baseCols * 4;
|
||||
}
|
||||
|
||||
int baseRows = (baseSize - 1) / baseCols + 1;
|
||||
int targetCols = baseCols;
|
||||
int targetRows = baseRows;
|
||||
|
||||
// Each applied level adds its value: func 38 to the column count, func 5 to the row count.
|
||||
ForEachAppliedFunction(history, 38, (proto, lastApplied, value) =>
|
||||
targetCols += ToInt(value) * (lastApplied - proto.Level + 1));
|
||||
ForEachAppliedFunction(history, 5, (proto, lastApplied, value) =>
|
||||
targetRows += ToInt(value) * (lastApplied - proto.Level + 1));
|
||||
|
||||
if (targetCols < baseCols)
|
||||
{
|
||||
targetCols = baseCols;
|
||||
}
|
||||
|
||||
if (targetRows < baseRows)
|
||||
{
|
||||
targetRows = baseRows;
|
||||
}
|
||||
|
||||
int targetSize = targetRows * targetCols;
|
||||
|
||||
StorageComponent package = player.package;
|
||||
StorageComponent.GRID[] oldGrid = package.grids;
|
||||
if (oldGrid == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int oldCols = player.packageColCount < 1 ? baseCols : player.packageColCount;
|
||||
int oldSize = package.size;
|
||||
if (oldSize <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int oldRows = (oldSize - 1) / oldCols + 1;
|
||||
if (oldCols == targetCols && oldSize == targetSize)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
for (int r = 0; r < oldRows; r++)
|
||||
{
|
||||
for (int c = 0; c < oldCols; c++)
|
||||
{
|
||||
int index = r * oldCols + c;
|
||||
if (index >= oldGrid.Length || index >= oldSize || oldGrid[index].itemId == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (r < targetRows && c < targetCols)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
TechLog.Warn($"package resize skipped: cell {index} (row {r}, column {c}) is not empty and would " +
|
||||
"fall outside the new layout, so no item is destroyed. The tech level was still reverted.");
|
||||
UIRealtimeTip.Popup(Localization.PackageResizeSkippedOccupiedCells.Translate());
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var newGrid = new StorageComponent.GRID[targetSize];
|
||||
for (int r = 0; r < oldRows; r++)
|
||||
{
|
||||
for (int c = 0; c < oldCols; c++)
|
||||
{
|
||||
if (r >= targetRows || c >= targetCols)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int from = r * oldCols + c;
|
||||
if (from >= oldGrid.Length || from >= oldSize)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
newGrid[r * targetCols + c] = oldGrid[from];
|
||||
}
|
||||
}
|
||||
|
||||
player.packageColCount = targetCols;
|
||||
package.grids = newGrid;
|
||||
package.size = targetSize;
|
||||
package.searchStart = 0;
|
||||
package.ResetOptimizationFlags();
|
||||
package.NotifyStorageChange();
|
||||
package.NotifyStorageSizeChange();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
namespace CheatEnabler.Patches.Tech;
|
||||
|
||||
/// <summary>
|
||||
/// The key-modifier semantics shared by the upgrade and the downgrade side.
|
||||
///
|
||||
/// The mapping mirrors the built-in <see cref="GamePatch.UnlockTech"/> handler so both features behave
|
||||
/// identically, and the downgrade side is its exact mirror:
|
||||
///
|
||||
/// <list type="table">
|
||||
/// <item><term>Shift</term><description>+1 / -1</description></item>
|
||||
/// <item><term>Ctrl</term><description>+10 / -10</description></item>
|
||||
/// <item><term>Ctrl + Shift</term><description>+100 / -100</description></item>
|
||||
/// <item><term>Alt</term><description>to MAX / back to locked</description></item>
|
||||
/// <item><term>Shift + Alt, Ctrl + Alt</term><description>ignored</description></item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
internal static class TechKeyCombo
|
||||
{
|
||||
/// <summary>Sentinel for the "Alt" combination: apply or revert everything this click can.</summary>
|
||||
public const int LevelToMax = int.MaxValue;
|
||||
|
||||
/// <summary>
|
||||
/// Decodes the currently held modifiers.
|
||||
/// Returns false when the combination carries no meaning and the click must be left alone.
|
||||
/// </summary>
|
||||
public static bool TryDecode(out int steps)
|
||||
{
|
||||
steps = 0;
|
||||
|
||||
if (VFInput.shift)
|
||||
{
|
||||
if (VFInput.alt)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
steps = VFInput.control ? 100 : 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (VFInput.control)
|
||||
{
|
||||
if (VFInput.alt)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
steps = 10;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (VFInput.alt)
|
||||
{
|
||||
steps = LevelToMax;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace CheatEnabler.Patches.Tech;
|
||||
|
||||
/// <summary>
|
||||
/// Single funnel for the tech unlock / downgrade feature's log output.
|
||||
///
|
||||
/// Only real problems are reported: a Harmony target that no longer resolves, a tech function without
|
||||
/// a known inverse, or a refused package resize. Those are conditions the player or the maintainer
|
||||
/// needs to know about after a game update.
|
||||
/// </summary>
|
||||
internal static class TechLog
|
||||
{
|
||||
public static void Warn(string message)
|
||||
{
|
||||
CheatEnabler.Logger.LogWarning("[TechTweaks] " + message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace CheatEnabler.Patches.Tech;
|
||||
|
||||
/// <summary>
|
||||
/// Help button for the tech / upgrade window.
|
||||
///
|
||||
/// The button is created once under the <c>UITechTree</c> window itself, so it inherits the window's
|
||||
/// lifetime and disappears with it.
|
||||
///
|
||||
/// It is anchored directly under the "Tech" tab caption in the top-left corner
|
||||
/// (<c>UITechTree.tabButtonText0</c>). It was originally placed in the bottom-left corner, but the
|
||||
/// tooltip is tall and the game's bottom HUD bar clipped it there.
|
||||
///
|
||||
/// The button clones the game's own tip-button prefab used by the sandbox settings
|
||||
/// (<c>galaxySelect.sandboxToggle</c> parent / <c>tip-button</c>), which is what UXAssist's
|
||||
/// <c>LayoutHelper.AddTipsButton</c> does as well. The prefab's <c>UIButton.TipSettings</c> carries
|
||||
/// the tip prefab plumbing and tip delay, so it is saved before the button state is normalised and
|
||||
/// restored afterwards - dropping it would produce a button without a tooltip.
|
||||
/// </summary>
|
||||
internal static class TechTreeUI
|
||||
{
|
||||
private const float HelpButtonGap = 4f;
|
||||
private const float HelpButtonLeftFallback = 24f;
|
||||
private const float HelpButtonBottomFallback = 24f;
|
||||
|
||||
private static RectTransform _root;
|
||||
private static UIButton _helpButton;
|
||||
|
||||
public static void OnTechTreeOpened(UITechTree window)
|
||||
{
|
||||
EnsureCreated(window);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The window's whole GameObject is destroyed when it is freed, taking our elements with it,
|
||||
/// so the cached references only have to be dropped.
|
||||
/// </summary>
|
||||
public static void OnTechTreeFreed()
|
||||
{
|
||||
_root = null;
|
||||
_helpButton = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drops the created elements. The window's own GameObject may still be alive here (the feature was
|
||||
/// switched off while the tech tree was open), so the root is destroyed explicitly instead of only
|
||||
/// clearing the cached references.
|
||||
/// </summary>
|
||||
public static void Reset()
|
||||
{
|
||||
if (_root != null)
|
||||
{
|
||||
Object.Destroy(_root.gameObject);
|
||||
}
|
||||
|
||||
_root = null;
|
||||
_helpButton = null;
|
||||
}
|
||||
|
||||
private static void EnsureCreated(UITechTree window)
|
||||
{
|
||||
if (_root != null || window == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!(window.transform is RectTransform windowRect))
|
||||
{
|
||||
TechLog.Warn("tech tree window has no RectTransform, help button was not created");
|
||||
return;
|
||||
}
|
||||
|
||||
var rootGo = new GameObject("TechTweaks-UI", typeof(RectTransform));
|
||||
_root = (RectTransform)rootGo.transform;
|
||||
_root.SetParent(windowRect, false);
|
||||
_root.anchorMin = Vector2.zero;
|
||||
_root.anchorMax = Vector2.one;
|
||||
_root.pivot = new Vector2(0.5f, 0.5f);
|
||||
_root.anchoredPosition3D = Vector3.zero;
|
||||
_root.offsetMin = Vector2.zero;
|
||||
_root.offsetMax = Vector2.zero;
|
||||
_root.SetAsLastSibling();
|
||||
|
||||
_helpButton = CreateHelpButton(window, _root);
|
||||
}
|
||||
|
||||
private static UIButton CreateHelpButton(UITechTree window, RectTransform root)
|
||||
{
|
||||
Transform source = FindTipsButtonPrefab();
|
||||
if (source == null)
|
||||
{
|
||||
TechLog.Warn("native tip-button prefab not found, tech tree help button was not created");
|
||||
return null;
|
||||
}
|
||||
|
||||
GameObject clone = Object.Instantiate(source.gameObject);
|
||||
clone.name = "TechTweaks-HelpButton";
|
||||
var button = clone.GetComponent<UIButton>();
|
||||
if (button == null)
|
||||
{
|
||||
TechLog.Warn("tip-button prefab has no UIButton, tech tree help button was not created");
|
||||
Object.Destroy(clone);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Keep the prefab's tip plumbing (simpleGeneralTipPrefab, level, delay, corner, width)
|
||||
// before the state reset wipes it out.
|
||||
UIButton.TipSettings tipSettings = button.tips;
|
||||
button.Init();
|
||||
button.enabled = true;
|
||||
button.highlighted = false;
|
||||
button.updating = true;
|
||||
button.data = 0;
|
||||
if (button.button != null)
|
||||
{
|
||||
button.button.onClick.RemoveAllListeners();
|
||||
button.button.enabled = true;
|
||||
button.button.interactable = true;
|
||||
}
|
||||
|
||||
button.MReset();
|
||||
button.tips = tipSettings;
|
||||
button.tips.topLevel = true;
|
||||
// corner selects which corner of the button the tooltip hangs off (3 = below-right, see
|
||||
// UISimpleGeneralTip.SetTip). The prefab defaults to a vertically centred placement, which
|
||||
// pushes a tall tooltip off the top of the screen once the button sits in the header area.
|
||||
button.tips.corner = 3;
|
||||
// Same title and body as the config panel's tooltip button, so the two read identically.
|
||||
button.tips.tipTitle = Localization.UnlockDowngradeTechWithKeyModifiers.Translate();
|
||||
button.tips.tipText = Localization.TechModifierHelpBody.Translate();
|
||||
|
||||
var rect = (RectTransform)clone.transform;
|
||||
PlaceHelpButton(window, rect, root);
|
||||
button.UpdateTip();
|
||||
clone.SetActive(true);
|
||||
return button;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts the button right under the "Tech" tab caption in the window's top-left corner, reusing
|
||||
/// that caption's anchors and pivot so the offset means the same thing at any resolution. Falls
|
||||
/// back to the bottom-left corner if the caption is not available.
|
||||
/// </summary>
|
||||
private static void PlaceHelpButton(UITechTree window, RectTransform rect, RectTransform root)
|
||||
{
|
||||
Text caption = window.tabButtonText0;
|
||||
RectTransform captionRect = caption != null ? caption.rectTransform : null;
|
||||
|
||||
if (captionRect != null && captionRect.parent != null)
|
||||
{
|
||||
rect.SetParent(captionRect.parent, false);
|
||||
rect.anchorMin = captionRect.anchorMin;
|
||||
rect.anchorMax = captionRect.anchorMax;
|
||||
rect.pivot = captionRect.pivot;
|
||||
Vector3 position = captionRect.anchoredPosition3D;
|
||||
rect.anchoredPosition3D = new Vector3(
|
||||
position.x,
|
||||
position.y - captionRect.rect.height - HelpButtonGap,
|
||||
position.z);
|
||||
rect.localScale = Vector3.one;
|
||||
return;
|
||||
}
|
||||
|
||||
rect.SetParent(root, false);
|
||||
rect.anchorMin = new Vector2(0f, 0f);
|
||||
rect.anchorMax = new Vector2(0f, 0f);
|
||||
rect.pivot = new Vector2(0f, 0f);
|
||||
rect.anchoredPosition3D = new Vector3(HelpButtonLeftFallback, HelpButtonBottomFallback, 0f);
|
||||
rect.localScale = Vector3.one;
|
||||
}
|
||||
|
||||
private static Transform FindTipsButtonPrefab()
|
||||
{
|
||||
UIGalaxySelect galaxySelect = UIRoot.instance != null ? UIRoot.instance.galaxySelect : null;
|
||||
Transform sandboxToggle = galaxySelect?.sandboxToggle != null
|
||||
? galaxySelect.sandboxToggle.transform
|
||||
: null;
|
||||
Transform container = sandboxToggle != null ? sandboxToggle.parent : null;
|
||||
return container != null ? container.Find("tip-button") : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
using System;
|
||||
|
||||
namespace CheatEnabler.Patches.Tech;
|
||||
|
||||
/// <summary>
|
||||
/// Upgrade side - unlock techs by clicking them with a key-modifier held while downgrade mode is off.
|
||||
///
|
||||
/// <see cref="UnlockTechRecursive"/> mirrors the built-in <see cref="GamePatch.UnlockTech"/>
|
||||
/// implementation so the reference behaviour is reproduced exactly: prerequisites are unlocked
|
||||
/// recursively (<c>PreTechs</c> / <c>PreTechsImplicit</c>, driven by <c>PreTechsMax</c>), recipes are
|
||||
/// unlocked on level 0, every level calls <c>UnlockTechFunction</c>, tech awards are granted, the hash
|
||||
/// counters are maintained and <c>NotifyTechUnlock</c> plus <c>RegFeatureKey(1000100)</c> are fired.
|
||||
/// </summary>
|
||||
internal static class TechUnlock
|
||||
{
|
||||
public static void Run(GameHistoryData history, TechProto techProto, int steps)
|
||||
{
|
||||
// Mirrors the built-in maxLevel argument: "to MAX" passes the default, the other combinations
|
||||
// pass -(steps) so the loop advances exactly `steps` levels.
|
||||
int maxLevel = steps == TechKeyCombo.LevelToMax ? 10000 : -steps;
|
||||
|
||||
UnlockTechRecursive(history, techProto, maxLevel);
|
||||
|
||||
FinishClick(history);
|
||||
}
|
||||
|
||||
/// <summary>Same post-click queue fix-up the built-in feature performs.</summary>
|
||||
internal static void FinishClick(GameHistoryData history)
|
||||
{
|
||||
history.VerifyTechQueue();
|
||||
if (history.techQueue != null && history.techQueue.Length > 0 && history.currentTech != history.techQueue[0])
|
||||
{
|
||||
history.currentTech = history.techQueue[0];
|
||||
}
|
||||
}
|
||||
|
||||
private static void UnlockTechRecursive(GameHistoryData history, TechProto techProto, int maxLevel = 10000)
|
||||
{
|
||||
var techStates = history.techStates;
|
||||
int techID = techProto.ID;
|
||||
if (techStates == null || !techStates.TryGetValue(techID, out TechState value))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (value.unlocked)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int maxLvl = Math.Min(maxLevel < 0 ? value.curLevel - maxLevel - 1 : maxLevel, value.maxLevel);
|
||||
|
||||
foreach (int preid in techProto.PreTechs)
|
||||
{
|
||||
TechProto preProto = LDB.techs.Select(preid);
|
||||
if (preProto != null)
|
||||
{
|
||||
UnlockTechRecursive(history, preProto, techProto.PreTechsMax ? 10000 : -1);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (int preid in techProto.PreTechsImplicit)
|
||||
{
|
||||
TechProto preProto = LDB.techs.Select(preid);
|
||||
if (preProto != null)
|
||||
{
|
||||
UnlockTechRecursive(history, preProto, techProto.PreTechsMax ? 10000 : -1);
|
||||
}
|
||||
}
|
||||
|
||||
if (value.curLevel < techProto.Level)
|
||||
{
|
||||
value.curLevel = techProto.Level;
|
||||
}
|
||||
|
||||
while (value.curLevel <= maxLvl)
|
||||
{
|
||||
if (value.curLevel == 0)
|
||||
{
|
||||
foreach (int recipe in techProto.UnlockRecipes)
|
||||
{
|
||||
history.UnlockRecipe(recipe);
|
||||
}
|
||||
}
|
||||
|
||||
for (int j = 0; j < techProto.UnlockFunctions.Length; j++)
|
||||
{
|
||||
history.UnlockTechFunction(techProto.UnlockFunctions[j], techProto.UnlockValues[j], value.curLevel);
|
||||
}
|
||||
|
||||
for (int k = 0; k < techProto.AddItems.Length; k++)
|
||||
{
|
||||
history.GainTechAwards(techProto.AddItems[k], techProto.AddItemCounts[k]);
|
||||
}
|
||||
|
||||
value.curLevel++;
|
||||
}
|
||||
|
||||
// No trace inside the loop above on purpose: a single Alt-click on an "infinite" tech applies
|
||||
// thousands of levels, and one log write per level makes the game freeze.
|
||||
value.unlocked = maxLvl >= value.maxLevel;
|
||||
value.curLevel = value.unlocked ? maxLvl : maxLvl + 1;
|
||||
value.hashNeeded = techProto.GetHashNeeded(value.curLevel);
|
||||
value.hashUploaded = value.unlocked ? value.hashNeeded : 0L;
|
||||
techStates[techID] = value;
|
||||
history.RegFeatureKey(1000100);
|
||||
history.NotifyTechUnlock(techID, maxLvl, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using System.Reflection.Emit;
|
||||
using CheatEnabler.Patches.Tech;
|
||||
using BepInEx.Configuration;
|
||||
using HarmonyLib;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
using UXAssist.Common.Patching;
|
||||
using GameLogicProc = UXAssist.Common.GameLogic;
|
||||
|
||||
namespace CheatEnabler.Patches;
|
||||
|
||||
/// <summary>
|
||||
/// Unlock / downgrade techs by clicking the tech tree with a key-modifier held.
|
||||
///
|
||||
/// This replaces the previous unlock-only handler: the option keeps its original config key
|
||||
/// (<c>General/UnlockTech</c>) and its position in the config panel, but now it also owns downgrade
|
||||
/// mode, so a single switch covers both directions.
|
||||
///
|
||||
/// <list type="bullet">
|
||||
/// <item><c>UITechNode.OnPointerDown</c> - transpiler that injects <see cref="TechClickHandler"/>.</item>
|
||||
/// <item><c>UITechTree._OnOpen</c> / <c>_OnFree</c> - create and release the help button.</item>
|
||||
/// <item>The per-frame <c>Caps Lock</c> poll runs through <see cref="OnInputUpdate"/>, the registry
|
||||
/// lifecycle hook, so no separate <c>VFInput.OnUpdate</c> patch is needed.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
[ModFeature("TechTweaks")]
|
||||
public static class TechTweaksPatch
|
||||
{
|
||||
public static ConfigEntry<bool> Enabled;
|
||||
|
||||
public static void Init()
|
||||
{
|
||||
Enabled.SettingChanged += (_, _) =>
|
||||
{
|
||||
Impl.Enable(Enabled.Value);
|
||||
DowngradeMode.Reset();
|
||||
};
|
||||
GameLogicProc.OnGameEnd += ResetState;
|
||||
}
|
||||
|
||||
public static void Start()
|
||||
{
|
||||
Impl.Enable(Enabled.Value);
|
||||
}
|
||||
|
||||
public static void Uninit()
|
||||
{
|
||||
GameLogicProc.OnGameEnd -= ResetState;
|
||||
Impl.Enable(false);
|
||||
}
|
||||
|
||||
/// <summary>Per-frame input hook driven by the mod feature registry.</summary>
|
||||
public static void OnInputUpdate()
|
||||
{
|
||||
try
|
||||
{
|
||||
DowngradeMode.Update();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Warn($"downgrade mode update failed: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ResetState()
|
||||
{
|
||||
DowngradeMode.Reset();
|
||||
TechTreeUI.Reset();
|
||||
}
|
||||
|
||||
/// <summary>Harmony patch slot to use; mirrors <c>HarmonyLib.HarmonyPatchType</c>.</summary>
|
||||
private enum PatchKind
|
||||
{
|
||||
Postfix,
|
||||
Prefix,
|
||||
Transpiler
|
||||
}
|
||||
|
||||
public sealed class Impl : PatchImpl<Impl>
|
||||
{
|
||||
protected override void OnEnable()
|
||||
{
|
||||
// Downgrade mode is a per-session switch and always starts out off.
|
||||
DowngradeMode.Reset();
|
||||
|
||||
PatchMethod(typeof(UITechNode), "OnPointerDown", nameof(UITechNode_OnPointerDown_Transpiler),
|
||||
PatchKind.Transpiler);
|
||||
PatchMethod(typeof(UITechTree), "_OnOpen", nameof(UITechTree_OnOpen_Postfix));
|
||||
PatchMethod(typeof(UITechTree), "_OnFree", nameof(UITechTree_OnFree_Postfix));
|
||||
}
|
||||
|
||||
protected override void OnDisable()
|
||||
{
|
||||
DowngradeMode.Reset();
|
||||
TechTreeUI.Reset();
|
||||
}
|
||||
|
||||
private static void PatchMethod(Type type, string targetName, string patchName, PatchKind kind = PatchKind.Postfix)
|
||||
{
|
||||
var harmony = GetHarmony();
|
||||
if (harmony == null)
|
||||
{
|
||||
Log.Warn($"cannot patch {type.Name}.{targetName}: this feature is not enabled");
|
||||
return;
|
||||
}
|
||||
|
||||
MethodInfo target = AccessTools.Method(type, targetName);
|
||||
if (target == null)
|
||||
{
|
||||
Log.Warn($"patch target {type.Name}.{targetName} not found; a game update may have changed it. " +
|
||||
"This part of the feature stays inactive.");
|
||||
return;
|
||||
}
|
||||
|
||||
MethodInfo patch = AccessTools.Method(typeof(Impl), patchName);
|
||||
if (patch == null)
|
||||
{
|
||||
Log.Warn($"patch method {patchName} not found");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
harmony.Patch(target,
|
||||
kind == PatchKind.Prefix ? new HarmonyMethod(patch) : null,
|
||||
kind == PatchKind.Postfix ? new HarmonyMethod(patch) : null,
|
||||
kind == PatchKind.Transpiler ? new HarmonyMethod(patch) : null);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Warn($"failed to patch {type.Name}.{targetName}: {e.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void UITechTree_OnOpen_Postfix(UITechTree __instance)
|
||||
{
|
||||
try
|
||||
{
|
||||
TechTreeUI.OnTechTreeOpened(__instance);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Warn($"creating the tech tree UI failed: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void UITechTree_OnFree_Postfix()
|
||||
{
|
||||
try
|
||||
{
|
||||
TechTreeUI.OnTechTreeFreed();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Warn($"releasing the tech tree UI failed: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Injects <c>TechClickHandler.OnClickTech(UITechNode)</c> at the start of the click handling.
|
||||
/// The injection point is the <c>tree.selected</c> read, which is the first thing the method does
|
||||
/// after the "tech id 1" early-out, so ignored nodes never reach the handler.
|
||||
///
|
||||
/// The method is not rewritten in any other way; if the pattern is not found the original
|
||||
/// instructions are returned unchanged and the feature simply does not react to clicks.
|
||||
/// </summary>
|
||||
// Harmony transpiler: UITechNode_OnPointerDown_Transpiler
|
||||
// Target: UITechNode.OnPointerDown
|
||||
// Fallback: TranspilerGuard returns the original instructions and logs a warning — the
|
||||
// key-modifier click handling then stays inactive instead of throwing.
|
||||
private static IEnumerable<CodeInstruction> UITechNode_OnPointerDown_Transpiler(
|
||||
IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldarg_0),
|
||||
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(UITechNode), nameof(UITechNode.tree))),
|
||||
new CodeMatch(OpCodes.Callvirt,
|
||||
AccessTools.PropertyGetter(typeof(UITechTree), nameof(UITechTree.selected))));
|
||||
|
||||
if (matcher.IsInvalid)
|
||||
{
|
||||
return matcher.Finish(instructions, CheatEnabler.Logger, nameof(UITechNode_OnPointerDown_Transpiler));
|
||||
}
|
||||
|
||||
MethodInfo handler = AccessTools.Method(typeof(TechClickHandler), nameof(TechClickHandler.OnClickTech));
|
||||
if (handler == null)
|
||||
{
|
||||
Log.Warn("TechClickHandler.OnClickTech not found, key-modifier click handling is inactive");
|
||||
return instructions;
|
||||
}
|
||||
|
||||
// Move the labels of the matched instruction onto the injected sequence so that any branch
|
||||
// which used to land there now runs the handler first.
|
||||
List<Label> labels = matcher.Labels;
|
||||
matcher.Labels = null;
|
||||
matcher.Insert(
|
||||
new CodeInstruction(OpCodes.Ldarg_0).WithLabels(labels),
|
||||
new CodeInstruction(OpCodes.Call, handler));
|
||||
|
||||
return matcher.Finish(instructions, CheatEnabler.Logger, nameof(UITechNode_OnPointerDown_Transpiler));
|
||||
}
|
||||
}
|
||||
|
||||
private static class Log
|
||||
{
|
||||
public static void Warn(string message)
|
||||
{
|
||||
CheatEnabler.Logger.LogWarning("[TechTweaks] " + message);
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
-2
@@ -13,7 +13,12 @@
|
||||
* General:
|
||||
* Enable Dev Shortcuts (check config panel for usage)
|
||||
* Disable Abnormal Checks
|
||||
* Unlock techs with key-modifiers (Ctrl/Alt/Shift)
|
||||
* Quickly upgrade/downgrade tech with key-modifiers (click the tech tree while holding Ctrl/Alt/Shift)
|
||||
* `Alt` raises a tech to its maximum level, or reverts it to locked while downgrade mode is on
|
||||
* `Caps Lock` toggles downgrade mode; toggling reports itself with a realtime tip and a critical warning banner
|
||||
* Downgrading also reverts the upgrade values the tech had applied, so repeated up/down cycles do not drift
|
||||
* This option now replaces the old unlock-only behaviour; it keeps the same config entry
|
||||
* The `?` button in the tech tree window shows the full key reference
|
||||
* Remove all metadata consumption records
|
||||
* Remove metadata consumption record in current game
|
||||
* Clear metadata flag which bans achievements
|
||||
@@ -88,7 +93,12 @@
|
||||
* 常规:
|
||||
* 启用开发模式快捷键(使用说明见设置面板)
|
||||
* 屏蔽异常检测
|
||||
* 使用组合键解锁科技(Ctrl/Alt/Shift)
|
||||
* 使用组合键快速升降级科技(按住 Ctrl/Alt/Shift 点击科技树)
|
||||
* `Alt` 将科技升到最大等级;开启降级模式后则回退到未解锁
|
||||
* `Caps Lock` 切换降级模式,切换时会用实时弹窗和严重警告横幅提示
|
||||
* 降级会同时回退该科技已应用的升级数值,反复升降级不会产生数值漂移
|
||||
* 本选项已取代原来的「仅解锁」行为,配置文件条目保持不变
|
||||
* 科技树界面的 `?` 按钮显示完整组合键说明
|
||||
* 移除所有元数据消耗记录
|
||||
* 移除当前存档的元数据消耗记录
|
||||
* 解除当前存档因使用元数据导致的成就限制
|
||||
|
||||
@@ -91,10 +91,11 @@ public static class UIConfigWindow
|
||||
y += 30f;
|
||||
wnd.AddCheckBox(x, y, tab1, GamePatch.AbnormalDisablerEnabled, "Disable Abnormal Checks");
|
||||
y += 36f;
|
||||
cb = wnd.AddCheckBox(x, y, tab1, GamePatch.UnlockTechEnabled, "Unlock Tech with Key-Modifiers");
|
||||
cb = wnd.AddCheckBox(x, y, tab1, TechTweaksPatch.Enabled, Localization.UnlockDowngradeTechWithKeyModifiers);
|
||||
x += cb.Width + 5f;
|
||||
y += 6f;
|
||||
wnd.AddTipsButton2(x, y, tab1, "Unlock Tech with Key-Modifiers", "Unlock Tech with Key-Modifiers Tips", "unlock-tech-tips");
|
||||
wnd.AddTipsButton2(x, y, tab1, Localization.UnlockDowngradeTechWithKeyModifiers,
|
||||
Localization.TechModifierHelpBody, "unlock-tech-tips");
|
||||
x = 0f;
|
||||
y += 30f + 36f;
|
||||
wnd.AddButton(x, y, 400f, tab1, "Remove all metadata consumption records", 16, "button-remove-all-metadata-consumption", PlayerFunctions.RemoveAllMetadataConsumptions);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "CheatEnabler",
|
||||
"version_number": "2.4.6",
|
||||
"version_number": "2.4.7",
|
||||
"website_url": "https://github.com/soarqin/DSP_Mods/tree/master/CheatEnabler",
|
||||
"description": "Add various cheat functions while disabling abnormal determinants / 添加一些作弊功能,同时屏蔽异常检测",
|
||||
"dependencies": [
|
||||
|
||||
Reference in new issue
Block a user