Author SHA1 Message Date
soarqin 58d08cbcd7 fix(uxassist): use standard blueprint option controls
Match the native description title baseline, add clearance from the popup corner, and use the rectangular settings selector. Let its list overlay the footer without resizing the popup, and reduce checkbox spacing. Reset cloned resolution rows and external events locally.

Assisted-by: Cindy (https://cindy.app)
2026-11-05 21:43:21 +08:00
soarqin 19d19ce38d fix(uxassist): respect blueprint text and icon bounds
Account for the native background's trimmed border, keep checkbox captions independently sized, and place Auto-fill after the measured title while reserving the native icon. Limit changes to owned controls.

Assisted-by: Cindy (https://cindy.app)
2026-11-05 11:41:51 +08:00
soarqin 51af1430bc fix(uxassist): anchor blueprint options and use native popup controls
Follow the Auto-fill entry after native layout and scrolling, flip or constrain placement at canvas edges, and close detached or hidden popups.

Use the native close-X artwork with an isolated callback, compact settings, and one footer Generate action. Keep dropdown choices above the action and preserve native blueprint layout and production calculations.
2026-11-04 22:57:23 +08:00
soarqin 8fd449d991 fix(uxassist): correct blueprint description selector layout
Remove the cloned star-panel Localizer before sizing the production-basis selector so reopening options or changing languages cannot overwrite its stretched width.

Fill the main button and left-align selector text while preserving native inspector geometry and production calculations.
2026-11-04 22:02:55 +08:00
54 changed files with 1320 additions and 253 deletions

No files matched your search

@@ -1,10 +1,12 @@
using System; using System;
using UnityEngine; using UnityEngine;
using UXAssist.Common; using UXAssist.Common;
using UXAssist.Common.ModFeatures;
using CheatEnabler; using CheatEnabler;
namespace CheatEnabler.Functions.DysonSphere; namespace CheatEnabler.Functions.DysonSphere;
[ModFeature("DysonSphereResolver")]
public static class DysonSphereResolver public static class DysonSphereResolver
{ {
public static (global::DysonSphere sphere, StarData star)? ResolveCurrent() public static (global::DysonSphere sphere, StarData star)? ResolveCurrent()
@@ -3,11 +3,13 @@ using HarmonyLib;
using UnityEngine; using UnityEngine;
using UXAssist.Common; using UXAssist.Common;
using UXAssist.Common.GameConstants; using UXAssist.Common.GameConstants;
using UXAssist.Common.ModFeatures;
using UXAssist.Common.Utils; using UXAssist.Common.Utils;
using CheatEnabler; using CheatEnabler;
namespace CheatEnabler.Functions.DysonSphere; namespace CheatEnabler.Functions.DysonSphere;
[ModFeature("FrameRemovalFunctions")]
public static class FrameRemovalFunctions public static class FrameRemovalFunctions
{ {
public static void RemoveAllFrames() public static void RemoveAllFrames()
@@ -7,10 +7,12 @@ using static CheatEnabler.Functions.DysonSphere.GeometryHelpers;
using UnityEngine; using UnityEngine;
using UXAssist.Common; using UXAssist.Common;
using UXAssist.Common.GameConstants; using UXAssist.Common.GameConstants;
using UXAssist.Common.ModFeatures;
using CheatEnabler; using CheatEnabler;
namespace CheatEnabler.Functions.DysonSphere; namespace CheatEnabler.Functions.DysonSphere;
[ModFeature("IllegalShellFunctions")]
public static class IllegalShellFunctions public static class IllegalShellFunctions
{ {
private static void EnsureDysonShellMaps() private static void EnsureDysonShellMaps()
@@ -39,7 +41,7 @@ public static class IllegalShellFunctions
layer.shellCursor = 1; layer.shellCursor = 1;
} }
private static void FinalizeDysonSphereChanges(global::DysonSphere sphere, bool notify = false, bool resetRenderMasks = false) private static void FinalizeDysonSphereChanges(global::DysonSphere sphere, DysonSphereLayer layer, bool notify = false, bool resetRenderMasks = false)
{ {
if (sphere == null) return; if (sphere == null) return;
sphere.CheckAutoNodes(); sphere.CheckAutoNodes();
@@ -138,7 +140,7 @@ public static class IllegalShellFunctions
node.RecalcSpReq(); node.RecalcSpReq();
node.RecalcCpReq(); node.RecalcCpReq();
} }
FinalizeDysonSphereChanges(dysonSphere, true, true); FinalizeDysonSphereChanges(dysonSphere, layer, true, true);
} }
public static void KeepMaxProductionShells() public static void KeepMaxProductionShells()
@@ -243,7 +245,7 @@ public static class IllegalShellFunctions
node.RecalcCpReq(); node.RecalcCpReq();
} }
} }
FinalizeDysonSphereChanges(dysonSphere); FinalizeDysonSphereChanges(dysonSphere, null);
} }
public static void CreateIllegalDysonShellQuickly(int triangleCount) public static void CreateIllegalDysonShellQuickly(int triangleCount)
@@ -315,7 +317,7 @@ public static class IllegalShellFunctions
node.RecalcSpReq(); node.RecalcSpReq();
node.RecalcCpReq(); node.RecalcCpReq();
} }
FinalizeDysonSphereChanges(dysonSphere, true); FinalizeDysonSphereChanges(dysonSphere, layer, true);
return; return;
} }
} }
@@ -431,7 +433,7 @@ public static class IllegalShellFunctions
var shellsChanged = CreateIllegalDysonShellWithMaxOutputForLayer(layer); var shellsChanged = CreateIllegalDysonShellWithMaxOutputForLayer(layer);
FinalizeDysonSphereChanges(dysonSphere, shellsChanged, true); FinalizeDysonSphereChanges(dysonSphere, layer, shellsChanged, true);
} }
public static void CreateIllegalDysonShellWithMaxOutputForAllLayers() public static void CreateIllegalDysonShellWithMaxOutputForAllLayers()
@@ -447,7 +449,7 @@ public static class IllegalShellFunctions
shellsChanged = CreateIllegalDysonShellWithMaxOutputForLayer(layer) || shellsChanged; shellsChanged = CreateIllegalDysonShellWithMaxOutputForLayer(layer) || shellsChanged;
} }
FinalizeDysonSphereChanges(dysonSphere, shellsChanged, true); FinalizeDysonSphereChanges(dysonSphere, dysonSphere.layersSorted.FirstOrDefault(l => l != null), shellsChanged, true);
} }
public static void CreateIllegalDysonShellsSpecially() public static void CreateIllegalDysonShellsSpecially()
@@ -475,6 +477,8 @@ public static class IllegalShellFunctions
for (var idx = 1; idx <= 2; idx++) for (var idx = 1; idx <= 2; idx++)
{ {
Dictionary<(int, int), int> availableFrames = [];
HashSet<int> unusedFrameIds = [];
var layer = dysonSphere.layersIdBased[idx]; var layer = dysonSphere.layersIdBased[idx];
if (layer != null) if (layer != null)
{ {
@@ -567,6 +571,6 @@ public static class IllegalShellFunctions
} }
} }
FinalizeDysonSphereChanges(dysonSphere, shellsChanged, true); FinalizeDysonSphereChanges(dysonSphere, dysonSphere.layersIdBased[2], shellsChanged, true);
} }
} }
@@ -3,11 +3,13 @@ using System.Linq;
using HarmonyLib; using HarmonyLib;
using UnityEngine; using UnityEngine;
using UXAssist.Common; using UXAssist.Common;
using UXAssist.Common.ModFeatures;
using UXAssist.Common.Utils; using UXAssist.Common.Utils;
using CheatEnabler; using CheatEnabler;
namespace CheatEnabler.Functions.DysonSphere; namespace CheatEnabler.Functions.DysonSphere;
[ModFeature("ShellCompletionFunctions")]
public static class ShellCompletionFunctions public static class ShellCompletionFunctions
{ {
public static void CompleteShellsInstantly() public static void CompleteShellsInstantly()
@@ -1,9 +1,11 @@
using BepInEx.Configuration; using BepInEx.Configuration;
using CheatEnabler.Functions.DysonSphere; using CheatEnabler.Functions.DysonSphere;
using UXAssist.Common; using UXAssist.Common;
using UXAssist.Common.ModFeatures;
namespace CheatEnabler.Functions; namespace CheatEnabler.Functions;
[ModFeature("CheatDysonSphere", Order = 20)]
public static class DysonSphereFunctions public static class DysonSphereFunctions
{ {
public const int MinShellsCountForFunctions = 1; public const int MinShellsCountForFunctions = 1;
+3 -1
View File
@@ -1,7 +1,9 @@
using Random = UnityEngine.Random; using Random = UnityEngine.Random;
using UXAssist.Common.ModFeatures;
namespace CheatEnabler.Functions; namespace CheatEnabler.Functions;
[ModFeature("PlanetFunctions")]
public static class PlanetFunctions public static class PlanetFunctions
{ {
public static void BuryAllVeins(bool bury) public static void BuryAllVeins(bool bury)
@@ -33,4 +35,4 @@ public static class PlanetFunctions
} }
GameMain.gpuiManager.SyncAllGPUBuffer(); GameMain.gpuiManager.SyncAllGPUBuffer();
} }
} }
@@ -2,9 +2,11 @@
using System.Linq; using System.Linq;
using UXAssist.Common; using UXAssist.Common;
using UXAssist.Common.GameConstants; using UXAssist.Common.GameConstants;
using UXAssist.Common.ModFeatures;
namespace CheatEnabler.Functions; namespace CheatEnabler.Functions;
[ModFeature("PlayerFunctions")]
public static class PlayerFunctions public static class PlayerFunctions
{ {
public static void Init() public static void Init()
@@ -16,6 +16,7 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
private static Dictionary<int, BeltSignal>[] _signalBelts; private static Dictionary<int, BeltSignal>[] _signalBelts;
private static Dictionary<long, int> _portalFrom; private static Dictionary<long, int> _portalFrom;
private static Dictionary<int, HashSet<long>> _portalTo; private static Dictionary<int, HashSet<long>> _portalTo;
private static int _signalBeltsCapacity;
private static bool _initialized; private static bool _initialized;
private static ProductionCatalog _sourceCatalog; private static ProductionCatalog _sourceCatalog;
private static ProductionItem _preferredProliferator; private static ProductionItem _preferredProliferator;
@@ -49,6 +50,7 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
_signalBelts = null; _signalBelts = null;
_portalFrom = null; _portalFrom = null;
_portalTo = null; _portalTo = null;
_signalBeltsCapacity = 0;
PendingSources.Clear(); PendingSources.Clear();
ClearSourceCache(); ClearSourceCache();
} }
@@ -82,6 +84,7 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
GameLogicProc.OnGameBegin -= OnGameBegin; GameLogicProc.OnGameBegin -= OnGameBegin;
_initialized = false; _initialized = false;
_signalBelts = null; _signalBelts = null;
_signalBeltsCapacity = 0;
PendingSources.Clear(); PendingSources.Clear();
ClearSourceCache(); ClearSourceCache();
} }
@@ -178,6 +181,7 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
{ {
if (DSPGame.IsMenuDemo) return; if (DSPGame.IsMenuDemo) return;
_signalBelts = new Dictionary<int, BeltSignal>[64]; _signalBelts = new Dictionary<int, BeltSignal>[64];
_signalBeltsCapacity = 64;
_portalFrom = []; _portalFrom = [];
_portalTo = []; _portalTo = [];
@@ -221,12 +225,13 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
{ {
Dictionary<int, BeltSignal> obj; Dictionary<int, BeltSignal> obj;
if (index < 0) return null; if (index < 0) return null;
if (index >= _signalBelts.Length) if (index >= _signalBeltsCapacity)
{ {
var newCapacity = _signalBelts.Length * 2; var newCapacity = _signalBeltsCapacity * 2;
var newSignalBelts = new Dictionary<int, BeltSignal>[newCapacity]; var newSignalBelts = new Dictionary<int, BeltSignal>[newCapacity];
Array.Copy(_signalBelts, newSignalBelts, _signalBelts.Length); Array.Copy(_signalBelts, newSignalBelts, _signalBeltsCapacity);
_signalBelts = newSignalBelts; _signalBelts = newSignalBelts;
_signalBeltsCapacity = newCapacity;
} }
else else
{ {
@@ -241,7 +246,7 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
private static Dictionary<int, BeltSignal> GetSignalBelts(int index) private static Dictionary<int, BeltSignal> GetSignalBelts(int index)
{ {
return index >= 0 && _signalBelts != null && index < _signalBelts.Length ? _signalBelts[index] : null; return index >= 0 && index < _signalBeltsCapacity ? _signalBelts[index] : null;
} }
private static void SetSignalBelt(int factory, int beltId, int signalId, int number) private static void SetSignalBelt(int factory, int beltId, int signalId, int number)
+2 -30
View File
@@ -17,7 +17,7 @@ internal static class TechClickHandler
} }
catch (Exception e) catch (Exception e)
{ {
CheatEnabler.Logger.LogWarning($"[TechTweaks] click handling failed: {e}"); TechLog.Warn($"click handling failed: {e}");
} }
} }
@@ -40,7 +40,7 @@ internal static class TechClickHandler
return; return;
} }
if (!TryDecodeModifiers(out int steps)) if (!TechKeyCombo.TryDecode(out int steps))
{ {
return; return;
} }
@@ -54,32 +54,4 @@ internal static class TechClickHandler
TechUnlock.Run(history, techProto, steps); TechUnlock.Run(history, techProto, steps);
} }
} }
private static bool TryDecodeModifiers(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)
{
// Alt applies or reverts every level available to this click.
steps = int.MaxValue;
return true;
}
return false;
}
} }
+1 -1
View File
@@ -20,7 +20,7 @@ internal static class TechDowngrade
{ {
if (!TryGetLastAppliedLevel(history, techProto, out int lastApplied) || steps <= 0) return; if (!TryGetLastAppliedLevel(history, techProto, out int lastApplied) || steps <= 0) return;
int target = steps == int.MaxValue int target = steps == TechKeyCombo.LevelToMax
? techProto.Level - 1 ? techProto.Level - 1
: System.Math.Max(techProto.Level - 1, lastApplied - steps); : System.Math.Max(techProto.Level - 1, lastApplied - steps);
Targets.Clear(); Targets.Clear();
+4 -4
View File
@@ -410,7 +410,7 @@ namespace CheatEnabler.Patches.Tech
// a downgrade can walk thousands of levels and must not flood the log. // a downgrade can walk thousands of levels and must not flood the log.
if (UnknownFuncsWarned.Add(func)) if (UnknownFuncsWarned.Add(func))
{ {
CheatEnabler.Logger.LogWarning($"[TechTweaks] revert: no inverse known for tech function {func} (value={value}, level={level}); " + 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."); "the field was left untouched. A game update may have added a new function.");
} }
@@ -429,7 +429,7 @@ namespace CheatEnabler.Patches.Tech
ModeConfig freeMode = Configs.freeMode; ModeConfig freeMode = Configs.freeMode;
if (freeMode == null) if (freeMode == null)
{ {
CheatEnabler.Logger.LogWarning($"[TechTweaks] recompute of tech function {func} skipped: Configs.freeMode is not available"); TechLog.Warn($"recompute of tech function {func} skipped: Configs.freeMode is not available");
return; return;
} }
@@ -819,7 +819,7 @@ namespace CheatEnabler.Patches.Tech
if (Configs.freeMode == null || history.gameData == null || player?.mecha == null || if (Configs.freeMode == null || history.gameData == null || player?.mecha == null ||
player.package?.grids == null || player.deliveryPackage?.grids == null) player.package?.grids == null || player.deliveryPackage?.grids == null)
{ {
CheatEnabler.Logger.LogWarning("[TechTweaks] downgrade skipped: game data is not ready"); TechLog.Warn("downgrade skipped: game data is not ready");
return false; return false;
} }
@@ -836,7 +836,7 @@ namespace CheatEnabler.Patches.Tech
int func = proto.UnlockFunctions[j]; int func = proto.UnlockFunctions[j];
if (!(func is >= 1 and <= 45 or >= 61 and <= 86 or 99)) if (!(func is >= 1 and <= 45 or >= 61 and <= 86 or 99))
{ {
CheatEnabler.Logger.LogWarning($"[TechTweaks] downgrade skipped: unsupported tech function {func} in tech {proto.ID}"); TechLog.Warn($"downgrade skipped: unsupported tech function {func} in tech {proto.ID}");
UIRealtimeTip.Popup(Localization.TechDowngradeUnsupportedFunction.Translate()); UIRealtimeTip.Popup(Localization.TechDowngradeUnsupportedFunction.Translate());
return false; return false;
} }
+59
View File
@@ -0,0 +1,59 @@
namespace CheatEnabler.Patches.Tech;
/// <summary>
/// The key-modifier semantics shared by the upgrade and the downgrade side.
///
/// Both directions use the same modifier mapping:
///
/// <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);
}
}
+1 -1
View File
@@ -17,7 +17,7 @@ internal static class TechUnlock
{ {
// Mirrors the built-in maxLevel argument: "to MAX" passes the default, the other combinations // Mirrors the built-in maxLevel argument: "to MAX" passes the default, the other combinations
// pass -(steps) so the loop advances exactly `steps` levels. // pass -(steps) so the loop advances exactly `steps` levels.
int maxLevel = steps == int.MaxValue ? 10000 : -steps; int maxLevel = steps == TechKeyCombo.LevelToMax ? 10000 : -steps;
UnlockTechRecursive(history, techProto, maxLevel); UnlockTechRecursive(history, techProto, maxLevel);
+13 -5
View File
@@ -12,6 +12,8 @@ namespace CheatEnabler;
public static class UIConfigWindow public static class UIConfigWindow
{ {
private static RectTransform _windowTrans;
private static UIButton _resignGameBtn; private static UIButton _resignGameBtn;
private static UIButton _clearBanBtn; private static UIButton _clearBanBtn;
@@ -74,12 +76,13 @@ public static class UIConfigWindow
private static void CreateUI(MyConfigWindow wnd, RectTransform trans) private static void CreateUI(MyConfigWindow wnd, RectTransform trans)
{ {
_windowTrans = trans;
// General tab // General tab
var x = 0f; var x = 0f;
var y = 10f; var y = 10f;
wnd.AddSplitter(trans, 10f); wnd.AddSplitter(trans, 10f);
wnd.AddTabGroup(trans, "Cheat Enabler", "tab-group-cheatenabler"); wnd.AddTabGroup(trans, "Cheat Enabler", "tab-group-cheatenabler");
var tab1 = wnd.AddTab(trans, "General"); var tab1 = wnd.AddTab(_windowTrans, "General");
var cb = wnd.AddCheckBox(x, y, tab1, GamePatch.DevShortcutsEnabled, "Enable Dev Shortcuts"); var cb = wnd.AddCheckBox(x, y, tab1, GamePatch.DevShortcutsEnabled, "Enable Dev Shortcuts");
x += cb.Width + 5f; x += cb.Width + 5f;
y += 6f; y += 6f;
@@ -104,7 +107,7 @@ public static class UIConfigWindow
y = 10f; y = 10f;
_resignGameBtn = wnd.AddButton(x, y, 300f, tab1, "Assign gamesave to current account", 16, "resign-game-btn", () => { GameMain.data.account = AccountData.me; }); _resignGameBtn = wnd.AddButton(x, y, 300f, tab1, "Assign gamesave to current account", 16, "resign-game-btn", () => { GameMain.data.account = AccountData.me; });
var tab2 = wnd.AddTab(trans, "Factory"); var tab2 = wnd.AddTab(_windowTrans, "Factory");
x = 0f; x = 0f;
y = 10f; y = 10f;
wnd.AddCheckBox(x, y, tab2, FactoryPatch.ImmediateEnabled, "Finish build immediately"); wnd.AddCheckBox(x, y, tab2, FactoryPatch.ImmediateEnabled, "Finish build immediately");
@@ -167,7 +170,7 @@ public static class UIConfigWindow
wnd.AddText2(x + 32f, y, tab2, "Boost fuel power 2", 13); wnd.AddText2(x + 32f, y, tab2, "Boost fuel power 2", 13);
// Planet Tab // Planet Tab
var tab3 = wnd.AddTab(trans, "Planet"); var tab3 = wnd.AddTab(_windowTrans, "Planet");
x = 0f; x = 0f;
y = 10f; y = 10f;
wnd.AddCheckBox(x, y, tab3, ResourcePatch.InfiniteResourceEnabled, "Infinite Natural Resources"); wnd.AddCheckBox(x, y, tab3, ResourcePatch.InfiniteResourceEnabled, "Infinite Natural Resources");
@@ -204,7 +207,7 @@ public static class UIConfigWindow
GameMain.localPlanet.factory.PlanetReformRevert(); GameMain.localPlanet.factory.PlanetReformRevert();
}); });
var tab4 = wnd.AddTab(trans, "Dyson Sphere"); var tab4 = wnd.AddTab(_windowTrans, "Dyson Sphere");
x = 0f; x = 0f;
y = 10f; y = 10f;
wnd.AddCheckBox(x, y, tab4, DysonSpherePatch.SkipBulletEnabled, "Skip bullet period"); wnd.AddCheckBox(x, y, tab4, DysonSpherePatch.SkipBulletEnabled, "Skip bullet period");
@@ -296,7 +299,7 @@ public static class UIConfigWindow
} }
} }
var tab5 = wnd.AddTab(trans, "Mecha/Combat"); var tab5 = wnd.AddTab(_windowTrans, "Mecha/Combat");
x = 0f; x = 0f;
y = 10f; y = 10f;
wnd.AddCheckBox(x, y, tab5, CombatPatch.MechaInvincibleEnabled, "Mecha and Drones/Fleets invicible"); wnd.AddCheckBox(x, y, tab5, CombatPatch.MechaInvincibleEnabled, "Mecha and Drones/Fleets invicible");
@@ -312,6 +315,11 @@ public static class UIConfigWindow
} }
private static void UpdateUI() private static void UpdateUI()
{
UpdateButtons();
}
private static void UpdateButtons()
{ {
if (_resignGameBtn == null || _clearBanBtn == null) return; if (_resignGameBtn == null || _clearBanBtn == null) return;
var data = GameMain.data; var data = GameMain.data;
+23 -5
View File
@@ -28,14 +28,31 @@ public static class BeltSignal
} }
} }
private static Sprite LoadDustbinSprite() private static byte[] LoadEmbeddedResource(string path, Assembly assembly = null)
{ {
using var stream = Assembly.GetExecutingAssembly() if (assembly == null)
.GetManifestResourceStream("Dustbin.assets.icon.signal-410.png")!; {
assembly = Assembly.GetCallingAssembly();
}
var info = assembly.GetName();
var name = info.Name;
using var stream = assembly.GetManifestResourceStream($"{name}.{path.Replace('/', '.')}")!;
var buffer = new byte[stream.Length]; var buffer = new byte[stream.Length];
_ = stream.Read(buffer, 0, buffer.Length); _ = stream.Read(buffer, 0, buffer.Length);
return buffer;
}
private static Texture2D LoadEmbeddedTexture(string path, Assembly assembly = null)
{
var fileData = LoadEmbeddedResource(path, assembly);
var tex = new Texture2D(2, 2); var tex = new Texture2D(2, 2);
tex.LoadImage(buffer); tex.LoadImage(fileData);
return tex;
}
private static Sprite LoadEmbeddedSprite(string path, Assembly assembly = null)
{
var tex = LoadEmbeddedTexture(path, assembly);
return Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f)); return Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
} }
@@ -44,6 +61,7 @@ public static class BeltSignal
private static void VFPreload_InvokeOnLoadWorkEnded_Postfix() private static void VFPreload_InvokeOnLoadWorkEnded_Postfix()
{ {
if (_initialized) return; if (_initialized) return;
var assembly = Assembly.GetExecutingAssembly();
var signals = LDB._signals; var signals = LDB._signals;
var index = signals.dataArray.Length; var index = signals.dataArray.Length;
var p = new SignalProto var p = new SignalProto
@@ -52,7 +70,7 @@ public static class BeltSignal
Name = "DUSTBIN", Name = "DUSTBIN",
GridIndex = 3110, GridIndex = 3110,
IconPath = "Assets/signal-410.png", IconPath = "Assets/signal-410.png",
_iconSprite = LoadDustbinSprite(), _iconSprite = LoadEmbeddedSprite("assets/icon/signal-410.png", assembly),
SID = "" SID = ""
}; };
p.name = p.Name.Translate(); p.name = p.Name.Translate();
+87
View File
@@ -20,6 +20,9 @@ public class HideTips : BaseUnityPlugin
private static bool _noResearchCompletionPopups = true; private static bool _noResearchCompletionPopups = true;
private static bool _noResearchCompletionTips; private static bool _noResearchCompletionTips;
private static bool _skipPrologue = true; private static bool _skipPrologue = true;
// private static bool _hideMenuDemo;
private static Harmony _patch;
private void Awake() private void Awake()
{ {
@@ -31,8 +34,21 @@ public class HideTips : BaseUnityPlugin
_noResearchCompletionPopups = Config.Bind("General", "NoResearchCompletionPopups", _noResearchCompletionPopups, "Disable Research Completion Popup Windows").Value; _noResearchCompletionPopups = Config.Bind("General", "NoResearchCompletionPopups", _noResearchCompletionPopups, "Disable Research Completion Popup Windows").Value;
_noResearchCompletionTips = Config.Bind("General", "NoResearchCompletionTips", _noResearchCompletionTips, "Disable Research Completion Tips").Value; _noResearchCompletionTips = Config.Bind("General", "NoResearchCompletionTips", _noResearchCompletionTips, "Disable Research Completion Tips").Value;
_skipPrologue = Config.Bind("General", "SkipPrologue", _skipPrologue, "Skip prologue for new game").Value; _skipPrologue = Config.Bind("General", "SkipPrologue", _skipPrologue, "Skip prologue for new game").Value;
// _hideMenuDemo = Config.Bind("General", "HideMenuDemo", _hideMenuDemo, "Disable title screen demo scene loading").Value;
if (!_cfgEnabled) return; if (!_cfgEnabled) return;
Harmony.CreateAndPatchAll(typeof(HideTips)); Harmony.CreateAndPatchAll(typeof(HideTips));
/*
if (_hideMenuDemo)
{
_patch = Harmony.CreateAndPatchAll(typeof(HideMenuDemo));
}
*/
}
private void OnDestroy()
{
_patch?.UnpatchSelf();
_patch = null;
} }
[HarmonyPrefix] [HarmonyPrefix]
@@ -130,3 +146,74 @@ public class HideTips : BaseUnityPlugin
return false; return false;
} }
} }
/*
[HarmonyPatch]
class HideMenuDemo
{
[HarmonyPriority(Priority.First), HarmonyPrefix]
[HarmonyPatch(typeof(DSPGame), nameof(DSPGame.StartDemoGame), typeof(int))]
private static bool DSPGame_StartDemoGame_Prefix()
{
if (DSPGame.Game != null)
{
DSPGame.EndGame();
}
DSPGame.IsMenuDemo = true;
DSPGame.CreateGameMainObject();
DSPGame.Game.isMenuDemo = true;
DSPGame.Game.CreateIconSet();
GameMain.data = new GameData();
GameMain.data.mainPlayer = Player.Create(GameMain.data, 1);
GameMain.data.galaxy = new GalaxyData
{
starCount = 0
};
if (GameMain.universeSimulator != null)
{
UnityEngine.Object.Destroy(GameMain.universeSimulator.gameObject);
}
GameMain.universeSimulator = UnityEngine.Object.Instantiate(Configs.builtin.universeSimulatorPrefab);
GameMain.universeSimulator.spaceAudio = new GameObject("Space Audio")
{
transform =
{
parent = GameMain.universeSimulator.transform
}
}.AddComponent<SpaceAudio>();
GameMain.Begin();
return false;
}
[HarmonyPriority(Priority.First), HarmonyPrefix]
[HarmonyPatch(typeof(VFPreload), nameof(VFPreload.IsMenuDemoLoaded))]
private static bool VFPreload_IsMenuDemoLoaded_Prefix(ref bool __result)
{
__result = true;
return false;
}
[HarmonyPriority(Priority.First), HarmonyPrefix]
[HarmonyPatch(typeof(DSPGame), nameof(DSPGame.LateUpdate))]
[HarmonyPatch(typeof(GameMain), nameof(GameMain.LateUpdate))]
[HarmonyPatch(typeof(GameMain), nameof(GameMain.FixedUpdate))]
[HarmonyPatch(typeof(GameMain), nameof(GameMain.Update))]
[HarmonyPatch(typeof(GameCamera), nameof(GameCamera.LateUpdate))]
private static bool DSPGame_LateUpdate_Prefix()
{
return !DSPGame.IsMenuDemo;
}
[HarmonyPriority(Priority.First), HarmonyPrefix]
[HarmonyPatch(typeof(GameMain), nameof(GameMain.Begin))]
private static bool GameMain_Begin_Prefix()
{
if (!DSPGame.IsMenuDemo) return true;
DSPGame.Game._loading = false;
DSPGame.Game._running = true;
return false;
}
}
*/
+15 -5
View File
@@ -21,6 +21,17 @@ function New-OpCts {
[Threading.CancellationTokenSource]::new([TimeSpan]::FromSeconds($TimeoutSec)) [Threading.CancellationTokenSource]::new([TimeSpan]::FromSeconds($TimeoutSec))
} }
function Get-ConnSocket {
param($Conn)
if ($null -eq $Conn) { return $null }
if ($Conn -is [hashtable]) {
if ($Conn.ContainsKey('Ws')) { return $Conn['Ws'] }
return $null
}
if ($Conn.PSObject.Properties.Name -contains 'Ws') { return $Conn.Ws }
return $null
}
function Connect-Api { function Connect-Api {
param([string] $Uri) param([string] $Uri)
$ws = [Net.WebSockets.ClientWebSocket]::new() $ws = [Net.WebSockets.ClientWebSocket]::new()
@@ -38,8 +49,7 @@ function Connect-Api {
function Close-Api { function Close-Api {
param($Conn) param($Conn)
if ($null -eq $Conn) { return } $ws = Get-ConnSocket $Conn
$ws = $Conn.Ws
if ($null -eq $ws) { return } if ($null -eq $ws) { return }
$cts = New-OpCts $cts = New-OpCts
try { try {
@@ -54,7 +64,7 @@ function Close-Api {
function Send-Text { function Send-Text {
param($Conn, [string] $Text, [bool] $End = $true) param($Conn, [string] $Text, [bool] $End = $true)
$ws = $Conn.Ws $ws = Get-ConnSocket $Conn
$bytes = $utf8.GetBytes($Text) $bytes = $utf8.GetBytes($Text)
$seg = [ArraySegment[byte]]::new($bytes) $seg = [ArraySegment[byte]]::new($bytes)
$cts = New-OpCts $cts = New-OpCts
@@ -65,7 +75,7 @@ function Send-Text {
function Receive-Message { function Receive-Message {
param($Conn) param($Conn)
$ws = $Conn.Ws $ws = Get-ConnSocket $Conn
$buffer = [byte[]]::new(65536) $buffer = [byte[]]::new(65536)
$ms = [IO.MemoryStream]::new() $ms = [IO.MemoryStream]::new()
$cts = New-OpCts $cts = New-OpCts
@@ -173,7 +183,7 @@ try {
$cts = New-OpCts $cts = New-OpCts
try { try {
$null = $conn.Ws.SendAsync( $null = (Get-ConnSocket $conn).SendAsync(
[ArraySegment[byte]]::new([byte[]](1, 2, 3)), [ArraySegment[byte]]::new([byte[]](1, 2, 3)),
[Net.WebSockets.WebSocketMessageType]::Binary, [Net.WebSockets.WebSocketMessageType]::Binary,
$true, $true,
+25
View File
@@ -0,0 +1,25 @@
using HarmonyLib;
namespace MechaDronesTweaks;
class FastDronesRemover
{
public const string FastDronesGuid = "com.dkoppstein.plugin.DSP.FastDrones";
private const string FastDronesVersion = "0.0.5";
public static bool Run(Harmony harmony)
{
if (!BepInEx.Bootstrap.Chainloader.PluginInfos.TryGetValue(FastDronesGuid, out var pluginInfo) ||
pluginInfo.Metadata.Version.ToString() != FastDronesVersion) return false;
var assembly = pluginInfo.Instance.GetType().Assembly;
var classType = assembly.GetType("com.dkoppstein.plugin.DSP.FastDrones.FastDronesPlugin");
harmony.Patch(AccessTools.Method(classType, "Start"),
new HarmonyMethod(typeof(FastDronesRemover).GetMethod("PatchFastDronesStart")));
return true;
}
public static bool PatchFastDronesStart()
{
return false;
}
}
+6 -11
View File
@@ -9,11 +9,9 @@ using UnityEngine;
namespace MechaDronesTweaks; namespace MechaDronesTweaks;
[BepInPlugin(PluginInfo.PLUGIN_GUID, PluginInfo.PLUGIN_NAME, PluginInfo.PLUGIN_VERSION)] [BepInPlugin(PluginInfo.PLUGIN_GUID, PluginInfo.PLUGIN_NAME, PluginInfo.PLUGIN_VERSION)]
[BepInDependency(FastDronesGuid, BepInDependency.DependencyFlags.SoftDependency)] [BepInDependency(FastDronesRemover.FastDronesGuid, BepInDependency.DependencyFlags.SoftDependency)]
public class MechaDronesTweaksPlugin : BaseUnityPlugin public class MechaDronesTweaksPlugin : BaseUnityPlugin
{ {
private const string FastDronesGuid = "com.dkoppstein.plugin.DSP.FastDrones";
public new static readonly BepInEx.Logging.ManualLogSource Logger = public new static readonly BepInEx.Logging.ManualLogSource Logger =
BepInEx.Logging.Logger.CreateLogSource(PluginInfo.PLUGIN_NAME); BepInEx.Logging.Logger.CreateLogSource(PluginInfo.PLUGIN_NAME);
@@ -24,13 +22,8 @@ public class MechaDronesTweaksPlugin : BaseUnityPlugin
/* Remove FastDrones MOD if loaded */ /* Remove FastDrones MOD if loaded */
try try
{ {
if (BepInEx.Bootstrap.Chainloader.PluginInfos.TryGetValue(FastDronesGuid, out var pluginInfo) && if (FastDronesRemover.Run(_harmony))
pluginInfo.Metadata.Version.ToString() == "0.0.5")
{ {
var assembly = pluginInfo.Instance.GetType().Assembly;
var classType = assembly.GetType("com.dkoppstein.plugin.DSP.FastDrones.FastDronesPlugin");
_harmony.Patch(AccessTools.Method(classType, "Start"),
new HarmonyMethod(AccessTools.Method(typeof(MechaDronesTweaksPlugin), nameof(PatchFastDronesStart))));
Logger.LogInfo("Unpatch FastDrones - OK"); Logger.LogInfo("Unpatch FastDrones - OK");
} }
} }
@@ -40,8 +33,6 @@ public class MechaDronesTweaksPlugin : BaseUnityPlugin
} }
} }
private static bool PatchFastDronesStart() => false;
public void Awake() public void Awake()
{ {
MechaDronesTweaks.UseFixedSpeed = Config.Bind("MechaDrones", "UseFixedSpeed", MechaDronesTweaks.UseFixedSpeed, MechaDronesTweaks.UseFixedSpeed = Config.Bind("MechaDrones", "UseFixedSpeed", MechaDronesTweaks.UseFixedSpeed,
@@ -63,6 +54,10 @@ public class MechaDronesTweaksPlugin : BaseUnityPlugin
MechaDronesTweaks.EnergyMultiplier, MechaDronesTweaks.EnergyMultiplier,
new ConfigDescription("Energy consumption multiplier for mecha drones", new ConfigDescription("Energy consumption multiplier for mecha drones",
new AcceptableValueRange<float>(0f, 1f))).Value; new AcceptableValueRange<float>(0f, 1f))).Value;
MechaDronesTweaks.EnergyMultiplier = Config.Bind("MechaDrones", "EnergyMultiplier",
MechaDronesTweaks.EnergyMultiplier,
new ConfigDescription("Energy consumption multiplier for mecha drones",
new AcceptableValueRange<float>(0f, 1f))).Value;
_harmony.PatchAll(typeof(MechaDronesTweaks)); _harmony.PatchAll(typeof(MechaDronesTweaks));
} }
+42 -1
View File
@@ -104,6 +104,21 @@ public class Patch : BaseUnityPlugin, IModCanSave
{ {
} }
/* Belt fix for GalacticScale old versions, should be of no use now.
[HarmonyTranspiler, HarmonyPatch(typeof(BuildTool_Path), "CheckBuildConditions")]
private static IEnumerable<CodeInstruction> BuildTool_Path_CheckBuildConditions_Transpiler(
IEnumerable<CodeInstruction> instructions)
{
foreach (var instr in instructions)
{
if (instr.opcode == OpCodes.Ldc_R4 && instr.OperandIs(0.28f))
{
instr.operand = 0.21f;
}
yield return instr;
}
}
*/
[HarmonyPostfix, HarmonyPatch(typeof(LabComponent), "SetFunction")] [HarmonyPostfix, HarmonyPatch(typeof(LabComponent), "SetFunction")]
private static void LabComponent_SetFunction_Postfix(ref LabComponent __instance) private static void LabComponent_SetFunction_Postfix(ref LabComponent __instance)
@@ -365,6 +380,20 @@ public class Patch : BaseUnityPlugin, IModCanSave
foreach (var proto in LDB.items.dataArray) foreach (var proto in LDB.items.dataArray)
{ {
var prefabDesc = proto.prefabDesc; var prefabDesc = proto.prefabDesc;
/* Fix collision sizes, for GalacticScale old versions, should be of no use now.
FixExtValue(ref prefabDesc.buildCollider.ext.x);
FixExtValue(ref prefabDesc.buildCollider.ext.y);
FixExtValue(ref prefabDesc.buildCollider.ext.z);
if (prefabDesc.buildColliders != null)
{
for (var i = 0; i < prefabDesc.buildColliders.Length; i++)
{
FixExtValue(ref prefabDesc.buildColliders[i].ext.x);
FixExtValue(ref prefabDesc.buildColliders[i].ext.y);
FixExtValue(ref prefabDesc.buildColliders[i].ext.z);
}
}
*/
if (prefabDesc.isInserter) if (prefabDesc.isInserter)
{ {
@@ -443,4 +472,16 @@ public class Patch : BaseUnityPlugin, IModCanSave
} }
} }
} /*
private static void FixExtValue(ref float v)
{
if (v == 0f)
{
return;
}
var b = Math.Abs(v);
v = (v - b) * 0.75f + b;
}
*/
}
+109 -70
View File
@@ -24,23 +24,23 @@ public class PoolOptPatch : BaseUnityPlugin
foreach (var planet in GameMain.data.factories) foreach (var planet in GameMain.data.factories)
{ {
if (planet == null) continue; if (planet == null) continue;
if (OptimizePool((in EntityData n, int index) => n.id == index, () => if (OptimizePool((in EntityData n) => n.id, () =>
{ {
planet.entityCapacity = 0; planet.entityCapacity = 0;
planet.SetEntityCapacity(1024); planet.SetEntityCapacity(1024);
}, },
ref planet.entityPool, ref planet.entityCursor, ref planet.entityPool, ref planet.entityCursor, ref planet.entityCapacity,
ref planet.entityRecycle, ref planet.entityRecycleCursor)) ref planet.entityRecycle, ref planet.entityRecycleCursor))
{ {
Logger.LogDebug($"Optimized `{nameof(planet.entityPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(planet.entityPool)}` on Planet {planet.planetId}");
} }
if (OptimizePool((in PrebuildData n, int index) => n.id == index, () => if (OptimizePool((in PrebuildData n) => n.id, () =>
{ {
planet.prebuildCapacity = 0; planet.prebuildCapacity = 0;
planet.SetPrebuildCapacity(256); planet.SetPrebuildCapacity(256);
}, },
ref planet.prebuildPool, ref planet.prebuildCursor, ref planet.prebuildPool, ref planet.prebuildCursor, ref planet.prebuildCapacity,
ref planet.prebuildRecycle, ref planet.prebuildRecycleCursor)) ref planet.prebuildRecycle, ref planet.prebuildRecycleCursor))
{ {
Logger.LogDebug($"Optimized `{nameof(planet.prebuildPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(planet.prebuildPool)}` on Planet {planet.planetId}");
@@ -49,152 +49,152 @@ public class PoolOptPatch : BaseUnityPlugin
var cargoTraffic = planet.cargoTraffic; var cargoTraffic = planet.cargoTraffic;
if (cargoTraffic != null) if (cargoTraffic != null)
{ {
if (OptimizePool((in BeltComponent n, int index) => n.id == index, () => if (OptimizePool((in BeltComponent n) => n.id, () =>
{ {
cargoTraffic.beltCapacity = 0; cargoTraffic.beltCapacity = 0;
cargoTraffic.SetBeltCapacity(16); cargoTraffic.SetBeltCapacity(16);
}, },
ref cargoTraffic.beltPool, ref cargoTraffic.beltCursor, ref cargoTraffic.beltPool, ref cargoTraffic.beltCursor, ref cargoTraffic.beltCapacity,
ref cargoTraffic.beltRecycle, ref cargoTraffic.beltRecycleCursor)) ref cargoTraffic.beltRecycle, ref cargoTraffic.beltRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(cargoTraffic.beltPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(cargoTraffic.beltPool)}` on Planet {planet.planetId}");
if (OptimizePool((in CargoPath n, int index) => (n?.id ?? 0) == index, () => if (OptimizePool((in CargoPath n) => n?.id ?? 0, () =>
{ {
cargoTraffic.pathCapacity = 0; cargoTraffic.pathCapacity = 0;
cargoTraffic.SetPathCapacity(16); cargoTraffic.SetPathCapacity(16);
}, },
ref cargoTraffic.pathPool, ref cargoTraffic.pathCursor, ref cargoTraffic.pathPool, ref cargoTraffic.pathCursor, ref cargoTraffic.pathCapacity,
ref cargoTraffic.pathRecycle, ref cargoTraffic.pathRecycleCursor)) ref cargoTraffic.pathRecycle, ref cargoTraffic.pathRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(cargoTraffic.pathPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(cargoTraffic.pathPool)}` on Planet {planet.planetId}");
if (OptimizePool((in SplitterComponent n, int index) => n.id == index, () => if (OptimizePool((in SplitterComponent n) => n.id, () =>
{ {
cargoTraffic.splitterCapacity = 0; cargoTraffic.splitterCapacity = 0;
cargoTraffic.SetSplitterCapacity(16); cargoTraffic.SetSplitterCapacity(16);
}, },
ref cargoTraffic.splitterPool, ref cargoTraffic.splitterCursor, ref cargoTraffic.splitterPool, ref cargoTraffic.splitterCursor, ref cargoTraffic.splitterCapacity,
ref cargoTraffic.splitterRecycle, ref cargoTraffic.splitterRecycleCursor)) ref cargoTraffic.splitterRecycle, ref cargoTraffic.splitterRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(cargoTraffic.splitterPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(cargoTraffic.splitterPool)}` on Planet {planet.planetId}");
if (OptimizePool((in MonitorComponent n, int index) => n.id == index, () => if (OptimizePool((in MonitorComponent n) => n.id, () =>
{ {
cargoTraffic.monitorCapacity = 0; cargoTraffic.monitorCapacity = 0;
cargoTraffic.SetMonitorCapacity(16); cargoTraffic.SetMonitorCapacity(16);
}, },
ref cargoTraffic.monitorPool, ref cargoTraffic.monitorCursor, ref cargoTraffic.monitorPool, ref cargoTraffic.monitorCursor, ref cargoTraffic.monitorCapacity,
ref cargoTraffic.monitorRecycle, ref cargoTraffic.monitorRecycleCursor)) ref cargoTraffic.monitorRecycle, ref cargoTraffic.monitorRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(cargoTraffic.monitorPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(cargoTraffic.monitorPool)}` on Planet {planet.planetId}");
if (OptimizePool((in SpraycoaterComponent n, int index) => n.id == index, () => if (OptimizePool((in SpraycoaterComponent n) => n.id, () =>
{ {
cargoTraffic.spraycoaterCapacity = 0; cargoTraffic.spraycoaterCapacity = 0;
cargoTraffic.SetSpraycoaterCapacity(16); cargoTraffic.SetSpraycoaterCapacity(16);
}, },
ref cargoTraffic.spraycoaterPool, ref cargoTraffic.spraycoaterCursor, ref cargoTraffic.spraycoaterPool, ref cargoTraffic.spraycoaterCursor, ref cargoTraffic.spraycoaterCapacity,
ref cargoTraffic.spraycoaterRecycle, ref cargoTraffic.spraycoaterRecycleCursor)) ref cargoTraffic.spraycoaterRecycle, ref cargoTraffic.spraycoaterRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(cargoTraffic.spraycoaterPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(cargoTraffic.spraycoaterPool)}` on Planet {planet.planetId}");
if (OptimizePool((in PilerComponent n, int index) => n.id == index, () => if (OptimizePool((in PilerComponent n) => n.id, () =>
{ {
cargoTraffic.pilerCapacity = 0; cargoTraffic.pilerCapacity = 0;
cargoTraffic.SetPilerCapacity(16); cargoTraffic.SetPilerCapacity(16);
}, },
ref cargoTraffic.pilerPool, ref cargoTraffic.pilerCursor, ref cargoTraffic.pilerPool, ref cargoTraffic.pilerCursor, ref cargoTraffic.pilerCapacity,
ref cargoTraffic.pilerRecycle, ref cargoTraffic.pilerRecycleCursor)) ref cargoTraffic.pilerRecycle, ref cargoTraffic.pilerRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(cargoTraffic.pilerPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(cargoTraffic.pilerPool)}` on Planet {planet.planetId}");
} }
var factoryStorage = planet.factoryStorage; var factoryStorage = planet.factoryStorage;
if (factoryStorage != null) if (factoryStorage != null)
{ {
if (OptimizePool((in StorageComponent n, int index) => (n?.id ?? 0) == index, () => if (OptimizePool((in StorageComponent n) => n?.id ?? 0, () =>
{ {
factoryStorage.storageCapacity = 0; factoryStorage.storageCapacity = 0;
factoryStorage.SetStorageCapacity(64); factoryStorage.SetStorageCapacity(64);
}, },
ref factoryStorage.storagePool, ref factoryStorage.storageCursor, ref factoryStorage.storagePool, ref factoryStorage.storageCursor, ref factoryStorage.storageCapacity,
ref factoryStorage.storageRecycle, ref factoryStorage.storageRecycleCursor)) ref factoryStorage.storageRecycle, ref factoryStorage.storageRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(factoryStorage.storagePool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(factoryStorage.storagePool)}` on Planet {planet.planetId}");
if (OptimizePool((in TankComponent n, int index) => n.id == index, () => if (OptimizePool((in TankComponent n) => n.id, () =>
{ {
factoryStorage.tankCapacity = 0; factoryStorage.tankCapacity = 0;
factoryStorage.SetTankCapacity(256); factoryStorage.SetTankCapacity(256);
}, },
ref factoryStorage.tankPool, ref factoryStorage.tankCursor, ref factoryStorage.tankPool, ref factoryStorage.tankCursor, ref factoryStorage.tankCapacity,
ref factoryStorage.tankRecycle, ref factoryStorage.tankRecycleCursor)) ref factoryStorage.tankRecycle, ref factoryStorage.tankRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(factoryStorage.tankPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(factoryStorage.tankPool)}` on Planet {planet.planetId}");
} }
var factorySystem = planet.factorySystem; var factorySystem = planet.factorySystem;
if (factorySystem != null) if (factorySystem != null)
{ {
if (OptimizePool((in MinerComponent n, int index) => n.id == index, () => if (OptimizePool((in MinerComponent n) => n.id, () =>
{ {
factorySystem.minerCapacity = 0; factorySystem.minerCapacity = 0;
factorySystem.SetMinerCapacity(256); factorySystem.SetMinerCapacity(256);
}, },
ref factorySystem.minerPool, ref factorySystem.minerCursor, ref factorySystem.minerPool, ref factorySystem.minerCursor, ref factorySystem.minerCapacity,
ref factorySystem.minerRecycle, ref factorySystem.minerRecycleCursor)) ref factorySystem.minerRecycle, ref factorySystem.minerRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(factorySystem.minerPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(factorySystem.minerPool)}` on Planet {planet.planetId}");
if (OptimizePool((in InserterComponent n, int index) => n.id == index, () => if (OptimizePool((in InserterComponent n) => n.id, () =>
{ {
factorySystem.inserterCapacity = 0; factorySystem.inserterCapacity = 0;
factorySystem.SetInserterCapacity(256); factorySystem.SetInserterCapacity(256);
}, },
ref factorySystem.inserterPool, ref factorySystem.inserterCursor, ref factorySystem.inserterPool, ref factorySystem.inserterCursor, ref factorySystem.inserterCapacity,
ref factorySystem.inserterRecycle, ref factorySystem.inserterRecycleCursor)) ref factorySystem.inserterRecycle, ref factorySystem.inserterRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(factorySystem.inserterPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(factorySystem.inserterPool)}` on Planet {planet.planetId}");
if (OptimizePool((in AssemblerComponent n, int index) => n.id == index, () => if (OptimizePool((in AssemblerComponent n) => n.id, () =>
{ {
factorySystem.assemblerCapacity = 0; factorySystem.assemblerCapacity = 0;
factorySystem.SetAssemblerCapacity(256); factorySystem.SetAssemblerCapacity(256);
}, },
ref factorySystem.assemblerPool, ref factorySystem.assemblerCursor, ref factorySystem.assemblerPool, ref factorySystem.assemblerCursor, ref factorySystem.assemblerCapacity,
ref factorySystem.assemblerRecycle, ref factorySystem.assemblerRecycleCursor)) ref factorySystem.assemblerRecycle, ref factorySystem.assemblerRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(factorySystem.assemblerPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(factorySystem.assemblerPool)}` on Planet {planet.planetId}");
if (OptimizePool((in FractionatorComponent n, int index) => n.id == index, () => if (OptimizePool((in FractionatorComponent n) => n.id, () =>
{ {
factorySystem.fractionatorCapacity = 0; factorySystem.fractionatorCapacity = 0;
factorySystem.SetFractionatorCapacity(32); factorySystem.SetFractionatorCapacity(32);
}, },
ref factorySystem.fractionatorPool, ref factorySystem.fractionatorCursor, ref factorySystem.fractionatorPool, ref factorySystem.fractionatorCursor, ref factorySystem.fractionatorCapacity,
ref factorySystem.fractionatorRecycle, ref factorySystem.fractionatorRecycleCursor)) ref factorySystem.fractionatorRecycle, ref factorySystem.fractionatorRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(factorySystem.fractionatorPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(factorySystem.fractionatorPool)}` on Planet {planet.planetId}");
if (OptimizePool((in EjectorComponent n, int index) => n.id == index, () => if (OptimizePool((in EjectorComponent n) => n.id, () =>
{ {
factorySystem.ejectorCapacity = 0; factorySystem.ejectorCapacity = 0;
factorySystem.SetEjectorCapacity(32); factorySystem.SetEjectorCapacity(32);
}, },
ref factorySystem.ejectorPool, ref factorySystem.ejectorCursor, ref factorySystem.ejectorPool, ref factorySystem.ejectorCursor, ref factorySystem.ejectorCapacity,
ref factorySystem.ejectorRecycle, ref factorySystem.ejectorRecycleCursor)) ref factorySystem.ejectorRecycle, ref factorySystem.ejectorRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(factorySystem.ejectorPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(factorySystem.ejectorPool)}` on Planet {planet.planetId}");
if (OptimizePool((in SiloComponent n, int index) => n.id == index, () => if (OptimizePool((in SiloComponent n) => n.id, () =>
{ {
factorySystem.siloCapacity = 0; factorySystem.siloCapacity = 0;
factorySystem.SetSiloCapacity(32); factorySystem.SetSiloCapacity(32);
}, },
ref factorySystem.siloPool, ref factorySystem.siloCursor, ref factorySystem.siloPool, ref factorySystem.siloCursor, ref factorySystem.siloCapacity,
ref factorySystem.siloRecycle, ref factorySystem.siloRecycleCursor)) ref factorySystem.siloRecycle, ref factorySystem.siloRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(factorySystem.siloPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(factorySystem.siloPool)}` on Planet {planet.planetId}");
if (OptimizePool((in LabComponent n, int index) => n.id == index, () => if (OptimizePool((in LabComponent n) => n.id, () =>
{ {
factorySystem.labCapacity = 0; factorySystem.labCapacity = 0;
factorySystem.SetLabCapacity(256); factorySystem.SetLabCapacity(256);
}, },
ref factorySystem.labPool, ref factorySystem.labCursor, ref factorySystem.labPool, ref factorySystem.labCursor, ref factorySystem.labCapacity,
ref factorySystem.labRecycle, ref factorySystem.labRecycleCursor)) ref factorySystem.labRecycle, ref factorySystem.labRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(factorySystem.labPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(factorySystem.labPool)}` on Planet {planet.planetId}");
} }
var transport = planet.transport; var transport = planet.transport;
if (transport != null) if (transport != null)
{ {
if (OptimizePool((in StationComponent n, int index) => (n?.id ?? 0) == index, () => if (OptimizePool((in StationComponent n) => n?.id ?? 0, () =>
{ {
transport.stationCapacity = 0; transport.stationCapacity = 0;
transport.SetStationCapacity(16); transport.SetStationCapacity(16);
}, },
ref transport.stationPool, ref transport.stationCursor, ref transport.stationPool, ref transport.stationCursor, ref transport.stationCapacity,
ref transport.stationRecycle, ref transport.stationRecycleCursor)) ref transport.stationRecycle, ref transport.stationRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(transport.stationPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(transport.stationPool)}` on Planet {planet.planetId}");
if (OptimizePool((in DispenserComponent n, int index) => (n?.id ?? 0) == index, () => if (OptimizePool((in DispenserComponent n) => n?.id ?? 0, () =>
{ {
transport.dispenserCapacity = 0; transport.dispenserCapacity = 0;
transport.SetDispenserCapacity(8); transport.SetDispenserCapacity(8);
}, },
ref transport.dispenserPool, ref transport.dispenserCursor, ref transport.dispenserPool, ref transport.dispenserCursor, ref transport.dispenserCapacity,
ref transport.dispenserRecycle, ref transport.dispenserRecycleCursor)) ref transport.dispenserRecycle, ref transport.dispenserRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(transport.dispenserPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(transport.dispenserPool)}` on Planet {planet.planetId}");
} }
@@ -202,54 +202,54 @@ public class PoolOptPatch : BaseUnityPlugin
var powerSystem = planet.powerSystem; var powerSystem = planet.powerSystem;
if (powerSystem != null) if (powerSystem != null)
{ {
if (OptimizePool((in PowerGeneratorComponent n, int index) => n.id == index, () => if (OptimizePool((in PowerGeneratorComponent n) => n.id, () =>
{ {
powerSystem.genCapacity = 0; powerSystem.genCapacity = 0;
powerSystem.SetGeneratorCapacity(8); powerSystem.SetGeneratorCapacity(8);
}, },
ref powerSystem.genPool, ref powerSystem.genCursor, ref powerSystem.genPool, ref powerSystem.genCursor, ref powerSystem.genCapacity,
ref powerSystem.genRecycle, ref powerSystem.genRecycleCursor)) ref powerSystem.genRecycle, ref powerSystem.genRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(powerSystem.genPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(powerSystem.genPool)}` on Planet {planet.planetId}");
if (OptimizePool((in PowerNodeComponent n, int index) => n.id == index, () => if (OptimizePool((in PowerNodeComponent n) => n.id, () =>
{ {
powerSystem.nodeCapacity = 0; powerSystem.nodeCapacity = 0;
powerSystem.SetNodeCapacity(8); powerSystem.SetNodeCapacity(8);
}, },
ref powerSystem.nodePool, ref powerSystem.nodeCursor, ref powerSystem.nodePool, ref powerSystem.nodeCursor, ref powerSystem.nodeCapacity,
ref powerSystem.nodeRecycle, ref powerSystem.nodeRecycleCursor)) ref powerSystem.nodeRecycle, ref powerSystem.nodeRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(powerSystem.nodePool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(powerSystem.nodePool)}` on Planet {planet.planetId}");
if (OptimizePool((in PowerConsumerComponent n, int index) => n.id == index, () => if (OptimizePool((in PowerConsumerComponent n) => n.id, () =>
{ {
powerSystem.consumerCapacity = 0; powerSystem.consumerCapacity = 0;
powerSystem.SetConsumerCapacity(8); powerSystem.SetConsumerCapacity(8);
}, },
ref powerSystem.consumerPool, ref powerSystem.consumerCursor, ref powerSystem.consumerPool, ref powerSystem.consumerCursor, ref powerSystem.consumerCapacity,
ref powerSystem.consumerRecycle, ref powerSystem.consumerRecycleCursor)) ref powerSystem.consumerRecycle, ref powerSystem.consumerRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(powerSystem.consumerPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(powerSystem.consumerPool)}` on Planet {planet.planetId}");
if (OptimizePool((in PowerAccumulatorComponent n, int index) => n.id == index, () => if (OptimizePool((in PowerAccumulatorComponent n) => n.id, () =>
{ {
powerSystem.accCapacity = 0; powerSystem.accCapacity = 0;
powerSystem.SetAccumulatorCapacity(8); powerSystem.SetAccumulatorCapacity(8);
}, },
ref powerSystem.accPool, ref powerSystem.accCursor, ref powerSystem.accPool, ref powerSystem.accCursor, ref powerSystem.accCapacity,
ref powerSystem.accRecycle, ref powerSystem.accRecycleCursor)) ref powerSystem.accRecycle, ref powerSystem.accRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(powerSystem.accPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(powerSystem.accPool)}` on Planet {planet.planetId}");
if (OptimizePool((in PowerExchangerComponent n, int index) => n.id == index, () => if (OptimizePool((in PowerExchangerComponent n) => n.id, () =>
{ {
powerSystem.excCapacity = 0; powerSystem.excCapacity = 0;
powerSystem.SetExchangerCapacity(8); powerSystem.SetExchangerCapacity(8);
}, },
ref powerSystem.excPool, ref powerSystem.excCursor, ref powerSystem.excPool, ref powerSystem.excCursor, ref powerSystem.excCapacity,
ref powerSystem.excRecycle, ref powerSystem.excRecycleCursor)) ref powerSystem.excRecycle, ref powerSystem.excRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(powerSystem.excPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(powerSystem.excPool)}` on Planet {planet.planetId}");
if (OptimizePool((in PowerNetwork n, int index) => (n?.id ?? 0) == index, () => if (OptimizePool((in PowerNetwork n) => n?.id ?? 0, () =>
{ {
powerSystem.netCapacity = 0; powerSystem.netCapacity = 0;
powerSystem.SetNetworkCapacity(8); powerSystem.SetNetworkCapacity(8);
powerSystem.netPool[0] = new PowerNetwork(); powerSystem.netPool[0] = new PowerNetwork();
powerSystem.netPool[0].Reset(0); powerSystem.netPool[0].Reset(0);
}, },
ref powerSystem.netPool, ref powerSystem.netCursor, ref powerSystem.netPool, ref powerSystem.netCursor, ref powerSystem.netCapacity,
ref powerSystem.netRecycle, ref powerSystem.netRecycleCursor)) ref powerSystem.netRecycle, ref powerSystem.netRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(powerSystem.netPool)}` on Planet {planet.planetId}"); Logger.LogDebug($"Optimized `{nameof(powerSystem.netPool)}` on Planet {planet.planetId}");
} }
@@ -257,12 +257,12 @@ public class PoolOptPatch : BaseUnityPlugin
var trashContainer = GameMain.data.trashSystem?.container; var trashContainer = GameMain.data.trashSystem?.container;
if (trashContainer != null) if (trashContainer != null)
{ {
if (OptimizePool((in TrashObject n, int index) => n.item != 0, () => if (OptimizePool((in TrashObject n) => n.item == 0, () =>
{ {
trashContainer.trashCapacity = 0; trashContainer.trashCapacity = 0;
trashContainer.SetTrashCapacity(16); trashContainer.SetTrashCapacity(16);
}, },
ref trashContainer.trashObjPool, ref trashContainer.trashCursor, ref trashContainer.trashObjPool, ref trashContainer.trashCursor, ref trashContainer.trashCapacity,
ref trashContainer.trashRecycle, ref trashContainer.trashRecycleCursor)) ref trashContainer.trashRecycle, ref trashContainer.trashRecycleCursor))
{ {
Logger.LogDebug($"Optimized `{nameof(trashContainer.trashObjPool)}`"); Logger.LogDebug($"Optimized `{nameof(trashContainer.trashObjPool)}`");
@@ -271,12 +271,12 @@ public class PoolOptPatch : BaseUnityPlugin
var warningSystem = GameMain.data.warningSystem; var warningSystem = GameMain.data.warningSystem;
if (warningSystem != null) if (warningSystem != null)
{ {
if (OptimizePool((in WarningData n, int index) => n.id == index, () => if (OptimizePool((in WarningData n) => n.id, () =>
{ {
warningSystem.warningCapacity = 0; warningSystem.warningCapacity = 0;
warningSystem.SetWarningCapacity(32); warningSystem.SetWarningCapacity(32);
}, },
ref warningSystem.warningPool, ref warningSystem.warningCursor, ref warningSystem.warningPool, ref warningSystem.warningCursor, ref warningSystem.warningCapacity,
ref warningSystem.warningRecycle, ref warningSystem.warningRecycleCursor)) ref warningSystem.warningRecycle, ref warningSystem.warningRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(warningSystem.warningPool)}`"); Logger.LogDebug($"Optimized `{nameof(warningSystem.warningPool)}`");
} }
@@ -286,48 +286,48 @@ public class PoolOptPatch : BaseUnityPlugin
foreach (var dysonSphere in dysonSpheres) foreach (var dysonSphere in dysonSpheres)
{ {
if (dysonSphere == null) continue; if (dysonSphere == null) continue;
if (OptimizePool((in DysonRocket n, int index) => n.id == index, () => if (OptimizePool((in DysonRocket n) => n.id, () =>
{ {
dysonSphere.rocketCapacity = 0; dysonSphere.rocketCapacity = 0;
dysonSphere.SetRocketCapacity(256); dysonSphere.SetRocketCapacity(256);
}, },
ref dysonSphere.rocketPool, ref dysonSphere.rocketCursor, ref dysonSphere.rocketPool, ref dysonSphere.rocketCursor, ref dysonSphere.rocketCapacity,
ref dysonSphere.rocketRecycle, ref dysonSphere.rocketRecycleCursor)) ref dysonSphere.rocketRecycle, ref dysonSphere.rocketRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(dysonSphere.rocketPool)}` on Star {dysonSphere.starData.id}"); Logger.LogDebug($"Optimized `{nameof(dysonSphere.rocketPool)}` on Star {dysonSphere.starData.id}");
if (OptimizePool((in DysonNodeRData n, int index) => n.id == index, () => if (OptimizePool((in DysonNodeRData n) => n.id, () =>
{ {
dysonSphere.nrdCapacity = 0; dysonSphere.nrdCapacity = 0;
dysonSphere.SetNrdCapacity(128); dysonSphere.SetNrdCapacity(128);
}, },
ref dysonSphere.nrdPool, ref dysonSphere.nrdCursor, ref dysonSphere.nrdPool, ref dysonSphere.nrdCursor, ref dysonSphere.nrdCapacity,
ref dysonSphere.nrdRecycle, ref dysonSphere.nrdRecycleCursor)) ref dysonSphere.nrdRecycle, ref dysonSphere.nrdRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(dysonSphere.nrdPool)}` on Star {dysonSphere.starData.id}"); Logger.LogDebug($"Optimized `{nameof(dysonSphere.nrdPool)}` on Star {dysonSphere.starData.id}");
if (dysonSphere.layersIdBased == null) continue; if (dysonSphere.layersIdBased == null) continue;
foreach (var layer in dysonSphere.layersSorted) foreach (var layer in dysonSphere.layersSorted)
{ {
if (layer == null) continue; if (layer == null) continue;
if (OptimizePool((in DysonNode n, int index) => (n?.id ?? 0) == index, () => if (OptimizePool((in DysonNode n) => n?.id ?? 0, () =>
{ {
layer.nodeCapacity = 64; layer.nodeCapacity = 64;
layer.SetNodeCapacity(64); layer.SetNodeCapacity(64);
}, },
ref layer.nodePool, ref layer.nodeCursor, ref layer.nodePool, ref layer.nodeCursor, ref layer.nodeCapacity,
ref layer.nodeRecycle, ref layer.nodeRecycleCursor)) ref layer.nodeRecycle, ref layer.nodeRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(layer.nodePool)}` on Star {dysonSphere.starData.id} layer {layer.id}"); Logger.LogDebug($"Optimized `{nameof(layer.nodePool)}` on Star {dysonSphere.starData.id} layer {layer.id}");
if (OptimizePool((in DysonFrame n, int index) => (n?.id ?? 0) == index, () => if (OptimizePool((in DysonFrame n) => n?.id ?? 0, () =>
{ {
layer.frameCapacity = 64; layer.frameCapacity = 64;
layer.SetFrameCapacity(64); layer.SetFrameCapacity(64);
}, },
ref layer.framePool, ref layer.frameCursor, ref layer.framePool, ref layer.frameCursor, ref layer.frameCapacity,
ref layer.frameRecycle, ref layer.frameRecycleCursor)) ref layer.frameRecycle, ref layer.frameRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(layer.framePool)}` on Star {dysonSphere.starData.id} layer {layer.id}"); Logger.LogDebug($"Optimized `{nameof(layer.framePool)}` on Star {dysonSphere.starData.id} layer {layer.id}");
if (OptimizePool((in DysonShell n, int index) => (n?.id ?? 0) == index, () => if (OptimizePool((in DysonShell n) => n?.id ?? 0, () =>
{ {
layer.shellCapacity = 64; layer.shellCapacity = 64;
layer.SetShellCapacity(64); layer.SetShellCapacity(64);
}, },
ref layer.shellPool, ref layer.shellCursor, ref layer.shellPool, ref layer.shellCursor, ref layer.shellCapacity,
ref layer.shellRecycle, ref layer.shellRecycleCursor)) ref layer.shellRecycle, ref layer.shellRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(layer.shellPool)}` on Star {dysonSphere.starData.id} layer {layer.id}"); Logger.LogDebug($"Optimized `{nameof(layer.shellPool)}` on Star {dysonSphere.starData.id} layer {layer.id}");
} }
@@ -335,12 +335,12 @@ public class PoolOptPatch : BaseUnityPlugin
var swarm = dysonSphere.swarm; var swarm = dysonSphere.swarm;
if (swarm != null) if (swarm != null)
{ {
if (OptimizePool((in SailBullet n, int index) => n.id == index, () => if (OptimizePool((in SailBullet n) => n.id, () =>
{ {
swarm.bulletCapacity = 0; swarm.bulletCapacity = 0;
swarm.SetBulletCapacity(128); swarm.SetBulletCapacity(128);
}, },
ref swarm.bulletPool, ref swarm.bulletCursor, ref swarm.bulletPool, ref swarm.bulletCursor, ref swarm.bulletCapacity,
ref swarm.bulletRecycle, ref swarm.bulletRecycleCursor)) ref swarm.bulletRecycle, ref swarm.bulletRecycleCursor))
Logger.LogDebug($"Optimized `{nameof(swarm.bulletPool)}` on Star {dysonSphere.starData.id}"); Logger.LogDebug($"Optimized `{nameof(swarm.bulletPool)}` on Star {dysonSphere.starData.id}");
} }
@@ -350,10 +350,12 @@ public class PoolOptPatch : BaseUnityPlugin
GC.Collect(); GC.Collect();
} }
private delegate bool IsOccupied<T>(in T s, int index); private delegate int GetId<T>(in T s);
private delegate void SetToInitialCapacity();
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool OptimizePool<T>(IsOccupied<T> isOccupied, Action initCapacity, ref T[] pool, ref int cursor, ref int[] recycle, ref int recycleCursor) private static bool OptimizePool<T>(GetId<T> getter, SetToInitialCapacity initCapacity, ref T[] pool, ref int cursor, ref int capacity, ref int[] recycle, ref int recycleCursor)
{ {
if (cursor <= 1) return false; if (cursor <= 1) return false;
if (recycleCursor == cursor - 1) if (recycleCursor == cursor - 1)
@@ -367,7 +369,7 @@ public class PoolOptPatch : BaseUnityPlugin
var pos = cursor - 1; var pos = cursor - 1;
while (pos > 0) while (pos > 0)
{ {
if (isOccupied(pool[pos], pos)) break; if (getter(pool[pos]) == pos) break;
pos--; pos--;
} }
@@ -389,4 +391,41 @@ public class PoolOptPatch : BaseUnityPlugin
return true; return true;
} }
} private delegate bool IsEmpty<T>(in T s);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool OptimizePool<T>(IsEmpty<T> checker, SetToInitialCapacity initCapacity, ref T[] pool, ref int cursor, ref int capacity, ref int[] recycle, ref int recycleCursor)
{
if (cursor <= 1) return false;
if (recycleCursor == cursor - 1)
{
cursor = 1;
recycleCursor = 0;
initCapacity();
Logger.LogDebug("Resetted pool to initial status");
return true;
}
var pos = cursor - 1;
while (pos > 0)
{
if (!checker(pool[pos])) break;
pos--;
}
if (pos + 1 == cursor) return false;
if (pos == 0)
{
cursor = 1;
recycleCursor = 0;
initCapacity();
return true;
}
cursor = pos + 1;
Array.Sort(recycle, 0, recycleCursor);
var idx = Array.BinarySearch(recycle, 0, recycleCursor, pos + 1);
recycleCursor = idx < 0 ? ~idx : idx;
Logger.LogDebug($"Shrinked pool size to {cursor} and recycle size to {recycleCursor}");
return true;
}
}
+2
View File
@@ -4,6 +4,7 @@
## Changlog ## Changlog
* 1.6.4 * 1.6.4
* `Blueprint descriptions`: Align `Auto-fill` with the description title while reserving space for the native icon button. Generation options follow the entry while scrolling and adjust at screen edges, with extra title padding, compact checkbox spacing, and text sized for the current language. Use a standard rectangular dropdown that overlays the footer without resizing the panel or moving its single `Generate` action. Close with the native X, an outside click, or Esc; Esc first closes an expanded list. Preserve the native inspector layout.
* `Hide battle-related techs in Peace mode`: Fix an array index error when opening the tech tree after switching from a Peace-mode save to a Combat-mode save in the same game process, including when disabling the option after loading another Peace-mode save. * `Hide battle-related techs in Peace mode`: Fix an array index error when opening the tech tree after switching from a Peace-mode save to a Combat-mode save in the same game process, including when disabling the option after loading another Peace-mode save.
* 1.6.3 * 1.6.3
* `Quick build Mining Machines`: * `Quick build Mining Machines`:
@@ -447,6 +448,7 @@
## 更新日志 ## 更新日志
* 1.6.4 * 1.6.4
* `蓝图说明`:「自动填写」入口与说明标题的文字基线对齐,并为原生图标按钮保留空间。生成选项滚动时跟随入口,在屏幕边缘调整位置;标题保留边距,复选框间距紧凑,文字尺寸适应当前语言。使用原生直边下拉框,展开时覆盖底部操作区域,面板尺寸和单个「生成说明」按钮的位置保持不变。可通过原生叉号、点击外部或 Esc 关闭;下拉列表展开时,Esc 先收起列表。保留原生检查面板布局。
* `在和平模式下隐藏战斗相关科技`:修复在同一次游戏运行中从和平模式存档切换到战斗模式存档后打开科技树时的数组越界,以及再次加载和平模式存档后关闭选项时的同类问题。 * `在和平模式下隐藏战斗相关科技`:修复在同一次游戏运行中从和平模式存档切换到战斗模式存档后打开科技树时的数组越界,以及再次加载和平模式存档后关闭选项时的同类问题。
* 1.6.3 * 1.6.3
* `快速铺设采矿机`: * `快速铺设采矿机`:
+15
View File
@@ -133,6 +133,21 @@ public static class I18N
ApplyIndexers(); ApplyIndexers();
} }
/// <summary>
/// Returns the localized text for the given key in the currently active language,
/// falling back to the key itself when no entry is registered.
/// </summary>
/// <param name="key">The lookup key.</param>
/// <returns>The localized text, or <paramref name="key"/> if no entry exists.</returns>
internal static string Translate(string key)
{
if (!Entries.TryGetValue(key, out var loc)) return key;
var languageIndex = Localization.currentLanguageIndex;
if (languageIndex >= 0 && languageIndex < Localization.Languages.Length && Localization.Languages[languageIndex].lcId == 2052)
return loc.Zh;
return loc.En;
}
[HarmonyPostfix, HarmonyPriority(Priority.Last), HarmonyPatch(typeof(Localization), nameof(Localization.LoadSettings))] [HarmonyPostfix, HarmonyPriority(Priority.Last), HarmonyPatch(typeof(Localization), nameof(Localization.LoadSettings))]
private static void Localization_LoadSettings_Postfix() private static void Localization_LoadSettings_Postfix()
{ {
+2
View File
@@ -6,6 +6,7 @@ public static class I18NKeys
{ {
public const string Unknown = "Unknown"; public const string Unknown = "Unknown";
public const string BlueprintAutoFillDescription = "UXAssist Blueprint Auto-fill description"; public const string BlueprintAutoFillDescription = "UXAssist Blueprint Auto-fill description";
public const string BlueprintGenerateDescription = "UXAssist Blueprint Generate Description";
public const string BlueprintDescriptionOptions = "UXAssist Blueprint Description Options"; public const string BlueprintDescriptionOptions = "UXAssist Blueprint Description Options";
public const string BlueprintDescriptionOptionsTip = "UXAssist Blueprint Description Options Tip"; public const string BlueprintDescriptionOptionsTip = "UXAssist Blueprint Description Options Tip";
public const string BlueprintProliferation = "UXAssist Blueprint Proliferation"; public const string BlueprintProliferation = "UXAssist Blueprint Proliferation";
@@ -244,6 +245,7 @@ public static class I18NKeys
{ {
I18N.Add(Unknown, "Unknown", "未知"); I18N.Add(Unknown, "Unknown", "未知");
I18N.Add(BlueprintAutoFillDescription, "Auto-fill description", "自动填写说明"); I18N.Add(BlueprintAutoFillDescription, "Auto-fill description", "自动填写说明");
I18N.Add(BlueprintGenerateDescription, "Generate", "生成说明");
I18N.Add(BlueprintDescriptionOptions, "Auto-fill…", "自动填写…"); I18N.Add(BlueprintDescriptionOptions, "Auto-fill…", "自动填写…");
I18N.Add(BlueprintDescriptionOptionsTip, I18N.Add(BlueprintDescriptionOptionsTip,
"Choose production basis and proliferation, then fill the blueprint description.", "Choose production basis and proliferation, then fill the blueprint description.",
+4 -4
View File
@@ -2,8 +2,8 @@ namespace UXAssist.Common;
public enum KnownItemId : int public enum KnownItemId : int
{ {
Drone = GameConstants.ItemIds.LogisticsDrone, Drone = 5001,
Ship = GameConstants.ItemIds.LogisticsVessel, Ship = 5002,
Bot = GameConstants.ItemIds.LogisticsBot, Bot = 5003,
Warper = GameConstants.ItemIds.SpaceWarper, Warper = 1210,
} }
+6
View File
@@ -80,6 +80,12 @@ public static class WinApi
#endregion #endregion
#region Errors
private const int ERROR_INSUFFICIENT_BUFFER = 122;
#endregion
#region Structs #region Structs
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
+12
View File
@@ -27,6 +27,14 @@ internal static class MenuButtonUI
I18N.OnInitialized += RecreateConfigWindow; I18N.OnInitialized += RecreateConfigWindow;
} }
public static void Start()
{
}
public static void Uninit()
{
}
public static void OnInputUpdate() public static void OnInputUpdate()
{ {
if (_toggleKey.keyValue) if (_toggleKey.keyValue)
@@ -35,6 +43,10 @@ internal static class MenuButtonUI
} }
} }
public static void OnUpdate()
{
}
public static void ToggleConfigWindow() public static void ToggleConfigWindow()
{ {
if (!_configWinInitialized) if (!_configWinInitialized)
+12
View File
@@ -35,6 +35,10 @@ internal static class MilkyWayUI
GameLogicProc.OnGameEnd += ResetState; GameLogicProc.OnGameEnd += ResetState;
} }
public static void Start()
{
}
public static void Uninit() public static void Uninit()
{ {
GameLogicProc.OnGameEnd -= ResetState; GameLogicProc.OnGameEnd -= ResetState;
@@ -46,6 +50,14 @@ internal static class MilkyWayUI
_topTenPlayerData = null; _topTenPlayerData = null;
} }
public static void OnInputUpdate()
{
}
public static void OnUpdate()
{
}
public static void AddClusterUploadResult(int result, float requestTime) public static void AddClusterUploadResult(int result, float requestTime)
{ {
lock (_clusterUploadResultsLock) lock (_clusterUploadResultsLock)
+20
View File
@@ -58,6 +58,26 @@ internal static class StarmapFilterUI
{1000, 23}, {1000, 23},
}; };
public static void Init()
{
}
public static void Start()
{
}
public static void Uninit()
{
}
public static void OnInputUpdate()
{
}
public static void OnUpdate()
{
}
public static void InitStarmapButtons() public static void InitStarmapButtons()
{ {
var uiRoot = UIRoot.instance; var uiRoot = UIRoot.instance;
+11
View File
@@ -10,6 +10,7 @@ public static class UIFunctions
public static void Init() public static void Init()
{ {
MenuButtonUI.Init(); MenuButtonUI.Init();
StarmapFilterUI.Init();
MilkyWayUI.Init(); MilkyWayUI.Init();
UXAssist.RegisterExporter(ExportClusterUploadResults); UXAssist.RegisterExporter(ExportClusterUploadResults);
@@ -18,22 +19,32 @@ public static class UIFunctions
public static void Start() public static void Start()
{ {
MenuButtonUI.Start();
StarmapFilterUI.Start();
MilkyWayUI.Start();
} }
public static void Uninit() public static void Uninit()
{ {
MenuButtonUI.Uninit();
StarmapFilterUI.Uninit();
MilkyWayUI.Uninit(); MilkyWayUI.Uninit();
} }
public static void OnInputUpdate() public static void OnInputUpdate()
{ {
MenuButtonUI.OnInputUpdate(); MenuButtonUI.OnInputUpdate();
StarmapFilterUI.OnInputUpdate();
MilkyWayUI.OnInputUpdate();
} }
public static void OnUpdate() public static void OnUpdate()
{ {
MenuButtonUI.OnUpdate();
AutoCruiseUI.OnUpdate(); AutoCruiseUI.OnUpdate();
AutoConstructUI.OnUpdate(); AutoConstructUI.OnUpdate();
StarmapFilterUI.OnUpdate();
MilkyWayUI.OnUpdate();
} }
public static void InitMenuButtons() public static void InitMenuButtons()
+13
View File
@@ -46,6 +46,19 @@ public static class WindowFunctions
process.PriorityClass = (ProcessPriorityClass)ProrityFlags[ProcessPriority.Value]; process.PriorityClass = (ProcessPriorityClass)ProrityFlags[ProcessPriority.Value];
} }
private static string GetPriorityName(int priority)
{
return priority switch
{
WinApi.HIGH_PRIORITY_CLASS => I18NKeys.High.Translate(),
WinApi.ABOVE_NORMAL_PRIORITY_CLASS => I18NKeys.AboveNormal.Translate(),
WinApi.NORMAL_PRIORITY_CLASS => I18NKeys.Normal.Translate(),
WinApi.BELOW_NORMAL_PRIORITY_CLASS => I18NKeys.BelowNormal.Translate(),
WinApi.IDLE_PRIORITY_CLASS => I18NKeys.Idle.Translate(),
_ => I18NKeys.Unknown.Translate()
};
}
public static void SetWindowTitle() public static void SetWindowTitle()
{ {
// Get profile name from command line arguments, and set window title accordingly // Get profile name from command line arguments, and set window title accordingly
+269 -50
View File
@@ -70,6 +70,12 @@ public class BlueprintDescriptionPatch : PatchImpl<BlueprintDescriptionPatch>
} }
} }
[HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), nameof(UIBlueprintInspector._OnUpdate))]
private static void OnUpdate(UIBlueprintInspector __instance)
{
if (Inspectors.TryGetValue(__instance, out var controls)) controls.HandleInput();
}
[HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), nameof(UIBlueprintInspector.OnLanguageChanged))] [HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), nameof(UIBlueprintInspector.OnLanguageChanged))]
private static void OnLanguageChanged(UIBlueprintInspector __instance) private static void OnLanguageChanged(UIBlueprintInspector __instance)
{ {
@@ -103,7 +109,7 @@ public class BlueprintDescriptionPatch : PatchImpl<BlueprintDescriptionPatch>
private sealed class InspectorControls private sealed class InspectorControls
{ {
private const float Left = 12f; private const float Left = 12f;
private const float ControlsGap = 12f; private const float ControlsGap = 6f;
private readonly UIBlueprintInspector _inspector; private readonly UIBlueprintInspector _inspector;
private RectTransform _panel; private RectTransform _panel;
@@ -111,10 +117,16 @@ public class BlueprintDescriptionPatch : PatchImpl<BlueprintDescriptionPatch>
private Text _entryText; private Text _entryText;
private UIButton _button; private UIButton _button;
private Text _buttonText; private Text _buttonText;
private UIButton _cancelButton; private UIButton _closeButton;
private Text _cancelText; private Text _title;
private readonly Vector3[] _corners = new Vector3[4];
private readonly Canvas _canvas;
private readonly RectTransform _viewport;
private readonly Text _descriptionLabel;
private readonly RectTransform _descriptionIcon;
private bool _optionsOpen;
private MyCheckBox _checkbox; private MyCheckBox _checkbox;
private MyCornerComboBox _basisCombo; private UIComboBox _basisCombo;
private Text _basisLabel; private Text _basisLabel;
private UIButton _basisHelp; private UIButton _basisHelp;
private BlueprintData _currentBlueprint; private BlueprintData _currentBlueprint;
@@ -123,56 +135,103 @@ public class BlueprintDescriptionPatch : PatchImpl<BlueprintDescriptionPatch>
public InspectorControls(UIBlueprintInspector inspector) public InspectorControls(UIBlueprintInspector inspector)
{ {
_inspector = inspector; _inspector = inspector;
_canvas = inspector.rectTrans.GetComponentInParent<Canvas>().rootCanvas;
_viewport = inspector.descGroupTrans.GetComponentInParent<ScrollRect>()?.viewport;
_descriptionLabel = inspector.descGroupTrans.Find("label").GetComponent<Text>();
_descriptionIcon = (RectTransform)inspector.descTextInput.transform.Find("sel-icon-btn");
try try
{ {
// The native description has a 22px title row above its editable text. // The native description has a 22px title row above its editable text.
_entry = LayoutHelper.AddButton(0, 0, inspector.descGroupTrans, _entry = LayoutHelper.AddButton(0, 0, inspector.descGroupTrans,
I18NKeys.BlueprintDescriptionOptions, 13, "blueprint-description-options", ToggleOptions); I18NKeys.BlueprintDescriptionOptions, 12, "blueprint-description-options", ToggleOptions);
_entryText = _entry.transform.Find("button-text").GetComponent<Text>(); _entryText = _entry.transform.Find("button-text").GetComponent<Text>();
_entry.tips = inspector.tipButton2.tips; _entry.tips = inspector.tipButton2.tips;
_entry.tips.topLevel = true; _entry.tips.topLevel = true;
Util.NormalizeRectWithTopRight(_entry, 0, 0, inspector.descGroupTrans); _entryText.resizeTextForBestFit = false;
Util.NormalizeRectWithMargin(_entryText, 0, 8, 0, 8);
// Reuse the native background, including its blur material, only while options are open. // Reuse the native background, including its blur material, only while options are open.
var source = UIRoot.instance.uiGame.inserterWindow.transform.Find("panel-bg").GetComponent<Image>(); var source = UIRoot.instance.uiGame.inserterWindow.transform.Find("panel-bg").GetComponent<Image>();
_panel = UnityEngine.Object.Instantiate(source, inspector.rectTrans).rectTransform; _panel = UnityEngine.Object.Instantiate(source, inspector.rectTrans).rectTransform;
_panel.gameObject.name = "uxassist-blueprint-description-options"; _panel.gameObject.name = "uxassist-blueprint-description-options";
_panel.gameObject.SetActive(false);
for (var i = _panel.childCount - 1; i >= 0; i--) for (var i = _panel.childCount - 1; i >= 0; i--)
{ {
var child = _panel.GetChild(i).gameObject; var child = _panel.GetChild(i).gameObject;
child.SetActive(false); child.SetActive(false);
UnityEngine.Object.Destroy(child); UnityEngine.Object.Destroy(child);
} }
_panel.anchorMin = new Vector2(0, 1); _panel.anchorMin = _panel.anchorMax = new Vector2(0, 1);
_panel.anchorMax = Vector2.one;
_panel.pivot = new Vector2(0, 1); _panel.pivot = new Vector2(0, 1);
_panel.anchoredPosition = new Vector2(Left, -Left); _panel.GetComponent<Image>().raycastTarget = true;
_panel.sizeDelta = new Vector2(-Left * 2, 152); _title = LayoutHelper.AddText(Left, 10, _panel, I18NKeys.BlueprintAutoFillDescription, 16);
_button = LayoutHelper.AddButton(Left, 12, _panel, _title.color = _entryText.color;
I18NKeys.BlueprintAutoFillDescription, 15, "blueprint-auto-fill-description", Generate); var closeSource = UIRoot.instance.uiGame.inserterWindow.transform
.Find("panel-bg/btn-box/close-wnd-btn").GetComponent<UIButton>();
_closeButton = UnityEngine.Object.Instantiate(closeSource, _panel);
Util.ResetButton(_closeButton);
// The source's persistent callback closes the original inserter window.
_closeButton.button.onClick = new Button.ButtonClickedEvent();
_closeButton.button.onClick.AddListener(CloseOptions);
Util.NormalizeRectWithTopRight(_closeButton, 0, 0, _panel);
_button = LayoutHelper.AddButton(0, 0, _panel,
I18NKeys.BlueprintGenerateDescription, 15, "blueprint-auto-fill-description", Generate);
_buttonText = _button.transform.Find("button-text").GetComponent<Text>(); _buttonText = _button.transform.Find("button-text").GetComponent<Text>();
_cancelButton = LayoutHelper.AddButton(0, 0, _panel, _buttonText.resizeTextForBestFit = false;
I18NKeys.Cancel, 14, "blueprint-description-cancel", CloseOptions); _buttonText.alignment = TextAnchor.MiddleCenter;
_cancelText = _cancelButton.transform.Find("button-text").GetComponent<Text>(); Util.NormalizeRectWithMargin(_buttonText, 4, 10, 4, 10);
Util.NormalizeRectWithTopRight(_cancelButton, Left, 14, _panel); _checkbox = MyCheckBox.CreateCheckBox(Left, 42, _panel, false,
_checkbox = MyCheckBox.CreateCheckBox(Left, 52, _panel, false, I18NKeys.BlueprintProliferation.Translate(), 15);
I18NKeys.BlueprintProliferation.Translate(), 15).WithSmallerBox(22f); _checkbox.rectTrans.sizeDelta = new Vector2(20, 20);
_checkbox.checkImage.rectTransform.sizeDelta = new Vector2(20, 20);
_checkbox.labelText.verticalOverflow = VerticalWrapMode.Overflow;
_checkbox.gameObject.name = "blueprint-proliferation"; _checkbox.gameObject.name = "blueprint-proliferation";
_checkbox.OnChecked += OnProliferationChecked; _checkbox.OnChecked += OnProliferationChecked;
_basisLabel = LayoutHelper.AddText(Left, 80, _panel, I18NKeys.BlueprintProductionBasis, 14); _basisLabel = LayoutHelper.AddText(Left, 68, _panel, I18NKeys.BlueprintProductionBasis, 14);
_basisCombo = MyCornerComboBox.CreateComboBox(Left, 108, _panel).WithFontSize(14) _basisCombo = UnityEngine.Object.Instantiate(UIRoot.instance.optionWindow.resolutionComp, _panel);
.WithItems(I18NKeys.BlueprintFinalProducts, I18NKeys.BlueprintBottleneckIntermediate) _basisCombo.gameObject.name = "blueprint-production-basis";
.WithIndex(0); _basisCombo.gameObject.SetActive(true);
var combo = _basisCombo.GetComponent<UIComboBox>(); foreach (var button in _basisCombo.GetComponentsInChildren<UIButton>(true)) Util.ResetButton(button);
var combo = _basisCombo;
// Runtime resolution rows are cloned as children, but their private tracking list is not serialized.
for (var i = combo.m_DropDownContent.childCount - 1; i >= 0; i--)
{
var button = combo.m_DropDownContent.GetChild(i).GetComponent<Button>();
if (!button || button == combo.m_ListItemRes) continue;
button.gameObject.SetActive(false);
UnityEngine.Object.Destroy(button.gameObject);
}
combo.ItemButtons.Clear();
combo.Items.Clear();
combo.onSubmit = new UIComboBox.SubmitEvent();
combo.onItemIndexChange = new UIComboBox.ChangeEvent();
combo.CanInput = false; combo.CanInput = false;
combo.autoWidth = false; combo.autoWidth = false;
var comboRect = (RectTransform)_basisCombo.transform; combo.parentSibling = false;
comboRect.anchorMax = Vector2.one; combo.itemIndex = -1;
comboRect.sizeDelta = new Vector2(-Left * 2, 28); combo.isDroppedDown = false;
_basisHelp = LayoutHelper.AddTipsButton(Left, 80, _panel, combo.m_DropDownContent.anchoredPosition = Vector2.zero;
combo.m_DropDownList.gameObject.SetActive(false);
combo.m_EmptyItemRes.gameObject.SetActive(false);
combo.m_SelectionBG.gameObject.SetActive(false);
combo.m_Scrollbar.gameObject.SetActive(false);
Util.NormalizeRectWithMargin(_basisCombo.transform.Find("Main Button"), 0, 0, 0, 0);
combo.m_Text.alignment = TextAnchor.MiddleLeft;
combo.m_Text.fontSize = 14;
combo.m_Text.resizeTextForBestFit = false;
combo.m_Text.horizontalOverflow = HorizontalWrapMode.Overflow;
combo.m_Text.verticalOverflow = VerticalWrapMode.Overflow;
Util.NormalizeRectWithMargin(combo.m_Text, 2, 8, 2, 30);
var itemText = combo.m_ListItemRes.GetComponentInChildren<Text>();
itemText.alignment = TextAnchor.MiddleLeft;
itemText.fontSize = 14;
itemText.resizeTextForBestFit = false;
itemText.horizontalOverflow = HorizontalWrapMode.Overflow;
itemText.verticalOverflow = VerticalWrapMode.Overflow;
Util.NormalizeRectWithMargin(itemText, 2, 8, 2, 8);
_basisHelp = LayoutHelper.AddTipsButton(Left, 68, _panel,
I18NKeys.BlueprintProductionBasis.Translate(), I18NKeys.BlueprintProductionBasisTip.Translate(), ""); I18NKeys.BlueprintProductionBasis.Translate(), I18NKeys.BlueprintProductionBasisTip.Translate(), "");
UpdateLabels(); UpdateLabels();
_panel.gameObject.SetActive(false);
} }
catch catch
{ {
@@ -185,58 +244,218 @@ public class BlueprintDescriptionPatch : PatchImpl<BlueprintDescriptionPatch>
{ {
_currentBlueprint = null; _currentBlueprint = null;
_manualProliferation = false; _manualProliferation = false;
_basisCombo.SetIndex(0); _basisCombo.itemIndex = 0;
if (_inspector.blueprint != null) SyncDefault(); if (_inspector.blueprint != null) SyncDefault();
else _checkbox.Checked = false; else _checkbox.Checked = false;
CloseOptions(); CloseOptions();
_entry.gameObject.SetActive(_inspector.blueprint != null); UpdateLabels();
} }
public void Refresh() public void Refresh()
{ {
SyncDefault(); SyncDefault();
_entry.gameObject.SetActive(_inspector.blueprint != null); PositionEntry();
} }
private void ToggleOptions() private void ToggleOptions()
{ {
if (_optionsOpen)
{
CloseOptions();
return;
}
_optionsOpen = true;
_panel.SetAsLastSibling(); _panel.SetAsLastSibling();
_panel.gameObject.SetActive(!_panel.gameObject.activeSelf); _panel.gameObject.SetActive(true);
PositionOptions();
if (_optionsOpen) Canvas.willRenderCanvases += PositionOptions;
} }
private void CloseOptions() => _panel.gameObject.SetActive(false); private void CloseOptions()
{
Canvas.willRenderCanvases -= PositionOptions;
_optionsOpen = false;
if (_panel) _panel.gameObject.SetActive(false);
}
public void HandleInput()
{
PositionEntry();
if (!_optionsOpen) return;
var combo = _basisCombo;
if (VFInput.escape)
{
if (combo.isDroppedDown)
{
combo.isDroppedDown = false;
combo.m_DropDownList.gameObject.SetActive(false);
}
else CloseOptions();
VFInput.UseEscape();
return;
}
if (!Input.GetMouseButtonDown(0) && !Input.GetMouseButtonDown(1) && !Input.GetMouseButtonDown(2)) return;
var mouse = (Vector2)Input.mousePosition;
if (RectTransformUtility.RectangleContainsScreenPoint(_panel, mouse, _canvas.worldCamera) ||
RectTransformUtility.RectangleContainsScreenPoint((RectTransform)_entry.transform, mouse, _canvas.worldCamera) ||
combo.isDroppedDown && RectTransformUtility.RectangleContainsScreenPoint(combo.m_DropDownList, mouse, _canvas.worldCamera))
return;
CloseOptions();
}
private Rect BoundsIn(RectTransform rect, Transform parent)
{
rect.GetWorldCorners(_corners);
var min = new Vector2(float.PositiveInfinity, float.PositiveInfinity);
var max = new Vector2(float.NegativeInfinity, float.NegativeInfinity);
foreach (var corner in _corners)
{
var point = parent.InverseTransformPoint(corner);
min = Vector2.Min(min, point);
max = Vector2.Max(max, point);
}
return Rect.MinMaxRect(min.x, min.y, max.x, max.y);
}
private void PositionEntry()
{
var parent = _inspector.descGroupTrans;
var label = BoundsIn(_descriptionLabel.rectTransform, parent);
var labelWidth = parent.InverseTransformVector(_descriptionLabel.transform.TransformVector(
new Vector3(Util.GetPreferredWidth(_descriptionLabel), 0, 0))).x;
var left = label.xMin + labelWidth + 8;
var right = Math.Min(parent.rect.xMax, BoundsIn(_descriptionIcon, parent).xMin) - 8;
var entryRect = (RectTransform)_entry.transform;
var visible = _inspector.blueprint != null && left + entryRect.rect.width <= right;
_entry.gameObject.SetActive(visible);
if (!visible) return;
Util.NormalizeRectWithTopLeft(_entry, left - parent.rect.xMin,
parent.rect.yMax - label.yMax, parent);
}
private void PositionOptions()
{
if (!_optionsOpen) return;
if (!_entry || !_entry.gameObject.activeInHierarchy)
{
CloseOptions();
return;
}
var anchor = BoundsIn((RectTransform)_entry.transform, _panel.parent);
var screen = BoundsIn((RectTransform)_canvas.transform, _panel.parent);
if (!anchor.Overlaps(screen) || _viewport && !anchor.Overlaps(BoundsIn(_viewport, _panel.parent)))
{
CloseOptions();
return;
}
if (!TryGetPopupPosition(anchor, screen, _panel.sizeDelta, out var position))
{
CloseOptions();
return;
}
var parent = (RectTransform)_panel.parent;
_panel.anchoredPosition = position - new Vector2(parent.rect.xMin, parent.rect.yMax);
}
private static bool TryGetPopupPosition(Rect anchor, Rect screen, Vector2 size, out Vector2 position)
{
const float gap = 6;
const float margin = 8;
position = default;
if (size.x > screen.width - margin * 2 || size.y > screen.height - margin * 2) return false;
var left = Math.Max(screen.xMin + margin,
Math.Min(anchor.xMax - size.x, screen.xMax - margin - size.x));
var top = anchor.yMin - gap;
if (top - size.y < screen.yMin + margin)
top = anchor.yMax + gap + size.y;
top = Math.Min(screen.yMax - margin, Math.Max(screen.yMin + margin + size.y, top));
position = new Vector2(left, top);
return true;
}
public void UpdateLabels() public void UpdateLabels()
{ {
_entryText.font = _descriptionLabel.font;
_entryText.fontSize = _descriptionLabel.fontSize;
_entryText.fontStyle = _descriptionLabel.fontStyle;
_entryText.lineSpacing = _descriptionLabel.lineSpacing;
_entryText.alignment = _descriptionLabel.alignment;
_entryText.text = I18NKeys.BlueprintDescriptionOptions.Translate(); _entryText.text = I18NKeys.BlueprintDescriptionOptions.Translate();
((RectTransform)_entry.transform).sizeDelta = ((RectTransform)_entry.transform).sizeDelta =
new Vector2(Util.GetPreferredWidth(_entryText) + 16, 20); new Vector2(Util.GetPreferredWidth(_entryText) + 20, 22);
_entry.tips.tipTitle = I18NKeys.BlueprintAutoFillDescription.Translate(); _entry.tips.tipTitle = I18NKeys.BlueprintAutoFillDescription.Translate();
_entry.tips.tipText = I18NKeys.BlueprintDescriptionOptionsTip.Translate(); _entry.tips.tipText = I18NKeys.BlueprintDescriptionOptionsTip.Translate();
_entry.UpdateTip(); _entry.UpdateTip();
_buttonText.text = I18NKeys.BlueprintAutoFillDescription.Translate(); _title.text = I18NKeys.BlueprintAutoFillDescription.Translate();
_cancelText.text = I18NKeys.Cancel.Translate(); _buttonText.text = I18NKeys.BlueprintGenerateDescription.Translate();
((RectTransform)_cancelButton.transform).sizeDelta =
new Vector2(Util.GetPreferredWidth(_cancelText) + 20, 24);
_checkbox.SetLabelText(I18NKeys.BlueprintProliferation.Translate()); _checkbox.SetLabelText(I18NKeys.BlueprintProliferation.Translate());
_basisLabel.text = I18NKeys.BlueprintProductionBasis.Translate(); _basisLabel.text = I18NKeys.BlueprintProductionBasis.Translate();
var combo = _basisCombo.GetComponent<UIComboBox>(); var combo = _basisCombo;
var index = combo.itemIndex; var index = Math.Max(0, combo.itemIndex);
_basisCombo.SetItems(I18NKeys.BlueprintFinalProducts, I18NKeys.BlueprintBottleneckIntermediate); combo.Items = [I18NKeys.BlueprintFinalProducts.Translate(), I18NKeys.BlueprintBottleneckIntermediate.Translate()];
_basisCombo.SetIndex(index); combo.DropDownCount = combo.Items.Count;
_basisHelp.tips.tipTitle = I18NKeys.BlueprintProductionBasis.Translate(); _basisHelp.tips.tipTitle = I18NKeys.BlueprintProductionBasis.Translate();
_basisHelp.tips.tipText = I18NKeys.BlueprintProductionBasisTip.Translate(); _basisHelp.tips.tipText = I18NKeys.BlueprintProductionBasisTip.Translate();
_basisHelp.UpdateTip(); _basisHelp.UpdateTip();
var width = Math.Max(160f, Util.GetPreferredWidth(_buttonText) + 26f); var image = _panel.GetComponent<Image>();
_button.transform.GetComponent<RectTransform>().sizeDelta = // Sliced window artwork has transparent borders; content margins start inside its visible fill.
new Vector2(width, _button.transform.GetComponent<RectTransform>().sizeDelta.y); var padding = UnityEngine.Sprites.DataUtility.GetPadding(image.sprite) / image.pixelsPerUnit;
var left = Mathf.Ceil(padding.x) + Left;
var right = Mathf.Ceil(padding.z) + Left;
var top = Mathf.Ceil(padding.w) + 18;
var titleHeight = Math.Max(30, Mathf.Ceil(_title.preferredHeight) + 4);
var titleLeft = left + 12;
Util.NormalizeRectWithTopLeft(_title, titleLeft, top, _panel);
Util.NormalizeRectWithTopRight(_closeButton, right, top, _panel);
var rowTop = top + titleHeight + 8;
var labelHeight = Math.Max(26, Mathf.Ceil(_checkbox.labelText.preferredHeight) + 4);
Util.NormalizeRectWithTopLeft(_checkbox, left, rowTop + (labelHeight - 20) / 2, _panel);
var checkLabel = _checkbox.labelText.rectTransform;
checkLabel.anchorMin = checkLabel.anchorMax = new Vector2(0, 0.5f);
checkLabel.pivot = new Vector2(0, 0.5f);
checkLabel.anchoredPosition = new Vector2(24, 0);
checkLabel.sizeDelta = new Vector2(Util.GetPreferredWidth(_checkbox.labelText) + 4, labelHeight);
rowTop += labelHeight + 8;
var labelWidth = Util.GetPreferredWidth(_basisLabel); var labelWidth = Util.GetPreferredWidth(_basisLabel);
_basisLabel.rectTransform.sizeDelta = new Vector2(labelWidth, _basisLabel.rectTransform.sizeDelta.y); var itemText = combo.m_ListItemRes.GetComponentInChildren<Text>();
Util.NormalizeRectWithTopLeft(_basisHelp, Left + labelWidth + ControlsGap, 80, _panel); var comboWidth = 180f;
var textHeight = 0f;
foreach (var item in combo.Items)
{
combo.m_Text.text = item;
itemText.text = item;
comboWidth = Math.Max(comboWidth, Util.GetPreferredWidth(combo.m_Text) + 42);
textHeight = Math.Max(textHeight, Math.Max(combo.m_Text.preferredHeight, itemText.preferredHeight));
}
combo.itemIndex = index;
combo.ItemHeight = (int)Math.Max(24, Mathf.Ceil(textHeight) + 4);
var rowHeight = Math.Max(28, Math.Max(Mathf.Ceil(_basisLabel.preferredHeight), Mathf.Ceil(textHeight)) + 4);
Util.NormalizeRectWithTopLeft(_basisLabel, left, rowTop, _panel);
_basisLabel.rectTransform.sizeDelta = new Vector2(labelWidth, rowHeight);
var helpRect = (RectTransform)_basisHelp.transform;
Util.NormalizeRectWithTopLeft(_basisHelp, left + labelWidth + ControlsGap,
rowTop + (rowHeight - helpRect.rect.height) / 2, _panel);
var comboLeft = left + labelWidth + ControlsGap + helpRect.rect.width + ControlsGap;
Util.NormalizeRectWithTopLeft(_basisCombo, comboLeft, rowTop, _panel);
var comboRect = (RectTransform)_basisCombo.transform;
comboRect.sizeDelta = new Vector2(comboWidth, rowHeight);
var width = Math.Max(90f, Util.GetPreferredWidth(_buttonText) + 20);
((RectTransform)_button.transform).sizeDelta = new Vector2(width,
Math.Max(30, Mathf.Ceil(_buttonText.preferredHeight) + 8));
var popupWidth = Math.Max(320, Math.Max(comboLeft + comboWidth + right,
Util.GetPreferredWidth(_title) + titleLeft + right + 50));
var footerTop = rowTop + rowHeight + 16;
var bottom = Mathf.Ceil(padding.y) + Left;
_panel.sizeDelta = new Vector2(popupWidth, footerTop + ((RectTransform)_button.transform).rect.height + bottom);
Util.NormalizeRectWithTopRight(_button, right, footerTop, _panel);
_title.rectTransform.sizeDelta = new Vector2(popupWidth - titleLeft - right - 50, titleHeight);
PositionEntry();
PositionOptions();
} }
public void Destroy() public void Destroy()
{ {
CloseOptions();
if (_entry) if (_entry)
{ {
_entry.button.onClick.RemoveListener(ToggleOptions); _entry.button.onClick.RemoveListener(ToggleOptions);
@@ -244,8 +463,8 @@ public class BlueprintDescriptionPatch : PatchImpl<BlueprintDescriptionPatch>
} }
if (_button) if (_button)
_button.button.onClick.RemoveListener(Generate); _button.button.onClick.RemoveListener(Generate);
if (_cancelButton) if (_closeButton)
_cancelButton.button.onClick.RemoveListener(CloseOptions); _closeButton.button.onClick.RemoveListener(CloseOptions);
if (_checkbox) if (_checkbox)
_checkbox.OnChecked -= OnProliferationChecked; _checkbox.OnChecked -= OnProliferationChecked;
if (!_panel) return; if (!_panel) return;
@@ -318,7 +537,7 @@ public class BlueprintDescriptionPatch : PatchImpl<BlueprintDescriptionPatch>
} }
var request = capture.CreateRequest(_checkbox.Checked); var request = capture.CreateRequest(_checkbox.Checked);
request.ProductionBasis = (BlueprintProductionBasis)_basisCombo.GetComponent<UIComboBox>().itemIndex; request.ProductionBasis = (BlueprintProductionBasis)_basisCombo.itemIndex;
var report = new FactoryBlackBoxAnalyzer(catalog).Analyze(request); var report = new FactoryBlackBoxAnalyzer(catalog).Analyze(request);
if (report.Diagnostics.Any(diagnostic => diagnostic.Code == ProductionDiagnosticCode.BlueprintBasisUnavailable)) if (report.Diagnostics.Any(diagnostic => diagnostic.Code == ProductionDiagnosticCode.BlueprintBasisUnavailable))
{ {
@@ -10,6 +10,15 @@ namespace UXAssist.Patches.Factory;
internal static class ArchitectModePatch internal static class ArchitectModePatch
{ {
public static void Enable(bool enable)
{
UnlimitInteractive.Enable(enable);
RemoveSomeConditionBuild.Enable(enable);
RemoveBuildRangeLimit.Enable(enable);
LargerAreaForUpgradeAndDismantle.Enable(enable);
LargerAreaForTerraform.Enable(enable);
}
internal class UnlimitInteractive : PatchImpl<UnlimitInteractive> internal class UnlimitInteractive : PatchImpl<UnlimitInteractive>
{ {
// Harmony transpiler: PlayerAction_Inspect_GetObjectSelectDistance_Transpiler // Harmony transpiler: PlayerAction_Inspect_GetObjectSelectDistance_Transpiler
@@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using System.Reflection; using System.Reflection;
using HarmonyLib; using HarmonyLib;
using UXAssist.Common; using UXAssist.Common;
@@ -13,6 +14,11 @@ namespace UXAssist.Patches.Factory;
[ModFeature("BeltSignalsForBuyOut")] [ModFeature("BeltSignalsForBuyOut")]
internal static class BeltSignalPatch internal static class BeltSignalPatch
{ {
public static void Enable(bool enable)
{
BeltSignalsForBuyOut.Enable(enable);
}
public static void InitPersist() public static void InitPersist()
{ {
BeltSignalsForBuyOut.InitPersist(); BeltSignalsForBuyOut.InitPersist();
@@ -119,6 +125,23 @@ internal static class BeltSignalPatch
_loaded = true; _loaded = true;
} }
private static void RemoveBeltSignalProtos()
{
if (!_initialized || !_loaded) return;
var signals = LDB._signals;
if (signals.dataIndices.TryGetValue(301, out var index))
{
signals.dataArray = [.. signals.dataArray.Take(index), .. signals.dataArray.Skip(index + 6)];
for (var id = 301; id <= 306; id++)
signals.dataIndices.Remove(id);
var len = signals.dataArray.Length;
for (; index < len; index++)
signals.dataIndices[signals.dataArray[index].ID] = index;
}
_loaded = false;
}
private static void InitSignalBelts() private static void InitSignalBelts()
{ {
if (!GameMain.isRunning) return; if (!GameMain.isRunning) return;
@@ -79,6 +79,8 @@ internal static class BuildToolPatch
internal class OffGridBuilding : PatchImpl<OffGridBuilding> internal class OffGridBuilding : PatchImpl<OffGridBuilding>
{ {
// private const float SteppedRotationDegrees = 15f;
private static bool _initialized; private static bool _initialized;
private static void SetupRichTextSupport() private static void SetupRichTextSupport()
@@ -290,6 +292,62 @@ internal static class BuildToolPatch
return matcher.InstructionEnumeration(); return matcher.InstructionEnumeration();
} }
/*
public static IEnumerable<CodeInstruction> PatchToPerformSteppedRotate(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var matcher = new CodeMatcher(instructions, generator);
MatchIgnoreGridAndCheckIfRotatable(matcher, out var ifBlockEntryLabel, out var elseBlockEntryLabel);
if (matcher.IsInvalid)
return instructions;
while (!matcher.Labels.Contains(elseBlockEntryLabel.Value))
matcher.Advance(1);
Label? ifBlockExitLabel = null;
matcher.MatchBack(false, new CodeMatch(ci => ci.Branches(out ifBlockExitLabel)));
if (matcher.IsInvalid)
return instructions;
while (!matcher.Labels.Contains(ifBlockEntryLabel.Value))
matcher.Advance(-1);
var instructionToClone = matcher.Instruction.Clone();
var overwriteWith = CodeInstruction.LoadField(typeof(VFInput), nameof(VFInput.control));
matcher.SetAndAdvance(overwriteWith.opcode, overwriteWith.operand);
matcher.Insert(instructionToClone);
matcher.CreateLabel(out var existingEntryLabel);
matcher.InsertAndAdvance(
new CodeInstruction(OpCodes.Brfalse, existingEntryLabel),
new CodeInstruction(OpCodes.Ldarg_0),
CodeInstruction.Call(typeof(OffGridBuilding), nameof(RotateStepped)),
new CodeInstruction(OpCodes.Br, ifBlockExitLabel)
);
return matcher.InstructionEnumeration();
}
public static void RotateStepped(BuildTool_Click instance)
{
if (VFInput._rotate.onDown)
{
instance.yaw += SteppedRotationDegrees;
instance.yaw = Mathf.Repeat(instance.yaw, 360f);
instance.yaw = Mathf.Round(instance.yaw / SteppedRotationDegrees) * SteppedRotationDegrees;
}
if (VFInput._counterRotate.onDown)
{
instance.yaw -= SteppedRotationDegrees;
instance.yaw = Mathf.Repeat(instance.yaw, 360f);
instance.yaw = Mathf.Round(instance.yaw / SteppedRotationDegrees) * SteppedRotationDegrees;
}
}
*/
} }
internal class TreatStackingAsSingle : PatchImpl<TreatStackingAsSingle> internal class TreatStackingAsSingle : PatchImpl<TreatStackingAsSingle>
@@ -8,6 +8,11 @@ namespace UXAssist.Patches.Factory;
internal static class BuildingBufferPatch internal static class BuildingBufferPatch
{ {
public static void Enable(bool enable)
{
TweakBuildingBuffer.Enable(enable);
}
internal class TweakBuildingBuffer : PatchImpl<TweakBuildingBuffer> internal class TweakBuildingBuffer : PatchImpl<TweakBuildingBuffer>
{ {
public static void RefreshAssemblerBufferMultipliers() public static void RefreshAssemblerBufferMultipliers()
@@ -10,6 +10,11 @@ namespace UXAssist.Patches.Factory;
[ModFeature("VeinProtection")] [ModFeature("VeinProtection")]
internal static partial class VeinProtectionPatch internal static partial class VeinProtectionPatch
{ {
public static void Enable(bool enable)
{
ProtectVeinsFromExhaustion.Enable(enable);
}
public static void InitConfig() public static void InitConfig()
{ {
ProtectVeinsFromExhaustion.InitConfig(); ProtectVeinsFromExhaustion.InitConfig();
+143
View File
@@ -19,6 +19,7 @@ public class GamePatch : PatchImpl<GamePatch>
public static ConfigEntry<bool> EnableWindowResizeEnabled; public static ConfigEntry<bool> EnableWindowResizeEnabled;
public static ConfigEntry<bool> LoadLastWindowRectEnabled; public static ConfigEntry<bool> LoadLastWindowRectEnabled;
// public static ConfigEntry<bool> AutoSaveOptEnabled;
public static ConfigEntry<bool> ConvertSavesFromPeaceEnabled; public static ConfigEntry<bool> ConvertSavesFromPeaceEnabled;
public static ConfigEntry<Vector4> LastWindowRect; public static ConfigEntry<Vector4> LastWindowRect;
public static ConfigEntry<bool> ProfileBasedSaveFolderEnabled; public static ConfigEntry<bool> ProfileBasedSaveFolderEnabled;
@@ -80,6 +81,7 @@ public class GamePatch : PatchImpl<GamePatch>
FixLastWindowRect(); FixLastWindowRect();
} }
}; };
// AutoSaveOptEnabled.SettingChanged += (_, _) => AutoSaveOpt.Enable(AutoSaveOptEnabled.Value);
ConvertSavesFromPeaceEnabled.SettingChanged += (_, _) => ConvertSavesFromPeace.Enable(ConvertSavesFromPeaceEnabled.Value); ConvertSavesFromPeaceEnabled.SettingChanged += (_, _) => ConvertSavesFromPeace.Enable(ConvertSavesFromPeaceEnabled.Value);
ProfileBasedSaveFolderEnabled.SettingChanged += (_, _) => RefreshSavePath(); ProfileBasedSaveFolderEnabled.SettingChanged += (_, _) => RefreshSavePath();
ProfileBasedOptionEnabled.SettingChanged += (_, _) => ProfileBasedOption.Enable(ProfileBasedOptionEnabled.Value); ProfileBasedOptionEnabled.SettingChanged += (_, _) => ProfileBasedOption.Enable(ProfileBasedOptionEnabled.Value);
@@ -110,6 +112,7 @@ public class GamePatch : PatchImpl<GamePatch>
} }
} }
EnableWindowResize.Enable(EnableWindowResizeEnabled.Value); EnableWindowResize.Enable(EnableWindowResizeEnabled.Value);
// AutoSaveOpt.Enable(AutoSaveOptEnabled.Value);
ConvertSavesFromPeace.Enable(ConvertSavesFromPeaceEnabled.Value); ConvertSavesFromPeace.Enable(ConvertSavesFromPeaceEnabled.Value);
Enable(true); Enable(true);
@@ -120,6 +123,7 @@ public class GamePatch : PatchImpl<GamePatch>
{ {
Enable(false); Enable(false);
EnableWindowResize.Enable(false); EnableWindowResize.Enable(false);
// AutoSaveOpt.Enable(false);
ConvertSavesFromPeace.Enable(false); ConvertSavesFromPeace.Enable(false);
} }
@@ -307,6 +311,145 @@ public class GamePatch : PatchImpl<GamePatch>
} }
} }
/*
private class AutoSaveOpt: PatchImpl<AutoSaveOpt>
{
protected override void OnEnable()
{
Directory.CreateDirectory(GameConfig.gameSaveFolder + "AutoSaves/");
}
[HarmonyPrefix]
[HarmonyPatch(typeof(GameSave), nameof(GameSave.AutoSave))]
private static bool GameSave_AutoSave_Prefix(ref bool __result)
{
if (!GameSave.SaveCurrentGame(GameSave.AutoSaveTmp))
{
GlobalObject.SaveOpCounter();
__result = false;
return false;
}
var tmpFilename = GameConfig.gameSaveFolder + GameSave.AutoSaveTmp + GameSave.saveExt;
var targetFilename = $"{GameConfig.gameSaveFolder}AutoSaves/[{GameMain.data.gameDesc.clusterString}] {DateTime.Now:yyyy-MM-dd_hh-mm-ss}{GameSave.saveExt}";
File.Move(tmpFilename, targetFilename);
__result = true;
return false;
}
[HarmonyPostfix]
[HarmonyPatch(typeof(UILoadGameWindow), nameof(UILoadGameWindow.RefreshList))]
public static void UILoadGameWindow_RefreshList_Postfix(UILoadGameWindow __instance)
{
var baseDir = GameConfig.gameSaveFolder + "AutoSaves/";
var files = Directory.GetFiles(baseDir, "*" + GameSave.saveExt, SearchOption.TopDirectoryOnly);
var entries = __instance.entries;
var entries2 = new List<UIGameSaveEntry>();
var entryPrefab = __instance.entryPrefab;
var entryPrefabParent = entryPrefab.transform.parent;
foreach (var f in files)
{
var fileInfo = new FileInfo(f);
var entry = Object.Instantiate(entryPrefab, entryPrefabParent);
entry.fileInfo = fileInfo;
entries2.Add(entry);
}
entries2.Sort((x, y) => -x.fileDate.CompareTo(y.fileDate));
if (entries2.Count > 10)
entries2.RemoveRange(10, entries2.Count - 10);
var autoSaveText = ">> " + I18NKeys.AutoSaveEntry.Translate();
foreach (var entry in entries2)
{
entry.indexText.text = "";
var saveName = entry.saveName;
entry._saveName = $"AutoSaves/{saveName}";
var quoteIndex = saveName.IndexOf('[');
if (quoteIndex >= 0)
{
var quoteIndex2 = saveName.IndexOf(']', quoteIndex + 1);
if (quoteIndex2 > 0) saveName = saveName.Substring(quoteIndex, quoteIndex2 + 1 - quoteIndex);
}
entry.nameText.text = $"{autoSaveText} {saveName}";
entry.nameText.fontStyle = FontStyle.Italic;
entry.nameText.color = new Color(1f, 1f, 1f, 0.7f);
entry.timeText.text = $"{entry.fileDate:yyyy-MM-dd HH:mm:ss}";
GameSave.ReadModes(entry.fileInfo.FullName, out var isSandbox, out var isPeace);
if (entry.sandboxIcon != null)
{
entry.sandboxIcon.gameObject.SetActive(isSandbox);
}
if (entry.combatIcon != null)
{
entry.combatIcon.gameObject.SetActive(!isPeace);
}
entry.selected = false;
entry.gameObject.SetActive(true);
}
entries.AddRange(entries2);
entries.Sort((x, y) => -x.fileDate.CompareTo(y.fileDate));
var displayIndex = 1;
for (var i = 0; i < entries.Count; i++)
{
var entry = entries[i];
entry.index = i + 1;
entry.rectTrans.anchoredPosition = new Vector2(entry.rectTrans.anchoredPosition.x, -40 * i);
if (string.IsNullOrEmpty(entry.indexText.text)) continue;
entry.indexText.text = displayIndex.ToString();
displayIndex++;
}
}
[HarmonyPostfix]
[HarmonyPatch(typeof(UISaveGameWindow), nameof(UISaveGameWindow.RefreshList))]
public static void UISaveGameWindow_RefreshList_Postfix(UISaveGameWindow __instance)
{
var entries = __instance.entries;
entries.Sort((x, y) => -x.fileDate.CompareTo(y.fileDate));
for (var i = 0; i < entries.Count; i++)
{
var entry = entries[i];
entry.index = i + 1;
entry.rectTrans.anchoredPosition = new Vector2(entry.rectTrans.anchoredPosition.x, -40 * i);
entry.indexText.text = (i + 1).ToString();
}
}
// Harmony transpiler: UILoadGameWindow_ReplaceSaveName_Transpiler
// Target: UILoadGameWindow.DoLoadSelectedGame, UILoadGameWindow.OnSelectedChange
// Fallback: None — patch will fail loudly if the target method body changes.
[HarmonyTranspiler]
[HarmonyPatch(typeof(UILoadGameWindow), nameof(UILoadGameWindow.DoLoadSelectedGame))]
[HarmonyPatch(typeof(UILoadGameWindow), nameof(UILoadGameWindow.OnSelectedChange))]
private static IEnumerable<CodeInstruction> UILoadGameWindow_ReplaceSaveName_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var matcher = new CodeMatcher(instructions, generator);
matcher.Start().MatchForward(false,
new CodeMatch(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(UIGameSaveEntry), nameof(UIGameSaveEntry.saveName)))
);
matcher.Repeat(m => m.SetAndAdvance(OpCodes.Ldfld, AccessTools.Field(typeof(UIGameSaveEntry), nameof(UIGameSaveEntry._saveName))));
return matcher.InstructionEnumeration();
}
// Harmony transpiler: GameSave_RemoveValidateOnLoad_Transpiler
// Target: GameSave.LoadCurrentGame, GameSave.LoadGameDesc, GameSave.ReadHeader, GameSave.ReadHeaderAndDescAndProperty, GameSave.SaveExist, GameSave.SavePath
// Fallback: Checks CodeMatcher.IsInvalid/IsValid and returns original instructions on mismatch.
[HarmonyTranspiler]
[HarmonyPatch(typeof(GameSave), nameof(GameSave.LoadCurrentGame))]
[HarmonyPatch(typeof(GameSave), nameof(GameSave.LoadGameDesc))]
[HarmonyPatch(typeof(GameSave), nameof(GameSave.ReadHeader))]
[HarmonyPatch(typeof(GameSave), nameof(GameSave.ReadHeaderAndDescAndProperty))]
[HarmonyPatch(typeof(GameSave), nameof(GameSave.SaveExist))]
[HarmonyPatch(typeof(GameSave), nameof(GameSave.SavePath))]
private static IEnumerable<CodeInstruction> GameSave_RemoveValidateOnLoad_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var matcher = new CodeMatcher(instructions, generator);
matcher.Start().MatchForward(false,
new CodeMatch(OpCodes.Call, AccessTools.Method(typeof(CommonUtils), nameof(CommonUtils.ValidFileName)))
);
matcher.RemoveInstruction();
return matcher.InstructionEnumeration();
}
}
*/
private class ConvertSavesFromPeace : PatchImpl<ConvertSavesFromPeace> private class ConvertSavesFromPeace : PatchImpl<ConvertSavesFromPeace>
{ {
private static bool _needConvert; private static bool _needConvert;
@@ -639,7 +639,7 @@ internal static class RealtimeLogisticsInfoPanel
|| rectPoint.x is < -4096f or > 4096f || rectPoint.x is < -4096f or > 4096f
|| rectPoint.y is < -4096f or > 4096f || rectPoint.y is < -4096f or > 4096f
|| Phys.RayCastSphere(localPosition, vec / magnitude, magnitude, Vector3.zero, realRadius, out _) || Phys.RayCastSphere(localPosition, vec / magnitude, magnitude, Vector3.zero, realRadius, out _)
|| storageArray.All(storage => storage.itemId == 0)) || storageArray.Select(x => x.itemId).All(x => x == 0))
{ {
stationTip.gameObject.SetActive(false); stationTip.gameObject.SetActive(false);
continue; continue;
+104
View File
@@ -204,6 +204,110 @@ public class PlayerPatch : PatchImpl<PlayerPatch>
{ {
ShowAllStarsNameStatus = 0; ShowAllStarsNameStatus = 0;
} }
/*
// Harmony transpiler: UIStarmapPlanet__OnLateUpdate_Transpiler
// Target: UIStarmapPlanet._OnLateUpdate
// Fallback: None — patch will fail loudly if the target method body changes.
[HarmonyTranspiler]
[HarmonyPatch(typeof(UIStarmapPlanet), nameof(UIStarmapPlanet._OnLateUpdate))]
private static IEnumerable<CodeInstruction> UIStarmapPlanet__OnLateUpdate_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var matcher = new CodeMatcher(instructions, generator);
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Ldloc_3),
new CodeMatch(OpCodes.Stfld, AccessTools.Field(typeof(UIStarmapPlanet), nameof(UIStarmapPlanet.projected)))
);
matcher.Advance(3);
matcher.CreateLabel(out var jumpPos1);
matcher.InsertAndAdvance(
new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(ShortcutKeysForStarsName), nameof(_showAllStarsNameStatus))),
new CodeInstruction(OpCodes.Ldc_I4_2),
new CodeInstruction(OpCodes.Ceq),
new CodeInstruction(OpCodes.Brfalse, jumpPos1),
new CodeInstruction(OpCodes.Ldc_I4_0),
new CodeInstruction(OpCodes.Stloc_3)
);
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(UIStarmapPlanet), nameof(UIStarmapPlanet.gameHistory))),
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(UIStarmapPlanet), nameof(UIStarmapPlanet.planet))),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(PlanetData), nameof(PlanetData.id))),
new CodeMatch(OpCodes.Callvirt, AccessTools.Field(typeof(GameHistoryData), nameof(GameHistoryData.GetPlanetPin))),
new CodeMatch(OpCodes.Ldc_I4_1),
new CodeMatch(ci => ci.Branches(out _)),
new CodeMatch(OpCodes.Ldc_I4_1),
new CodeMatch(ci => ci.IsStloc()),
new CodeMatch(ci => ci.Branches(out _))
);
matcher.CreateLabelAt(matcher.Pos + 8, out var jumpPos);
var labels = matcher.Labels;
matcher.Labels = [];
matcher.InsertAndAdvance(
new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(ShortcutKeysForStarsName), nameof(_showAllStarsNameStatus))).WithLabels(labels),
new CodeInstruction(OpCodes.Ldc_I4_1),
new CodeInstruction(OpCodes.Ceq),
new CodeInstruction(OpCodes.Brtrue, jumpPos),
new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(PlayerPatch), nameof(_showAllStarsNameKey))),
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(KeyBindings), nameof(KeyBindings.IsKeyPressing))),
new CodeInstruction(OpCodes.Brtrue, jumpPos)
);
return matcher.InstructionEnumeration();
}
// Harmony transpiler: UIStarmapDFHive__OnLateUpdate_Transpiler
// Target: UIStarmapDFHive._OnLateUpdate
// Fallback: None — patch will fail loudly if the target method body changes.
[HarmonyTranspiler]
[HarmonyPatch(typeof(UIStarmapDFHive), nameof(UIStarmapDFHive._OnLateUpdate))]
private static IEnumerable<CodeInstruction> UIStarmapDFHive__OnLateUpdate_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var matcher = new CodeMatcher(instructions, generator);
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(ci => ci.IsLdloc()),
new CodeMatch(OpCodes.Stfld, AccessTools.Field(typeof(UIStarmapDFHive), nameof(UIStarmapDFHive.projected)))
);
matcher.Advance(3);
matcher.CreateLabel(out var jumpPos1);
matcher.InsertAndAdvance(
new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(ShortcutKeysForStarsName), nameof(_showAllStarsNameStatus))),
new CodeInstruction(OpCodes.Ldc_I4_2),
new CodeInstruction(OpCodes.Ceq),
new CodeInstruction(OpCodes.Brfalse, jumpPos1),
new CodeInstruction(OpCodes.Ldc_I4_0),
new CodeInstruction(OpCodes.Stloc_S, 4)
);
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(UIStarmapDFHive), nameof(UIStarmapDFHive.gameHistory))),
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(UIStarmapDFHive), nameof(UIStarmapDFHive.hive))),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(EnemyDFHiveSystem), nameof(EnemyDFHiveSystem.hiveStarId))),
new CodeMatch(OpCodes.Ldc_I4, 1000000),
new CodeMatch(OpCodes.Sub),
new CodeMatch(OpCodes.Callvirt, AccessTools.Field(typeof(GameHistoryData), nameof(GameHistoryData.GetHivePin))),
new CodeMatch(OpCodes.Ldc_I4_1),
new CodeMatch(ci => ci.Branches(out _)),
new CodeMatch(OpCodes.Ldc_I4_1),
new CodeMatch(ci => ci.IsStloc()),
new CodeMatch(ci => ci.Branches(out _))
);
matcher.CreateLabelAt(matcher.Pos + 10, out var jumpPos);
var labels = matcher.Labels;
matcher.Labels = [];
matcher.InsertAndAdvance(
new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(ShortcutKeysForStarsName), nameof(_showAllStarsNameStatus))).WithLabels(labels),
new CodeInstruction(OpCodes.Ldc_I4_1),
new CodeInstruction(OpCodes.Ceq),
new CodeInstruction(OpCodes.Brtrue, jumpPos),
new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(PlayerPatch), nameof(_showAllStarsNameKey))),
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(KeyBindings), nameof(KeyBindings.IsKeyPressing))),
new CodeInstruction(OpCodes.Brtrue, jumpPos)
);
return matcher.InstructionEnumeration();
}
*/
} }
+5
View File
@@ -106,6 +106,11 @@ public class UIPatch : PatchImpl<UIPatch>
} }
} }
private static Vector2 GetAdjustedSizeDelta(Vector2 origSizeDelta)
{
return new Vector2(origSizeDelta.x + 40f, origSizeDelta.y);
}
protected override void OnDisable() protected override void OnDisable()
{ {
if (planetVeinCount != null) if (planetVeinCount != null)
@@ -88,8 +88,7 @@ public static class BlueprintDescriptionFormatter
var input = new List<string>(); var input = new List<string>();
var output = new SortedDictionary<int, double>(); var output = new SortedDictionary<int, double>();
var research = new SortedDictionary<int, double>(); var research = new SortedDictionary<int, double>();
var orderedFlows = report.ItemFlows.Values.OrderBy(flow => flow.ItemId).ToArray(); foreach (var flow in report.ItemFlows.Values.OrderBy(flow => flow.ItemId))
foreach (var flow in orderedFlows)
{ {
var shortage = Math.Min(flow.IntermediateShortage, var shortage = Math.Min(flow.IntermediateShortage,
flow.SteadyStateExternalSupply ?? flow.RequiredExternalSupply); flow.SteadyStateExternalSupply ?? flow.RequiredExternalSupply);
@@ -99,14 +98,14 @@ public static class BlueprintDescriptionFormatter
if (report.MaterialComplete) if (report.MaterialComplete)
{ {
foreach (var flow in orderedFlows) foreach (var flow in report.ItemFlows.Values.OrderBy(flow => flow.ItemId))
{ {
if (flow.OverbuildSurplus.GetValueOrDefault() > Tolerance) if (flow.OverbuildSurplus.GetValueOrDefault() > Tolerance)
excess.Add(FormatItem(flow.ItemId, flow.OverbuildSurplus.Value, itemTag)); excess.Add(FormatItem(flow.ItemId, flow.OverbuildSurplus.Value, itemTag));
} }
} }
foreach (var flow in orderedFlows) foreach (var flow in report.ItemFlows.Values.OrderBy(flow => flow.ItemId))
{ {
var requiredSupply = flow.SteadyStateExternalSupply ?? flow.RequiredExternalSupply; var requiredSupply = flow.SteadyStateExternalSupply ?? flow.RequiredExternalSupply;
if (requiredSupply > Tolerance && flow.IntermediateShortage <= Tolerance) if (requiredSupply > Tolerance && flow.IntermediateShortage <= Tolerance)
@@ -119,7 +119,8 @@ public static class ProductionCatalogReader
} }
return new ProductionCatalog(items, recipes, buildings, return new ProductionCatalog(items, recipes, buildings,
Cargo.accTableMilli, Cargo.incTableMilli, Cargo.powerTableRatio, technologies, matrixIds); (double[])Cargo.accTableMilli.Clone(), (double[])Cargo.incTableMilli.Clone(),
(double[])Cargo.powerTableRatio.Clone(), technologies, matrixIds);
} }
private static void AddSpecialRecipes(IEnumerable<ItemProto> itemProtos, private static void AddSpecialRecipes(IEnumerable<ItemProto> itemProtos,
+4 -2
View File
@@ -17,7 +17,8 @@
* Strict hotkey dectection for build menu, thus building hotkeys(0~9, F1~F10, X, U) are not triggered while holding Ctrl/Alt/Shift. * Strict hotkey dectection for build menu, thus building hotkeys(0~9, F1~F10, X, U) are not triggered while holding Ctrl/Alt/Shift.
* Fix a bug that warning popup on `Veins Utilization` upgraded to level 8000+ * Fix a bug that warning popup on `Veins Utilization` upgraded to level 8000+
* Sort blueprint structures before saving, to reduce generated blueprint data size a little * Sort blueprint structures before saving, to reduce generated blueprint data size a little
* Add an `Auto-fill` entry to the description header in the blueprint browser, copy, and paste inspectors. Click it to open generation options without moving or resizing native fields or covering the file list * Add an `Auto-fill` entry to the description header in the blueprint browser, copy, and paste inspectors. Click it to open options beside the entry without moving or resizing native fields; the popup follows the entry while scrolling and adjusts its position at screen edges
* The popup has an `Auto-fill description` title, a native X close button, proliferation and production-basis options, and one `Generate` button at the bottom. The dropdown overlays the footer without resizing the popup or moving the action. Close with the X, an outside click, or Esc; when the dropdown is open, Esc closes it first. Successful generation closes the popup.
* `Production basis` defaults to `Final-product output` each time the inspector opens, retaining rated final outputs and showing intermediate shortages and excess. Choose `Lowest intermediate throughput` to scale the final-product mix together to the bottleneck, using recipe ratios and shared intermediate demand. Complete, balanceable chains then have no internal shortages; unused intermediate capacity appears as excess. External inputs and final outputs use the same basis. * `Production basis` defaults to `Final-product output` each time the inspector opens, retaining rated final outputs and showing intermediate shortages and excess. Choose `Lowest intermediate throughput` to scale the final-product mix together to the bottleneck, using recipe ratios and shared intermediate demand. Complete, balanceable chains then have no internal shortages; unused intermediate capacity appears as excess. External inputs and final outputs use the same basis.
* `Proliferation` defaults to on when the blueprint contains a Spray Coater; it can be changed manually. Power demand still estimates all selected buildings at full load in either production basis. * `Proliferation` defaults to on when the blueprint contains a Spray Coater; it can be changed manually. Power demand still estimates all selected buildings at full load in either production basis.
* Replaces the main description with material flows per minute and writes power demand to a `Power` custom field, preserving other custom fields. If the bottleneck basis cannot be determined, the existing description is kept; check missing building settings and chain outputs, or select `Final-product output`. Save the blueprint manually to keep generated changes. * Replaces the main description with material flows per minute and writes power demand to a `Power` custom field, preserving other custom fields. If the bottleneck basis cannot be determined, the existing description is kept; check missing building settings and chain outputs, or select `Final-product output`. Save the blueprint manually to keep generated changes.
@@ -225,7 +226,8 @@
* 更严格的建造菜单热键检测,因此在按住Ctrl/Alt/Shift时不再会触发建造热键(0~9, F1~F10, X, U) * 更严格的建造菜单热键检测,因此在按住Ctrl/Alt/Shift时不再会触发建造热键(0~9, F1~F10, X, U)
* 修复了`矿物利用`升级到8000级以上时弹出警告的bug * 修复了`矿物利用`升级到8000级以上时弹出警告的bug
* 保存蓝图前对建筑进行排序,以减少生成的蓝图数据大小 * 保存蓝图前对建筑进行排序,以减少生成的蓝图数据大小
* 在蓝图浏览、复制和粘贴检查面板的说明标题行增加「自动填写」入口,点击展开生成选项,不移动或缩放原生字段,也不遮挡文件列表 * 在蓝图浏览、复制和粘贴检查面板的说明标题行增加「自动填写」入口,点击后在入口旁打开生成选项,不移动或缩放原生字段;滚动时弹出面板跟随入口,并在屏幕边缘调整位置
* 面板包含「自动填写说明」标题、原生叉号关闭按钮、增产和产量基准选项,以及底部单个「生成说明」按钮。展开下拉列表时,列表覆盖在底部操作区域前方,面板尺寸和按钮位置保持不变。可通过叉号、点击外部或 Esc 关闭;下拉列表展开时,Esc 先收起列表。生成成功后关闭面板。
* 每次打开检查面板时,「产量基准」默认为「最终产物产量」,保留最终产物的额定产量,并显示中间产物的缺口和余量。选择「最低产量中间产物」后,按配方比例和共享中间物料的需求换算瓶颈,等比例缩放各最终产物。数据完整且可平衡的生产链没有内部缺口,未使用的中间产能列为「多余」;外部输入和最终输出采用同一基准。 * 每次打开检查面板时,「产量基准」默认为「最终产物产量」,保留最终产物的额定产量,并显示中间产物的缺口和余量。选择「最低产量中间产物」后,按配方比例和共享中间物料的需求换算瓶颈,等比例缩放各最终产物。数据完整且可平衡的生产链没有内部缺口,未使用的中间产能列为「多余」;外部输入和最终输出采用同一基准。
* 蓝图含喷涂机时默认勾选「增产」,也可手动修改。两种产量基准均按所选全部建筑满载估算耗电。 * 蓝图含喷涂机时默认勾选「增产」,也可手动修改。两种产量基准均按所选全部建筑满载估算耗电。
* 用每分钟的物料流量替换原说明,将耗电写入「耗电」自定义字段,保留其他自定义字段。无法确定瓶颈基准时保留原说明;可检查缺失的建筑参数和生产链输出,或改选「最终产物产量」。填写后需手动保存蓝图。 * 用每分钟的物料流量替换原说明,将耗电写入「耗电」自定义字段,保留其他自定义字段。无法确定瓶颈基准时保留原说明;可检查缺失的建筑参数和生产链输出,或改选「最终产物产量」。填写后需手动保存蓝图。
+7
View File
@@ -32,6 +32,8 @@ public class MyKeyBinder : MonoBehaviour
[SerializeField] public UIButton setNoneKeyUIButton; [SerializeField] public UIButton setNoneKeyUIButton;
private bool _nextNotOn;
protected void OnDestroy() protected void OnDestroy()
{ {
OnFree?.Invoke(); OnFree?.Invoke();
@@ -221,6 +223,11 @@ public class MyKeyBinder : MonoBehaviour
{ {
inputUIButton.highlighted = true; inputUIButton.highlighted = true;
if (!_nextNotOn) return;
_nextNotOn = false;
inputUIButton.highlighted = false;
setTheKeyToggle.isOn = false;
waitingText.gameObject.SetActive(false);
} }
public void OnSetDefaultKeyClick(int data) public void OnSetDefaultKeyClick(int data)
+28
View File
@@ -559,6 +559,15 @@ public abstract class MyWindowManager
win._Destroy(); win._Destroy();
} }
/*
public static void SetRect(ManualBehaviour win, RectTransform rect)
{
var rectTransform = win.GetComponent<RectTransform>();
//rectTransform.position =
//rectTransform.sizeDelta = rect;
}
*/
public class Patch : PatchImpl<Patch> public class Patch : PatchImpl<Patch>
{ {
protected override void OnEnable() protected override void OnEnable()
@@ -577,6 +586,14 @@ public abstract class MyWindowManager
Initialized = true; Initialized = true;
} }
/*
//_Create -> _Init
[HarmonyPostfix, HarmonyPatch(typeof(UIGame), nameof(UIGame._OnCreate))]
public static void UIGame__OnCreate_Postfix()
{
}
*/
[HarmonyPostfix, HarmonyPatch(typeof(UIRoot), nameof(UIRoot._OnDestroy))] [HarmonyPostfix, HarmonyPatch(typeof(UIRoot), nameof(UIRoot._OnDestroy))]
public static void UIRoot__OnDestroy_Postfix() public static void UIRoot__OnDestroy_Postfix()
{ {
@@ -595,6 +612,17 @@ public abstract class MyWindowManager
InitAllWindows(); InitAllWindows();
} }
/*
[HarmonyPostfix, HarmonyPatch(typeof(UIGame), nameof(UIGame._OnFree))]
public static void UIGame__OnFree_Postfix()
{
foreach (var win in Windows)
{
win._Free();
}
}
*/
[HarmonyPostfix, HarmonyPatch(typeof(UIRoot), nameof(UIRoot._OnUpdate))] [HarmonyPostfix, HarmonyPatch(typeof(UIRoot), nameof(UIRoot._OnUpdate))]
public static void UIRoot__OnUpdate_Postfix() public static void UIRoot__OnUpdate_Postfix()
{ {
+36 -12
View File
@@ -96,19 +96,37 @@ public static class UIConfigWindow
private class AutoConfigDispenserChargePowerMapper() : MyWindow.RangeValueMapper<int>(3, 30) private class AutoConfigDispenserChargePowerMapper() : MyWindow.RangeValueMapper<int>(3, 30)
{ {
public override string FormatValue(string format, int value) => FormatPower(value * 300000L); public override string FormatValue(string format, int value)
{
var sb = new StringBuilder(" ");
StringBuilderUtility.WriteKMG(sb, 8, value * 300000L, false);
sb.Append('W');
return sb.ToString().Trim();
}
} }
private class AutoConfigBattleBaseChargePowerMapper() : MyWindow.RangeValueMapper<int>(4, 40) private class AutoConfigBattleBaseChargePowerMapper() : MyWindow.RangeValueMapper<int>(4, 40)
{ {
public override string FormatValue(string format, int value) => FormatPower(value * 300000L); public override string FormatValue(string format, int value)
{
var sb = new StringBuilder(" ");
StringBuilderUtility.WriteKMG(sb, 8, value * 300000L, false);
sb.Append('W');
return sb.ToString().Trim();
}
} }
private class AutoConfigPLSChargePowerMapper() : MyWindow.RangeValueMapper<int>(2, 20) private class AutoConfigPLSChargePowerMapper() : MyWindow.RangeValueMapper<int>(2, 20)
{ {
public override string FormatValue(string format, int value) => FormatPower(value * 3000000L); public override string FormatValue(string format, int value)
{
var sb = new StringBuilder(" ");
StringBuilderUtility.WriteKMG(sb, 8, value * 3000000L, false);
sb.Append('W');
return sb.ToString().Trim();
}
} }
private class AutoConfigCarrierMinDeliverMapper() : MyWindow.RangeValueMapper<int>(0, 10) private class AutoConfigCarrierMinDeliverMapper() : MyWindow.RangeValueMapper<int>(0, 10)
@@ -129,7 +147,13 @@ public static class UIConfigWindow
private class AutoConfigILSChargePowerMapper() : MyWindow.RangeValueMapper<int>(2, 20) private class AutoConfigILSChargePowerMapper() : MyWindow.RangeValueMapper<int>(2, 20)
{ {
public override string FormatValue(string format, int value) => FormatPower(value * 15000000L); public override string FormatValue(string format, int value)
{
var sb = new StringBuilder(" ");
StringBuilderUtility.WriteKMG(sb, 8, value * 15000000L, false);
sb.Append('W');
return sb.ToString().Trim();
}
} }
private class AutoConfigILSMaxTripShipMapper() : MyWindow.RangeValueMapper<int>(1, 41) private class AutoConfigILSMaxTripShipMapper() : MyWindow.RangeValueMapper<int>(1, 41)
@@ -168,14 +192,6 @@ public static class UIConfigWindow
} }
} }
private static string FormatPower(long watts)
{
var sb = new StringBuilder(" ");
StringBuilderUtility.WriteKMG(sb, 8, watts, false);
sb.Append('W');
return sb.ToString().Trim();
}
private static void CreateUI(MyConfigWindow wnd, RectTransform trans) private static void CreateUI(MyConfigWindow wnd, RectTransform trans)
{ {
UnityEngine.UI.Text txt; UnityEngine.UI.Text txt;
@@ -187,6 +203,14 @@ public static class UIConfigWindow
wnd.AddCheckBox(x, y, tab1, GamePatch.EnableWindowResizeEnabled, I18NKeys.EnableGameWindowResize); wnd.AddCheckBox(x, y, tab1, GamePatch.EnableWindowResizeEnabled, I18NKeys.EnableGameWindowResize);
y += 36f; y += 36f;
wnd.AddCheckBox(x, y, tab1, GamePatch.LoadLastWindowRectEnabled, I18NKeys.RemeberWindowPositionAndSizeOnLastExit); wnd.AddCheckBox(x, y, tab1, GamePatch.LoadLastWindowRectEnabled, I18NKeys.RemeberWindowPositionAndSizeOnLastExit);
/*
y += 30f;
wnd.AddCheckBox(x, y, tab1, GamePatch.AutoSaveOptEnabled, "Better auto-save mechanism");
x = 200f;
y += 6f;
wnd.AddTipsButton2(x, y, tab1, "Better auto-save mechanism", "Better auto-save mechanism tips", "auto-save-opt-tips");
x = 0f;
*/
y += 36f; y += 36f;
wnd.AddCheckBox(x, y, tab1, GamePatch.ConvertSavesFromPeaceEnabled, I18NKeys.ConvertOldSavesToCombatModeOnLoading); wnd.AddCheckBox(x, y, tab1, GamePatch.ConvertSavesFromPeaceEnabled, I18NKeys.ConvertOldSavesToCombatModeOnLoading);
MyCheckBox checkBoxForMeasureTextWidth; MyCheckBox checkBoxForMeasureTextWidth;
+4
View File
@@ -89,6 +89,10 @@ public class UXAssist : BaseUnityPlugin, IModCanSave
"Profile-based option"); "Profile-based option");
GamePatch.DefaultProfileName = Config.Bind("Game", "DefaultProfileName", "Default", GamePatch.DefaultProfileName = Config.Bind("Game", "DefaultProfileName", "Default",
"Default profile name, used when profile-based save folder is enabled. Use original game save folder if matched"); "Default profile name, used when profile-based save folder is enabled. Use original game save folder if matched");
/*
GamePatch.AutoSaveOptEnabled = Config.Bind("Game", "AutoSaveOpt", false,
"Better auto-save mechanism");
*/
GamePatch.ConvertSavesFromPeaceEnabled = Config.Bind("Game", "ConvertSavesFromPeace", false, GamePatch.ConvertSavesFromPeaceEnabled = Config.Bind("Game", "ConvertSavesFromPeace", false,
"Convert saves from Peace mode to Combat mode on save loading"); "Convert saves from Peace mode to Combat mode on save loading");
GamePatch.GameUpsFactor = _dummyConfig.Bind("Game", "GameUpsFactor", 1.0, GamePatch.GameUpsFactor = _dummyConfig.Bind("Game", "GameUpsFactor", 1.0,
+40 -11
View File
@@ -4,13 +4,14 @@ This document records the native layout evidence for the UXAssist description-he
## Native evidence ## Native evidence
Inspected on 2026-11-01 after discovering Steam through `HKCU`'s Steam path and `steamapps/libraryfolders.vdf`: Original installed DSP sources, rechecked on 2026-11-05 after discovery through the Steam registry and `steamapps/libraryfolders.vdf`:
- Original assembly: `D:/Steam/steamapps/common/Dyson Sphere Program/DSPGAME_Data/Managed/Assembly-CSharp.dll`, SHA-256 `EF314425DADE51F529F184F07BE136CD3C2660A6A81515603C7226FBE7AB1D8C`. - Original assembly: `D:/Steam/steamapps/common/Dyson Sphere Program/DSPGAME_Data/Managed/Assembly-CSharp.dll`, SHA-256 `EF314425DADE51F529F184F07BE136CD3C2660A6A81515603C7226FBE7AB1D8C`.
- Original `UnityEngine.UI.dll`, SHA-256 `C5ACC25EBD597B586D323AF506FB88E760322550940F1A3B0EA4FC8143FCB26C`.
- Native UI assets: `DSPGAME_Data/level0`, SHA-256 `04655A46BBEB113113688BCDC0E0EA8EC5F128B348E32194FC9743ADB48C8E91`. - Native UI assets: `DSPGAME_Data/level0`, SHA-256 `04655A46BBEB113113688BCDC0E0EA8EC5F128B348E32194FC9743ADB48C8E91`.
- The installed version history ends at `0.10.35.29151`; the Steam manifest reports build ID `25955035`. Assembly file version `0.0.0.0` alone does not identify this game build. - The installed version history ends at `0.10.35.29151`; the Steam manifest reports build ID `25955035`. Assembly file version `0.0.0.0` alone does not identify this game build.
The original `UIBlueprintInspector.Refresh` sizes the description and native groups, places groups 2 through 4, and updates the scroll content height. It does not restore group 1's position. The previous UXAssist layout shifted group 1 and repeatedly offset the later groups and content height, making both the native refresh and other layout patches share ownership of those transforms. Native `UIBlueprintInspector.Refresh` owns description and group sizes, later group positions, and scroll content height. UXAssist positions only its own entry and popup.
The relevant original methods can be reproduced by decompiling the following types from the original assembly: The relevant original methods can be reproduced by decompiling the following types from the original assembly:
@@ -22,11 +23,37 @@ The relevant original methods can be reproduced by decompiling the following typ
| `UIBlueprintInspector.OnCustomFieldEndEdit(string str)` and `CollectExternalFields(int excludeTargetId = -1)` | Collect, escape, and validate pending custom-field edits through the native path. | | `UIBlueprintInspector.OnCustomFieldEndEdit(string str)` and `CollectExternalFields(int excludeTargetId = -1)` | Collect, escape, and validate pending custom-field edits through the native path. |
| `UIBlueprintInspector.OnCopyClick()`, `OnSaveChangesClick()`, and `OnSaveClick()` | Serialize or save the current blueprint with the game's native workflow. | | `UIBlueprintInspector.OnCopyClick()`, `OnSaveChangesClick()`, and `OnSaveClick()` | Serialize or save the current blueprint with the game's native workflow. |
The native `descGroupTrans` in all three inspectors contains a description label at the top and an input beginning 22 pixels below it. The compact UXAssist entry occupies the right side of this existing title row; it does not move the title, input, groups, or scroll content. Options appear only on request inside the inspector and close after successful generation or inspector closure. The browser's file grid remains outside the UXAssist controls. Following the separate native settings panel is unnecessary, and no per-frame positioning patch is used. The native description input starts 22 pixels below its title. The entry copies the title's font, size, style, line spacing, and alignment, with zero top text inset, while its hit rectangle stays 22 pixels high. It follows the title's measured text width plus 8 pixels and reserves 8 pixels before the actual native icon, including when the icon is inactive. It hides if it cannot fit. The title's 30-pixel Text rectangle must not become the button's hit rectangle, which would extend into the input below. Native labels, inputs, groups, scroll content, and settings retain their layout.
`UIBlueprintInspector.Refresh(forModify: true)` does not reload `descTextInput`. Successful generation must assign both the blueprint description and its input before using the native modification refresh. Pending custom fields must first pass through the native field collection and escaping rules. Native copy and save handlers serialize the current blueprint, so they remain the actions used to share or persist a generated description. `UIBlueprintInspector.Refresh(forModify: true)` does not reload `descTextInput`. Successful generation must assign both the blueprint description and its input before using the native modification refresh. Pending custom fields must first pass through the native field collection and escaping rules. Native copy and save handlers serialize the current blueprint, so they remain the actions used to share or persist a generated description.
Decompiled methods and extracted rectangle data are development artifacts under `UXAssist/obj/native-inspector/`. Reinspect the installed original assembly and assets after a game update; the publicized compile-time references omit method bodies. Reinspect the installed original assemblies and assets after a game update; the publicized compile-time references omit method bodies.
## Anchored options and native conventions
The popup uses the entry's world corners, transformed into its parent's coordinates, and actual root-canvas bounds. Placement prefers below the entry with a 6-pixel gap and aligned right edges, flips above when needed, and clamps against an 8-pixel canvas inset. A panel too large for that area is closed. `Canvas.willRenderCanvases` reconciles placement while open. An inactive or fully clipped entry closes its popup.
The panel has a title and native X, proliferation, production basis with help, and one footer `Generate` action. Content insets include the sliced sprite's approximately 13-pixel horizontal and 11-pixel vertical trim before pixels-per-unit conversion. The title has extra left and top clearance from the visible border. The 20-pixel checkbox has an independently sized label with a 4-pixel gap and vertical overflow allowed; label height remains at least 26 pixels or preferred glyph height plus padding. The panel and footer are sized from the form alone. Opening the dropdown overlays the footer without resizing the popup or moving the action.
The X comes from `inserterWindow/panel-bg/btn-box/close-wnd-btn`: a 40-by-30 native button with a centered 16-by-16 icon and a transparent 30-by-19 raycast child. Its original serialized `Button.onClick` targets the original inserter window's `_Close`. The owned clone replaces the entire `Button.ButtonClickedEvent` before adding its popup callback; removing runtime listeners alone would leave that persistent callback active.
The production-basis selector directly clones the standard rectangular `optionWindow.resolutionComp`. Cloned runtime resolution rows are removed and submit/change events are replaced before the two production choices are assigned, so changing the owned selection cannot change native resolution settings. The main caption uses 8-pixel left and 30-pixel right insets; row text uses 8-pixel horizontal insets. Native row selection closes the list, with no extra submit-close handler. The shared combo helper is unchanged.
| Original source | Behavior used by the popup |
| --- | --- |
| `UIRoot._OnUpdate()` and `EscapeInputLogic()` | Give native message boxes Escape priority before the game UI updates. |
| `UIGame._OnUpdate()` | Updates blueprint inspectors before later native picker and function-window Escape handlers. The owned inspector postfix consumes Escape after closing an expanded dropdown or its popup. |
| `UIItemPicker._OnUpdate()` | Tests left, right, and middle clicks outside a screen rectangle using the overlay canvas camera. The owned test also accepts the entry and an open dropdown. |
| `UIPopupMenu.SetState()` | Constrains popup placement to game UI bounds and brings it to the front. |
| Native inserter close-button subtree and combo row event routing | Supply the actual X artwork/hit area and the select-then-close event order. |
Original font, sprite, header, standard-resolution-control, and close-button captures and focused decompilations are retained in the external task evidence under `2026-11-05-UXAssist-BlueprintTextLayout/`, including `standard-controls/`. Native generator rules support keeping glyph height independent of checkbox size; native header captures identify the icon's actual 20-pixel slot. Source analysis and embedded-font calculations do not execute Unity's runtime preferred-size calculation, rasterization, or interaction. Investigation reports remain outside the repository.
## Recorded checks
The placement harness extracts the actual private `TryGetPopupPosition` method and compiles it with data-only `Rect` and `Vector2` substitutes. It checks supplied bounds, including parent transforms, canvas edges, below/above placement, and oversized-panel rejection. This validates the placement calculation, not current text rendering. Run font and sprite analysis against the current source and captured standard control.
For this revision, the normal Release build passed with 0 warnings and 0 errors, and `git diff --check` passed. These checks do not execute Unity rendering or interaction.
## Managed production checks ## Managed production checks
@@ -44,10 +71,12 @@ The production-basis cases check an undersupplied chain, recipe-ratio conversion
No in-game, Unity event-loop, or third-party mod integration test has been performed for this change. Repeat these checks at the target profile's resolutions and UI scales, with each installed blueprint UI mod. The header entry avoids native layout writes but another mod may use the same extension space. No in-game, Unity event-loop, or third-party mod integration test has been performed for this change. Repeat these checks at the target profile's resolutions and UI scales, with each installed blueprint UI mod. The header entry avoids native layout writes but another mod may use the same extension space.
1. Open all three inspectors in English and Simplified Chinese. Confirm the header entry is readable without covering the title or editable description. Open and close its options, generate, and close the inspector. The options must not remain over the file grid or survive an inspector close. 1. Open each inspector in English and Simplified Chinese with different custom-field counts. Confirm the entry text shares the native title's baseline. Focus the description input so its icon appears; the entry must remain before that icon and its clickable area must not cover the input below. Open the options and check title clearance, compact checkbox spacing, visible captions, native X, and one footer action. At screen edges, confirm it flips or shifts into available canvas space.
2. Scroll the native description and custom fields and expand native foundation, fill-only, and reform settings. All native fields must retain their positions and sizes, and scrolling must reach every field. 2. Scroll while the popup is open. Confirm it follows the entry after native layout and closes when the entry is fully clipped. Expand native foundation, fill-only, and reform settings; all native fields must retain their positions and sizes, and scrolling must reach every field.
3. Reopen each inspector and repeatedly refresh or change the blueprint selection. Confirm there is one entry, options are initially closed, the production basis resets to final-product output on opening, Spray Coaters set the automatic proliferation default, and a manual checkbox choice survives content refreshes in the current session. 3. Open the rectangular production-basis list. Confirm text has clear left padding and space for the arrow. The list must overlay the footer without changing panel size or footer position. Select each item and confirm it closes the list without generating text or changing the native resolution setting. Reopen the popup and change language; selector dimensions and text spacing must remain valid.
4. Generate both production bases for an unbalanced chain. Final-product output should retain rated final capacity and show the missing intermediate; lowest intermediate throughput should reduce the common final-output mix, use correspondingly reduced external inputs, and show no internal shortage when the chain is complete and balanceable. Power should remain the same full-load estimate. Check necessary coproduct output separately from unused intermediate capacity. 4. Close the popup with its X; the inspector and an open inserter window must remain open. Reopen and click outside with the left, right, and middle mouse buttons: the popup should close, and the clicked native control or world target should retain its normal behavior. Press Esc with the list expanded: only the list should close. Press Esc again: the popup should close while the inspector stays open. With a native message box present, its Escape handler must retain priority.
5. Edit the description and unrelated custom fields before generating. Generate twice, including with 20 custom fields and with existing English or Chinese power fields. Confirm unrelated edits survive, duplicate power fields are consolidated, and failed generation leaves the prior description and fields intact. Include missing building settings, an unavailable bottleneck basis, and the native description length limit. 5. Reopen each inspector and repeatedly refresh or change the blueprint selection. Confirm there is one entry, options are initially closed, the production basis resets to final-product output on opening, Spray Coaters set the automatic proliferation default, and a manual checkbox choice survives content refreshes in the current session. Successful generation, a replacement blueprint, and inspector closure must dismiss the popup.
6. Save, copy the share code, and reopen or paste the blueprint through the native buttons. Confirm the generated main description, power field, and unrelated fields persist correctly. With a research-mode lab, confirm net produced matrices appear under Research without fabricated matrix imports or research speed. 6. Generate both production bases for an unbalanced chain. Final-product output should retain rated final capacity and show the missing intermediate; lowest intermediate throughput should reduce the common final-output mix, use correspondingly reduced external inputs, and show no internal shortage when the chain is complete and balanceable. Power should remain the same full-load estimate. Check necessary coproduct output separately from unused intermediate capacity.
7. Restart the test profile without UXAssist, then restore it and restart again. Confirm the entry and options are absent without UXAssist, native fields keep their normal layout in both cases, and repeated opening and generation work with the installed blueprint mods. `OnDisable` and inspector-destruction cleanup are code-review checks unless a development harness exercises them; a supported user-facing hot-disable workflow is not assumed. 7. Edit the description and unrelated custom fields before generating. Generate twice, including with 20 custom fields and with existing English or Chinese power fields. Confirm unrelated edits survive, duplicate power fields are consolidated, and failed generation leaves the prior description and fields intact. Include missing building settings, an unavailable bottleneck basis, and the native description length limit.
8. Save, copy the share code, and reopen or paste the blueprint through the native buttons. Confirm the generated main description, power field, and unrelated fields persist correctly. With a research-mode lab, confirm net produced matrices appear under Research without fabricated matrix imports or research speed.
9. Restart the test profile without UXAssist, then restore it and restart again. Confirm the entry and options are absent without UXAssist, native fields keep their normal layout in both cases, and repeated opening and generation work with the installed blueprint mods. `OnDisable` and inspector-destruction cleanup are code-review checks unless a development harness exercises them; a supported user-facing hot-disable workflow is not assumed.
+9 -3
View File
@@ -70,9 +70,15 @@ Native research uses the current lab technology's matrix point requirements, wit
## Blueprint descriptions ## Blueprint descriptions
The shared `UIBlueprintInspector` in browser, copy, and paste modes adds a compact `Auto-fill` entry to the existing description header. Its options open on demand within the inspector, rather than occupying the browser file grid. Only UXAssist-owned transforms are positioned: native fields, groups, anchors, and scroll height remain owned by the game. No per-frame layout patch or native-settings tracking is needed. Disable and destruction remove only the UXAssist controls. The shared `UIBlueprintInspector` in browser, copy, and paste modes adds a compact `Auto-fill` entry after the measured native description title, with an 8-pixel gap. Its text copies the native title's font, size, style, line spacing, and alignment, with a zero top inset; its hit rectangle stays within the 22-pixel header. Reserve the actual native icon button's bounds and another 8-pixel gap even when that icon is inactive; hide the owned entry if it cannot fit. Its options panel is an owned child of `inspector.rectTrans`, outside the scroll mask. On opening, actual entry corners and root-canvas bounds are converted into that parent's coordinates. The private placement method in `InspectorControls` prefers a position below the entry with their right edges aligned, flips above when needed, and clamps against canvas bounds; a panel too large for those bounds is closed. A `Canvas.willRenderCanvases` subscription follows the entry after native layout and scrolling only while the options are open; hiding the entry or scrolling it completely outside its viewport closes the popup. Native fields, groups, anchors, and scroll height remain owned by the game. Closing, disabling, and destruction unsubscribe the positioning callback and remove only owned controls as appropriate.
The options contain `Auto-fill description`, `Proliferation`, and a `Production basis` selector with a localized help tip. Each inspector open resets the basis to `Final-product output`, retaining existing calculation behavior; selecting `Lowest intermediate throughput` opts into `BottleneckIntermediate` for generation. The checkbox initially reflects the blueprint's Spray Coater prefab capability and tracks content changes until manually changed in the current editing session; changing it does not modify the blueprint. Generation captures only `blueprint.buildings` with `BlueprintSelectionReader.FromBlueprint` on the game thread, then runs `FactoryBlackBoxAnalyzer` against the captured catalog. A successful bottleneck solve supplies classification and steady-state balances directly; the original classifier runs only in final-product mode or after an unavailable bottleneck result. The maximum supported proliferation level applies while each building keeps its acceleration or extra-products mode. Input coating is assumed to be supplied externally; no spray routing or spray consumption is inferred from the Spray Coater. The options use a title and the actual native X subtree, followed by proliferation, production basis with help, and one `Generate` action at the lower right. Content margins start inside the sliced background's visible fill: add `DataUtility.GetPadding(sprite) / image.pixelsPerUnit` to the desired gaps. The title has 12 pixels more left inset than the body and 18 pixels after the top sprite trim. Keep the 20-pixel checkbox independent of its label's height, at least 26 pixels or preferred glyph height plus padding, with vertical overflow allowed and a 4-pixel horizontal gap. Owned button and combo captions disable inherited best-fit sizing and have explicit text insets. Localized preferred sizes determine the form dimensions; opening the dropdown overlays the footer without changing panel size or footer position. The cloned X must receive a new `Button.ButtonClickedEvent`: its source has a persistent callback to the original inserter window that `RemoveAllListeners` does not remove.
The production-basis selector directly clones the standard rectangular `optionWindow.resolutionComp` as an owned `UIComboBox`. Remove cloned runtime resolution rows, clear items, and replace its submit/change events before assigning the two production choices. Keep the native row-selection and dropdown behavior; the main caption has 8-pixel left and 30-pixel right insets, and the row template has 8-pixel horizontal insets. Main and item captions use single-line overflow so measuring preferred height before the new width is assigned cannot wrap against the previous width. The shared combo helper is unchanged.
Handle dismissal in the owning inspector's `_OnUpdate` postfix. Processed `VFInput.escape` respects an earlier native message-box handler; close an expanded dropdown first, otherwise close the popup, then consume Escape before later native window-closing handlers run. Left, right, or middle clicks outside the popup, entry, and open dropdown close the options while preserving the clicked native target's normal behavior. Successful generation, blueprint replacement, and inspector closure also close the options.
Each inspector open resets the basis to `Final-product output`, retaining existing calculation behavior; selecting `Lowest intermediate throughput` opts into `BottleneckIntermediate` for generation. The checkbox initially reflects the blueprint's Spray Coater prefab capability and tracks content changes until manually changed in the current editing session; changing it does not modify the blueprint. Generation captures only `blueprint.buildings` with `BlueprintSelectionReader.FromBlueprint` on the game thread, then runs `FactoryBlackBoxAnalyzer` against the captured catalog. A successful bottleneck solve supplies classification and steady-state balances directly; the original classifier runs only in final-product mode or after an unavailable bottleneck result. The maximum supported proliferation level applies while each building keeps its acceleration or extra-products mode. Input coating is assumed to be supplied externally; no spray routing or spray consumption is inferred from the Spray Coater.
`BlueprintDescriptionFormatter` builds replacement multiline `blueprint.desc` text in this order: optional `Missing:` and `Excess:` lines for intermediate shortages and excess classified by the selected production basis; `Input:` for external inputs capped by downstream demand; `Output:` for ordinary final products and necessary coproduct surplus; and `Research:` for positive net matrix production accepted by a selected research-mode lab. Each warning category has one label followed by comma-separated items; warnings do not repeat in Input, and a matrix on Research does not repeat in Output. It uses `SteadyStateExternalSupply` for complete and independently known partial inputs, labeling partial values as known portions. The assumed lab adds no numerical matrix consumption or external input; other buildings' known matrix demand is subtracted from the Research rate. Omit each empty line, including Research when no produced matrix remains. A single optional `Power` custom field separates factory and configured logistics consumption, omitting categories with no demand and removing the field altogether if neither consumes power; a present but unknown category displays `Unknown` rather than zero. Material rates remain items per minute even though the description labels omit the unit. Rates are rounded only for display. Large displayed rates use the largest exact K/M/G suffix with at most one decimal place (for example, 1,234,000 becomes 1,234K); if no suffix preserves that display precision, keep the ordinary number. Numbers with four or more integer digits use comma thousands separators, including coefficients before material or power units. Rates are ordered by item ID within each category, and use native item icon/name tags with comma-separated entries inside each description line. Uncertain final-product, overbuild, or coproduct conclusions are omitted. Veins and other scene objects are not blueprint entries or requested parameters. `BlueprintDescriptionFormatter` builds replacement multiline `blueprint.desc` text in this order: optional `Missing:` and `Excess:` lines for intermediate shortages and excess classified by the selected production basis; `Input:` for external inputs capped by downstream demand; `Output:` for ordinary final products and necessary coproduct surplus; and `Research:` for positive net matrix production accepted by a selected research-mode lab. Each warning category has one label followed by comma-separated items; warnings do not repeat in Input, and a matrix on Research does not repeat in Output. It uses `SteadyStateExternalSupply` for complete and independently known partial inputs, labeling partial values as known portions. The assumed lab adds no numerical matrix consumption or external input; other buildings' known matrix demand is subtracted from the Research rate. Omit each empty line, including Research when no produced matrix remains. A single optional `Power` custom field separates factory and configured logistics consumption, omitting categories with no demand and removing the field altogether if neither consumes power; a present but unknown category displays `Unknown` rather than zero. Material rates remain items per minute even though the description labels omit the unit. Rates are rounded only for display. Large displayed rates use the largest exact K/M/G suffix with at most one decimal place (for example, 1,234,000 becomes 1,234K); if no suffix preserves that display precision, keep the ordinary number. Numbers with four or more integer digits use comma thousands separators, including coefficients before material or power units. Rates are ordered by item ID within each category, and use native item icon/name tags with comma-separated entries inside each description line. Uncertain final-product, overbuild, or coproduct conclusions are omitted. Veins and other scene objects are not blueprint entries or requested parameters.
@@ -129,7 +135,7 @@ Use a test game for the following manual checks. Compare full-load rates only wi
- Select miners at different machine speeds, including one with a backed-up output, a gas collector, and renewable generators. Check native miner power scaling, full-load miner output regardless of the output backlog, per-minute gas output without added grid demand, and ideal rated renewable power rather than local conditions. - Select miners at different machine speeds, including one with a backed-up output, a gas collector, and renewable generators. Check native miner power scaling, full-load miner output regardless of the output backlog, per-minute gas output without added grid demand, and ideal rated renewable power rather than local conditions.
- Select ray receivers in both modes, fuel generators, ejectors, and silos. Toggle proliferation and compare working power, generation, accumulator exchange, and Dyson demand as separate quantities. In a sandbox game, capture boosted artificial stars and launchers, and confirm that blueprint analysis of boosted buildings requires `BoostEnabled`. - Select ray receivers in both modes, fuel generators, ejectors, and silos. Toggle proliferation and compare working power, generation, accumulator exchange, and Dyson demand as separate quantities. In a sandbox game, capture boosted artificial stars and launchers, and confirm that blueprint analysis of boosted buildings requires `BoostEnabled`.
- Remove an upstream producer from a mixed production selection. Confirm that downstream capacity is unchanged and the missing material appears as required external supply. Add one producer more than downstream demand needs, and confirm that only that whole building's output is reported as excess. - Remove an upstream producer from a mixed production selection. Confirm that downstream capacity is unchanged and the missing material appears as required external supply. Add one producer more than downstream demand needs, and confirm that only that whole building's output is reported as excess.
- In browser, copy, and paste inspectors, check the localized description-header entry and options, Spray Coater defaults and manual overrides, and native item tags in the generated description and `Power` field. Confirm options close after successful generation or inspector closure, the file grid stays usable, and native settings and description fields retain their positions. Generate twice and at the 20-field limit; verify that pending manual edits, unrelated fields, save/copy behavior, and ordinary blueprint sharing remain intact. - In browser, copy, and paste inspectors, check that the localized options follow their header entry when scrolling and use the available canvas space. Verify the native X, outside-click dismissal, and Escape priority, including an expanded dropdown and a native message box. Confirm both dropdown rows fit above the footer, options close after successful generation or inspector closure, and native settings and description fields retain their positions. Check Spray Coater defaults and manual overrides, generate twice and at the 20-field limit, and verify pending edits, unrelated fields, native item tags, and save/copy behavior.
- Compare both production bases on an undersupplied chain, uneven recipe ratios, shared intermediate branches, and a joint-product chain. Final-product mode must retain rated final outputs and expose intermediate shortages. Bottleneck mode must scale final outputs together, update raw inputs to the same throughput, and leave no internal shortage for a complete, balanceable chain. Confirm unused intermediate capacity and necessary coproduct output remain distinct, and that power stays at the same full-load estimate. Test a chain without internal intermediates, missing building settings, and a cycle without a final outlet; an unavailable bottleneck basis must preserve existing description and fields. - Compare both production bases on an undersupplied chain, uneven recipe ratios, shared intermediate branches, and a joint-product chain. Final-product mode must retain rated final outputs and expose intermediate shortages. Bottleneck mode must scale final outputs together, update raw inputs to the same throughput, and leave no internal shortage for a complete, balanceable chain. Confirm unused intermediate capacity and necessary coproduct output remain distinct, and that power stays at the same full-load estimate. Test a chain without internal intermediates, missing building settings, and a cycle without a final outlet; an unavailable bottleneck basis must preserve existing description and fields.
- Place one research-mode lab alongside one or all six matrix production chains. Confirm the matrices' positive net production appears only in the Research line, other final products stay in Output, and known in-blueprint matrix consumption reduces the Research rate. Do not fabricate lab matrix imports, excess, or an estimated lab consumption rate; change current technology, add more labs, and toggle proliferation to check matrix routing stays independent while full working power updates. Without the lab, normal matrix output and overbuild rules resume. - Place one research-mode lab alongside one or all six matrix production chains. Confirm the matrices' positive net production appears only in the Research line, other final products stay in Output, and known in-blueprint matrix consumption reduces the Research rate. Do not fabricate lab matrix imports, excess, or an estimated lab consumption rate; change current technology, add more labs, and toggle proliferation to check matrix routing stays independent while full working power updates. Without the lab, normal matrix output and overbuild rules resume.
- Combine planner targets with shared coproducts, explicit raw-material boundaries, and alternate selected recipes. Confirm material conservation, shared surplus reuse, and no introduction of unselected recipes. - Combine planner targets with shared coproducts, explicit raw-material boundaries, and alternate selected recipes. Confirm material conservation, shared surplus reuse, and no introduction of unselected recipes.
@@ -1,7 +1,9 @@
using System.IO; using System.IO;
using UXAssist.Common.ModFeatures;
namespace UniverseGenTweaks; namespace UniverseGenTweaks;
[ModFeature("UniverseGenSave", Order = 13)]
public static class GalaxyGenSave public static class GalaxyGenSave
{ {
public static void Export(BinaryWriter w) public static void Export(BinaryWriter w)
@@ -12,6 +12,10 @@ namespace UniverseGenTweaks;
[ModFeature("UniverseGenGalaxySelectUI", Order = 10)] [ModFeature("UniverseGenGalaxySelectUI", Order = 10)]
public static class GalaxySelectUIPatch public static class GalaxySelectUIPatch
{ {
private static Text _minDistTitle;
private static Text _minStepTitle;
private static Text _maxStepTitle;
private static Text _flattenTitle;
private static Slider _minDistSlider; private static Slider _minDistSlider;
private static Slider _minStepSlider; private static Slider _minStepSlider;
private static Slider _maxStepSlider; private static Slider _maxStepSlider;
@@ -58,28 +62,28 @@ public static class GalaxySelectUIPatch
{ {
__instance.starCountSlider.maxValue = MoreSettings.MaxStarCount.Value; __instance.starCountSlider.maxValue = MoreSettings.MaxStarCount.Value;
CreateSliderWithText(__instance.starCountSlider, out var minDistTitle, out _minDistSlider, out _minDistText, out var minDistLocalizer); CreateSliderWithText(__instance.starCountSlider, out _minDistTitle, out _minDistSlider, out _minDistText, out var minDistLocalizer);
CreateSliderWithText(__instance.starCountSlider, out var minStepTitle, out _minStepSlider, out _minStepText, out var minStepLocalizer); CreateSliderWithText(__instance.starCountSlider, out _minStepTitle, out _minStepSlider, out _minStepText, out var minStepLocalizer);
CreateSliderWithText(__instance.starCountSlider, out var maxStepTitle, out _maxStepSlider, out _maxStepText, out var maxStepLocalizer); CreateSliderWithText(__instance.starCountSlider, out _maxStepTitle, out _maxStepSlider, out _maxStepText, out var maxStepLocalizer);
CreateSliderWithText(__instance.starCountSlider, out var flattenTitle, out _flattenSlider, out _flattenText, out var flattenLocalizer); CreateSliderWithText(__instance.starCountSlider, out _flattenTitle, out _flattenSlider, out _flattenText, out var flattenLocalizer);
minDistLocalizer.stringKey = Localization.StarDistanceMin; minDistLocalizer.stringKey = Localization.StarDistanceMin;
minDistTitle.text = Localization.StarDistanceMin.Translate(); _minDistTitle.text = Localization.StarDistanceMin.Translate();
minStepLocalizer.stringKey = Localization.StepDistanceMin; minStepLocalizer.stringKey = Localization.StepDistanceMin;
minStepTitle.text = Localization.StepDistanceMin.Translate(); _minStepTitle.text = Localization.StepDistanceMin.Translate();
maxStepLocalizer.stringKey = Localization.StepDistanceMax; maxStepLocalizer.stringKey = Localization.StepDistanceMax;
maxStepTitle.text = Localization.StepDistanceMax.Translate(); _maxStepTitle.text = Localization.StepDistanceMax.Translate();
flattenLocalizer.stringKey = Localization.Flatness; flattenLocalizer.stringKey = Localization.Flatness;
flattenTitle.text = Localization.Flatness.Translate(); _flattenTitle.text = Localization.Flatness.Translate();
minDistTitle.name = "min-dist"; _minDistTitle.name = "min-dist";
minStepTitle.name = "min-step"; _minStepTitle.name = "min-step";
maxStepTitle.name = "max-step"; _maxStepTitle.name = "max-step";
flattenTitle.name = "flatten"; _flattenTitle.name = "flatten";
TransformDeltaY(minDistTitle.transform, UniverseGenConstants.SliderRowSpacing); TransformDeltaY(_minDistTitle.transform, UniverseGenConstants.SliderRowSpacing);
TransformDeltaY(minStepTitle.transform, UniverseGenConstants.SliderRowSpacing * 2); TransformDeltaY(_minStepTitle.transform, UniverseGenConstants.SliderRowSpacing * 2);
TransformDeltaY(maxStepTitle.transform, UniverseGenConstants.SliderRowSpacing * 3); TransformDeltaY(_maxStepTitle.transform, UniverseGenConstants.SliderRowSpacing * 3);
TransformDeltaY(flattenTitle.transform, UniverseGenConstants.SliderRowSpacing * 4); TransformDeltaY(_flattenTitle.transform, UniverseGenConstants.SliderRowSpacing * 4);
TransformDeltaY(__instance.darkFogToggle.transform.parent, UniverseGenConstants.SliderRowSpacing * 4); TransformDeltaY(__instance.darkFogToggle.transform.parent, UniverseGenConstants.SliderRowSpacing * 4);
TransformDeltaY(__instance.resourceMultiplierSlider.transform.parent, UniverseGenConstants.SliderRowSpacing * 4); TransformDeltaY(__instance.resourceMultiplierSlider.transform.parent, UniverseGenConstants.SliderRowSpacing * 4);
TransformDeltaY(__instance.sandboxToggle.transform.parent, UniverseGenConstants.SliderRowSpacing * 4); TransformDeltaY(__instance.sandboxToggle.transform.parent, UniverseGenConstants.SliderRowSpacing * 4);
@@ -109,7 +113,10 @@ public static class GalaxySelectUIPatch
[HarmonyPatch(typeof(UIGalaxySelect), nameof(UIGalaxySelect._OnUnregEvent))] [HarmonyPatch(typeof(UIGalaxySelect), nameof(UIGalaxySelect._OnUnregEvent))]
private static void UIGalaxySelect__OnUnregEvent_Postfix() private static void UIGalaxySelect__OnUnregEvent_Postfix()
{ {
RemoveAllListeners(); _minDistSlider.onValueChanged.RemoveAllListeners();
_minStepSlider.onValueChanged.RemoveAllListeners();
_maxStepSlider.onValueChanged.RemoveAllListeners();
_flattenSlider.onValueChanged.RemoveAllListeners();
} }
} }
+6 -3
View File
@@ -7,6 +7,8 @@ namespace UniverseGenTweaks;
public static class UIConfigWindow public static class UIConfigWindow
{ {
private static RectTransform _windowTrans;
public static void Init() public static void Init()
{ {
MyConfigWindow.OnUICreated += CreateUI; MyConfigWindow.OnUICreated += CreateUI;
@@ -14,12 +16,13 @@ public static class UIConfigWindow
private static void CreateUI(MyConfigWindow wnd, RectTransform trans) private static void CreateUI(MyConfigWindow wnd, RectTransform trans)
{ {
_windowTrans = trans;
// General tab // General tab
var x = 0f; var x = 0f;
var y = 10f; var y = 10f;
wnd.AddSplitter(trans, 10f); wnd.AddSplitter(trans, 10f);
wnd.AddTabGroup(trans, Localization.UniverseGen, "tab-group-galaxygen"); wnd.AddTabGroup(trans, Localization.UniverseGen, "tab-group-galaxygen");
var tab1 = wnd.AddTab(trans, "General"); var tab1 = wnd.AddTab(_windowTrans, "General");
MyCheckBox.CreateCheckBox(x, y, tab1, MoreSettings.Enabled, Localization.EnableMoreSettingsOnUniverseGen); MyCheckBox.CreateCheckBox(x, y, tab1, MoreSettings.Enabled, Localization.EnableMoreSettingsOnUniverseGen);
x += 20f; x += 20f;
y += 26f; y += 26f;
@@ -67,7 +70,7 @@ public static class UIConfigWindow
EpicDifficulty.OilMultiplier.Value = val; EpicDifficulty.OilMultiplier.Value = val;
sl2.SetLabelText(val.ToString(sl2.labelFormat)); sl2.SetLabelText(val.ToString(sl2.labelFormat));
}; };
var tab2 = wnd.AddTab(trans, Localization.BirthStar); var tab2 = wnd.AddTab(_windowTrans, Localization.BirthStar);
x = 0f; x = 0f;
y = 10f; y = 10f;
MyCheckBox.CreateCheckBox(x, y, tab2, BirthPlanetPatch.SitiVeinsOnBirthPlanet, Localization.SiliconTitaniumOnBirthPlanet); MyCheckBox.CreateCheckBox(x, y, tab2, BirthPlanetPatch.SitiVeinsOnBirthPlanet, Localization.SiliconTitaniumOnBirthPlanet);
@@ -91,4 +94,4 @@ public static class UIConfigWindow
y += 36f; y += 36f;
MyCheckBox.CreateCheckBox(x, y, tab2, BirthPlanetPatch.HighLuminosityBirthStar, Localization.BirthStarHasHighLuminosity); MyCheckBox.CreateCheckBox(x, y, tab2, BirthPlanetPatch.HighLuminosityBirthStar, Localization.BirthStarHasHighLuminosity);
} }
} }