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:
TTenYX authored and Soar Qin committed 2026-10-10 23:49:40 +08:00
1 parent 6a292e0816
commit 6ced106901
19 files changed
+2072 -143

No files matched your search

@@ -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);
}
}
}
+320
View File
@@ -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();
}
+934
View File
@@ -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();
}
}
}
+60
View File
@@ -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;
}
}
+16
View File
@@ -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);
}
}
+183
View File
@@ -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;
}
}
+109
View File
@@ -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);
}
}